Beispiel #1
0
        // 检测目录是否已经存在
        private void textBox_dataDir_Leave(object sender, EventArgs e)
        {
            // 已经准备Cancel,就不检查了
            if (IsMouseOnCancelButton() == true)
            {
                return;
            }

            // 新建时
            if (IsNew == true &&
                String.IsNullOrEmpty(this.textBox_dataDir.Text) == false &&
                this.LoadedDataDir != this.textBox_dataDir.Text)
            {
                // 注意检查,不能是别的instance的数据目录
                if (this.VerifyDataDir != null)
                {
                    VerifyEventArgs e1 = new VerifyEventArgs();
                    e1.Value = this.textBox_dataDir.Text;
                    this.VerifyDataDir(this, e1);
                    if (String.IsNullOrEmpty(e1.ErrorInfo) == false)
                    {
                        MessageBox.Show(this, e1.ErrorInfo);
                        return;
                    }
                }

                string strXmlFilename = PathUtil.MergePath(this.textBox_dataDir.Text, "databases.xml");
                if (File.Exists(strXmlFilename) == true)
                {
                    DialogResult result = MessageBox.Show(ForegroundWindow.Instance,
                                                          "您指定的数据目录 '" + this.textBox_dataDir.Text + "' 中已经存在 database.xml 文件。\r\n\r\n是否要直接利用此其中(指xml文件和目录中有关帐户文件)的配置信息?",
                                                          "安装 dp2Kernel",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Question,
                                                          MessageBoxDefaultButton.Button1);
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        this.LoadedDataDir = this.textBox_dataDir.Text; // 防止重复询问
                        return;
                    }

                    // TODO: 检查 databases.xml 文件中的 SQL 数据库名是否和其他实例中的名字重复
                    if (this.VerifyDatabases != null)
                    {
                        VerifyEventArgs e1 = new VerifyEventArgs();
                        e1.Value  = this.textBox_dataDir.Text;
                        e1.Value1 = this.textBox_instanceName.Text;
                        this.VerifyDatabases(this, e1);
                        if (String.IsNullOrEmpty(e1.ErrorInfo) == false)
                        {
                            MessageBox.Show(this, e1.ErrorInfo);
                            return;
                        }
                    }

                    if (this.LoadXmlFileInfo != null)
                    {
                        LoadXmlFileInfoEventArgs e1 = new LoadXmlFileInfoEventArgs();
                        e1.DataDir = this.textBox_dataDir.Text;
                        this.LoadXmlFileInfo(this, e1);
                        if (string.IsNullOrEmpty(e1.ErrorInfo) == false)
                        {
                            MessageBox.Show(this, e1.ErrorInfo);
                            return;
                        }

                        // refresh
                        this.LineInfo = e1.LineInfo;
                        RefreshSqlDef();
                        RefreshRootUserInfo();
                        this.LoadedDataDir   = this.textBox_dataDir.Text; // 防止重复装载
                        this.m_bDataDirExist = true;                      // 防止OK时不合适的检查警告
                    }
                }

                return;
            }

            // 修改时
            if (IsNew == false &&
                String.IsNullOrEmpty(this.textBox_dataDir.Text) == false &&
                this.LoadedDataDir != this.textBox_dataDir.Text)
            {
                // 注意检查,不能是别的instance的数据目录
                if (this.VerifyDataDir != null)
                {
                    VerifyEventArgs e1 = new VerifyEventArgs();
                    e1.Value = this.textBox_dataDir.Text;
                    this.VerifyDataDir(this, e1);
                    if (String.IsNullOrEmpty(e1.ErrorInfo) == false)
                    {
                        MessageBox.Show(this, e1.ErrorInfo);
                        return;
                    }
                }

                string strXmlFilename = PathUtil.MergePath(this.textBox_dataDir.Text, "databases.xml");
                if (File.Exists(strXmlFilename) == true)
                {
                    DialogResult result = MessageBox.Show(ForegroundWindow.Instance,
                                                          "您指定的数据目录 '" + this.textBox_dataDir.Text + "' 中已经存在 database.xml 文件。\r\n\r\n是否要直接利用其中(指xml文件和目录中有关帐户文件)的配置信息?\r\n\r\n是:直接利用其中的信息,也即将其中的配置信息装入当前对话框\r\n否:利用这个数据目录,但其中xml文件和帐户文件的相关信息即将被当前对话框中的值覆盖\r\n\r\n(提示:无论您选“是”“否”,原有目录 '" + this.LoadedDataDir + "' 都会被闲置)",
                                                          "安装 dp2Kernel",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Question,
                                                          MessageBoxDefaultButton.Button1);
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        this.LoadedDataDir = this.textBox_dataDir.Text; // 防止重复询问
                        return;
                    }

                    // TODO: 检查 databases.xml 文件中的 SQL 数据库名是否和其他实例中的名字重复
                    if (this.VerifyDatabases != null)
                    {
                        VerifyEventArgs e1 = new VerifyEventArgs();
                        e1.Value  = this.textBox_dataDir.Text;
                        e1.Value1 = this.textBox_instanceName.Text;
                        this.VerifyDatabases(this, e1);
                        if (String.IsNullOrEmpty(e1.ErrorInfo) == false)
                        {
                            MessageBox.Show(this, e1.ErrorInfo);
                            return;
                        }
                    }

                    if (this.LoadXmlFileInfo != null)
                    {
                        LoadXmlFileInfoEventArgs e1 = new LoadXmlFileInfoEventArgs();
                        e1.DataDir = this.textBox_dataDir.Text;
                        this.LoadXmlFileInfo(this, e1);
                        if (string.IsNullOrEmpty(e1.ErrorInfo) == false)
                        {
                            MessageBox.Show(this, e1.ErrorInfo);
                            return;
                        }

                        // refresh
                        this.LineInfo = e1.LineInfo;
                        RefreshSqlDef();
                        RefreshRootUserInfo();
                        this.LoadedDataDir   = this.textBox_dataDir.Text; // 防止重复装载
                        this.m_bDataDirExist = true;                      // 防止OK时不合适的检查警告
                    }
                }
                else if (String.IsNullOrEmpty(this.LoadedDataDir) == false)
                {
                    // 修改目录名

                    DialogResult result = MessageBox.Show(ForegroundWindow.Instance,
                                                          "要将已经存在的数据目录 '" + this.LoadedDataDir + "' 更名为 '" + this.textBox_dataDir.Text + "' 么?\r\n\r\n(如果选择“否”,则安装程序在稍后将新创建一个数据目录,并复制进初始内容)",
                                                          "安装 dp2Kernel",
                                                          MessageBoxButtons.YesNo,
                                                          MessageBoxIcon.Question,
                                                          MessageBoxDefaultButton.Button1);
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        this.m_bDataDirExist = false;
                        return;
                    }

                    try
                    {
                        // TODO: 需要测试当数据目录中内容尺寸太大,而目标盘无妨容纳时的报错情况
                        Directory.Move(this.LoadedDataDir, this.textBox_dataDir.Text);

                        this.LoadedDataDir = this.textBox_dataDir.Text; // 防止重复装载
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(this, "将已经存在的数据目录 '" + this.LoadedDataDir + "' 更名为 '" + this.textBox_dataDir.Text + "' 时发生错误: " + ex.Message);
                    }
                }

                return;
            }
        }
Beispiel #2
0
        static async Task <int> Main(string[] args)
        {
            if (args.Length != 8)
            {
                throw new ArgumentException("Number of arguments does not match expected amount.");
            }

            var token          = args[0];
            var repository     = args[1];
            var owner          = repository.Split('/')[0];
            var repositoryName = repository.Split('/')[1];

            if (!int.TryParse(args[2], out var prNumber))
            {
                throw new ArgumentException("Error casting type");
            }
            if (!PathUtil.TryGetAbsoluteUri(args[3], out var oldFile) || !oldFile.IsFile)
            {
                throw new ArgumentException("Error casting type");
            }
            if (!PathUtil.TryGetAbsoluteUri(args[4], out var newFile) || !newFile.IsFile)
            {
                throw new ArgumentException("Error casting type");
            }
            var addComment = false;

            if (args.GetValue(5) != null && !bool.TryParse(args[5], out addComment))
            {
                throw new ArgumentException("Error casting type");
            }
            var excludeLabels = false;

            if (args.GetValue(6) != null && !bool.TryParse(args[6], out excludeLabels))
            {
                throw new ArgumentException("Error casting type");
            }
            if (!PathUtil.TryGetAbsoluteUri(args[7], out var outputPath))
            {
                throw new ArgumentException("Error casting type");
            }

            var serviceProvider  = Startup.Build();
            var openAPICompare   = serviceProvider.GetService <IOpenAPICompare>();
            var markdownRenderer = serviceProvider.GetService <IMarkdownRender>();
            var htmlRenderer     = serviceProvider.GetService <IHtmlRender>();

            var fileName = Path.GetFileNameWithoutExtension(oldFile.LocalPath);

            Console.WriteLine($"Running OpenAPI Diff for {fileName}");

            string         markdown;
            string         html;
            DiffResultEnum diffResult;

            try
            {
                var openAPIDiff = openAPICompare.FromLocations(oldFile.LocalPath, newFile.LocalPath);

                Console.WriteLine($"Creating Diff Result");
                diffResult = openAPIDiff.IsChanged().DiffResult;
                Console.WriteLine($"Completed OpenAPI DIff with Result {diffResult}");

                Console.WriteLine($"Generate Markdown");
                markdown = await markdownRenderer.Render(openAPIDiff);

                Console.WriteLine($"Generate HTML");
                html = await htmlRenderer.Render(openAPIDiff);


                var finalOutputFilePath = Path.Combine(outputPath.AbsolutePath, $"{fileName}.html");
                var file = new FileInfo(finalOutputFilePath);
                file.Directory?.Create(); // If the directory already exists, this method does nothing.

                Console.WriteLine($"Writing html report to: {finalOutputFilePath}");
                await File.WriteAllTextAsync(finalOutputFilePath, html);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Environment.ExitCode = 1;
                throw;
            }


            Console.WriteLine($"Create markdown comment in GitHub");

            var commentMarkdown = CommentUtil.GetCommentMarkdown(fileName, diffResult, markdown);

            var credentials = new InMemoryCredentialStore(new Credentials(token));
            var github      = new GitHubClient(new ProductHeaderValue("openapi-diff-action"), credentials);

            try
            {
                var comments = await github.Issue.Comment.GetAllForIssue(owner, repositoryName, prNumber);

                if (!addComment)
                {
                    var existingComment = comments.FirstOrDefault(x => x.Body.Contains(CommentUtil.GetIdentifierString(fileName)));
                    if (existingComment != null)
                    {
                        await github.Issue.Comment.Update(owner, repositoryName, existingComment.Id, commentMarkdown);

                        Console.WriteLine($"Updated existing comment with id {existingComment}");
                    }
                    else
                    {
                        await github.Issue.Comment.Create(owner, repositoryName, prNumber, commentMarkdown);

                        Console.WriteLine("Added new comment because no existing comment found");
                    }
                }
                else
                {
                    await github.Issue.Comment.Create(owner, repositoryName, prNumber, commentMarkdown);

                    Console.WriteLine($"Added new comment because addComment is true");
                }

                if (!excludeLabels)
                {
                    await LabelUtil.CreateIfNotExist(github, owner, repositoryName);

                    // get all comments with identifiers
                    // group all comments by unique identifier
                    // get latest change level for each unique identifier
                    // get highest change level including current changes
                    // remove all old change labels
                    // add new change label
                    var highestChangeLevel = comments
                                             .Select(x => new
                    {
                        comment    = x,
                        identifier = CommentUtil.GetIdentifier(x.Body)
                    }).Where(x => !x.identifier.IsNullOrEmpty())
                                             .GroupBy(x => x.identifier)
                                             .Select(x => new
                    {
                        key   = x.Key,
                        value = x.OrderByDescending(y => y.comment.CreatedAt)
                                .FirstOrDefault()
                    })
                                             .Select(x => CommentUtil.GetDiffResult(x.value.comment.Body))
                                             .DefaultIfEmpty(DiffResultEnum.NoChanges)
                                             .Max();

                    var allLabels = await github.Issue.Labels.GetAllForIssue(owner, repositoryName, prNumber);

                    foreach (var label in allLabels.Where(x => x.Name.StartsWith("OAS:")))
                    {
                        await github.Issue.Labels.RemoveFromIssue(owner, repositoryName, prNumber, label.Name);
                    }

                    var labelName = LabelUtil.GetLabelForDiffResult(diffResult > highestChangeLevel ? diffResult : highestChangeLevel);
                    await github.Issue.Labels.AddToIssue(owner, repositoryName, prNumber, new[] { labelName });

                    Console.WriteLine($"Added label {labelName}");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Environment.ExitCode = 1;
                throw;
            }

            return(Environment.ExitCode);
        }
        public RevisionData ProcessDirectory(string path, string tagMatch)
        {
            // Initialise data
            var data = new RevisionData
            {
                VcsProvider = this
            };

            // svn assumes case-sensitive path names on Windows, which is... bad.
            string fixedPath = PathUtil.GetExactPath(path);

            if (fixedPath != path)
            {
                Logger?.Warning($"Corrected path to: {fixedPath}");
            }
            path = fixedPath;

            // Get revision number
            Logger?.Trace("Executing: svnversion");
            Logger?.Trace($"  WorkingDirectory: {path}");
            var psi = new ProcessStartInfo(svnversionExec)
            {
                WorkingDirectory       = path,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                CreateNoWindow         = true
            };
            var    process = Process.Start(psi);
            string line    = null;

            while (!process.StandardOutput.EndOfStream)
            {
                line = process.StandardOutput.ReadLine();
                Logger?.RawOutput(line);
                // Possible output:
                // 1234          Revision 1234
                // 1100:1234     Mixed revisions 1100 to 1234
                // 1234M         Revision 1234, modified
                // 1100:1234MP   Mixed revisions 1100 to 1234, modified and partial
                Match m = Regex.Match(line, @"^([0-9]+:)?([0-9]+)");
                if (m.Success)
                {
                    data.IsMixed        = m.Groups[1].Success;
                    data.RevisionNumber = int.Parse(m.Groups[2].Value, CultureInfo.InvariantCulture);
                    break;
                }
            }
            process.StandardOutput.ReadToEnd();               // Kindly eat up the remaining output
            if (!process.WaitForExit(1000))
            {
                process.Kill();
            }

            if (data.RevisionNumber == 0)
            {
                return(data);                                        // Try no more
            }
            Logger?.Trace("Executing: svn status");
            Logger?.Trace($"  WorkingDirectory: {path}");
            psi = new ProcessStartInfo(svnExec, "status")
            {
                WorkingDirectory       = path,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                CreateNoWindow         = true
            };
            process = Process.Start(psi);
            line    = null;
            while (!process.StandardOutput.EndOfStream)
            {
                line = process.StandardOutput.ReadLine();
                Logger?.RawOutput(line);
            }
            if (!process.WaitForExit(1000))
            {
                process.Kill();
            }
            data.IsModified = !string.IsNullOrEmpty(line);

            Logger?.Trace($"Executing: svn info --revision {data.RevisionNumber}");
            Logger?.Trace($"  WorkingDirectory: {path}");
            psi = new ProcessStartInfo(svnExec, $"info --revision {data.RevisionNumber}")
            {
                WorkingDirectory       = path,
                RedirectStandardOutput = true,
                UseShellExecute        = false,
                CreateNoWindow         = true,
                //StandardOutputEncoding = Encoding.Default   // TODO: Test if it's necessary (Encoding.Default is not supported in .NET Standard 1.6)
            };
            process = Process.Start(psi);
            line    = null;
            string workingCopyRootPath = null;

            while (!process.StandardOutput.EndOfStream)
            {
                line = process.StandardOutput.ReadLine();
                Logger?.RawOutput(line);
                // WARNING: This is the info about the commit that has been *last updated to* in the
                //          specified *subdirectory* of the working directory. The revision number
                //          printed here belongs to that commit, but does not necessarily match the
                //          revision number determined above by 'svnversion'.
                //          If you need consistent data on the commit other than the revision
                //          number, be sure to always update the entire working directory and set
                //          the VCS path to its root.
                Match m = Regex.Match(line, @"^Working Copy Root Path: (.+)");
                if (m.Success)
                {
                    workingCopyRootPath = m.Groups[1].Value.Trim();
                }
                // Try to be smart and detect the branch from the relative path. This should work
                // fine if the standard SVN repository tree is used.
                m = Regex.Match(line, @"^Relative URL: \^(.+)");
                if (m.Success)
                {
                    data.Branch = m.Groups[1].Value.Trim().TrimStart('/');
                    if (data.Branch.StartsWith("branches/", StringComparison.Ordinal))
                    {
                        data.Branch = data.Branch.Substring(9);
                    }

                    // Cut off the current subdirectory
                    if (workingCopyRootPath != null &&
                        path.StartsWith(workingCopyRootPath, StringComparison.OrdinalIgnoreCase))
                    {
                        int subdirLength = path.Length - workingCopyRootPath.Length;
                        data.Branch = data.Branch.Substring(0, data.Branch.Length - subdirLength);
                    }
                }
                // Use "Repository Root" because "URL" is only the URL where the working directory
                // was checked out from. This can be a subdirectory of the repository if only a part
                // of it was checked out, like "/trunk" or a branch.
                m = Regex.Match(line, @"^Repository Root: (.+)");
                if (m.Success)
                {
                    data.RepositoryUrl = m.Groups[1].Value.Trim();
                }
                m = Regex.Match(line, @"^Last Changed Author: (.+)");
                if (m.Success)
                {
                    data.CommitterName = m.Groups[1].Value.Trim();
                }
                m = Regex.Match(line, @"^Last Changed Date: ([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} [+-][0-9]{4})");
                if (m.Success)
                {
                    data.CommitTime = DateTimeOffset.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
                }
            }
            if (!process.WaitForExit(1000))
            {
                process.Kill();
            }
            return(data);
        }
Beispiel #4
0
 private void btnTest_Click(object sender, EventArgs e)
 {
     PathUtil.DisplayAllProgram();
 }
Beispiel #5
0
        // 初始化
        public void Initial(string dataDir)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            // 如果数据目录不存,则创建
            PathUtil.CreateDirIfNeed(dataDir);

            // 日志目录
            DataDir = dataDir;
            LogDir  = Path.Combine(dataDir, "log");
            PathUtil.CreateDirIfNeed(LogDir);

            string strVersion = Assembly.GetAssembly(typeof(ServerInfo)).GetName().Version.ToString();

            WriteErrorLog("*** WebZ 开始启动 (WebZ 版本: " + strVersion + ")");

            string strCfgFileName = Path.Combine(dataDir, "config.xml");

            // 如果配置文件不存在,自动创建数据目录中的 config.xml 配置文件
            if (File.Exists(strCfgFileName) == false)
            {
                PathUtil.CreateDirIfNeed(Path.GetDirectoryName(strCfgFileName));
                this.CreateCfgFile(strCfgFileName);
                WriteErrorLog("首次创建配置文件 " + strCfgFileName);
            }

            string strMongoDbConnStr        = "";
            string strMongoDbInstancePrefix = "";

            try
            {
                XmlDocument cfgDom = new XmlDocument();
                cfgDom.Load(strCfgFileName);

                XmlNode root = cfgDom.DocumentElement;

                // 元素 <mongoDB>
                // 属性 connectionString / instancePrefix
                XmlElement node = root.SelectSingleNode("mongoDB") as XmlElement;
                if (node != null)
                {
                    strMongoDbConnStr        = node.GetAttribute("connectionString");
                    strMongoDbInstancePrefix = node.GetAttribute("instancePrefix");
                }
                else
                {
                    throw new Exception("尚未配置 mongoDB 元素");
                }

                // 初始化短信接口类
                string strError = "";
                int    nRet     = this.InitialExternalMessageInterfaces(cfgDom, out strError);
                if (nRet == -1)
                {
                    throw new Exception("初始化短信接口配置信息出错:" + strError);
                }

                this.WriteErrorLog("初始化短信接口配置完成。");
            }
            catch (Exception ex)
            {
                throw new Exception("装载配置文件 '" + strCfgFileName + "' 时出现异常: " + ExceptionUtil.GetExceptionText(ex));
            }

            // 初始化数据库
            _mongoClient = new MongoClient(strMongoDbConnStr);
            ZServerDb.Open(_mongoClient, strMongoDbInstancePrefix, "zserver", _cancel.Token);
        }
Beispiel #6
0
 public void CanBeGitURL(string url, bool expected)
 {
     Assert.AreEqual(expected, PathUtil.CanBeGitURL(url));
 }
Beispiel #7
0
        protected void Application_Start(Object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);

            OpacApplication app = null;

            try
            {
                int    nRet     = 0;
                string strError = "";

#if NO
                string strErrorLogDir = this.Server.MapPath(".\\log");
                PathUtil.CreateDirIfNeed(strErrorLogDir);
                string strErrorLogFileName = PathUtil.MergePath(strErrorLogDir, "error.txt");
#endif

                try
                {
                    string strDataDir = "";

                    // reutrn:
                    //      -1  error
                    //      0   not found start.xml
                    //      1   found start.xml
                    nRet = OpacApplication.GetDataDir(this.Server.MapPath("~/start.xml"),
                                                      out strDataDir,
                                                      out strError);
                    if (nRet == -1)
                    {
                        strError = "搜寻配置文件start.xml时出错: " + strError;
#if NO
                        OpacApplication.WriteErrorLog(strErrorLogFileName,
                                                      strError);
#endif
                        OpacApplication.WriteWindowsLog(strError);

                        Application["errorinfo"] = strError;
                        return;
                    }
                    if (nRet == 0)
                    {
#if NO
                        // 实在没有start.xml文件, 默认虚拟目录就是数据目录
                        strDataDir = this.Server.MapPath(".");
#endif
                        // 2014/2/21
                        // 不再允许虚拟目录中 start.xml 没有的情况
                        OpacApplication.WriteWindowsLog("OpacApplication.GetDataDir() error : " + strError);

                        Application["errorinfo"] = strError;
                        return;
                    }

                    app = new OpacApplication();
                    Application["app"] = app;

                    // string strHostDir = this.Server.MapPath(".");
                    string strHostDir = Path.GetDirectoryName(this.Server.MapPath("~/start.xml"));  // 2015/7/20

                    nRet = app.Load(
                        false,
                        strDataDir,
                        strHostDir,
                        out strError);
                    if (nRet == -1)
                    {
#if NO
                        OpacApplication.WriteErrorLog(strErrorLogFileName,
                                                      strError);
#endif
                        // TODO: 预先试探一下写入数据目录中的错误日志文件是否成功。如果成功,则可以把错误信息写入那里
                        OpacApplication.WriteWindowsLog(strError);

                        // Application["errorinfo"] = strError;
                        app.GlobalErrorInfo = strError;
                    }
                    else
                    {
                        nRet = app.Verify(out strError);
                        if (nRet == -1)
                        {
#if NO
                            OpacApplication.WriteErrorLog(strErrorLogFileName,
                                                          strError);
#endif
                            OpacApplication.WriteWindowsLog(strError);

                            // Application["errorinfo"] = strError;
                            app.GlobalErrorInfo = strError;
                        }
                    }

                    OpacApplication.WriteWindowsLog("dp2OPAC Application 启动成功", EventLogEntryType.Information);
                }
                catch (Exception ex)
                {
                    strError = "装载配置文件 opac.xml 出错: " + ExceptionUtil.GetDebugText(ex);
#if NO
                    OpacApplication.WriteErrorLog(strErrorLogFileName,
                                                  strError);
#endif
                    OpacApplication.WriteWindowsLog(strError);

                    if (app != null)
                    {
                        app.GlobalErrorInfo = strError;
                    }
                    else
                    {
                        Application["errorinfo"] = strError;
                    }
                }
            }
            catch (Exception ex)
            {
                string strErrorText = "Application_Start阶段出现异常: " + ExceptionUtil.GetDebugText(ex);
                OpacApplication.WriteWindowsLog(strErrorText);

                if (app != null)
                {
                    app.GlobalErrorInfo = strErrorText;
                }
                else
                {
                    Application["errorinfo"] = strErrorText;
                }
            }
        }
Beispiel #8
0
        // 初始化GlobalInfo
        // parameters:
        //		strDataDir	数据目录
        //		strError	out参数,返回出错信息
        // return:
        //		-1	error
        //		0	successed
        public int Initial(string strDataDir,
                           string strBinDir,
                           out string strError)
        {
            strError = "";
            int nRet = 0;

            DateTime start = DateTime.Now;

            this.DataDir = strDataDir;

            this.SessionDir = PathUtil.MergePath(this.DataDir, "session");

            // 清除 session 目录中的全部下级目录

            // 日志文件
            string strLogDir = this.DataDir + "\\log";

            try
            {
                PathUtil.TryCreateDir(strLogDir);
            }
            catch (Exception ex)
            {
                DirectoryInfo di = new DirectoryInfo(this.DataDir);
                if (di.Exists == false)
                {
                    strError = "创建日志目录出错: '" + ex.Message + "', 原因是上级目录 '" + this.DataDir + "' 不存在...";
                }
                else
                {
                    strError = "创建日志目录出错: " + ex.Message;
                }
                return(-1);
            }

            this.LogDir = strLogDir;

            // this.m_strLogFileName = strLogDir + "\\log.txt";
            this.m_strDebugFileName = strLogDir + "\\debug.txt";

            this.WriteErrorLog("kernel application 开始初始化");

            CleanSessionDir(this.SessionDir);

            // 全局结果集目录
            string strResultSetDir = Path.Combine(this.DataDir, "resultsets");

            try
            {
                PathUtil.TryCreateDir(strResultSetDir);
            }
            catch (Exception ex)
            {
                DirectoryInfo di = new DirectoryInfo(this.DataDir);
                if (di.Exists == false)
                {
                    strError = "创建全局结果集目录出错: '" + ex.Message + "', 原因是上级目录 '" + this.DataDir + "' 不存在...";
                }
                else
                {
                    strError = "创建全局结果集目录出错: " + ex.Message;
                }
                return(-1);
            }

            // 清除以前遗留的结果集文件
            CleanResultSetDir(strResultSetDir);

            this.ResultsetDir = strResultSetDir;

            this.ResultSets.ResultsetDir = strResultSetDir;

            // 初始化数据库集合
            this.Dbs = new DatabaseCollection();
            try
            {
                nRet = this.Dbs.Initial(
                    this,
                    // strDataDir,
                    strBinDir,
                    out strError);
                if (nRet == -1)
                {
                    return(-1);
                }
            }
            catch (Exception ex)
            {
                strError = "dbs的Initialize()抛出异常:" + ex.Message;
                return(-1);
            }

            // 检验各个数据库记录尾号
            // return:
            //      -1  出错
            //      0   成功
            // 线:安全
            nRet = this.Dbs.CheckDbsTailNo(out strError);
            if (nRet == -1)
            {
                // 虽然发生错误,但是初始化过程继续进行
                this.WriteErrorLog("ERR001 首次校验数据库尾号发生错误:" + strError);
            }

            /*
             * // 初始化用户库集合
             * UserDatabaseCollection userDbs = new UserDatabaseCollection();
             * // 初始化用户库集合对象
             * // paramter:
             * //		dbColl  总数据库集合
             * //      strError    out参数,返回出错信息
             * // return:
             * //      -1  出错
             * //      0   成功
             * // 线:安全
             * nRet = userDbs.Initial(this.Dbs,
             *  out strError);
             * if (nRet == -1)
             *  return -1;
             */

            // 初始化用户集合
            this.Users = new UserCollection();
            nRet       = this.Users.Initial(this,
                                            out strError);
            if (nRet == -1)
            {
                return(-1);
            }

            // 把帐户集合对象的指针传给DatabaseCollection对象。
            // this.Dbs.UserColl = Users;

            // 启动工作线程
            StartWorkerThread();

            TimeSpan delta = DateTime.Now - start;

            this.WriteErrorLog("kernel application 成功初始化。初始化操作耗费时间 " + delta.TotalSeconds.ToString() + " 秒");
            return(0);
        }
Beispiel #9
0
 public virtual void PrependPath(string directory)
 {
     ArgUtil.NotNull(directory, nameof(directory));
     PathUtil.PrependPath(directory);
     Output($"##vso[task.prependpath]{Escape(directory)}");
 }
Beispiel #10
0
 public void EmptyStringIsNotInsideDotGitPath()
 {
     PathUtil.IsPathInsideDotGit(string.Empty).ShouldEqual(false);
 }
 static SpatialOsEditor()
 {
     WorkerRootDir            = Path.GetFullPath(PathUtil.Combine(Application.dataPath, ".."));
     ApplicationRootDir       = Path.GetFullPath(PathUtil.Combine(WorkerRootDir, "..", ".."));
     WorkerSelectionAssetPath = PathUtil.Combine(WorkerRootDir, "build", "selected_workers.txt");
 }
Beispiel #12
0
        /// <summary>
        /// Checks in the given items</summary>
        /// <param name="uris">URIs representing the paths to items</param>
        /// <param name="description">Check-in description</param>
        public override void CheckIn(IEnumerable <Uri> uris, string description)
        {
            int count = uris.Count();

            if (count == 0)
            {
                return;
            }

            if (string.IsNullOrEmpty(description))
            {
                description = "No Comment!";
            }

            if (!(Enabled && m_connectionManager.InitializeConnection()))
            {
                return;
            }

            try
            {
                var changeList = m_connectionManager.CreateChangelist(description);

                foreach (Uri uri in uris)
                {
                    CheckUri(uri);
                    string path   = PathUtil.GetCanonicalPath(uri);
                    var    result = RunP4Command("fstat", path);
                    if (result.Success && result.TaggedOutput != null)
                    {
                        foreach (var record in result.TaggedOutput)
                        {
                            if (record.ContainsKey("change")) //already opened in changelist
                            //reopen an open file in order to move it to a different changelist
                            {
                                RunP4Command("reopen", "-c", changeList.Id.ToString(), path);
                            }
                            if (record.ContainsKey("action"))  // opens the files for edit within the specified changelist
                            {
                                RunP4Command("edit", "-c", changeList.Id.ToString(), path);
                            }
                        }
                    }
                }

                changeList.Submit(null);
                RefreshStatus(uris);
            }

            catch (P4Exception ex)
            {
                switch (ex.ErrorLevel)
                {
                case ErrorSeverity.E_WARN:
                    Outputs.WriteLine(OutputMessageType.Warning, ex.Message);
                    break;

                case ErrorSeverity.E_FAILED:
                    Outputs.WriteLine(OutputMessageType.Error, ex.Message);
                    break;

                case ErrorSeverity.E_INFO:
                    Outputs.WriteLine(OutputMessageType.Info, ex.Message);
                    break;
                }
                if (ThrowExceptions)
                {
                    throw;
                }
            }
        }
Beispiel #13
0
        public override void Init()
        {
#if DEBUG
            if (string.IsNullOrWhiteSpace(Settings.ConfigFile))
            {
                var config = new KtaneWebConfig();
                Console.WriteLine();
                ConsoleUtil.WriteLine("It appears that you are running KtaneWeb for the first time.".Color(ConsoleColor.White));
tryAgain1:
                ConsoleUtil.WriteLine(@"Please provide a location for the JSON settings file (for example: {0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(@"C:\Path\KtaneWeb.settings.json"));
                var path = Console.ReadLine();
                try
                {
                    ClassifyJson.SerializeToFile(config, path);
                }
                catch (Exception e)
                {
                    ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                    goto tryAgain1;
                }

                Console.WriteLine();
tryAgain2:
                ConsoleUtil.WriteLine("Do you already have a local clone of the KtaneContent repository that you want the website to use?".Color(ConsoleColor.White));
                Console.WriteLine("If yes, please type the full path to that repository. If no, just press Enter.");
                var ktaneContent       = Console.ReadLine();
                var expectedSubfolders = "HTML,More,JSON,Icons".Split(',');
                if (string.IsNullOrWhiteSpace(ktaneContent))
                {
                    ConsoleUtil.WriteLine(@"In that case we will create a new clone. I can do that automatically if you have git installed (if you don’t, please abort now).".Color(ConsoleColor.White));
                    ConsoleUtil.WriteLine("This will take a long time as the repository is large.".Color(ConsoleColor.White));
                    Console.WriteLine();
tryAgain3:
                    ConsoleUtil.WriteLine("Please choose a path where you would like all the data stored (for example: {0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(@"C:\Path\KtaneContent"));
                    var cloneFolder = Console.ReadLine();
                    try
                    {
                        Directory.CreateDirectory(cloneFolder);
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                        goto tryAgain3;
                    }
                    try
                    {
                        config.BaseDir = Path.Combine(cloneFolder, "Public");
                        CommandRunner.Run("git", "clone", "https://github.com/Timwi/KtaneContent.git", config.BaseDir).Go();
                        config.MergedPdfsDir = Path.Combine(cloneFolder, "MergedPdfs");
                        Directory.CreateDirectory(config.MergedPdfsDir);
                        config.LogfilesDir = Path.Combine(cloneFolder, "Logfiles");
                        Directory.CreateDirectory(config.LogfilesDir);
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                        goto tryAgain2;
                    }
                }
                else if (expectedSubfolders.Any(s => !Directory.Exists(Path.Combine(ktaneContent, s))))
                {
                    ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {"That folder does not appear to contain KtaneContent.".Color(ConsoleColor.Red)}", null);
                    ConsoleUtil.WriteLine("(We’re looking for a folder that contains subfolders named: {0/DarkMagenta})".Color(ConsoleColor.Magenta).Fmt(expectedSubfolders.JoinString(", ")));
                    goto tryAgain2;
                }
                else
                {
                    var p = ktaneContent;
                    while (p.EndsWith("\""))
                    {
                        p = Path.GetDirectoryName(p);
                    }
                    config.BaseDir = p;
                    p = Path.GetDirectoryName(p);

                    Console.WriteLine();
tryAgain4:
                    var logfiles = Path.Combine(p, "Logfiles");
                    ConsoleUtil.WriteLine("Please choose a path where you would like KtaneWeb to store logfiles uploaded through the Logfile Analyzer, or just press Enter to use the default ({0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(logfiles));
                    config.LogfilesDir = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(config.LogfilesDir))
                    {
                        ConsoleUtil.WriteLine("Using default: {0/DarkCyan}".Color(ConsoleColor.Gray).Fmt(logfiles));
                        config.LogfilesDir = logfiles;
                    }
                    try
                    {
                        Directory.CreateDirectory(config.LogfilesDir);
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                        goto tryAgain4;
                    }

                    Console.WriteLine();
tryAgain5:
                    var mergedPdfs = Path.Combine(p, "MergedPdfs");
                    ConsoleUtil.WriteLine("Please choose a path where you would like KtaneWeb to store merged PDFs, or just press Enter to use the default ({0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(mergedPdfs));

                    config.MergedPdfsDir = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(config.MergedPdfsDir))
                    {
                        ConsoleUtil.WriteLine("Using default: {0/DarkCyan}".Color(ConsoleColor.Gray).Fmt(mergedPdfs));
                        config.MergedPdfsDir = mergedPdfs;
                    }
                    try
                    {
                        Directory.CreateDirectory(config.MergedPdfsDir);
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                        goto tryAgain5;
                    }

                    var appPath = PathUtil.AppPathCombine("..", "..");
                    config.JavaScriptFile = Path.Combine(appPath, "Src", "Resources", "KtaneWeb.js");
                    config.CssFile        = Path.Combine(appPath, "Src", "Resources", "KtaneWeb.css");
                    if (!File.Exists(config.JavaScriptFile) || !File.Exists(config.CssFile))
                    {
                        Console.WriteLine();
tryAgain6:
                        ConsoleUtil.WriteLine("Finally, please let me know where you placed the KtaneWeb source code (what you’re running right now):".Color(ConsoleColor.Gray));
                        appPath = Console.ReadLine();
                        config.JavaScriptFile = Path.Combine(appPath, "Src", "Resources", "KtaneWeb.js");
                        config.CssFile        = Path.Combine(appPath, "Src", "Resources", "KtaneWeb.css");
                        if (!File.Exists(config.JavaScriptFile) || !File.Exists(config.CssFile))
                        {
                            ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {"That does not look like the KtaneWeb source code folder.".Color(ConsoleColor.Red)}", null);
                            goto tryAgain6;
                        }
                    }
                }

                try
                {
                    ClassifyJson.SerializeToFile(config, path);
                    Settings.ConfigFile = path;
                    SaveSettings();
                }
                catch (Exception e)
                {
                    ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                    goto tryAgain1;
                }

                Console.WriteLine();
                ConsoleUtil.WriteLine("That should be all set up for you now!".Color(ConsoleColor.Green));
                ConsoleUtil.WriteLine("Feel free to browse the settings file we just created if you’re curious.".Color(ConsoleColor.DarkGreen));
                ConsoleUtil.WriteLine(@"For automatic PDF generation, we are assuming that Google Chrome is at its default location; if not, please change it manually in the JSON file.".Color(ConsoleColor.DarkGreen));
                Console.WriteLine();
                Console.WriteLine();
            }
#endif
            var original = File.ReadAllText(Settings.ConfigFile);
            _config = ClassifyJson.Deserialize <KtaneWebConfig>(JsonValue.Parse(original));
            var rewrite = serializeConfig();
            if (rewrite != original)
            {
                File.WriteAllText(Settings.ConfigFile, rewrite);
            }

            generateTranslationCache();
            generateModuleInfoCache();
        }
Beispiel #14
0
        private bool PushChanges(IWin32Window owner)
        {
            ErrorOccurred = false;
            if (PushToUrl.Checked && !PathUtil.IsUrl(PushDestination.Text))
            {
                MessageBox.Show(owner, _selectDestinationDirectory.Text);
                return(false);
            }

            if (/* PushToRemote.Checked */ !CheckIfRemoteExist())
            {
                return(false);
            }

            var selectedRemoteName = _selectedRemote.Name;

            if (TabControlTagBranch.SelectedTab == TagTab && string.IsNullOrEmpty(TagComboBox.Text))
            {
                MessageBox.Show(owner, _selectTag.Text);
                return(false);
            }

            // Extra check if the branch is already known to the remote, give a warning when not.
            // This is not possible when the remote is an URL, but this is ok since most users push to
            // known remotes anyway.
            if (TabControlTagBranch.SelectedTab == BranchTab && PushToRemote.Checked &&
                !Module.IsBareRepository())
            {
                // If the current branch is not the default push, and not known by the remote
                // (as far as we know since we are disconnected....)
                if (_NO_TRANSLATE_Branch.Text != AllRefs &&
                    RemoteBranch.Text != _remotesManager.GetDefaultPushRemote(_selectedRemote, _NO_TRANSLATE_Branch.Text) &&
                    !IsBranchKnownToRemote(selectedRemoteName, RemoteBranch.Text))
                {
                    // Ask if this is really what the user wants
                    if (!AppSettings.DontConfirmPushNewBranch &&
                        MessageBox.Show(owner, _branchNewForRemote.Text, _pushCaption.Text, MessageBoxButtons.YesNo) == DialogResult.No)
                    {
                        return(false);
                    }
                }
            }

            if (PushToUrl.Checked)
            {
                var path = PushDestination.Text;
                ThreadHelper.JoinableTaskFactory.Run(() => RepositoryHistoryManager.Remotes.AddAsMostRecentAsync(path));
            }

            AppSettings.RecursiveSubmodules = RecursiveSubmodules.SelectedIndex;

            var    remote = "";
            string destination;

            if (PushToUrl.Checked)
            {
                destination = PushDestination.Text;
            }
            else
            {
                EnsurePageant(selectedRemoteName);

                destination = selectedRemoteName;
                remote      = selectedRemoteName.Trim();
            }

            string pushCmd;

            if (TabControlTagBranch.SelectedTab == BranchTab)
            {
                bool track = ReplaceTrackingReference.Checked;
                if (!track && !string.IsNullOrWhiteSpace(RemoteBranch.Text))
                {
                    GitRef selectedLocalBranch = _NO_TRANSLATE_Branch.SelectedItem as GitRef;
                    track = selectedLocalBranch != null && string.IsNullOrEmpty(selectedLocalBranch.TrackingRemote) &&
                            !UserGitRemotes.Any(x => _NO_TRANSLATE_Branch.Text.StartsWith(x.Name, StringComparison.OrdinalIgnoreCase));
                    var autoSetupMerge = Module.EffectiveConfigFile.GetValue("branch.autoSetupMerge");
                    if (autoSetupMerge.IsNotNullOrWhitespace() && autoSetupMerge.ToLowerInvariant() == "false")
                    {
                        track = false;
                    }

                    if (track && !AppSettings.DontConfirmAddTrackingRef)
                    {
                        var result = MessageBox.Show(owner,
                                                     string.Format(_updateTrackingReference.Text, selectedLocalBranch.Name, RemoteBranch.Text),
                                                     _pushCaption.Text,
                                                     MessageBoxButtons.YesNoCancel);
                        if (result == DialogResult.Cancel)
                        {
                            return(false);
                        }

                        track = result == DialogResult.Yes;
                    }
                }

                if (ForcePushBranches.Checked)
                {
                    if (GitVersion.Current.SupportPushForceWithLease)
                    {
                        var choice = MessageBox.Show(owner,
                                                     _useForceWithLeaseInstead.Text,
                                                     "", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
                                                     MessageBoxDefaultButton.Button1);
                        switch (choice)
                        {
                        case DialogResult.Yes:
                            ForcePushBranches.Checked = false;
                            ckForceWithLease.Checked  = true;
                            break;

                        case DialogResult.Cancel:
                            return(false);
                        }
                    }
                }

                if (_NO_TRANSLATE_Branch.Text == AllRefs)
                {
                    pushCmd = Module.PushAllCmd(destination, GetForcePushOption(), track, RecursiveSubmodules.SelectedIndex);
                }
                else
                {
                    pushCmd = Module.PushCmd(destination, _NO_TRANSLATE_Branch.Text, RemoteBranch.Text,
                                             GetForcePushOption(), track, RecursiveSubmodules.SelectedIndex);
                }
            }
            else if (TabControlTagBranch.SelectedTab == TagTab)
            {
                string tag         = TagComboBox.Text;
                bool   pushAllTags = false;
                if (tag == AllRefs)
                {
                    tag         = "";
                    pushAllTags = true;
                }

                pushCmd = GitCommandHelpers.PushTagCmd(destination, tag, pushAllTags, GetForcePushOption());
            }
            else
            {
                // Push Multiple Branches Tab selected
                var pushActions = new List <GitPushAction>();
                foreach (DataRow row in _branchTable.Rows)
                {
                    var push   = Convert.ToBoolean(row[PushColumnName]);
                    var force  = Convert.ToBoolean(row[ForceColumnName]);
                    var delete = Convert.ToBoolean(row[DeleteColumnName]);

                    if (push || force)
                    {
                        pushActions.Add(new GitPushAction(row[LocalColumnName].ToString(), row[RemoteColumnName].ToString(), force));
                    }
                    else if (delete)
                    {
                        pushActions.Add(GitPushAction.DeleteRemoteBranch(row[RemoteColumnName].ToString()));
                    }
                }

                pushCmd = GitCommandHelpers.PushMultipleCmd(destination, pushActions);
            }

            ScriptManager.RunEventScripts(this, ScriptEvent.BeforePush);

            // controls can be accessed only from UI thread
            _selectedBranch = _NO_TRANSLATE_Branch.Text;
            _candidateForRebasingMergeCommit = PushToRemote.Checked && (_selectedBranch != AllRefs) && TabControlTagBranch.SelectedTab == BranchTab;
            _selectedRemoteBranchName        = RemoteBranch.Text;

            using (var form = new FormRemoteProcess(Module, pushCmd)
            {
                Remote = remote,
                Text = string.Format(_pushToCaption.Text, destination),
                HandleOnExitCallback = HandlePushOnExit
            })
            {
                form.ShowDialog(owner);
                ErrorOccurred = form.ErrorOccurred();

                if (!Module.InTheMiddleOfAction() && !form.ErrorOccurred())
                {
                    ScriptManager.RunEventScripts(this, ScriptEvent.AfterPush);
                    if (_createPullRequestCB.Checked)
                    {
                        UICommands.StartCreatePullRequest(owner);
                    }

                    return(true);
                }
            }

            return(false);
        }
Beispiel #15
0
 public void IsWslPath(string path, bool expected)
 {
     PathUtil.IsWslPath(path).Should().Be(expected);
 }
Beispiel #16
0
        /// <summary>
        ///
        /// </summary>
        private void GenerateReportPortfolio(Application[] Applications, Snapshot[] ApplicationsSnapshots, string[] IgnoredApps, string[] IgnoredSnapshots)
        {
            string tmpReportFile      = String.Empty;
            string tmpReportFileFlexi = String.Empty;

            try
            {
                //Create temporary report
                string workDirectory = SettingsBLL.GetApplicationPath();
                tmpReportFile = PathUtil.CreateTempCopy(workDirectory, SelectedTemplateFile.FullName);
                if (tmpReportFile.Contains(".xlsx"))
                {
                    tmpReportFileFlexi = PathUtil.CreateTempCopyFlexi(workDirectory, SelectedTemplateFile.FullName);
                }
                //Build report
                ReportData reportData = new ReportData()
                {
                    FileName         = tmpReportFile,
                    Application      = null,
                    CurrentSnapshot  = null,
                    PreviousSnapshot = null,
                    Parameter        = Setting.ReportingParameter,
                    RuleExplorer     = new RuleBLL(ActiveConnection),
                    SnapshotExplorer = new SnapshotBLL(ActiveConnection, SelectedSnapshot),
                    CurrencySymbol   = "$",
                    Applications     = Applications,
                    Category         = SelectedCategory,
                    Tag                 = SelectedTag,
                    snapshots           = ApplicationsSnapshots,
                    IgnoresApplications = IgnoredApps,
                    IgnoresSnapshots    = IgnoredSnapshots
                };



                using (IDocumentBuilder docBuilder = BuilderFactory.CreateBuilder(reportData, tmpReportFileFlexi))
                {
                    docBuilder.BuildDocument();
                }


                if (tmpReportFile.Contains(".xlsx"))
                {
                    tmpReportFile = tmpReportFileFlexi;
                }

                //Copy report file to the selected destination
                File.Copy(tmpReportFile, ReportFileName, true);
            }
            catch (Exception ex)
            {
                ReportFileName = String.Empty;

                throw (ex);
            }
            finally
            {
                if (!String.IsNullOrEmpty(tmpReportFile))
                {
                    File.Delete(tmpReportFile);
                }
            }
        }
Beispiel #17
0
 public void FindAncestors(string path, string[] expected)
 {
     Assert.AreEqual(expected, PathUtil.FindAncestors(path).ToArray());
 }
Beispiel #18
0
        private BundleWrapper LoadBundle <T>(string bundleName) where T : Object
        {
            BundleWrapper bundleWrapper = new BundleWrapper();

            AssetBundle bundle = null;

            if (_cachedBundles.ContainsKey(bundleName))
            {
                bundle = _cachedBundles[bundleName];
                bundleWrapper.Init(bundleName, bundle);
            }
            else
            {
#if UNITY_EDITOR && !USE_BUNDLE
                string assetPath = GetAssetPathByBundleName(bundleName);
                if (!string.IsNullOrEmpty(assetPath))
                {
                    if (bundleName.StartsWith("/"))
                    {
                        bundleName = bundleName.Substring(1);
                    }
                    UnityEngine.Object resource = null;
                    resource = AssetDatabase.LoadAssetAtPath <T>(assetPath);
                    if (resource == null)  //找不到時用bundleName查找
                    {
                        resource = GetResourceByBundleNameEditor <T>(bundleName);
                    }
                    bundleWrapper.Init(bundleName, resource);
                }
                else
                {
                    if (bundleName.StartsWith("/"))
                    {
                        bundleName = bundleName.Substring(1);
                    }
                    UnityEngine.Object resource = GetResourceByBundleNameEditor <T>(bundleName);
                    if (resource != null)
                    {
                        bundleWrapper.Init(bundleName, resource);
                    }
                }

                ////                if (bundleName.StartsWith("/"))
                ////                    bundleName = bundleName.Substring(1);
                //string[] bundles = AssetDatabase.GetAssetPathsFromAssetBundle(bundleName);
                //if (bundles.Length == 0)
                //{
                //    Debug.LogError("bundleName no found:" + bundleName);
                //}
                //else
                //{
                //    UnityEngine.Object resource = AssetDatabase.LoadAssetAtPath<T>(bundles[0]);
                //    bundleWrapper.Init(bundleName, resource);
                //}
#else
                string path = PathUtil.GetPath(_platformBundlePath + bundleName, AssetLoader.ExternalHotfixPath);
                bundle = AssetBundle.LoadFromFile(path);
                if (bundle != null)
                {
                    _cachedBundles.Add(bundleName, bundle);
                }

                bundleWrapper.Init(bundleName, bundle);
#endif
            }


#if UNITY_EDITOR && USE_BUNDLE
            var materials = bundle.LoadAllAssets <Material>();
            foreach (var material in materials)
            {
                var shaderName = material.shader.name;

                var newShader = Shader.Find(shaderName);
                if (newShader != null)
                {
                    material.shader = newShader;
                }
                else
                {
                    Debug.LogWarning("unable to refresh shader: " + shaderName + " in material " + material.name);
                }
            }
#endif
            return(bundleWrapper);
        }
Beispiel #19
0
        /** App */
        void OnGUI_App()
        {
            Version version = appVersion;


            GUILayout.BeginHorizontal();
            HGUILayout.Version("App版本", version, VersionType.App);
            GUILayout.BeginVertical();
            if (GUILayout.Button("最后一次", GUILayout.Width(100), GUILayout.Height(30)))
            {
                VersionList.Read(true);

                version.Copy(VersionList.lastAppVersion);
                version.revised = 0;
                version.verType = VersionType.App;
            }

            if (GUILayout.Button("自动", GUILayout.Width(100), GUILayout.Height(30)))
            {
                VersionList.Read(true);

                version.Copy(VersionList.lastAppVersion);
                version.minor++;
                version.revised = 0;
                version.verType = VersionType.App;
            }
            GUILayout.EndVertical();
            GUILayout.EndHorizontal();

            GUILayout.Space(20);


            HGUILayout.BeginCenterHorizontal();
            if (GUILayout.Button("生成版本信息", GUILayout.MinHeight(50), GUILayout.MaxWidth(200)))
            {
                version.SetNowDatetime();


                bool isRefresh = false;
                if (currentDvancedSettingData.GetValue(DvancedSettingType.ClearAllPlatformDirctory))
                {
                    PathUtil.ClearAllPlatformDirctory();
                    isRefresh = true;
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.ClearOtherPlatformDirctory))
                {
                    PathUtil.ClearOtherPlatformDirctory(runtimePlatform);
                    isRefresh = true;
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.ClearTestData))
                {
                    PathUtil.ClearTestData();
                    isRefresh = true;
                }

                if (isRefresh)
                {
                    AssetDatabase.Refresh();
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.Clear_AssetBundleName))
                {
                    AssetBundleEditor.ClearAssetBundleNames();
                    AssetDatabase.RemoveUnusedAssetBundleNames();
                }


                if (currentDvancedSettingData.GetValue(DvancedSettingType.Set_AssetBundleName))
                {
                    AssetBundleEditor.SetNames();
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.AB_AssetBundle))
                {
                    AssetBundleEditor.BuildAssetBundles();
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.AB_luacode))
                {
                    AB.Lua();
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.AB_config))
                {
                    AB.Config();
                }



                if (currentDvancedSettingData.GetValue(DvancedSettingType.GameConstConfig))
                {
                    GameConstConfig config = GameConstConfig.Load();
                    config.DevelopMode = false;
                    config.Version     = version.ToConfig();
                    config.Save();
                }


                if (currentDvancedSettingData.GetValue(DvancedSettingType.GeneratorLoadAssetListCsv))
                {
                    LoadAssetListCsv.Generator();
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.GeneratorStreamingAssetsFilesCSV))
                {
                    FilesCsvForStreamingAssets.Generator();
                }


                if (currentDvancedSettingData.GetValue(DvancedSettingType.PlayerSettings))
                {
                    SetPlayerSettings(runtimePlatform);
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.PlayerSettingsVersion))
                {
                    SetPlayerSettingsVersion(appVersion);
                }

                if (currentDvancedSettingData.GetValue(DvancedSettingType.GenerateVersionInfo))
                {
                    FilesCsvForStreamingAssets.CopyStreamFilesCsvToVersion(version);
                }


                if (currentDvancedSettingData.GetValue(DvancedSettingType.GeneratorUpdateAssetList))
                {
                    FilesCsvForStreamingAssets.GeneratorUpdateList(null);
                }
            }
            HGUILayout.EndCenterHorizontal();
        }
Beispiel #20
0
 public void NormalizePath(string path)
 {
     PathUtil.NormalizePath(path).Should().BeEmpty();
 }
Beispiel #21
0
 public WebFileInfo GetFileInfo(string path)
 {
     return(new WebFileInfo(PathUtil.StripFileProtocolPrefix(path)));
 }
Beispiel #22
0
 public void NormalizePath(string path, string expected)
 {
     PathUtil.NormalizePath(path).Should().Be(expected);
 }
Beispiel #23
0
        public void TryFindFullPath_not_throw_if_file_not_exist(string fileName)
        {
            string fullPath;

            PathUtil.TryFindFullPath(fileName, out fullPath).Should().BeFalse();
        }
Beispiel #24
0
 public void Resolve(string path, string relativePath, string expected)
 {
     PathUtil.Resolve(path, relativePath).Should().Be(expected);
 }
Beispiel #25
0
        /// <summary>
        /// Creates an instance of <see cref="SymbolFile"/> from the symbol file task item and add the source file list to it.
        /// </summary>
        /// <param name="item">The symbol file task item.</param>
        /// <returns>An instance of <see cref="SymbolFile"/> or <c>null</c> if there was an error.</returns>
        protected virtual SymbolFile CreateSymbolFile(ITaskItem item)
        {
            SymbolFile symbolFile = new SymbolFile(item.ItemSpec);

            var srcTool = new SrcTool();

            CopyBuildEngine(srcTool);

            if (!string.IsNullOrEmpty(SourceServerSdkPath))
            {
                srcTool.ToolPath = SourceServerSdkPath;
            }

            srcTool.PdbFile = item;

            // step 1: check if source already indexed
            this.NoSourceInformationInPdb = false;
            srcTool.CountOnly             = true;
            srcTool.Execute();
            if (srcTool.SourceCount > 0)
            {
                Log.LogWarning("'{0}' already has source indexing information.", symbolFile.File.Name);
                Skipped++;
                return(null);
            }
            srcTool.CountOnly = false; // turn off

            // step 2: get source file list from pdb
            srcTool.SourceOnly = true;
            if (!srcTool.Execute())
            {
                if (srcTool.SourceFiles != null && srcTool.SourceFiles.Length > 0 &&
                    srcTool.SourceFiles[0].StartsWith("No source information in pdb for"))
                {
                    this.NoSourceInformationInPdb = true;
                }

                if (this.FailOnNoSourceInformationFound)
                {
                    Log.LogError("Error getting source files from '{0}'.{1}", symbolFile.File.Name, srcTool.SourceFiles != null && srcTool.SourceFiles.Length > 0 ? srcTool.SourceFiles[0] : string.Empty);
                    Failed++;
                }
                else
                {
                    Log.LogWarning("'{0}' has no source information inside the pdb. Check your pdb settings or perhaps your assembly doesn't have any real lines of code in it?", symbolFile.File.Name, srcTool.SourceFiles != null && srcTool.SourceFiles.Length > 0 ? srcTool.SourceFiles[0] : string.Empty);
                    Skipped++;
                }
                return(null);
            }

            foreach (string file in srcTool.SourceFiles)
            {
                // check that we didn't get garbage back from SrcTool.
                if (!PathUtil.IsPathValid(file))
                {
                    Log.LogMessage(MessageImportance.Low, "  Invalid path for source file '{0}'.", file);
                    continue;
                }

                SourceFile sourceFile = new SourceFile(file);
                symbolFile.SourceFiles.Add(sourceFile);
            }

            return(symbolFile);
        }
Beispiel #26
0
 public void ResolveWsl(string path, string expected)
 {
     PathUtil.ResolveWsl(path).Should().Be(expected);
 }
Beispiel #27
0
        // parameters:
        //      bLocal  是否从本地启动。 false 表示连安装带启动
        public static void StartDp2libraryXe(
            IWin32Window owner,
            string strDialogTitle,
            Font font,
            bool bLocal)
        {
            MessageBar messageBar = null;

            messageBar         = new MessageBar();
            messageBar.TopMost = false;
            if (font != null)
            {
                messageBar.Font = font;
            }
            messageBar.BackColor     = SystemColors.Info;
            messageBar.ForeColor     = SystemColors.InfoText;
            messageBar.Text          = "dp2 内务";
            messageBar.MessageText   = "正在启动 dp2Library XE V3,请等待 ...";
            messageBar.StartPosition = FormStartPosition.CenterScreen;
            messageBar.Show(owner);
            messageBar.Update();

            Application.DoEvents();
            try
            {
                TimeSpan waitTime = new TimeSpan(0, 1, 0);

                string strShortcutFilePath = "";
                if (bLocal == true)
                {
                    strShortcutFilePath = PathUtil.GetShortcutFilePath("DigitalPlatform/dp2 V3/dp2Library XE V3");
                }
                else
                {
                    strShortcutFilePath = "http://dp2003.com/dp2libraryxe/v3/dp2libraryxe.application";
                    waitTime            = new TimeSpan(0, 5, 0); // 安装需要的等待时间更长
                }

                // TODO: detect if already started
                using (EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset,
                                                                             "dp2libraryXE V3 library host started"))
                {
                    Application.DoEvents();

                    Process.Start(strShortcutFilePath);

                    DateTime start = DateTime.Now;
                    while (true)
                    {
                        Application.DoEvents();
                        // wait till started
                        // http://stackoverflow.com/questions/6816782/windows-net-cross-process-synchronization
                        if (eventWaitHandle.WaitOne(100, false) == true)
                        {
                            break;
                        }

                        // if timeout, prompt continue wait
                        if (DateTime.Now - start > waitTime)
                        {
                            DialogResult result = MessageBox.Show(owner,
                                                                  "dp2libraryXE V3 暂时没有响应。\r\n\r\n是否继续等待其响应?",
                                                                  strDialogTitle,
                                                                  MessageBoxButtons.YesNo,
                                                                  MessageBoxIcon.Question,
                                                                  MessageBoxDefaultButton.Button1);
                            if (result == System.Windows.Forms.DialogResult.No)
                            {
                                break;
                            }

                            start = DateTime.Now;   //
                        }
                    }
                }
            }
            finally
            {
                messageBar.Close();
            }
        }
Beispiel #28
0
 public void ResolveWsl(string input, Type expectedException)
 {
     Assert.Throws(expectedException, () => PathUtil.ResolveWsl(input));
 }
        private void HandleFinish_ExecuteCode(object sender, EventArgs e)
        {
            UploadedFile uploadedFile     = this.GetBinding <UploadedFile>("UploadedFile");
            bool         overwrite        = this.GetBinding <bool>("OverwriteExisting");
            string       parentFolderPath = this.GetBinding <string>("ParentFolderPath");

            if (uploadedFile.HasFile)
            {
                using (System.IO.Stream readStream = uploadedFile.FileStream)
                {
                    ZipArchive zipArchive;

                    try
                    {
                        zipArchive = new ZipArchive(readStream);
                    }
                    catch (Exception)
                    {
                        ShowUploadError(Texts.UploadAndExtractZipFile_NotZip);
                        return;
                    }

                    try
                    {
                        foreach (var entry in zipArchive.Entries)
                        {
                            string fullPath = Path.Combine(parentFolderPath, entry.FullName);
                            if (File.Exists(fullPath))
                            {
                                string websiteFilePath = PathUtil.GetWebsitePath(fullPath);

                                if (!overwrite)
                                {
                                    ShowUploadError(Texts.UploadAndExtractZipFile_FileExistsError(websiteFilePath));
                                    return;
                                }

                                var fileInfo = new FileInfo(fullPath);

                                if (fileInfo.IsReadOnly)
                                {
                                    ShowUploadError(Texts.UploadAndExtractZipFile_ExistingFileReadOnly(websiteFilePath));
                                    return;
                                }
                            }
                        }

                        foreach (var entry in zipArchive.Entries.Where(f => !string.IsNullOrWhiteSpace(f.Name)))
                        {
                            using (var zipStream = entry.Open())
                            {
                                string fullPath = Path.Combine(parentFolderPath, entry.FullName);

                                DirectoryUtils.EnsurePath(fullPath);

                                using (var newFile = File.Create(fullPath, 4096))
                                {
                                    zipStream.CopyTo(newFile);
                                }
                            }
                        }

                        _zipHasBeenUploaded = true;
                    }
                    catch (Exception ex)
                    {
                        Log.LogError(nameof(UploadAndExtractZipFileWorkflow), ex);
                        ShowUploadError(Texts.UploadAndExtractZipFile_UnexpectedError);
                    }
                }
            }
        }
Beispiel #30
0
            public void DeleteTemplate()
            {
                string filePath = PathUtil.Resolve(_templateDescriptor.VirtualPath);

                C1File.Delete(filePath);
            }