public static void ClassInitialize(TestContext context)
        {
            // static field initialization
            var projectPath  = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, PathUtils.NormalizePath(@"..\..\..")));
            var testsPath    = Path.GetFullPath(Path.Combine(projectPath, ".."));
            var solutionPath = Path.GetFullPath(Path.Combine(projectPath, PathUtils.NormalizePath(@"..\..")));
            var schemaPath   = Path.Combine(testsPath, "tests.schema");

            var ignoreFolders = new string[]
            {
                PathUtils.NormalizePath(@"Microsoft.Bot.Builder.TestBot.Json\Samples\EmailBot"),
                PathUtils.NormalizePath(@"Microsoft.Bot.Builder.TestBot.Json\Samples\CalendarBot"),
                "bin"
            };

            ResourceExplorer = new ResourceExplorer()
                               .AddFolders(Path.Combine(solutionPath, "libraries"), monitorChanges: false)
                               .AddFolders(Path.Combine(solutionPath, "tests"), monitorChanges: false);

            Dialogs = ResourceExplorer.GetResources(".dialog")
                      .Cast <FileResource>()
                      .Where(r => !r.Id.EndsWith(".schema.dialog") && !ignoreFolders.Any(f => r.FullName.Contains(f)))
                      .Select(resource => new object[] { resource });

            try
            {
                ProcessStartInfo startInfo;
                if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                {
                    File.Delete(schemaPath);
                    startInfo = new ProcessStartInfo("cmd.exe", $"/C bf dialog:merge ../../libraries/**/*.schema ../../libraries/**/*.uischema ../**/*.schema !../**/testbot.schema -o {schemaPath}");
                    startInfo.WorkingDirectory      = projectPath;
                    startInfo.UseShellExecute       = false;
                    startInfo.CreateNoWindow        = true;
                    startInfo.RedirectStandardError = true;

                    var process = Process.Start(startInfo);
                    var error   = process.StandardError.ReadToEnd();
                    process.WaitForExit();

                    Assert.AreEqual(error, string.Empty);
                }
            }
            catch (Exception err)
            {
                Assert.Fail(err.Message);
            }

            Assert.IsTrue(File.Exists(schemaPath));
            var json = File.ReadAllText(schemaPath);

            Schema = JSchema.Parse(json);
        }
示例#2
0
        private bool QueryIPythonEnabled(EnvironmentView view)
        {
            var path = GetScriptPath(view);

            return(path != null && File.Exists(PathUtils.GetAbsoluteFilePath(path, "mode.txt")));
        }
示例#3
0
        public void Page_Load(object sender, EventArgs e)
        {
            if (IsForbidden)
            {
                return;
            }

            PageUtils.CheckRequestParameter("siteId");

            _directoryPath = PathUtility.MapPath(SiteInfo, "@/include");

            if (Body.IsQueryExists("Delete"))
            {
                var fileName = Body.GetQueryString("FileName");

                try
                {
                    FileUtils.DeleteFileIfExists(PathUtils.Combine(_directoryPath, fileName));
                    Body.AddSiteLog(SiteId, "删除包含文件", $"包含文件:{fileName}");
                    SuccessDeleteMessage();
                }
                catch (Exception ex)
                {
                    FailDeleteMessage(ex);
                }
            }

            if (IsPostBack)
            {
                return;
            }

            VerifySitePermissions(ConfigManager.Permissions.WebSite.Template);

            DirectoryUtils.CreateDirectoryIfNotExists(_directoryPath);
            var fileNames    = DirectoryUtils.GetFileNames(_directoryPath);
            var fileNameList = new List <string>();

            foreach (var fileName in fileNames)
            {
                if (EFileSystemTypeUtils.IsTextEditable(EFileSystemTypeUtils.GetEnumType(PathUtils.GetExtension(fileName))))
                {
                    if (!fileName.Contains("_parsed"))
                    {
                        fileNameList.Add(fileName);
                    }
                }
            }

            RptContents.DataSource     = fileNameList;
            RptContents.ItemDataBound += RptContents_ItemDataBound;
            RptContents.DataBind();

            BtnAdd.Attributes.Add("onclick", $"location.href='{PageTemplateIncludeAdd.GetRedirectUrl(SiteId)}';return false");
        }
示例#4
0
        private async Task CacheInstalledPackagesAsync(
            bool alreadyHasLock,
            bool alreadyHasConcurrencyLock,
            CancellationToken cancellationToken
            )
        {
            if (!IsReady)
            {
                await UpdateIsReadyAsync(alreadyHasLock, cancellationToken);

                if (!IsReady)
                {
                    return;
                }
            }

            List <PackageSpec> packages = null;

            var workingLock = alreadyHasLock ? null : await _working.LockAsync(cancellationToken);

            try {
                var args = _extraInterpreterArgs.ToList();

                if (!SupportsDashMPip)
                {
                    args.Add("-c");
                    args.Add("\"import pip; pip.main()\"");
                }
                else
                {
                    args.Add("-m");
                    args.Add("pip");
                }
                args.Add("list");
                if (_pipListHasFormatOption)
                {
                    args.Add("--format=json");
                }

                var concurrencyLock = alreadyHasConcurrencyLock ? null : await _concurrencyLock.LockAsync(cancellationToken);

                try {
                    using (var proc = ProcessOutput.Run(
                               _factory.Configuration.InterpreterPath,
                               args,
                               _factory.Configuration.PrefixPath,
                               UnbufferedEnv,
                               false,
                               null
                               )) {
                        try {
                            if ((await proc) == 0)
                            {
                                if (_pipListHasFormatOption)
                                {
                                    try {
                                        var data = JToken.ReadFrom(new JsonTextReader(new StringListReader(proc.StandardOutputLines)));
                                        packages = data
                                                   .Select(j => new PackageSpec(j.Value <string>("name"), j.Value <string>("version")))
                                                   .Where(p => p.IsValid)
                                                   .OrderBy(p => p.Name)
                                                   .ToList();
                                    } catch (JsonException ex) {
                                        Debug.WriteLine("Failed to parse: {0}".FormatInvariant(ex.Message));
                                        foreach (var l in proc.StandardOutputLines)
                                        {
                                            Debug.WriteLine(l);
                                        }
                                    }
                                }
                                else
                                {
                                    packages = proc.StandardOutputLines
                                               .Select(i => PackageSpec.FromPipList(i))
                                               .Where(p => p.IsValid)
                                               .OrderBy(p => p.Name)
                                               .ToList();
                                }
                            }
                            else if (_pipListHasFormatOption)
                            {
                                // Actually, pip probably doesn't have the --format option
                                Debug.WriteLine("{0} does not support --format".FormatInvariant(_factory.Configuration.InterpreterPath));
                                _pipListHasFormatOption = false;
                                await CacheInstalledPackagesAsync(true, true, cancellationToken);

                                return;
                            }
                            else
                            {
                            }
                        } catch (OperationCanceledException) {
                            // Process failed to run
                            Debug.WriteLine("Failed to run pip to collect packages");
                            foreach (var line in proc.StandardOutputLines)
                            {
                                Debug.WriteLine(line);
                            }
                        }
                    }

                    if (packages == null)
                    {
                        // Pip failed, so return a directory listing
                        var paths = await PythonTypeDatabase.GetDatabaseSearchPathsAsync(_factory);

                        packages = await Task.Run(() => paths.Where(p => !p.IsStandardLibrary && Directory.Exists(p.Path))
                                                  .SelectMany(p => PathUtils.EnumerateDirectories(p.Path, recurse: false))
                                                  .Select(path => Path.GetFileName(path))
                                                  .Select(name => PackageNameRegex.Match(name))
                                                  .Where(match => match.Success)
                                                  .Select(match => new PackageSpec(match.Groups["name"].Value))
                                                  .Where(p => p.IsValid)
                                                  .OrderBy(p => p.Name)
                                                  .ToList());
                    }
                } finally {
                    concurrencyLock?.Dispose();
                }

                // Outside of concurrency lock, still in working lock

                _packages.Clear();
                _packages.AddRange(packages);
                _everCached = true;
            } finally {
                workingLock?.Dispose();
            }

            InstalledPackagesChanged?.Invoke(this, EventArgs.Empty);
        }
示例#5
0
        private async System.Threading.Tasks.Task DoCommand()
        {
            var pyProj   = CommonPackage.GetStartupProject(_serviceProvider) as PythonProjectNode;
            var textView = CommonPackage.GetActiveTextView(_serviceProvider);

            var scriptName = textView?.GetFilePath();

            if (!string.IsNullOrEmpty(scriptName) && pyProj != null)
            {
                if (pyProj.FindNodeByFullPath(scriptName) == null)
                {
                    // Starting a script that isn't in the project.
                    // Try and find the project. If we fail, we will
                    // use the default environment.
                    pyProj = _serviceProvider.GetProjectFromFile(scriptName);
                }
            }

            LaunchConfiguration config = null;

            try {
                config = pyProj?.GetLaunchConfigurationOrThrow();
            } catch (MissingInterpreterException ex) {
                MessageBox.Show(ex.Message, Strings.ProductTitle);
                return;
            }
            if (config == null)
            {
                var interpreters = _serviceProvider.GetComponentModel().GetService <IInterpreterOptionsService>();
                config = new LaunchConfiguration(interpreters.DefaultInterpreter.Configuration);
            }
            else
            {
                config = config.Clone();
            }

            if (!string.IsNullOrEmpty(scriptName))
            {
                config.ScriptName       = scriptName;
                config.WorkingDirectory = PathUtils.GetParent(scriptName);
            }

            if (config == null)
            {
                Debug.Fail("Should not be executing command when it is invisible");
                return;
            }

            var window = EnsureReplWindow(_serviceProvider, config.Interpreter, pyProj);

            window.Show(true);

            var eval = (IPythonInteractiveEvaluator)window.InteractiveWindow.Evaluator;

            // The interpreter may take some time to startup, do this off the UI thread.
            await ThreadHelper.JoinableTaskFactory.RunAsync(async() => {
                await((IInteractiveEvaluator)eval).ResetAsync();

                window.InteractiveWindow.WriteLine(Strings.ExecuteInReplCommand_RunningMessage.FormatUI(config.ScriptName));

                await eval.ExecuteFileAsync(config.ScriptName, config.ScriptArguments);
            });
        }
示例#6
0
        public void DrawFolderGUI()
        {
            // Title
            m_Config.m_ShowDestination = EditorGUILayout.Foldout(m_Config.m_ShowDestination, "Destination".ToUpper());
            if (m_Config.m_ShowDestination == false)
            {
                return;
            }
            EditorGUILayout.Separator();

            // Select destination type
            EditorGUILayout.PropertyField(m_DestinationFolder);

            // Path
            if (m_Config.m_DestinationFolder == ScreenshotNameParser.DestinationFolder.CUSTOM_FOLDER)
            {
                EditorGUILayout.BeginHorizontal();

                // Path
                newPath = EditorGUILayout.TextField(m_Config.m_RootedPath);
                if (newPath != m_Config.m_RootedPath)
                {
                    m_Config.m_RootedPath = newPath;
                    EditorUtility.SetDirty(m_Obj);
                }

                // Browse button
                if (GUILayout.Button("Browse", GUILayout.MaxWidth(70)))
                {
                    newPath = EditorUtility.OpenFolderPanel("Select destionation folder", m_Config.m_RootedPath, m_Config.m_RootedPath);
                    if (newPath != m_Config.m_RootedPath)
                    {
                        m_Config.m_RootedPath = newPath;
                        EditorUtility.SetDirty(m_Obj);

                        // Dirty hack
                        // The TextField is conflicting with the browse field:
                        // if the textfield is selected then it will not be updated after the folder selection.
                        GUI.FocusControl("");
                    }
                }
                EditorGUILayout.EndHorizontal();
            }
            else
            {
                EditorGUILayout.BeginHorizontal();

                // Path
                newPath = EditorGUILayout.TextField(m_Config.m_RelativePath);
                if (newPath != m_Config.m_RelativePath)
                {
                    m_Config.m_RelativePath = newPath;
                    EditorUtility.SetDirty(m_Obj);
                }

                EditorGUILayout.EndHorizontal();
            }


            if (GUILayout.Button("Open Folder"))
            {
                EditorUtility.RevealInFinder(m_Config.GetPath());
            }

            // Warning message
            if (!PathUtils.IsValidPath(m_Config.GetPath()))
            {
                EditorGUILayout.HelpBox("Path \"" + m_Config.GetPath() + "\" is invalid.", MessageType.Warning);
            }
        }
示例#7
0
        public virtual async Task <int> Execute(InstrumentationResult result,
                                                string output,
                                                string repoToken,
                                                string serviceJobId,
                                                string serviceName,
                                                string commitMessage,
                                                string rootFolder,
                                                string commit,
                                                string commitAuthorName,
                                                string commitAuthorEmail,
                                                string commitCommitterName,
                                                string commitCommitterEmail,
                                                string branch,
                                                string remoteName,
                                                string remoteUrl)
        {
            var hits = _hitsReader.TryReadFromDirectory(result.HitsPath);

            var files = result.GetSourceFiles();

            var coverallsJob = new CoverallsJobModel
            {
                ServiceJobId      = serviceJobId,
                ServiceName       = serviceName,
                RepoToken         = repoToken,
                CoverallsGitModel = !string.IsNullOrWhiteSpace(branch)
                    ? new CoverallsGitModel
                {
                    Head = !string.IsNullOrWhiteSpace(commit)
                            ? new CoverallsCommitModel
                    {
                        Id             = commit,
                        AuthorName     = commitAuthorName,
                        AuthorEmail    = commitAuthorEmail,
                        CommitterName  = commitCommitterName,
                        CommitterEmail = commitCommitterEmail,
                        Message        = commitMessage
                    }
                            : null,
                    Branch  = branch,
                    Remotes = !string.IsNullOrWhiteSpace(remoteUrl)
                            ? new List <CoverallsRemote>
                    {
                        new CoverallsRemote
                        {
                            Name = remoteName,
                            Url  = remoteUrl
                        }
                    }
                            : null
                }
                    : null,
                SourceFiles = new List <CoverallsSourceFileModel>()
            };

            foreach (var file in files)
            {
                var sourceFile = Path.Combine(result.SourcePath, file.Path);

                if (!_fileSystem.File.Exists(sourceFile))
                {
                    System.Console.WriteLine($"File not found: {sourceFile}");
                    continue;
                }

                var sourceLines = _fileSystem.File.ReadAllLines(sourceFile);

                var hitsPerLine = file.Sequences
                                  .GroupByMany(f => f.GetLines())
                                  .ToDictionary(g => g.Key, g => g.Sum(i => hits.GetHitCount(i.HitId)));

                var fileName = PathUtils.GetRelativePath(rootFolder, sourceFile).Replace("\\", "/");

                var coverallsSourceFileModel = new CoverallsSourceFileModel
                {
                    Name         = fileName,
                    SourceDigest = ComputeSourceDigest(sourceFile),
                    Coverage     = Enumerable.Range(1, sourceLines.Length).Select(line =>
                    {
                        return(hitsPerLine.ContainsKey(line)
                            ? hitsPerLine[line]
                            : default(int?));
                    }).ToArray()
                };

                coverallsJob.SourceFiles.Add(coverallsSourceFileModel);
            }

            var coverallsJson = JsonConvert.SerializeObject(coverallsJob, Formatting.None, new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore
            });

            if (!string.IsNullOrWhiteSpace(output))
            {
                _fileSystem.File.WriteAllText(output, coverallsJson);
            }

            return(await Post(coverallsJson));
        }
示例#8
0
 /// <summary>
 /// Returns a querystring with all the settings in this class. Querystring keys and values are URL encoded properly.
 /// </summary>
 /// <returns></returns>
 public string ToStringEncoded()
 {
     return(PathUtils.BuildQueryString(this));
 }
示例#9
0
 /// <summary>
 /// Parses the specified querystring into name/value pairs and merges
 /// it with defaultSettings in a new ResizeSettings instance.
 /// </summary>
 /// <param name="queryString"></param>
 /// <param name="defaultSettings"></param>
 public ResizeSettings(string queryString, NameValueCollection defaultSettings)
     : this(PathUtils.ParseQueryStringFriendlyAllowSemicolons(queryString), defaultSettings)
 {
 }
示例#10
0
 /// <summary>
 /// Parses the specified querystring into name/value pairs. leading ? not required.
 /// Discards everything after the first '#' character as a URL fragment.
 /// </summary>
 /// <param name="queryString"></param>
 public ResizeSettings(string queryString) : base(PathUtils.ParseQueryStringFriendlyAllowSemicolons(queryString))
 {
 }
示例#11
0
 /// <summary>
 /// Returns a string containing all the settings in the class, in querystring form. Use ToStringEncoded() to get a URL-safe querystring.
 /// This method does not encode commas, spaces, etc.
 /// </summary>
 /// <returns></returns>
 public override string ToString()
 {
     return(PathUtils.BuildQueryString(this, false));
 }
示例#12
0
 public BundlerTests()
 {
     _bbdir = PathUtils.Join(PathUtils.Normalize(Environment.CurrentDirectory), ".bbcore");
     _tools = new ToolsDir.ToolsDir(PathUtils.Join(_bbdir, "tools"));
 }
示例#13
0
        public async Task <ActionResult <List <int> > > Edit([FromBody] PutRequest request)
        {
            if (!await _authManager.HasChannelPermissionsAsync(request.SiteId, request.Id, Types.ChannelPermissions.Edit))
            {
                return(Unauthorized());
            }

            var site = await _siteRepository.GetAsync(request.SiteId);

            if (site == null)
            {
                return(NotFound());
            }

            if (string.IsNullOrEmpty(request.ChannelName))
            {
                return(this.Error("栏目修改失败,必须填写栏目名称!"));
            }

            var channel = await _channelRepository.GetAsync(request.Id);

            if (!StringUtils.Equals(channel.IndexName, request.IndexName) && !string.IsNullOrEmpty(request.IndexName))
            {
                if (await _channelRepository.IsIndexNameExistsAsync(request.SiteId, request.IndexName))
                {
                    return(this.Error("栏目修改失败,栏目索引已存在!"));
                }
            }

            if (!StringUtils.Equals(channel.FilePath, request.FilePath) && !string.IsNullOrEmpty(request.FilePath))
            {
                if (!DirectoryUtils.IsDirectoryNameCompliant(request.FilePath))
                {
                    return(this.Error("栏目页面路径不符合系统要求!"));
                }

                if (PathUtils.IsDirectoryPath(request.FilePath))
                {
                    request.FilePath = PageUtils.Combine(request.FilePath, "index.html");
                }

                if (await _channelRepository.IsFilePathExistsAsync(request.SiteId, request.FilePath))
                {
                    return(this.Error("栏目修改失败,栏目页面路径已存在!"));
                }
            }

            if (!string.IsNullOrEmpty(request.ChannelFilePathRule))
            {
                var filePathRule = request.ChannelFilePathRule.Replace("|", string.Empty);
                if (!DirectoryUtils.IsDirectoryNameCompliant(filePathRule))
                {
                    return(this.Error("栏目页面命名规则不符合系统要求!"));
                }
                if (PathUtils.IsDirectoryPath(filePathRule))
                {
                    return(this.Error("栏目页面命名规则必须包含生成文件的后缀!"));
                }
            }

            if (!string.IsNullOrEmpty(request.ContentFilePathRule))
            {
                var filePathRule = request.ContentFilePathRule.Replace("|", string.Empty);
                if (!DirectoryUtils.IsDirectoryNameCompliant(filePathRule))
                {
                    return(this.Error("内容页面命名规则不符合系统要求!"));
                }
                if (PathUtils.IsDirectoryPath(filePathRule))
                {
                    return(this.Error("内容页面命名规则必须包含生成文件的后缀!"));
                }
            }

            var styles = await GetInputStylesAsync(channel);

            foreach (var style in styles)
            {
                var inputType = style.InputType;
                if (inputType == InputType.TextEditor)
                {
                    var value = request.Get(style.AttributeName, string.Empty);
                    value = await _pathManager.EncodeTextEditorAsync(site, value);

                    value = UEditorUtils.TranslateToStlElement(value);
                    channel.Set(style.AttributeName, value);
                }
                else if (inputType == InputType.Image ||
                         inputType == InputType.Video ||
                         inputType == InputType.File)
                {
                    var count = request.Get(ColumnsManager.GetCountName(style.AttributeName), 0);
                    channel.Set(ColumnsManager.GetCountName(style.AttributeName), count);
                    for (var n = 0; n <= count; n++)
                    {
                        channel.Set(ColumnsManager.GetExtendName(style.AttributeName, n), request.Get(ColumnsManager.GetExtendName(style.AttributeName, n), string.Empty));
                    }
                }
                else if (inputType == InputType.CheckBox ||
                         style.InputType == InputType.SelectMultiple)
                {
                    var list = request.Get <List <object> >(style.AttributeName);
                    channel.Set(style.AttributeName, ListUtils.ToString(list));
                }
                else
                {
                    var value = request.Get(style.AttributeName, string.Empty);
                    channel.Set(style.AttributeName, value);
                }
            }

            channel.ChannelName         = request.ChannelName;
            channel.IndexName           = request.IndexName;
            channel.GroupNames          = request.GroupNames;
            channel.Content             = request.Content;
            channel.ChannelTemplateId   = request.ChannelTemplateId;
            channel.ContentTemplateId   = request.ContentTemplateId;
            channel.LinkUrl             = request.LinkUrl;
            channel.LinkType            = request.LinkType;
            channel.DefaultTaxisType    = request.DefaultTaxisType;
            channel.FilePath            = request.FilePath;
            channel.ChannelFilePathRule = request.ChannelFilePathRule;
            channel.ContentFilePathRule = request.ContentFilePathRule;
            channel.Keywords            = request.Keywords;
            channel.Description         = request.Description;

            await _channelRepository.UpdateAsync(channel);

            var expendedChannelIds = new List <int>
            {
                request.SiteId
            };

            if (!expendedChannelIds.Contains(channel.ParentId))
            {
                expendedChannelIds.Add(channel.ParentId);
            }

            return(expendedChannelIds);
        }
示例#14
0
        public override void SaveTo(Uri location)
        {
            var projectPath = location.LocalPath;
            var projectDir  = Path.GetDirectoryName(projectPath);

            var msBuildProject = MsBuild.Construction.ProjectRootElement.Create();

            msBuildProject.ToolsVersion   = "4.0";
            msBuildProject.DefaultTargets = "Build";

            {
                try
                {
                    var propertyGroup = msBuildProject.AddPropertyGroup();
                    propertyGroup.AddProperty("ProjectGuid", ProjectGuid.ToString("B").ToUpper());
                    propertyGroup.AppendChild(CreateProperty(msBuildProject, "Configuration", "Debug", " '$(Configuration)' == '' "));
                    propertyGroup.AppendChild(CreateProperty(msBuildProject, "Platform", "x86", " '$(Platform)' == '' "));
                    propertyGroup.AddProperty("OutputType", "Library");
                    propertyGroup.AddProperty("RootNamespace", "VVVV.Nodes");
                    propertyGroup.AddProperty("AssemblyName", AssemblyName);
                    propertyGroup.AddProperty("TargetFrameworkVersion", "v4.0");
                    propertyGroup.AddProperty("OutputPath", @"bin\$(Platform)\$(Configuration)\");
                    propertyGroup.AddProperty("AllowUnsafeBlocks", "True");

                    //add loaded reference paths
                    var referencePaths = ReferencePaths.Select(refPath =>
                                                               Path.IsPathRooted(refPath)
                            ? PathUtils.MakeRelativePath(projectDir + @"\", refPath + @"\")
                            : refPath);
                    var referencePathValue = string.Join(";", referencePaths);
                    if (!string.IsNullOrEmpty(referencePathValue))
                    {
                        propertyGroup.AddProperty("ReferencePath", referencePathValue);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
            }

            // From src/Default.Project.settings
            {
                var propertyGroup = msBuildProject.AddPropertyGroup();
                propertyGroup.Condition = " '$(Configuration)' == 'Debug' ";
                propertyGroup.AddProperty("DefineConstants", "DEBUG;TRACE");
                propertyGroup.AddProperty("Optimize", "False");
                propertyGroup.AddProperty("CheckForOverflowUnderflow", "True");
                propertyGroup.AddProperty("DebugType", "Full");
                propertyGroup.AddProperty("DebugSymbols", "True");
            }

            {
                var propertyGroup = msBuildProject.AddPropertyGroup();
                propertyGroup.Condition = " '$(Configuration)' == 'Release' ";
                propertyGroup.AddProperty("DefineConstants", "TRACE");
                propertyGroup.AddProperty("Optimize", "True");
                propertyGroup.AddProperty("CheckForOverflowUnderflow", "False");
                propertyGroup.AddProperty("DebugType", "None");
                propertyGroup.AddProperty("DebugSymbols", "False");
            }

            {
                var propertyGroup = msBuildProject.AddPropertyGroup();
                propertyGroup.Condition = " '$(Platform)' == 'AnyCPU' ";
                propertyGroup.AddProperty("PlatformTarget", "AnyCPU");
            }

            {
                var propertyGroup = msBuildProject.AddPropertyGroup();
                propertyGroup.Condition = " '$(Platform)' == 'x86' ";
                propertyGroup.AddProperty("PlatformTarget", "x86");
            }

            {
                var propertyGroup = msBuildProject.AddPropertyGroup();
                propertyGroup.Condition = " '$(Platform)' == 'x64' ";
                propertyGroup.AddProperty("PlatformTarget", "x64");
            }

            //add referenced items
            foreach (var reference in References)
            {
                var item = msBuildProject.AddItem("Reference", reference.Name);
                if (!reference.IsGlobal && !InReferencePaths(reference.Name))
                {
                    var hintPath = reference.GetRelativePath();
                    var dsc      = Path.DirectorySeparatorChar;
                    hintPath = hintPath.Replace(dsc + "x86" + dsc, dsc + "$(Platform)");
                    hintPath = hintPath.Replace(dsc + "x64" + dsc, dsc + "$(Platform)");
                    item.AddMetadata("HintPath", hintPath);
                }
            }

            foreach (var document in Documents)
            {
                msBuildProject.AddItem(document.CanBeCompiled ? "Compile" : "None", document.GetRelativePath());
            }

            msBuildProject.AddImport("$(MSBuildBinPath)\\Microsoft.CSharp.Targets");

            // Create the project directory if it doesn't exist yet.
            if (!Directory.Exists(projectDir))
            {
                Directory.CreateDirectory(projectDir);
            }

            msBuildProject.Save(projectPath);

            base.SaveTo(location);
        }
示例#15
0
        public void BtnStep1_Click(object sender, EventArgs e)
        {
            if (ChkIAgree.Checked)
            {
                BtnStep2.Visible = true;

                LtlDomain.Text     = PageUtils.GetHost();
                LtlVersion.Text    = SystemManager.Version;
                LtlNetVersion.Text = $"{Environment.Version.Major}.{Environment.Version.Minor}";
                LtlPhysicalApplicationPath.Text = WebConfigUtils.PhysicalApplicationPath;

                var isRootWritable = false;
                try
                {
                    var filePath = PathUtils.Combine(WebConfigUtils.PhysicalApplicationPath, "version.txt");
                    FileUtils.WriteText(filePath, ECharset.utf_8, SystemManager.Version);

                    var ioPermission = new FileIOPermission(FileIOPermissionAccess.Write, WebConfigUtils.PhysicalApplicationPath);
                    ioPermission.Demand();

                    isRootWritable = true;
                }
                catch
                {
                    // ignored
                }

                var isSiteFilesWritable = false;
                try
                {
                    var filePath = PathUtils.Combine(WebConfigUtils.PhysicalApplicationPath, DirectoryUtils.SiteFiles.DirectoryName, "index.htm");
                    FileUtils.WriteText(filePath, ECharset.utf_8, StringUtils.Constants.Html5Empty);

                    var ioPermission = new FileIOPermission(FileIOPermissionAccess.Write, PathUtils.Combine(WebConfigUtils.PhysicalApplicationPath, DirectoryUtils.SiteFiles.DirectoryName));
                    ioPermission.Demand();

                    isSiteFilesWritable = true;
                }
                catch
                {
                    // ignored
                }

                LtlRootWrite.Text = isRootWritable ? "<FONT color=green>[√]</FONT>" : "<FONT color=red>[×]</FONT>";

                LtlSiteFielsWrite.Text = isSiteFilesWritable ? "<FONT color=green>[√]</FONT>" : "<FONT color=red>[×]</FONT>";

                if (!isRootWritable || !isSiteFilesWritable)
                {
                    FailMessage("系统检测到文件夹权限不足,您需要赋予根目录 NETWORK SERVICE 以及 IIS_IUSRS 读写权限");
                    BtnStep2.Visible = false;
                }

                SetSetp(2);
            }
            else
            {
                FailMessage("您必须同意软件许可协议才能安装!");
            }
        }
        public async Task <ActionResult <UploadResult> > Upload([FromQuery] UploadRequest request, [FromForm] IFormFile file)
        {
            if (!await _authManager.HasSitePermissionsAsync(request.SiteId,
                                                            MenuUtils.SitePermissions.WxReplyAuto, MenuUtils.SitePermissions.WxReplyBeAdded))
            {
                return(Unauthorized());
            }

            var site = await _siteRepository.GetAsync(request.SiteId);

            if (file == null)
            {
                return(this.Error(Constants.ErrorUpload));
            }

            MaterialImage image = null;
            MaterialAudio audio = null;
            MaterialVideo video = null;

            if (request.MaterialType == MaterialType.Image)
            {
                var fileName = Path.GetFileName(file.FileName);
                var extName  = PathUtils.GetExtension(fileName);
                if (!_pathManager.IsImageExtensionAllowed(site, extName))
                {
                    return(this.Error(Constants.ErrorImageExtensionAllowed));
                }
                if (!_pathManager.IsImageSizeAllowed(site, file.Length))
                {
                    return(this.Error(Constants.ErrorImageSizeAllowed));
                }

                var materialFileName     = PathUtils.GetMaterialFileName(fileName);
                var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Image);

                var directoryPath = PathUtils.Combine(_pathManager.WebRootPath, virtualDirectoryPath);
                var filePath      = PathUtils.Combine(directoryPath, materialFileName);

                await _pathManager.UploadAsync(file, filePath);

                await _pathManager.AddWaterMarkAsync(site, filePath);

                image = new MaterialImage
                {
                    GroupId = -request.SiteId,
                    Title   = fileName,
                    Url     = PageUtils.Combine(virtualDirectoryPath, materialFileName)
                };

                await _materialImageRepository.InsertAsync(image);
            }
            else if (request.MaterialType == MaterialType.Audio)
            {
                var fileName = Path.GetFileName(file.FileName);
                var fileType = PathUtils.GetExtension(fileName);
                if (!_pathManager.IsAudioExtensionAllowed(site, fileType))
                {
                    return(this.Error(Constants.ErrorAudioExtensionAllowed));
                }
                if (!_pathManager.IsAudioSizeAllowed(site, file.Length))
                {
                    return(this.Error(Constants.ErrorAudioSizeAllowed));
                }

                var materialFileName     = PathUtils.GetMaterialFileName(fileName);
                var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Audio);

                var directoryPath = PathUtils.Combine(_pathManager.WebRootPath, virtualDirectoryPath);
                var filePath      = PathUtils.Combine(directoryPath, materialFileName);

                await _pathManager.UploadAsync(file, filePath);

                audio = new MaterialAudio
                {
                    GroupId  = -request.SiteId,
                    Title    = PathUtils.RemoveExtension(fileName),
                    FileType = fileType.ToUpper().Replace(".", string.Empty),
                    Url      = PageUtils.Combine(virtualDirectoryPath, materialFileName)
                };

                await _materialAudioRepository.InsertAsync(audio);
            }
            else if (request.MaterialType == MaterialType.Video)
            {
                var fileName = Path.GetFileName(file.FileName);

                var fileType = PathUtils.GetExtension(fileName);
                if (!_pathManager.IsVideoExtensionAllowed(site, fileType))
                {
                    return(this.Error(Constants.ErrorVideoExtensionAllowed));
                }
                if (!_pathManager.IsVideoSizeAllowed(site, file.Length))
                {
                    return(this.Error(Constants.ErrorVideoSizeAllowed));
                }

                var materialVideoName    = PathUtils.GetMaterialFileName(fileName);
                var virtualDirectoryPath = PathUtils.GetMaterialVirtualDirectoryPath(UploadType.Video);

                var directoryPath = PathUtils.Combine(_pathManager.WebRootPath, virtualDirectoryPath);
                var filePath      = PathUtils.Combine(directoryPath, materialVideoName);

                await _pathManager.UploadAsync(file, filePath);

                video = new MaterialVideo
                {
                    GroupId  = -request.SiteId,
                    Title    = PathUtils.RemoveExtension(fileName),
                    FileType = fileType.ToUpper().Replace(".", string.Empty),
                    Url      = PageUtils.Combine(virtualDirectoryPath, materialVideoName)
                };

                await _materialVideoRepository.InsertAsync(video);
            }

            return(new UploadResult
            {
                MaterialType = request.MaterialType,
                Image = image,
                Audio = audio,
                Video = video
            });
        }
 public static Card CreateCard(String name, String text, String imageName, CardType type,
                               IEnumerable <ITalismanAction> actions)
 {
     return(Card.createCard(name, text, PathUtils.getPathToCard(type, imageName), type, actions));
 }
示例#18
0
文件: Entity.cs 项目: trylock/viewer
 public FileEntity(string path)
 {
     Path = PathUtils.NormalizePath(path);
 }
示例#19
0
        public void DrawNameGUI()
        {
            //Title
            m_Config.m_ShowName = EditorGUILayout.Foldout(m_Config.m_ShowName, "File Name".ToUpper());
            if (m_Config.m_ShowName == false)
            {
                return;
            }
            EditorGUILayout.Separator();


            // Name
            EditorGUILayout.BeginHorizontal();

            newPath = EditorGUILayout.TextField(m_Config.m_FileName);
            if (newPath != m_Config.m_FileName)
            {
                m_Config.m_FileName = newPath;
                EditorUtility.SetDirty(m_Obj);
            }

            // Create Name Examples Menu
            if (GUILayout.Button("Presets", GUILayout.MaxWidth(70)))
            {
                var menu = new GenericMenu();
                foreach (ScreenshotNamePresets.NamePreset path in ScreenshotNamePresets.m_NamePresets)
                {
                    menu.AddItem(new GUIContent(path.m_Description), false, OnNameSelectCallback, path.m_Path);
                }
                menu.ShowAsContext();
            }

            EditorGUILayout.EndHorizontal();


            if (m_Config.m_Resolutions.Count > 0)
            {
                fullName = m_Config.ParseFileName(m_Config.m_Resolutions[0], System.DateTime.Now);
            }
            else
            {
                fullName = m_Config.ParseFileName(m_Config.m_GameViewResolution, System.DateTime.Now);
            }
            if (m_Config.m_FileName == "" || PathUtils.IsValidPath(m_Config.GetPath()) && !PathUtils.IsValidPath(fullName))
            {
                EditorGUILayout.HelpBox("Name is invalid.", MessageType.Warning);
            }

            // Override


            EditorGUILayout.PropertyField(m_OverrideFiles);


            // Format
            //			if (m_Config.m_CaptureMode != ScreenshotTaker.CaptureMode.FIXED_GAMEVIEW) {
            EditorGUILayout.PropertyField(m_FileFormat);
            if (m_Config.m_FileFormat == TextureExporter.ImageFileFormat.JPG)
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.Slider(m_JPGQuality, 1f, 100f);
                EditorGUI.indentLevel--;
            }
            else
            {
                EditorGUI.indentLevel++;
                EditorGUILayout.PropertyField(m_ColorFormat);

                if (m_Config.m_ColorFormat == ScreenshotTaker.ColorFormat.RGBA)
                {
                    EditorGUILayout.PropertyField(m_RecomputeAlphaLayer);
                }

                EditorGUI.indentLevel--;
            }
            //			}


            EditorGUILayout.Separator();
            EditorGUILayout.Separator();

            // Display full name
            EditorGUILayout.LabelField("Full name: " + fullName, EditorStyles.miniLabel);
        }
示例#20
0
文件: Entity.cs 项目: trylock/viewer
 public IEntity ChangePath(string path)
 {
     Path = PathUtils.NormalizePath(path);
     return(this);
 }
        private async Task CompiledBuiltinScrapeAsync(InterpreterConfiguration configuration)
        {
            configuration.AssertInstalled();

            var moduleUri       = TestData.GetDefaultModuleUri();
            var moduleDirectory = Path.GetDirectoryName(moduleUri.LocalPath);

            var services = await CreateServicesAsync(moduleDirectory, configuration);

            var interpreter = services.GetService <IPythonInterpreter>();

            // TODO: this is Windows only
            var dllsDir = Path.Combine(Path.GetDirectoryName(interpreter.Configuration.LibraryPath), "DLLs");

            if (!Directory.Exists(dllsDir))
            {
                Assert.Inconclusive("Configuration does not have DLLs");
            }

            var report           = new List <string>();
            var permittedImports = interpreter.LanguageVersion.Is2x() ?
                                   new[] { interpreter.ModuleResolution.BuiltinModuleName, "exceptions" } :
            new[] { interpreter.ModuleResolution.BuiltinModuleName };

            foreach (var pyd in PathUtils.EnumerateFiles(dllsDir, "*", recurse: false).Where(ModulePath.IsPythonFile))
            {
                var mp = ModulePath.FromFullPath(pyd);
                if (mp.IsDebug)
                {
                    continue;
                }

                Console.WriteLine("Importing {0} from {1}", mp.ModuleName, mp.SourceFile);
                var mod = await interpreter.ModuleResolution.ImportModuleAsync(mp.ModuleName);

                Assert.IsInstanceOfType(mod, typeof(CompiledPythonModule));

                var modPath = interpreter.ModuleResolution.ModuleCache.GetCacheFilePath(pyd);
                Assert.IsTrue(File.Exists(modPath), "No cache file created");
                var moduleCache = File.ReadAllText(modPath);

                var doc = (IDocument)mod;
                var ast = await doc.GetAstAsync();

                var errors = doc.GetParseErrors().ToArray();
                foreach (var err in errors)
                {
                    Console.WriteLine(err);
                }
                Assert.AreEqual(0, errors.Count(), "Parse errors occurred");


                var imports = ((SuiteStatement)ast.Body).Statements
                              .OfType <ImportStatement>()
                              .SelectMany(s => s.Names)
                              .Select(n => n.MakeString())
                              .Except(permittedImports)
                              .ToArray();

                // We expect no imports (after excluding builtins)
                report.AddRange(imports.Select(n => $"{mp.ModuleName} imported {n}"));
            }

            report.Should().BeEmpty();
        }
示例#22
0
文件: Entity.cs 项目: trylock/viewer
 public DirectoryEntity(string path)
 {
     Path = PathUtils.NormalizePath(path);
 }
示例#23
0
        private async Task CreateLibraryWatchers()
        {
            Debug.Assert(_libWatchers != null, "Should not create watchers when suppressed");

            IList <PythonLibraryPath> paths;

            try {
                paths = await PythonTypeDatabase.GetDatabaseSearchPathsAsync(_factory);
            } catch (InvalidOperationException) {
                return;
            }

            paths = paths
                    .Where(p => Directory.Exists(p.Path))
                    .OrderBy(p => p.Path.Length)
                    .ToList();

            var watching = new List <string>();
            var watchers = new List <FileSystemWatcher>();

            foreach (var path in paths)
            {
                if (watching.Any(p => PathUtils.IsSubpathOf(p, path.Path)))
                {
                    continue;
                }

                FileSystemWatcher watcher = null;
                try {
                    watcher = new FileSystemWatcher {
                        IncludeSubdirectories = true,
                        Path         = path.Path,
                        NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite
                    };
                    watcher.Created            += OnChanged;
                    watcher.Deleted            += OnChanged;
                    watcher.Changed            += OnChanged;
                    watcher.Renamed            += OnRenamed;
                    watcher.EnableRaisingEvents = true;

                    watching.Add(path.Path);
                    watchers.Add(watcher);
                } catch (IOException) {
                    // Raced with directory deletion. We normally handle the
                    // library being deleted by disposing the watcher, but this
                    // occurs in response to an event from the watcher. Because
                    // we never got to start watching, we will just dispose
                    // immediately.
                    watcher?.Dispose();
                } catch (ArgumentException ex) {
                    watcher?.Dispose();
                    Debug.WriteLine("Error starting FileSystemWatcher:\r\n{0}", ex);
                }
            }

            List <FileSystemWatcher> oldWatchers;

            lock (_libWatchers) {
                oldWatchers = _libWatchers.ToList();
                _libWatchers.Clear();
                _libWatchers.AddRange(watchers);
            }

            foreach (var oldWatcher in oldWatchers)
            {
                oldWatcher.EnableRaisingEvents = false;
                oldWatcher.Dispose();
            }
        }
示例#24
0
        public static void Parse(PageInfo pageInfo, ContextInfo contextInfo, StringBuilder contentBuilder, string filePath, bool isDynamic)
        {
            foreach (var service in PluginManager.Services)
            {
                try
                {
                    service.OnBeforeStlParse(new ParseEventArgs(pageInfo.SiteId, pageInfo.PageChannelId, pageInfo.PageContentId, pageInfo.TemplateInfo.TemplateType, pageInfo.TemplateInfo.Id, filePath, pageInfo.HeadCodes, pageInfo.BodyCodes, pageInfo.FootCodes, contentBuilder));
                }
                catch (Exception ex)
                {
                    LogUtils.AddErrorLog(service.PluginId, ex, nameof(service.OnBeforeStlParse));
                }
            }

            if (contentBuilder.Length > 0)
            {
                StlParserManager.ParseTemplateContent(contentBuilder, pageInfo, contextInfo);
            }

            foreach (var service in PluginManager.Services)
            {
                try
                {
                    service.OnAfterStlParse(new ParseEventArgs(pageInfo.SiteId, pageInfo.PageChannelId, pageInfo.PageContentId, pageInfo.TemplateInfo.TemplateType, pageInfo.TemplateInfo.Id, filePath, pageInfo.HeadCodes, pageInfo.BodyCodes, pageInfo.FootCodes, contentBuilder));
                }
                catch (Exception ex)
                {
                    LogUtils.AddErrorLog(service.PluginId, ex, nameof(service.OnAfterStlParse));
                }
            }

            if (EFileSystemTypeUtils.IsHtml(PathUtils.GetExtension(filePath)))
            {
                if (isDynamic)
                {
                    var    pageUrl        = PageUtils.AddProtocolToUrl(PageUtils.ParseNavigationUrl($"~/{PathUtils.GetPathDifference(WebConfigUtils.PhysicalApplicationPath, filePath)}"));
                    string templateString = $@"
<base href=""{pageUrl}"" />";
                    StringUtils.InsertAfter(new[] { "<head>", "<HEAD>" }, contentBuilder, templateString);
                }

                if (pageInfo.SiteInfo.Additional.IsCreateBrowserNoCache)
                {
                    const string templateString = @"
<META HTTP-EQUIV=""Pragma"" CONTENT=""no-cache"">
<META HTTP-EQUIV=""Expires"" CONTENT=""-1"">";
                    StringUtils.InsertAfter(new[] { "<head>", "<HEAD>" }, contentBuilder, templateString);
                }

                if (pageInfo.SiteInfo.Additional.IsCreateIe8Compatible)
                {
                    const string templateString = @"
<META HTTP-EQUIV=""x-ua-compatible"" CONTENT=""ie=7"" />";
                    StringUtils.InsertAfter(new[] { "<head>", "<HEAD>" }, contentBuilder, templateString);
                }

                if (pageInfo.SiteInfo.Additional.IsCreateJsIgnoreError)
                {
                    const string templateString = @"
<script type=""text/javascript"">window.onerror=function(){return true;}</script>";
                    StringUtils.InsertAfter(new[] { "<head>", "<HEAD>" }, contentBuilder, templateString);
                }

                if (pageInfo.PageContentId > 0 && pageInfo.SiteInfo.Additional.IsCountHits && !pageInfo.BodyCodes.ContainsKey(PageInfo.Const.JsAdStlCountHits))
                {
                    if (!pageInfo.FootCodes.ContainsKey(PageInfo.Const.JsAdStlCountHits))
                    {
                        pageInfo.FootCodes.Add(PageInfo.Const.JsAdStlCountHits, $@"
<script src=""{ApiRouteActionsAddContentHits.GetUrl(pageInfo.ApiUrl, pageInfo.SiteId, pageInfo.PageChannelId, pageInfo.PageContentId)}"" type=""text/javascript""></script>");
                    }
                }

                var isShowPageInfo = pageInfo.SiteInfo.Additional.IsCreateShowPageInfo;

                if (!pageInfo.IsLocal)
                {
                    if (pageInfo.SiteInfo.Additional.IsCreateDoubleClick)
                    {
                        var fileTemplateId = 0;
                        if (pageInfo.TemplateInfo.TemplateType == TemplateType.FileTemplate)
                        {
                            fileTemplateId = pageInfo.TemplateInfo.Id;
                        }

                        var apiUrl  = pageInfo.ApiUrl;
                        var ajaxUrl = ApiRouteActionsTrigger.GetUrl(apiUrl, pageInfo.SiteId, contextInfo.ChannelId,
                                                                    contextInfo.ContentId, fileTemplateId, true);
                        if (!pageInfo.FootCodes.ContainsKey("CreateDoubleClick"))
                        {
                            pageInfo.FootCodes.Add("CreateDoubleClick", $@"
<script type=""text/javascript"" language=""javascript"">document.ondblclick=function(x){{location.href = '{ajaxUrl}&returnUrl=' + encodeURIComponent(location.search);}}</script>");
                        }
                    }
                }
                else
                {
                    isShowPageInfo = true;
                }

                if (isShowPageInfo)
                {
                    contentBuilder.Append($@"
<!-- {pageInfo.TemplateInfo.RelatedFileName}({TemplateTypeUtils.GetText(pageInfo.TemplateInfo.TemplateType)}) -->");
                }

                var headCodesHtml = pageInfo.HeadCodesHtml;
                if (!string.IsNullOrEmpty(headCodesHtml))
                {
                    if (contentBuilder.ToString().IndexOf("</head>", StringComparison.Ordinal) != -1 || contentBuilder.ToString().IndexOf("</HEAD>", StringComparison.Ordinal) != -1)
                    {
                        StringUtils.InsertBefore(new[] { "</head>", "</HEAD>" }, contentBuilder, headCodesHtml);
                    }
                    else
                    {
                        contentBuilder.Insert(0, headCodesHtml);
                    }
                }

                var bodyCodesHtml = pageInfo.BodyCodesHtml;
                if (!string.IsNullOrEmpty(bodyCodesHtml))
                {
                    if (contentBuilder.ToString().IndexOf("<body", StringComparison.Ordinal) != -1 || contentBuilder.ToString().IndexOf("<BODY", StringComparison.Ordinal) != -1)
                    {
                        var index = contentBuilder.ToString().IndexOf("<body", StringComparison.Ordinal);
                        if (index == -1)
                        {
                            index = contentBuilder.ToString().IndexOf("<BODY", StringComparison.Ordinal);
                        }
                        index = contentBuilder.ToString().IndexOf(">", index, StringComparison.Ordinal);
                        contentBuilder.Insert(index + 1, StringUtils.Constants.ReturnAndNewline + bodyCodesHtml + StringUtils.Constants.ReturnAndNewline);
                    }
                    else
                    {
                        contentBuilder.Insert(0, bodyCodesHtml);
                    }
                }

                var footCodesHtml = pageInfo.FootCodesHtml;
                if (!string.IsNullOrEmpty(footCodesHtml))
                {
                    contentBuilder.Append(footCodesHtml + StringUtils.Constants.ReturnAndNewline);
                }
            }
        }
示例#25
0
    void OnDownloadConfig(string versionValue)
    {
        string fileName = versionValue + ".zip";
        string url      = GameConfig.HOST_RES_ZIP() + "zip/" + fileName + "?t=" + TimeUtils.CurLocalTimeMilliSecond();
        string filePath = PathUtils.MakeFilePath(fileName, PathUtils.PathType.MobileDiskWrite);

        float progress = 0f;

        //使用流操作文件
        FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
        //获取文件现在的长度
        long fileLength = fs.Length;
        //获取下载文件的总长度
        //long totalLength = GetLength(url);
        HttpWebRequest request = HttpWebRequest.Create(url) as HttpWebRequest;

        request.Timeout = 60000;
        HttpWebResponse response    = request.GetResponse() as HttpWebResponse;
        long            totalLength = response.ContentLength;
        string          size        = (totalLength / 1048576f).ToString("0.00") + "MB";
        string          tips        = "下载更新包:0/" + size;
        DownloadTips    dt          = new DownloadTips()
        {
            tips = tips
        };

        MessageSystem.Instance().PostMessage(MessageId.DOWNLOAD_CONFIG_PROGRESS, dt, 0);
        DateTime startTime = DateTime.Now;

        //如果没下载完
        if (fileLength < totalLength)
        {
            //断点续传核心,设置本地文件流的起始位置
            fs.Seek(fileLength, SeekOrigin.Begin);
            //断点续传核心,设置远程访问文件流的起始位置
            request.AddRange((int)fileLength);
            Stream stream = response.GetResponseStream();

            byte[] buffer = new byte[1024];
            //使用流读取内容到buffer中
            //注意方法返回值代表读取的实际长度,并不是buffer有多大,stream就会读进去多少
            int length = stream.Read(buffer, 0, buffer.Length);
            while (length > 0)
            {
                //将内容再写入本地文件中
                fs.Write(buffer, 0, length);
                //计算进度
                fileLength += length;
                progress    = (float)fileLength / (float)totalLength;

                dt.tips     = "下载更新包:" + (fileLength / 1048576f).ToString("0.00") + "/" + size;
                dt.progress = progress;
                dt.speed    = "速度:" + (int)(fileLength / 1024f / (DateTime.Now - startTime).TotalSeconds) + "KB/s";

                MessageSystem.Instance().PostMessage(MessageId.DOWNLOAD_CONFIG_PROGRESS, dt, 0);
                //类似尾递归
                length = stream.Read(buffer, 0, buffer.Length);
            }
            stream.Close();
            stream.Dispose();
        }
        else
        {
            progress = 1;
        }
        fs.Close();
        fs.Dispose();
        //如果下载完毕,执行回调
        if (progress == 1)
        {
            OnDecompressConfig(versionValue);
        }
    }
示例#26
0
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            if (Page.IsPostBack && Page.IsValid)
            {
                NodeInfo nodeInfo;
                try
                {
                    nodeInfo = NodeManager.GetNodeInfo(PublishmentSystemId, _nodeId);
                    if (!nodeInfo.NodeIndexName.Equals(NodeIndexName.Text) && NodeIndexName.Text.Length != 0)
                    {
                        var nodeIndexNameList = DataProvider.NodeDao.GetNodeIndexNameList(PublishmentSystemId);
                        if (nodeIndexNameList.IndexOf(NodeIndexName.Text) != -1)
                        {
                            FailMessage("栏目属性修改失败,栏目索引已存在!");
                            return;
                        }
                    }

                    if (nodeInfo.ContentModelId != ContentModelID.SelectedValue)
                    {
                        nodeInfo.ContentModelId = ContentModelID.SelectedValue;
                        nodeInfo.ContentNum     = BaiRongDataProvider.ContentDao.GetCount(NodeManager.GetTableName(PublishmentSystemInfo, nodeInfo.ContentModelId), nodeInfo.NodeId);
                    }

                    FilePath.Text = FilePath.Text.Trim();
                    if (!nodeInfo.FilePath.Equals(FilePath.Text) && FilePath.Text.Length != 0)
                    {
                        if (!DirectoryUtils.IsDirectoryNameCompliant(FilePath.Text))
                        {
                            FailMessage("栏目页面路径不符合系统要求!");
                            return;
                        }

                        if (PathUtils.IsDirectoryPath(FilePath.Text))
                        {
                            FilePath.Text = PageUtils.Combine(FilePath.Text, "index.html");
                        }

                        var filePathArrayList = DataProvider.NodeDao.GetAllFilePathByPublishmentSystemId(PublishmentSystemId);
                        if (filePathArrayList.IndexOf(FilePath.Text) != -1)
                        {
                            FailMessage("栏目修改失败,栏目页面路径已存在!");
                            return;
                        }
                    }

                    if (!string.IsNullOrEmpty(ChannelFilePathRule.Text))
                    {
                        var filePathRule = ChannelFilePathRule.Text.Replace("|", string.Empty);
                        if (!DirectoryUtils.IsDirectoryNameCompliant(filePathRule))
                        {
                            FailMessage("栏目页面命名规则不符合系统要求!");
                            return;
                        }
                        if (PathUtils.IsDirectoryPath(filePathRule))
                        {
                            FailMessage("栏目页面命名规则必须包含生成文件的后缀!");
                            return;
                        }
                    }

                    if (!string.IsNullOrEmpty(ContentFilePathRule.Text))
                    {
                        var filePathRule = ContentFilePathRule.Text.Replace("|", string.Empty);
                        if (!DirectoryUtils.IsDirectoryNameCompliant(filePathRule))
                        {
                            FailMessage("内容页面命名规则不符合系统要求!");
                            return;
                        }
                        if (PathUtils.IsDirectoryPath(filePathRule))
                        {
                            FailMessage("内容页面命名规则必须包含生成文件的后缀!");
                            return;
                        }
                    }

                    var extendedAttributes = new ExtendedAttributes();
                    var relatedIdentities  = RelatedIdentities.GetChannelRelatedIdentities(PublishmentSystemId, _nodeId);
                    BackgroundInputTypeParser.AddValuesToAttributes(ETableStyle.Channel, DataProvider.NodeDao.TableName, PublishmentSystemInfo, relatedIdentities, Request.Form, extendedAttributes.Attributes);
                    var attributes = extendedAttributes.Attributes;
                    foreach (string key in attributes)
                    {
                        nodeInfo.Additional.SetExtendedAttribute(key, attributes[key]);
                    }

                    nodeInfo.NodeName            = NodeName.Text;
                    nodeInfo.NodeIndexName       = NodeIndexName.Text;
                    nodeInfo.FilePath            = FilePath.Text;
                    nodeInfo.ChannelFilePathRule = ChannelFilePathRule.Text;
                    nodeInfo.ContentFilePathRule = ContentFilePathRule.Text;

                    var list = new ArrayList();
                    foreach (ListItem item in NodeGroupNameCollection.Items)
                    {
                        if (item.Selected)
                        {
                            list.Add(item.Value);
                        }
                    }
                    nodeInfo.NodeGroupNameCollection = TranslateUtils.ObjectCollectionToString(list);
                    nodeInfo.ImageUrl = NavigationPicPath.Text;
                    nodeInfo.Content  = StringUtility.TextEditorContentEncode(Request.Form[NodeAttribute.Content], PublishmentSystemInfo, PublishmentSystemInfo.Additional.IsSaveImageInTextEditor);

                    nodeInfo.Keywords    = Keywords.Text;
                    nodeInfo.Description = Description.Text;

                    nodeInfo.Additional.IsChannelAddable = TranslateUtils.ToBool(IsChannelAddable.SelectedValue);
                    nodeInfo.Additional.IsContentAddable = TranslateUtils.ToBool(IsContentAddable.SelectedValue);

                    nodeInfo.LinkUrl           = LinkUrl.Text;
                    nodeInfo.LinkType          = ELinkTypeUtils.GetEnumType(LinkType.SelectedValue);
                    nodeInfo.ChannelTemplateId = (ChannelTemplateID.Items.Count > 0) ? int.Parse(ChannelTemplateID.SelectedValue) : 0;
                    nodeInfo.ContentTemplateId = (ContentTemplateID.Items.Count > 0) ? int.Parse(ContentTemplateID.SelectedValue) : 0;

                    DataProvider.NodeDao.UpdateNodeInfo(nodeInfo);
                }
                catch (Exception ex)
                {
                    FailMessage(ex, $"栏目修改失败:{ex.Message}");
                    LogUtils.AddErrorLog(ex);
                    return;
                }

                CreateManager.CreateChannel(PublishmentSystemId, nodeInfo.NodeId);

                Body.AddSiteLog(PublishmentSystemId, "修改栏目", $"栏目:{NodeName.Text}");

                SuccessMessage("栏目修改成功!");
                PageUtils.Redirect(_returnUrl);
            }
        }
示例#27
0
            public async Task CheckDefinitionLocations(int pos, int length, params LocationInfo[] expectedLocations)
            {
                var entry = (AnalysisEntry)_view.GetAnalysisEntry();

                entry.Analyzer.WaitForCompleteAnalysis(_ => true);

                var trackingSpan = _view.CurrentSnapshot.CreateTrackingSpan(pos, length, SpanTrackingMode.EdgeInclusive);
                var snapshotSpan = trackingSpan.GetSpan(_view.CurrentSnapshot);

                Console.WriteLine("Finding definition of \"{0}\"", snapshotSpan.GetText());
                var actualLocations = await NavigableSymbolSource.GetDefinitionLocationsAsync(entry, snapshotSpan.Start);

                Console.WriteLine($"Actual locations for pos={pos}, length={length}:");
                foreach (var actualLocation in actualLocations)
                {
                    Console.WriteLine($"file={actualLocation.Location.DocumentUri},line={actualLocation.Location.StartLine},col={actualLocation.Location.StartColumn}");
                }

                // Check that any real locations are not our test files. These may be included in debug builds,
                // but we don't want to be testing them.
                // Fake paths are from our tests, so always include them.
                actualLocations = actualLocations
                                  .Where(v => !File.Exists(v.Location.FilePath) || !PathUtils.IsSubpathOf(PathUtils.GetParent(typeof(IAnalysisVariable).Assembly.Location), v.Location.FilePath))
                                  .ToArray();

                if (expectedLocations != null)
                {
                    Assert.IsNotNull(actualLocations);

                    Assert.AreEqual(expectedLocations.Length, actualLocations.Length, "incorrect number of locations");
                    for (int i = 0; i < expectedLocations.Length; i++)
                    {
                        Assert.AreEqual(expectedLocations[i].StartLine, actualLocations[i].Location.StartLine, "incorrect line");
                        Assert.AreEqual(expectedLocations[i].StartColumn, actualLocations[i].Location.StartColumn, "incorrect column");
                        if (expectedLocations[i].FilePath != null)
                        {
                            Assert.AreEqual(expectedLocations[i].FilePath, Path.GetFileName(actualLocations[i].Location.FilePath));
                        }
                    }
                }
                else
                {
                    Assert.AreEqual(0, actualLocations.Length, "incorrect number of locations");
                }
            }
示例#28
0
        public override void Submit_OnClick(object sender, EventArgs e)
        {
            if (CbIsTitleImage.Checked && string.IsNullOrEmpty(TbTitleImageWidth.Text) && string.IsNullOrEmpty(TbTitleImageHeight.Text))
            {
                FailMessage("缩略图尺寸不能为空!");
                return;
            }
            if (CbIsSmallImage.Checked && string.IsNullOrEmpty(TbSmallImageWidth.Text) && string.IsNullOrEmpty(TbSmallImageHeight.Text))
            {
                FailMessage("缩略图尺寸不能为空!");
                return;
            }

            ConfigSettings(false);

            if (HifUpload.PostedFile == null || "" == HifUpload.PostedFile.FileName)
            {
                return;
            }

            var filePath = HifUpload.PostedFile.FileName;

            try
            {
                var fileExtName        = PathUtils.GetExtension(filePath).ToLower();
                var localDirectoryPath = PathUtility.GetUploadDirectoryPath(SiteInfo, fileExtName);
                var localFileName      = PathUtility.GetUploadFileName(SiteInfo, filePath);
                var localTitleFileName = StringUtils.Constants.TitleImageAppendix + localFileName;
                var localSmallFileName = StringUtils.Constants.SmallImageAppendix + localFileName;
                var localFilePath      = PathUtils.Combine(localDirectoryPath, localFileName);
                var localTitleFilePath = PathUtils.Combine(localDirectoryPath, localTitleFileName);
                var localSmallFilePath = PathUtils.Combine(localDirectoryPath, localSmallFileName);

                if (!PathUtility.IsImageExtenstionAllowed(SiteInfo, fileExtName))
                {
                    FailMessage("上传失败,上传图片格式不正确!");
                    return;
                }
                if (!PathUtility.IsImageSizeAllowed(SiteInfo, HifUpload.PostedFile.ContentLength))
                {
                    FailMessage("上传失败,上传图片超出规定文件大小!");
                    return;
                }

                HifUpload.PostedFile.SaveAs(localFilePath);

                var isImage = EFileSystemTypeUtils.IsImage(fileExtName);

                //处理上半部分
                if (isImage)
                {
                    FileUtility.AddWaterMark(SiteInfo, localFilePath);
                    if (CbIsTitleImage.Checked)
                    {
                        var width  = TranslateUtils.ToInt(TbTitleImageWidth.Text);
                        var height = TranslateUtils.ToInt(TbTitleImageHeight.Text);
                        ImageUtils.MakeThumbnail(localFilePath, localTitleFilePath, width, height, true);
                    }
                }

                var imageUrl = PageUtility.GetSiteUrlByPhysicalPath(SiteInfo, localFilePath, true);
                if (CbIsTitleImage.Checked)
                {
                    imageUrl = PageUtility.GetSiteUrlByPhysicalPath(SiteInfo, localTitleFilePath, true);
                }

                var textBoxUrl = PageUtility.GetVirtualUrl(SiteInfo, imageUrl);

                var script = $@"
if (parent.document.getElementById('{_textBoxClientId}'))
{{
    parent.document.getElementById('{_textBoxClientId}').value = '{textBoxUrl}';
}}
";

                //处理下半部分
                if (CbIsShowImageInTextEditor.Checked && isImage)
                {
                    imageUrl = PageUtility.GetSiteUrlByPhysicalPath(SiteInfo, localFilePath, true);
                    var smallImageUrl = imageUrl;
                    if (CbIsSmallImage.Checked)
                    {
                        smallImageUrl = PageUtility.GetSiteUrlByPhysicalPath(SiteInfo, localSmallFilePath, true);
                    }

                    if (CbIsSmallImage.Checked)
                    {
                        var width  = TranslateUtils.ToInt(TbSmallImageWidth.Text);
                        var height = TranslateUtils.ToInt(TbSmallImageHeight.Text);
                        ImageUtils.MakeThumbnail(localFilePath, localSmallFilePath, width, height, true);
                    }

                    var insertHtml = CbIsLinkToOriginal.Checked ? $@"<a href=""{imageUrl}"" target=""_blank""><img src=""{smallImageUrl}"" border=""0"" /></a>" : $@"<img src=""{smallImageUrl}"" border=""0"" />";

                    script += "if(parent." + UEditorUtils.GetEditorInstanceScript() + ") parent." + UEditorUtils.GetInsertHtmlScript("Content", insertHtml);
                }

                LtlScript.Text = $@"
<script type=""text/javascript"" language=""javascript"">
    {script}
    {LayerUtils.CloseScript}
</script>";
            }
            catch (Exception ex)
            {
                FailMessage(ex, ex.Message);
            }
        }
示例#29
0
        public static void SamePathOrUnder(string path1, string path2)
        {
            string msg = "\r\n\texpected: Same path or under <{0}>\r\n\t but was: <{1}>";

            Assert.That(PathUtils.SamePathOrUnder(path1, path2), Is.True, msg, path1, path2);
        }
示例#30
0
        private InterpreterConfiguration TryReadConfiguration(
            string company,
            string tag,
            RegistryKey tagKey,
            RegistryKey installKey,
            bool pythonCoreCompatibility,
            InterpreterArchitecture assumedArch
            )
        {
            if (tagKey == null || installKey == null)
            {
                return(null);
            }

            string prefixPath, exePath, exewPath;

            try {
                prefixPath = PathUtils.NormalizePath(installKey.GetValue(null) as string);
                exePath    = PathUtils.NormalizePath(installKey.GetValue("ExecutablePath") as string);
                exewPath   = PathUtils.NormalizePath(installKey.GetValue("WindowedExecutablePath") as string);
            } catch (ArgumentException ex) {
                Debug.Fail(ex.ToUnhandledExceptionMessage(GetType()));
                return(null);
            }
            if (pythonCoreCompatibility && !string.IsNullOrEmpty(prefixPath))
            {
                if (string.IsNullOrEmpty(exePath))
                {
                    try {
                        exePath = PathUtils.GetAbsoluteFilePath(prefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable);
                    } catch (ArgumentException) {
                    }
                }
                if (string.IsNullOrEmpty(exewPath))
                {
                    try {
                        exewPath = PathUtils.GetAbsoluteFilePath(prefixPath, CPythonInterpreterFactoryConstants.WindowsExecutable);
                    } catch (ArgumentException) {
                    }
                }
            }

            var version = tagKey.GetValue("Version") as string;

            if (pythonCoreCompatibility && string.IsNullOrEmpty(version) && tag.Length >= 3)
            {
                version = tag.Substring(0, 3);
            }

            Version sysVersion;
            var     sysVersionString = tagKey.GetValue("SysVersion") as string;

            if (pythonCoreCompatibility && string.IsNullOrEmpty(sysVersionString) && tag.Length >= 3)
            {
                sysVersionString = tag.Substring(0, 3);
            }
            if (string.IsNullOrEmpty(sysVersionString) || !Version.TryParse(sysVersionString, out sysVersion))
            {
                sysVersion = new Version(0, 0);
            }

            PythonLanguageVersion langVersion;

            try {
                langVersion = sysVersion.ToLanguageVersion();
            } catch (InvalidOperationException) {
                langVersion = PythonLanguageVersion.None;
                sysVersion  = new Version(0, 0);
            }

            InterpreterArchitecture arch;

            if (!InterpreterArchitecture.TryParse(tagKey.GetValue("SysArchitecture", null) as string, out arch))
            {
                arch = assumedArch;
            }

            if (arch == InterpreterArchitecture.Unknown && File.Exists(exePath))
            {
                switch (NativeMethods.GetBinaryType(exePath))
                {
                case System.Reflection.ProcessorArchitecture.X86:
                    arch = InterpreterArchitecture.x86;
                    break;

                case System.Reflection.ProcessorArchitecture.Amd64:
                    arch = InterpreterArchitecture.x64;
                    break;
                }
            }

            if (pythonCoreCompatibility && sysVersion != null && sysVersion < new Version(3, 5) && arch == InterpreterArchitecture.x86)
            {
                // Older versions of CPython did not include
                // "-32" in their Tag, so we will add it here
                // for uniqueness.
                tag += "-32";
            }

            var pathVar = tagKey.GetValue("PathEnvironmentVariable") as string ??
                          CPythonInterpreterFactoryConstants.PathEnvironmentVariableName;

            var id = CPythonInterpreterFactoryConstants.GetInterpreterId(company, tag);

            var description = tagKey.GetValue("DisplayName") as string;

            if (string.IsNullOrEmpty(description))
            {
                if (pythonCoreCompatibility)
                {
                    description = "Python {0}{1: ()}".FormatUI(version, arch);
                }
                else
                {
                    description = "{0} {1}".FormatUI(company, tag);
                }
            }

            return(new InterpreterConfiguration(
                       id,
                       description,
                       prefixPath,
                       exePath,
                       exewPath,
                       pathVar,
                       arch,
                       sysVersion
                       ));
        }