Here are the examples of the csharp api System.IO.Path.GetFullPath(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
4059 Examples
19
Source : PluginManager.cs
with GNU General Public License v3.0
from alexdillon
with GNU General Public License v3.0
from alexdillon
private static replacedembly LoadPlugin(string relativePath)
{
// Navigate up to the solution root
string root = Path.GetFullPath(Path.Combine(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(
Path.GetDirectoryName(typeof(Program).replacedembly.Location)))))));
string pluginLocation = Path.GetFullPath(Path.Combine(root, relativePath.Replace('\\', Path.DirectorySeparatorChar)));
Console.WriteLine($"Loading commands from: {pluginLocation}");
PluginLoadContext loadContext = new PluginLoadContext(pluginLocation);
return loadContext.LoadFromreplacedemblyName(new replacedemblyName(Path.GetFileNameWithoutExtension(pluginLocation)));
}
19
Source : PythonScriptCreator.cs
with MIT License
from AlexLemminG
with MIT License
from AlexLemminG
internal static UnityEngine.Object CreateScriptreplacedetFromTemplate(string pathName, string resourceFile)
{
string fullPath = Path.GetFullPath(pathName);
string text = TemplateText;
// string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(pathName);
// text = Regex.Replace(text, "#NAME#", fileNameWithoutExtension);
bool encoderShouldEmitUTF8Identifier = true;
bool throwOnInvalidBytes = false;
UTF8Encoding encoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier, throwOnInvalidBytes);
bool append = false;
StreamWriter streamWriter = new StreamWriter(fullPath, append, encoding);
streamWriter.Write(text);
streamWriter.Close();
replacedetDatabase.Importreplacedet(pathName);
return replacedetDatabase.LoadreplacedetAtPath(pathName, typeof(UnityEngine.Object));
}
19
Source : Startup.cs
with MIT License
from alexyakunin
with MIT License
from alexyakunin
public void Configure(IApplicationBuilder app, ILogger<Startup> log)
{
if (HostSettings.replacedumeHttps) {
Log.LogInformation("replacedumeHttps on");
app.Use((context, next) => {
context.Request.Scheme = "https";
return next();
});
}
// This server serves static content from Blazor Client,
// and since we don't copy it to local wwwroot,
// we need to find Client's wwwroot in bin/(Debug/Release) folder
// and set it as this server's content root.
var baseDir = Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location) ?? "";
var binCfgPart = Regex.Match(baseDir, @"[\\/]bin[\\/]\w+[\\/]").Value;
var wwwRootPath = Path.Combine(baseDir, "wwwroot");
if (!Directory.Exists(Path.Combine(wwwRootPath, "_framework")))
// This is a regular build, not a build produced w/ "publish",
// so we remap wwwroot to the client's wwwroot folder
wwwRootPath = Path.GetFullPath(Path.Combine(baseDir, $"../../../../UI/{binCfgPart}/net5.0/wwwroot"));
Env.WebRootPath = wwwRootPath;
Env.WebRootFileProvider = new PhysicalFileProvider(Env.WebRootPath);
StaticWebreplacedetsLoader.UseStaticWebreplacedets(Env, Cfg);
if (Env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
app.UseWebreplacedemblyDebugging();
}
else {
// app.UseExceptionHandler("/Error");
app.UseDeveloperExceptionPage();
app.UseHsts();
}
if (HostSettings.UseHttpsRedirection) {
Log.LogInformation("UseHttpsRedirection on");
app.UseHttpsRedirection();
}
if (HostSettings.UseForwardedHeaders) {
Log.LogInformation("UseForwardedHeaders on");
app.UseForwardedHeaders();
}
app.UseWebSockets(new WebSocketOptions() {
KeepAliveInterval = TimeSpan.FromSeconds(30),
});
app.UseFusionSession();
// Static + Swagger
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1");
});
// API controllers
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapBlazorHub();
endpoints.MapFusionWebSocketServer();
endpoints.MapControllers();
endpoints.MapFallbackToPage("/_Host");
});
}
19
Source : Extensions.cs
with Apache License 2.0
from Algoryx
with Apache License 2.0
from Algoryx
public static string PrettyPath( this string path )
{
var result = string.Copy( path );
// Unity replacedetDataBase and/or Resources doesn't support
// intermediate relative (..) path, e.g., replacedets/Foo/../Bar/file.txt.
if ( result.Contains( ".." ) )
result = System.IO.Path.GetFullPath( result );
result = result.Replace( '\\', '/' );
if ( System.IO.Path.IsPathRooted( result ) )
result = result.MakeRelative( Application.dataPath );
if ( result.StartsWith( "./" ) )
result = result.Remove( 0, 2 );
return result;
}
19
Source : BaseIntegrationTest.cs
with MIT License
from alimon808
with MIT License
from alimon808
private static string GetProjectPath(string solutionRelativePath, replacedembly startupreplacedembly)
{
// Get name of the target project which we want to test
var projectName = startupreplacedembly.GetName().Name;
// Get currently executing test project path
var applicationBasePath = PlatformServices.Default.Application.ApplicationBasePath;
// Find the folder which contains the solution file. We then use this information to find the target
// project which we want to test.
var directoryInfo = new DirectoryInfo(applicationBasePath);
do
{
var solutionFileInfo = new FileInfo(Path.Combine(directoryInfo.FullName, SolutionName));
if (solutionFileInfo.Exists)
{
return Path.GetFullPath(Path.Combine(directoryInfo.FullName, solutionRelativePath, projectName));
}
directoryInfo = directoryInfo.Parent;
}
while (directoryInfo.Parent != null);
throw new Exception($"Solution root could not be located using application root {applicationBasePath}.");
}
19
Source : FileIsExtensions.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
public static bool IsAbsoluteDirectoryPath(this string value)
{
if (value == null)
{
return true;
}
else
{
value.MustBeValidDirectoryPath();
return value == Path.GetFullPath(value);
}
}
19
Source : FileIsExtensions.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
public static bool IsAbsoluteFilePath(this string value)
{
if (value == null)
{
return true;
}
else
{
value.MustBeValidFilePath();
return value == Path.GetFullPath(value);
}
}
19
Source : CheckDependencies.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private static string GetFullPath(string fileName)
{
if (File.Exists(fileName))
return Path.GetFullPath(fileName);
var values = Environment.GetEnvironmentVariable("PATH");
foreach (var path in values.Split(Path.PathSeparator))
{
var fullPath = Path.Combine(path, fileName);
if (File.Exists(fullPath))
return fullPath;
}
return null;
}
19
Source : CheckDependencies.cs
with MIT License
from Alkl58
with MIT License
from Alkl58
private static string GetFullPathWithOutName(string fileName)
{
if (File.Exists(fileName))
return Path.GetFullPath(fileName);
var values = Environment.GetEnvironmentVariable("PATH");
foreach (var path in values.Split(Path.PathSeparator))
{
var fullPath = Path.Combine(path, fileName);
if (File.Exists(fullPath))
return path; // Returns the PATH without Filename
}
return null;
}
19
Source : FileLoader.cs
with MIT License
from allenwp
with MIT License
from allenwp
public static string FullPath(string path)
{
return Path.GetFullPath(Path.Combine(replacedetsPath, path));
}
19
Source : Library.cs
with MIT License
from allisterb
with MIT License
from allisterb
public virtual bool CleanAndFixup()
{
if (File.Exists(Path.Combine(OutputDirName, Module.OutputNamespace + "-symbols.cpp")))
{
File.Delete(Path.Combine(OutputDirName, Module.OutputNamespace + "-symbols.cpp"));
Info($"Removing unneeded file {Path.Combine(OutputDirName, Module.OutputNamespace + "-symbols.cpp")}");
}
if (File.Exists(Path.Combine(OutputDirName, "Std.cs")))
{
File.Delete(Path.Combine(OutputDirName, "Std.cs"));
Info($"Removing unneeded file {Path.Combine(OutputDirName, "Std.cs")}");
}
if (!string.IsNullOrEmpty(OutputFileName))
{
string f = Path.Combine(Path.GetFullPath(OutputDirName), OutputFileName);
if (!string.IsNullOrEmpty(OutputFileName) && F != f)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT && F.ToLowerInvariant() == f.ToLowerInvariant())
{
}
else if (File.Exists(f))
{
Warn($"Overwriting file {f}.");
File.Delete(f);
}
File.Move(F, f);
F = f;
}
}
if (!string.IsNullOrEmpty(Clreplaced))
{
string s = File.ReadAllText(F);
s = Regex.Replace(s, $"public unsafe partial clreplaced {ModuleName}\\r?$", "public unsafe partial clreplaced " + Clreplaced, RegexOptions.Multiline);
File.WriteAllText(F, s);
}
return true;
}
19
Source : IntegrationTests.cs
with Apache License 2.0
from allure-framework
with Apache License 2.0
from allure-framework
[OneTimeSetUp]
public void Init()
{
var featuresProjectPath = Path.GetFullPath(
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"./../../../../Allure.Features"));
Process.Start(new ProcessStartInfo
{
WorkingDirectory = featuresProjectPath,
FileName = "dotnet",
Arguments = $"test"
}).WaitForExit();
var allureResultsDirectory = new DirectoryInfo(featuresProjectPath).GetDirectories("allure-results", SearchOption.AllDirectories)
.First();
var featuresDirectory = Path.Combine(featuresProjectPath, "TestData");
// parse allure suites
ParseAllureSuites(allureResultsDirectory.FullName);
ParseFeatures(featuresDirectory);
}
19
Source : PulseLogPrivesc.cs
with Apache License 2.0
from AlmondOffSec
with Apache License 2.0
from AlmondOffSec
public static int Main(string[] args)
{
string outPath = "C:\\Windows\\System32\\evil.dll";
string inPath = null;
if (args.Length == 0) {
Console.WriteLine("usage: pi.exe OUTPUT_FILE_PATH [INPUT_FILE_PATH]");
return 0;
} else {
try {
outPath = Path.GetFullPath(args[0]);
Log("Attempting to create file:\t" + outPath);
if(args.Length > 1) {
inPath = Path.GetFullPath(args[1]);
Log("With content of file:\t\t" + inPath);
}
bool res = exploit(outPath, inPath, true);
if(res)
Log("Succeeded!");
else
Log("Failed!");
} catch (Exception ex) {
Console.WriteLine("Error: ");
Console.WriteLine(ex);
}
}
return 0;
}
19
Source : ParquetMrIntegrationTest.cs
with MIT License
from aloneguid
with MIT License
from aloneguid
private void CompareWithMr(Table t)
{
string testFileName = Path.GetFullPath("temp.parquet");
if (F.Exists(testFileName))
F.Delete(testFileName);
//produce file
using (Stream s = F.OpenWrite(testFileName))
{
using (var writer = new ParquetWriter(t.Schema, s))
{
writer.Write(t);
}
}
//read back
Table t2 = ParquetReader.ReadTableFromFile(testFileName);
//check we don't have a bug internally before launching MR
replacedert.Equal(t.ToString("j"), t2.ToString("j"), ignoreLineEndingDifferences: true);
string mrJson = ExecAndGetOutput(_javaExecName, $"-jar {_toolsJarPath} cat -j {testFileName}");
replacedert.Equal(t.ToString("j"), mrJson);
}
19
Source : Utils.cs
with MIT License
from Alprog
with MIT License
from Alprog
public static string ResolvePath(string a, string b)
{
return ToUnixPath(Path.GetFullPath(Path.Combine(a, b)));
}
19
Source : PathHelper.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static bool ValidateLegalFilePath(string legalPath, string filePath)
{
var fullRootedFolder = Path.GetFullPath(legalPath + Path.DirectorySeparatorChar);
var expandedFilename = Path.GetFullPath(filePath);
return expandedFilename.StartsWith(fullRootedFolder);
}
19
Source : GitRepository.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
protected string GetAbsoluteFilePathSanitized(string relativeFilePath)
{
if (relativeFilePath.StartsWith("/") || relativeFilePath.StartsWith("\\"))
{
relativeFilePath = relativeFilePath[1..];
}
// We do this to avoid paths like c:\altinn\repositories\developer\org\repo\..\..\somefile.txt
// By first combining the paths, the getting the full path you will get c:\altinn\repositories\developer\org\repo\somefile.txt
// This also makes it easier to avoid people trying to get outside their repository directory.
var absoluteFilePath = Path.Combine(new string[] { RepositoryDirectory, relativeFilePath });
absoluteFilePath = Path.GetFullPath(absoluteFilePath);
return absoluteFilePath;
}
19
Source : TestDataHelper.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static string GetTestDataDirectory()
{
var unitTestFolder = Path.GetDirectoryName(new Uri(replacedembly.GetExecutingreplacedembly().Location).LocalPath);
return Path.GetFullPath(Path.Combine(unitTestFolder, @"..\..\..\_TestData\"));
}
19
Source : YoloAnnotationExportProvider.cs
with MIT License
from AlturosDestinations
with MIT License
from AlturosDestinations
private void CreateFiles(string dataPath, string imagePath, AnnotationImage[] images, ObjectClreplaced[] objectClreplacedes)
{
var stringBuilderDict = new Dictionary<int, StringBuilder>();
foreach (var objectClreplaced in objectClreplacedes)
{
stringBuilderDict[objectClreplaced.Id] = new StringBuilder();
}
var packagesFolder = ConfigurationManager.AppSettings["extractionFolder"];
var mappingsFile = "mappings.txt";
var imageMappingSb = new StringBuilder();
foreach (var image in images)
{
imageMappingSb.AppendLine($"{this._exportedNames[image]} {Path.Combine(image.Package.PackageName, image.ImageName)}");
var newFilePath = Path.Combine(imagePath, this._exportedNames[image]);
for (var j = 0; j < image.BoundingBoxes.Count; j++)
{
if (image.BoundingBoxes[j] != null)
{
stringBuilderDict[image.BoundingBoxes[j].ObjectIndex].AppendLine(Path.GetFullPath(newFilePath));
}
}
// Copy image
File.Copy(Path.Combine(packagesFolder, image.Package.PackageName, image.ImageName), newFilePath, true);
// Create bounding boxes
this.CreateBoundingBoxes(image.BoundingBoxes, Path.ChangeExtension(newFilePath, "txt"), objectClreplacedes);
}
// Create mappings file
File.WriteAllText(Path.Combine(dataPath, mappingsFile), imageMappingSb.ToString());
}
19
Source : TMP_EditorUtility.cs
with MIT License
from Alword
with MIT License
from Alword
private static string GetPackageRelativePath()
{
// Check for potential UPM package
string packagePath = Path.GetFullPath("Packages/com.unity.textmeshpro");
if (Directory.Exists(packagePath))
{
return "Packages/com.unity.textmeshpro";
}
packagePath = Path.GetFullPath("replacedets/..");
if (Directory.Exists(packagePath))
{
// Search default location for development package
if (Directory.Exists(packagePath + "/replacedets/Packages/com.unity.TextMeshPro/Editor Resources"))
{
return "replacedets/Packages/com.unity.TextMeshPro";
}
// Search for default location of normal TextMesh Pro replacedetStore package
if (Directory.Exists(packagePath + "/replacedets/TextMesh Pro/Editor Resources"))
{
return "replacedets/TextMesh Pro";
}
// Search for potential alternative locations in the user project
string[] matchingPaths = Directory.GetDirectories(packagePath, "TextMesh Pro", SearchOption.AllDirectories);
packagePath = ValidateLocation(matchingPaths, packagePath);
if (packagePath != null) return packagePath;
}
return null;
}
19
Source : TMP_EditorUtility.cs
with MIT License
from Alword
with MIT License
from Alword
private static string GetPackageFullPath()
{
// Check for potential UPM package
string packagePath = Path.GetFullPath("Packages/com.unity.textmeshpro");
if (Directory.Exists(packagePath))
{
return packagePath;
}
packagePath = Path.GetFullPath("replacedets/..");
if (Directory.Exists(packagePath))
{
// Search default location for development package
if (Directory.Exists(packagePath + "/replacedets/Packages/com.unity.TextMeshPro/Editor Resources"))
{
return packagePath + "/replacedets/Packages/com.unity.TextMeshPro";
}
// Search for default location of normal TextMesh Pro replacedetStore package
if (Directory.Exists(packagePath + "/replacedets/TextMesh Pro/Editor Resources"))
{
return packagePath + "/replacedets/TextMesh Pro";
}
// Search for potential alternative locations in the user project
string[] matchingPaths = Directory.GetDirectories(packagePath, "TextMesh Pro", SearchOption.AllDirectories);
string path = ValidateLocation(matchingPaths, packagePath);
if (path != null) return packagePath + path;
}
return null;
}
19
Source : TMP_PackageUtilities.cs
with MIT License
from Alword
with MIT License
from Alword
void OnGUI()
{
GUILayout.BeginVertical();
{
// Scan project files and resources
GUILayout.BeginVertical(EditorStyles.helpBox);
{
GUILayout.Label("Scan Project Files", EditorStyles.boldLabel);
GUILayout.Label("Press the <i>Scan Project Files</i> button to begin scanning your project for files & resources that were created with a previous version of TextMesh Pro.", TMP_UIStyleManager.label);
GUILayout.Space(10f);
GUILayout.Label("Project folder to be scanned. Example \"replacedets/TextMesh Pro\"");
m_ProjectFolderToScan = EditorGUILayout.TextField("Folder Path: replacedets/", m_ProjectFolderToScan);
GUILayout.Space(5f);
GUI.enabled = m_IsAlreadyScanningProject == false ? true : false;
if (GUILayout.Button("Scan Project Files"))
{
m_CancelScanProcess = false;
// Make sure replacedet Serialization mode is set to ForceText and Version Control mode to Visible Meta Files.
if (CheckProjectSerializationAndSourceControlModes() == true)
{
m_ProjectPath = Path.GetFullPath("replacedets/..");
TMP_EditorCoroutine.StartCoroutine(ScanProjectFiles());
}
else
{
EditorUtility.DisplayDialog("Project Settings Change Required", "In menu options \"Edit - Project Settings - Editor\", please change replacedet Serialization Mode to ForceText and Source Control Mode to Visible Meta Files.", "OK", string.Empty);
}
}
GUI.enabled = true;
// Display progress bar
Rect rect = GUILayoutUtility.GetRect(0f, 20f, GUILayout.ExpandWidth(true));
EditorGUI.ProgressBar(rect, m_ProgressPercentage, "Scan Progress (" + m_ScanningCurrentFileIndex + "/" + m_ScanningTotalFiles + ")");
// Display cancel button and name of file currently being scanned.
if (m_IsAlreadyScanningProject)
{
Rect cancelRect = new Rect(rect.width - 20, rect.y + 2, 20, 16);
if (GUI.Button(cancelRect, "X"))
{
m_CancelScanProcess = true;
}
GUILayout.Label(k_ProjectScanLabelPrefix + m_ScanningCurrentFileName, TMP_UIStyleManager.label);
}
else
GUILayout.Label(string.Empty);
GUILayout.Space(5);
// Creation Feedback
GUILayout.BeginVertical(TMP_UIStyleManager.textAreaBoxWindow, GUILayout.ExpandHeight(true));
{
m_ProjectScanResultScrollPosition = EditorGUILayout.BeginScrollView(m_ProjectScanResultScrollPosition, GUILayout.ExpandHeight(true));
EditorGUILayout.LabelField(m_ProjectScanResults, TMP_UIStyleManager.label);
EditorGUILayout.EndScrollView();
}
GUILayout.EndVertical();
GUILayout.Space(5f);
}
GUILayout.EndVertical();
// Scan project files and resources
GUILayout.BeginVertical(EditorStyles.helpBox);
{
GUILayout.Label("Save Modified Project Files", EditorStyles.boldLabel);
GUILayout.Label("Pressing the <i>Save Modified Project Files</i> button will update the files in the <i>Project Scan Results</i> listed above. <color=#FFFF80>Please make sure that you have created a backup of your project first</color> as these file modifications are permanent and cannot be undone.", TMP_UIStyleManager.label);
GUILayout.Space(5f);
GUI.enabled = m_IsAlreadyScanningProject == false && m_ModifiedreplacedetList.Count > 0 ? true : false;
if (GUILayout.Button("Save Modified Project Files"))
{
UpdateProjectFiles();
}
GUILayout.Space(10f);
}
GUILayout.EndVertical();
}
GUILayout.EndVertical();
GUILayout.Space(5f);
}
19
Source : TMP_PackageUtilities.cs
with MIT License
from Alword
with MIT License
from Alword
private static void ExtractPackageGUIDs()
{
// Make sure replacedet Serialization mode is set to ForceText with Visible Meta Files.
SetProjectSerializationAndSourceControlModes();
string projectPath = Path.GetFullPath("replacedets/..");
// Create new instance of replacedetConversionData file
replacedetConversionData data = new replacedetConversionData();
data.replacedetRecords = new List<replacedetConversionRecord>();
// Get full list of GUIDs used in the package which including folders.
string[] packageGUIDs = replacedetDatabase.Findreplacedets("t:Object", new string[] { "replacedets/Packages/com.unity.TextMeshPro" });
for (int i = 0; i < packageGUIDs.Length; i++)
{
// Could add a progress bar for this process (if needed)
string guid = packageGUIDs[i];
string replacedetFilePath = replacedetDatabase.GUIDToreplacedetPath(guid);
//string replacedetMetaFilePath = replacedetDatabase.GetTextMetaFilePathFromreplacedetPath(replacedetFilePath);
//ObjectIdentifier[] localIdentifider = BundleBuildInterface.GetPlayerObjectIdentifiersInreplacedet(new GUID(guid), BuildTarget.NoTarget);
//System.Type[] types = BundleBuildInterface.GetTypeForObjects(localIdentifider);
System.Type replacedetType = replacedetDatabase.GetMainreplacedetTypeAtPath(replacedetFilePath);
// Filter out file types we are not interested in
if (replacedetType == typeof(Defaultreplacedet))
continue;
string newGuid = GenerateUniqueGUID();
replacedetConversionRecord record;
record.referencedResource = Path.GetFileName(replacedetFilePath);
record.target = "fileID: 2108210716, guid: " + newGuid;
record.replacement = "fileID: 11500000, guid: " + guid;
//if (m_replacedetRecords.FindIndex(item => item.oldGuid == guid) != -1)
// continue;
data.replacedetRecords.Add(record);
// Read the meta file for the given replacedet.
//string replacedetMetaFile = File.ReadAllText(projectPath + "/" + replacedetMetaFilePath);
//replacedetMetaFile = replacedetMetaFile.Replace("guid: " + guid, "guid: " + newGUID);
//File.WriteAllText(projectPath + "/" + replacedetMetaFilePath, replacedetMetaFile);
Debug.Log("replacedet: [" + Path.GetFileName(replacedetFilePath) + "] Type: " + replacedetType + " Current GUID: [" + guid + "] New GUID: [" + newGuid + "]");
}
// Write new information into JSON file
string dataFile = JsonUtility.ToJson(data, true);
File.WriteAllText(projectPath + "/replacedets/Packages/com.unity.TextMeshPro/PackageConversionData.json", dataFile);
// Restore project replacedet Serialization and Source Control modes.
RestoreProjectSerializationAndSourceControlModes();
}
19
Source : TMP_PostBuildProcessHandler.cs
with MIT License
from Alword
with MIT License
from Alword
private static string GetEssentialProjectResourcesPath()
{
// Find the potential location of the TextMesh Pro folder in the user project.
string projectPath = Path.GetFullPath("replacedets/..");
if (Directory.Exists(projectPath))
{
// Search for default location of TMP Essential Resources
if (Directory.Exists(projectPath + "/replacedets/TextMesh Pro/Resources"))
{
return "replacedets/TextMesh Pro";
}
// Search for potential alternative locations in the user project
string[] matchingPaths = Directory.GetDirectories(projectPath, "TextMesh Pro", SearchOption.AllDirectories);
projectPath = ValidateLocation(matchingPaths, projectPath);
if (projectPath != null) return projectPath;
}
return null;
}
19
Source : TMP_PackageUtilities.cs
with MIT License
from Alword
with MIT License
from Alword
private static void UpdateProjectFiles()
{
// Make sure replacedet Serialization mode is set to ForceText with Visible Meta Files.
CheckProjectSerializationAndSourceControlModes();
string projectPath = Path.GetFullPath("replacedets/..");
// Display dialogue to show user a list of project files that will be modified upon their consent.
if (EditorUtility.DisplayDialog("Save Modified replacedet(s)?", "Are you sure you want to save all modified replacedets?", "YES", "NO"))
{
for (int i = 0; i < m_ModifiedreplacedetList.Count; i++)
{
// Make sure all file streams that might have been opened by Unity are closed.
//replacedetDatabase.ReleaseCachedFileHandles();
//Debug.Log("Writing replacedet file [" + m_ModifiedreplacedetList[i].replacedetFilePath + "].");
File.WriteAllText(projectPath + "/" + m_ModifiedreplacedetList[i].replacedetFilePath, m_ModifiedreplacedetList[i].replacedetDataFile);
}
}
replacedetDatabase.Refresh();
m_ProgressPercentage = 0;
m_ProjectScanResults = k_ProjectScanReportDefaultText;
}
19
Source : TMP_PackageUtilities.cs
with MIT License
from Alword
with MIT License
from Alword
private static void GenerateNewPackageGUIDs()
{
// Make sure replacedet Serialization mode is set to ForceText with Visible Meta Files.
SetProjectSerializationAndSourceControlModes();
string projectPath = Path.GetFullPath("replacedets/..");
// Clear existing dictionary of replacedetRecords
List<replacedetRemappingRecord> replacedetRecords = new List<replacedetRemappingRecord>();
// Get full list of GUIDs used in the package which including folders.
string[] packageGUIDs = replacedetDatabase.Findreplacedets("t:Object", new string[] { "replacedets/Packages/com.unity.TextMeshPro" });
for (int i = 0; i < packageGUIDs.Length; i++)
{
// Could add a progress bar for this process (if needed)
string guid = packageGUIDs[i];
string replacedetFilePath = replacedetDatabase.GUIDToreplacedetPath(guid);
string replacedetMetaFilePath = replacedetDatabase.GetTextMetaFilePathFromreplacedetPath(replacedetFilePath);
//System.Type replacedetType = replacedetDatabase.GetMainreplacedetTypeAtPath(replacedetFilePath);
replacedetRemappingRecord replacedetRecord;
replacedetRecord.oldGuid = guid;
replacedetRecord.replacedetPath = replacedetFilePath;
string newGUID = GenerateUniqueGUID();
replacedetRecord.newGuid = newGUID;
if (replacedetRecords.FindIndex(item => item.oldGuid == guid) != -1)
continue;
replacedetRecords.Add(replacedetRecord);
// Read the meta file for the given replacedet.
string replacedetMetaFile = File.ReadAllText(projectPath + "/" + replacedetMetaFilePath);
replacedetMetaFile = replacedetMetaFile.Replace("guid: " + guid, "guid: " + newGUID);
File.WriteAllText(projectPath + "/" + replacedetMetaFilePath, replacedetMetaFile);
//Debug.Log("replacedet: [" + replacedetFilePath + "] Type: " + replacedetType + " Current GUID: [" + guid + "] New GUID: [" + newGUID + "]");
}
replacedetDatabase.Refresh();
// Get list of GUIDs for replacedets that might need references to previous GUIDs which need to be updated.
packageGUIDs = replacedetDatabase.Findreplacedets("t:Object"); // ("t:Object", new string[] { "replacedets/replacedet Importer" });
for (int i = 0; i < packageGUIDs.Length; i++)
{
// Could add a progress bar for this process
string guid = packageGUIDs[i];
string replacedetFilePath = replacedetDatabase.GUIDToreplacedetPath(guid);
System.Type replacedetType = replacedetDatabase.GetMainreplacedetTypeAtPath(replacedetFilePath);
// Filter out file types we are not interested in
if (replacedetType == typeof(Defaultreplacedet) || replacedetType == typeof(MonoScript) || replacedetType == typeof(Texture2D) || replacedetType == typeof(Textreplacedet) || replacedetType == typeof(Shader))
continue;
// Read the replacedet data file
string replacedetDataFile = File.ReadAllText(projectPath + "/" + replacedetFilePath);
//Debug.Log("Searching replacedet: [" + replacedetFilePath + "] of type: " + replacedetType);
bool hasFileChanged = false;
foreach (replacedetRemappingRecord record in replacedetRecords)
{
if (replacedetDataFile.Contains(record.oldGuid))
{
hasFileChanged = true;
replacedetDataFile = replacedetDataFile.Replace(record.oldGuid, record.newGuid);
Debug.Log("Replacing old GUID: [" + record.oldGuid + "] by new GUID: [" + record.newGuid + "] in replacedet file: [" + replacedetFilePath + "].");
}
}
if (hasFileChanged)
{
// Add file to list of changed files
File.WriteAllText(projectPath + "/" + replacedetFilePath, replacedetDataFile);
}
}
replacedetDatabase.Refresh();
// Restore project replacedet Serialization and Source Control modes.
RestoreProjectSerializationAndSourceControlModes();
}
19
Source : TMP_PackageUtilities.cs
with MIT License
from Alword
with MIT License
from Alword
private static void ConvertProjectGUIDsToUPM()
{
// Make sure replacedet Serialization mode is set to ForceText with Visible Meta Files.
SetProjectSerializationAndSourceControlModes();
string projectPath = Path.GetFullPath("replacedets/..");
string packageFullPath = EditorUtilities.TMP_EditorUtility.packageFullPath;
// List containing replacedets that have been modified.
List<replacedetModificationRecord> modifiedreplacedetList = new List<replacedetModificationRecord>();
// Read Conversion Data from Json file.
replacedetConversionData conversionData = JsonUtility.FromJson<replacedetConversionData>(File.ReadAllText(packageFullPath + "/PackageConversionData.json"));
// Get list of GUIDs for replacedets that might contain references to previous GUIDs that require updating.
string[] projectGUIDs = replacedetDatabase.Findreplacedets("t:Object");
for (int i = 0; i < projectGUIDs.Length; i++)
{
// Could add a progress bar for this process
string guid = projectGUIDs[i];
string replacedetFilePath = replacedetDatabase.GUIDToreplacedetPath(guid);
System.Type replacedetType = replacedetDatabase.GetMainreplacedetTypeAtPath(replacedetFilePath);
// Filter out file types we are not interested in
if (replacedetType == typeof(Defaultreplacedet) || replacedetType == typeof(MonoScript) || replacedetType == typeof(Texture2D) || replacedetType == typeof(Textreplacedet) || replacedetType == typeof(Shader))
continue;
// Read the replacedet data file
string replacedetDataFile = File.ReadAllText(projectPath + "/" + replacedetFilePath);
//Debug.Log("Searching replacedet: [" + replacedetFilePath + "] of type: " + replacedetType);
bool hasFileChanged = false;
foreach (replacedetConversionRecord record in conversionData.replacedetRecords)
{
if (replacedetDataFile.Contains(record.target))
{
hasFileChanged = true;
replacedetDataFile = replacedetDataFile.Replace(record.target, record.replacement);
Debug.Log("Replacing Reference to [" + record.referencedResource + "] using [" + record.target + "] with [" + record.replacement + "] in replacedet file: [" + replacedetFilePath + "].");
}
}
if (hasFileChanged)
{
Debug.Log("Adding [" + replacedetFilePath + "] to list of replacedets to be modified.");
replacedetModificationRecord modifiedreplacedet;
modifiedreplacedet.replacedetFilePath = replacedetFilePath;
modifiedreplacedet.replacedetDataFile = replacedetDataFile;
modifiedreplacedetList.Add(modifiedreplacedet);
}
}
// Scan project meta files to update GUIDs of replacedets whose GUID has changed.
projectGUIDs = replacedetDatabase.Findreplacedets("t:Object");
for (int i = 0; i < projectGUIDs.Length; i++)
{
string guid = projectGUIDs[i];
string replacedetFilePath = replacedetDatabase.GUIDToreplacedetPath(guid);
string replacedetMetaFilePath = replacedetDatabase.GetTextMetaFilePathFromreplacedetPath(replacedetFilePath);
// Read the replacedet meta data file
string replacedetMetaFile = File.ReadAllText(projectPath + "/" + replacedetMetaFilePath);
bool hasFileChanged = false;
foreach (replacedetConversionRecord record in conversionData.replacedetRecords)
{
if (replacedetMetaFile.Contains(record.target))
{
hasFileChanged = true;
replacedetMetaFile = replacedetMetaFile.Replace(record.target, record.replacement);
Debug.Log("Replacing Reference to [" + record.referencedResource + "] using [" + record.target + "] with [" + record.replacement + "] in replacedet file: [" + replacedetMetaFilePath + "].");
}
}
if (hasFileChanged)
{
Debug.Log("Adding [" + replacedetMetaFilePath + "] to list of meta files to be modified.");
replacedetModificationRecord modifiedreplacedet;
modifiedreplacedet.replacedetFilePath = replacedetMetaFilePath;
modifiedreplacedet.replacedetDataFile = replacedetMetaFile;
modifiedreplacedetList.Add(modifiedreplacedet);
}
}
// Display dialogue to show user a list of project files that will be modified upon their consent.
if (EditorUtility.DisplayDialog("Save Modified replacedet(s)?", "Are you sure you want to save all modified replacedets?", "YES", "NO"))
{
for (int i = 0; i < modifiedreplacedetList.Count; i++)
{
// Make sure all file streams that might have been opened by Unity are closed.
//replacedetDatabase.ReleaseCachedFileHandles();
Debug.Log("Writing replacedet file [" + modifiedreplacedetList[i].replacedetFilePath + "].");
//File.WriteAllText(projectPath + "/" + modifiedreplacedetList[i].replacedetFilePath, modifiedreplacedetList[i].replacedetDataFile);
}
}
replacedetDatabase.Refresh();
// Restore project replacedet Serialization and Source Control modes.
RestoreProjectSerializationAndSourceControlModes();
}
19
Source : TMP_EditorTests.cs
with MIT License
from Alword
with MIT License
from Alword
[OneTimeSetUp]
public void Setup()
{
if (Directory.Exists(Path.GetFullPath("replacedets/TextMesh Pro")) || Directory.Exists(Path.GetFullPath("Packages/com.unity.textmeshpro.tests/TextMesh Pro")))
{
GameObject textObject = new GameObject("Text Object");
m_TextComponent = textObject.AddComponent<TextMeshPro>();
m_TextComponent.fontSize = 18;
}
else
{
Debug.Log("Skipping over Editor tests as TMP Essential Resources are missing from the current test project.");
replacedert.Ignore();
return;
}
}
19
Source : JoplinExportService.cs
with GNU General Public License v3.0
from alxnbl
with GNU General Public License v3.0
from alxnbl
private void ExportSection(Node section, string pageNameFilter = "")
{
var sectionMdFileContent = AddJoplinNodeMetadata(section, "");
var notebookFolder = section.GetNotebookPath();
string onExportFolder;
if(_appSettings.UserTempFolder)
{
onExportFolder = Path.GetTempPath();
}
else
{
onExportFolder = Path.Combine("tmp", notebookFolder);
Directory.CreateDirectory(onExportFolder);
}
// Write Section Md File
File.WriteAllText(Path.Combine(notebookFolder, $"{section.Id}.md"), sectionMdFileContent);
if (section is Section sectionNode && !sectionNode.IsSectionGroup)
{
// For leaf section, export pages
Log.Debug($"Start export pages of section {section.replacedle}");
var pages = _oneNoteApp.GetPages(sectionNode).Where(p => string.IsNullOrEmpty(pageNameFilter) || p.replacedle == pageNameFilter).ToList();
var resourceFolderPath = Path.Combine(notebookFolder, "resources");
Directory.CreateDirectory(resourceFolderPath);
int cmpt = 0;
foreach (Page page in pages)
{
Log.Information($" Page {++cmpt}/{pages.Count} : {page.replacedleWithPageLevelTabulation}");
var docxFilePath = Path.Combine(onExportFolder, page.Id + ".docx");
try
{
File.Delete(docxFilePath);
Log.Debug($"{page.OneNoteId}: start OneNote docx publish");
_oneNoteApp.Publish(page.OneNoteId, Path.GetFullPath(docxFilePath), PublishFormat.pfWord);
Log.Debug($"{page.OneNoteId}: success");
var mdFilePath = Path.Combine(notebookFolder, $"{page.Id}.md");
// Convert docx file into Md using PanDoc
var pageMdFileContent = _convertServer.ConvertDocxToMd(page, docxFilePath, resourceFolderPath, section.GetLevel());
try
{
// Copy images extracted from DocX to Export folder and add them in list of attachments of the note
pageMdFileContent = _convertServer.ExtractImagesToResourceFolder(page, pageMdFileContent, resourceFolderPath, mdFilePath, true, _appSettings.PostProcessingMdImgRef);
}
catch (Exception ex)
{
Log.Warning($"Page '{page.GetPageFileRelativePath()}': {Localizer.GetString("ErrorImageExtract")}");
Log.Debug(ex, ex.Message);
}
// Export all page attachments
pageMdFileContent = ExportPageAttachments(page, pageMdFileContent, notebookFolder, resourceFolderPath);
// Apply post processing to Page Md content
pageMdFileContent = _convertServer.PostConvertion(page, pageMdFileContent, resourceFolderPath, mdFilePath, true);
pageMdFileContent = AddJoplinNodeMetadata(page, pageMdFileContent);
// Create page md file
File.WriteAllText(mdFilePath, pageMdFileContent);
if (!_appSettings.Debug)
{
File.Delete(docxFilePath);
}
}
catch (Exception ex)
{
Log.Error(ex, Localizer.GetString("ErrorDuringPageProcessing"), page.replacedleWithPageLevelTabulation, page.Id, ex.Message);
}
}
}
}
19
Source : MdExportService.cs
with GNU General Public License v3.0
from alxnbl
with GNU General Public License v3.0
from alxnbl
private void ExportSection(Node section, string pageNameFilter="")
{
if (!(section is Section sectionNote) || sectionNote.IsSectionGroup)
throw new InvalidOperationException("Cannot call ExportSection on section group with MdExport");
var pages = _oneNoteApp.GetPages(sectionNote).Where(p => string.IsNullOrEmpty(pageNameFilter) || p.replacedle == pageNameFilter).ToList();
var resourceFolderPath = Path.Combine(section.GetNotebookPath(), "_resources");
Directory.CreateDirectory(resourceFolderPath);
int cmpt = 0;
foreach (Page page in pages)
{
try
{
Log.Information($" Page {++cmpt}/{pages.Count} : {page.replacedleWithPageLevelTabulation}");
Directory.CreateDirectory(page.GetPageFolderRelativePath());
var docxFilePath = page.GetPageFileRelativePath() + ".docx";
File.Delete(docxFilePath);
_oneNoteApp.Publish(page.OneNoteId, Path.GetFullPath(docxFilePath), PublishFormat.pfWord);
var mdFileContent = _convertServer.ConvertDocxToMd(page, docxFilePath, resourceFolderPath, section.GetLevel());
var mdFilePath = page.GetPageFileRelativePath() + ".md";
try
{
mdFileContent = _convertServer.ExtractImagesToResourceFolder(page, mdFileContent, resourceFolderPath, mdFilePath, false, _appSettings.PostProcessingMdImgRef);
}
catch (Exception ex)
{
if (_appSettings.Debug)
Log.Warning($"Page '{page.GetPageFileRelativePath()}': {Localizer.GetString("ErrorImageExtract")}");
else
Log.Warning(ex, $"Page '{page.GetPageFileRelativePath()}'.");
}
mdFileContent = _convertServer.PostConvertion(page, mdFileContent, resourceFolderPath, mdFilePath, false);
File.WriteAllText(mdFilePath, mdFileContent);
}
catch (Exception e)
{
Log.Error(Localizer.GetString("ErrorDuringPageProcessing"), page.replacedleWithPageLevelTabulation, page.Id, e.Message);
}
}
}
19
Source : ConverterService.cs
with GNU General Public License v3.0
from alxnbl
with GNU General Public License v3.0
from alxnbl
public string ConvertDocxToMd(Page page, string inputFilePath, string resourceFolderPath, int sectionTreeLevel)
{
var mdFilePath = Path.Combine("tmp", page.replacedleWithNoInvalidChars + ".md");
var arguments = $"\"{Path.GetFullPath(inputFilePath)}\" " +
$"--to gfm " +
$"-o \"{Path.GetFullPath(mdFilePath)}\" " +
$"--wrap=none " + // Mandatory to avoid random quote bloc to be added to markdown
$"--extract-media=\"tmp\"";
var startInfo = new ProcessStartInfo
{
FileName = "pandoc.exe",
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
Log.Debug($"{page.Id} : Start Pandoc");
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
if(exeProcess.ExitCode == 0)
{
Log.Debug($"{page.Id} : Pandoc success");
}
else
{
Log.Error($"{page.Id} : Pandoc error");
var pandocError = exeProcess.StandardError.ReadToEnd();
Log.Error("Pandoc error output: {0}", pandocError);
}
if (_appSettings.Debug)
{
Log.Debug($"Pandoc output: {exeProcess.StandardOutput.ReadToEnd()}");
}
}
var mdFileContent = File.ReadAllText(mdFilePath);
if (!_appSettings.Debug)
File.Delete(inputFilePath);
return mdFileContent;
}
19
Source : Program.cs
with GNU General Public License v3.0
from alxnbl
with GNU General Public License v3.0
from alxnbl
private static void RunOptions(Options opts)
{
var appSettings = AppSettings.LoadAppSettings();
appSettings.Debug = opts.Debug;
InitLogger();
OneNoteApp = new OneNote.Application();
WelcomeScreen(opts);
IList<Notebook> notebookToProcess;
if (!opts.AllNotebooks)
{
if (string.IsNullOrEmpty(opts.NotebookName))
{
// Request user to select notebooks to export
notebookToProcess = NotebookSelectionForm();
}
else
{
// Notebook name provided in args
notebookToProcess = GetNotebookFromName(opts.NotebookName);
}
}
else
{
// if all-notebooks specified get all notebooks.
notebookToProcess = OneNoteApp.GetNotebooks();
}
if (notebookToProcess.Count == 0)
return;
ExportFormat exportFormat = ExportFormatSelectionForm(opts.ExportFormat);
if (exportFormat == ExportFormat.Undefined)
return;
var exportService = ExportServiceFactory.GetExportService(exportFormat, appSettings, OneNoteApp);
foreach (Notebook notebook in notebookToProcess)
{
Log.Information("\n***************************************");
Log.Information(Localizer.GetString("StartExportingNotebook"), notebook.replacedle);
Log.Information("***************************************");
exportService.ExportNotebook(notebook, opts.SectionName, opts.PageName);
var exportPath = Path.GetFullPath(notebook.replacedle);
Log.Information("");
Log.Information(Localizer.GetString("ExportSuccessful"), exportPath);
Log.Information("");
}
if (!opts.NoInput)
{
Log.Information(Localizer.GetString("EndOfExport"));
Console.ReadLine();
}
}
19
Source : Guard.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
protected void InitInstance(string argument)
{
Instance = new Process
{
StartInfo =
{
FileName = Path.GetFullPath($"bin\\{MainFile}"),
WorkingDirectory = $"{Global.NetchDir}\\bin",
Arguments = argument,
CreateNoWindow = true,
UseShellExecute = !RedirectStd,
RedirectStandardOutput = RedirectStd,
StandardOutputEncoding = RedirectStd ? InstanceOutputEncoding : null,
RedirectStandardError = RedirectStd,
StandardErrorEncoding = RedirectStd ? InstanceOutputEncoding : null,
WindowStyle = ProcessWindowStyle.Hidden
}
};
}
19
Source : Program.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
public static void Main(string[] args)
{
var result = false;
try
{
#region Check Arguments
if (CurrentProcess.MainModule == null)
{
Console.WriteLine("Current Process MainModule is null");
return;
}
if (args.Length != 3)
{
Console.WriteLine("The program is not user-oriented\n此程序不是面向用户的");
return;
}
// arg0 port
if (!int.TryParse(args[0], out var port))
{
Console.WriteLine("arg0 Port Parse failed");
return;
}
var updateExtracted = true;
// arg1 update File/Directory
var updatePath = Path.GetFullPath(args[1]);
if (File.Exists(updatePath))
{
updateExtracted = false;
}
else if (!Directory.Exists(updatePath))
{
Console.WriteLine("arg1 update file/directory Not found");
return;
}
// arg2 target Directory
string targetPath;
if (!File.Exists(Path.Combine(targetPath = Path.GetFullPath(args[2]), "Netch.exe")))
{
Console.Write("arg2 Netch Directory doesn't seems right");
return;
}
#region if under target Directory,then rerun in temp directory
if (UpdaterDirectory.StartsWith(targetPath))
{
// Updater 在目标目录下
// 将程序复制到临时目录,传递参数
var tempPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
var newUpdaterPath = Path.Combine(tempPath, UpdaterFriendlyName);
Directory.CreateDirectory(tempPath);
File.Copy(UpdaterFullName, newUpdaterPath);
Process.Start(new ProcessStartInfo
{
FileName = newUpdaterPath,
Arguments = $"{port} \"{updatePath}\" \"{targetPath}\"",
WorkingDirectory = tempPath,
UseShellExecute = false
});
result = true;
return;
}
#endregion
#endregion
/*Console.WriteLine("Waiting Attach");
while (!Debugger.IsAttached)
{
Thread.Sleep(1000);
}*/
#region Send Netch Exit command
Process[] _;
if ((_ = Process.GetProcessesByName("Netch")).Any())
{
Console.WriteLine("Found Netch process, Send exit command");
try
{
var udpClient = new UdpClient("127.0.0.1", port);
var sendBytes = Encoding.ASCII.GetBytes("Exit");
udpClient.Send(sendBytes, sendBytes.Length);
}
catch
{
Console.WriteLine("Send command failed");
return;
}
foreach (var proc in _)
{
try
{
proc.WaitForExit();
}
catch (Exception)
{
// ignored
}
}
}
#endregion
var counter = 0;
while (!TestFileFree(Path.Combine(targetPath, "Netch.exe")))
{
// wait 5 sec
if (counter > 25)
{
Console.WriteLine("Waiting Netch exit timeout");
return;
}
Thread.Sleep(200);
counter++;
}
#region Update
string extractPath = null;
if (!updateExtracted)
{
extractPath = Path.Combine(UpdaterDirectory, "extract");
Extract(updatePath, extractPath, true);
var netchExeFileInfo = FindFile("Netch.exe", extractPath);
if (netchExeFileInfo == null)
{
throw new Exception("Netch.exe not found in archive!");
}
updatePath = netchExeFileInfo.Directory.FullName;
}
MoveDirectory(updatePath, targetPath, true);
try
{
if (extractPath != null)
Directory.Delete(extractPath, true);
}
catch
{
// ignored
}
#endregion
#region Finished Update,Start Netch
Console.WriteLine("Start Netch");
Process.Start(new ProcessStartInfo
{
FileName = Path.Combine(targetPath, "Netch.exe"),
UseShellExecute = true,
});
#endregion
result = true;
}
catch (Exception e)
{
if (e is InvalidDataException)
Console.WriteLine("Archive file Broken");
Console.WriteLine(e.ToString());
}
finally
{
if (!result)
{
Console.WriteLine("Press any key to exit...");
Console.Read();
}
}
}
19
Source : Program.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
private static void Extract(string archiveFileName, string destDirName, bool overwrite)
{
archiveFileName = Path.GetFullPath(archiveFileName);
destDirName = Path.GetFullPath(destDirName);
if (!File.Exists("7za.exe"))
File.WriteAllBytes("7za.exe", Resources._7za);
var argument = new StringBuilder();
argument.Append($" x \"{archiveFileName}\" -o\"{destDirName}\" ");
if (overwrite)
argument.Append(" -y ");
Process.Start(new ProcessStartInfo
{
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden,
FileName = Path.GetFullPath("7za.exe"),
Arguments = argument.ToString()
})?.WaitForExit();
}
19
Source : Program.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
private static void MoveDirectory(string sourceDirName, string destDirName, bool overwrite)
{
sourceDirName = Path.GetFullPath(sourceDirName);
destDirName = Path.GetFullPath(destDirName);
if (!overwrite)
{
Directory.Move(sourceDirName, destDirName);
}
else
{
var dirStack = new Stack<string>();
dirStack.Push(sourceDirName);
while (dirStack.Count > 0)
{
var dirInfo = new DirectoryInfo(dirStack.Pop());
try
{
foreach (var dirChildInfo in dirInfo.GetDirectories())
{
var destPath = dirChildInfo.FullName.Replace(sourceDirName, destDirName);
try
{
if (!Directory.Exists(destPath))
{
Directory.CreateDirectory(destPath);
}
}
catch (Exception e)
{
Console.WriteLine($"Create {destPath} Folder Error: {e.Message}");
}
dirStack.Push(dirChildInfo.FullName);
}
foreach (var fileChildInfo in dirInfo.GetFiles())
{
var destPath = fileChildInfo.FullName.Replace(sourceDirName, destDirName);
try
{
if (File.Exists(destPath))
{
File.Delete(destPath);
}
fileChildInfo.MoveTo(destPath);
}
catch (Exception e)
{
Console.WriteLine($"Move {fileChildInfo.FullName} To {destPath} Error: {e.Message}");
}
}
}
catch (Exception e)
{
Console.WriteLine($"ERROR:{e.Message}");
}
}
}
}
19
Source : DNSController.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
public bool Start()
{
aiodns_dial((int) NameList.TYPE_REST, null);
aiodns_dial((int) NameList.TYPE_ADDR, Encoding.UTF8.GetBytes($"{Global.Settings.LocalAddress}:53"));
aiodns_dial((int) NameList.TYPE_LIST, Encoding.UTF8.GetBytes(Path.GetFullPath(Global.Settings.AioDNS.RulePath)));
aiodns_dial((int) NameList.TYPE_CDNS, Encoding.UTF8.GetBytes($"{Global.Settings.AioDNS.ChinaDNS}:53"));
aiodns_dial((int) NameList.TYPE_ODNS, Encoding.UTF8.GetBytes($"{Global.Settings.AioDNS.OtherDNS}:53"));
aiodns_dial((int) NameList.TYPE_METH, Encoding.UTF8.GetBytes(Global.Settings.AioDNS.Protocol));
return aiodns_init();
}
19
Source : Firewall.cs
with MIT License
from AmazingDM
with MIT License
from AmazingDM
public static void AddNetchFwRules()
{
try
{
if (GetFwRulePath(Netch).StartsWith(Global.NetchDir) && GetFwRulesNumber(Netch) >= ProgramPath.Length) return;
RemoveNetchFwRules();
foreach (var p in ProgramPath)
{
var path = Path.GetFullPath(p);
if (File.Exists(path))
{
AddFwRule("Netch", path);
}
}
}
catch (Exception e)
{
Logging.Warning("添加防火墙规则错误(如已关闭防火墙则可无视此错误)\n" + e);
}
}
19
Source : SelfUpdateProgressPage.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public override void OnActivate()
{
base.OnActivate();
// Setup self-update.
var selfUpdate = new BackgroundWorker() { WorkerReportsProgress = true };
selfUpdate.DoWork += (object sender, DoWorkEventArgs e) =>
{
selfUpdate.ReportProgress(0);
var random = new Random();
var tempFolder = Path.GetTempPath();
var workingFolder = tempFolder + Path.GetRandomFileName() + "\\";
Directory.CreateDirectory(workingFolder);
try
{
string installerFilename = null;
FileStream installerFile = null;
// Download installer.
while (DownloadUris.Count > 0)
{
Window.Abort.Token.ThrowIfCancellationRequested();
var uriIndex = random.Next(DownloadUris.Count);
try
{
var binaryUri = DownloadUris[uriIndex];
Trace.TraceInformation("Downloading installer file from {0}...", binaryUri.AbsoluteUri);
var request = WebRequest.Create(binaryUri);
request.Proxy = null;
using (var response = request.GetResponse())
{
// 1. Get installer filename from Content-Disposition header.
// 2. Get installer filename from the last segment of URI path.
// 3. Fallback to a predefined installer filename.
try { installerFilename = Path.GetFullPath(workingFolder + new ContentDisposition(request.Headers["Content-Disposition"]).FileName); }
catch
{
try { installerFilename = Path.GetFullPath(workingFolder + binaryUri.Segments[binaryUri.Segments.Length - 1]); }
catch { installerFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup.exe"); }
}
// Save response data to file.
installerFile = File.Open(installerFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
try
{
using (var stream = response.GetResponseStream())
{
installerFile.Seek(0, SeekOrigin.Begin);
var hash = new eduEd25519.SHA256();
var buffer = new byte[1048576];
long offset = 0, total = response.ContentLength;
for (; ; )
{
// Wait for the data to arrive.
Window.Abort.Token.ThrowIfCancellationRequested();
var bufferLength = stream.Read(buffer, 0, buffer.Length);
if (bufferLength == 0)
break;
//Window.Abort.Token.WaitHandle.WaitOne(100); // Mock a slow link for testing.
// Append it to the file and hash it.
Window.Abort.Token.ThrowIfCancellationRequested();
installerFile.Write(buffer, 0, bufferLength);
hash.TransformBlock(buffer, 0, bufferLength, buffer, 0);
// Report progress.
offset += bufferLength;
selfUpdate.ReportProgress((int)(offset * 100 / total));
}
hash.TransformFinalBlock(buffer, 0, 0);
if (!hash.Hash.SequenceEqual(Hash))
throw new DownloadedFileCorruptException(string.Format(Resources.Strings.ErrorDownloadedFileCorrupt, binaryUri.AbsoluteUri));
installerFile.SetLength(installerFile.Position);
break;
}
}
catch
{
// Close installer file.
installerFile.Close();
installerFile = null;
// Delete installer file. If possible.
Trace.TraceInformation("Deleting file {0}...", installerFilename);
try { File.Delete(installerFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
installerFilename = null;
throw;
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
Trace.TraceWarning("Error: {0}", ex.ToString());
DownloadUris.RemoveAt(uriIndex);
}
}
if (installerFilename == null || installerFile == null)
{
// The installer file is not ready.
throw new InstallerFileUnavailableException();
}
try
{
var updaterFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup and Relaunch.wsf");
var updaterFile = File.Open(updaterFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
try
{
// Prepare WSF file.
var writer = new XmlTextWriter(updaterFile, null);
writer.WriteStartDoreplacedent();
writer.WriteStartElement("package");
writer.WriteStartElement("job");
writer.WriteStartElement("reference");
writer.WriteAttributeString("object", "WScript.Shell");
writer.WriteEndElement(); // reference
writer.WriteStartElement("reference");
writer.WriteAttributeString("object", "Scripting.FileSystemObject");
writer.WriteEndElement(); // reference
writer.WriteStartElement("script");
writer.WriteAttributeString("language", "JScript");
var installerArgumentsEsc = string.IsNullOrEmpty(Arguments) ? "" : " " + HttpUtility.JavaScriptStringEncode(Arguments);
var argv = Environment.GetCommandLineArgs();
var arguments = new StringBuilder();
for (long i = 1, n = argv.LongLength; i < n; i++)
{
if (i > 1) arguments.Append(" ");
arguments.Append("\"");
arguments.Append(argv[i].Replace("\"", "\"\""));
arguments.Append("\"");
}
var script = new StringBuilder();
script.AppendLine("var wsh = WScript.CreateObject(\"WScript.Shell\");");
script.AppendLine("wsh.Run(\"\\\"" + HttpUtility.JavaScriptStringEncode(installerFilename.Replace("\"", "\"\"")) + "\\\"" + installerArgumentsEsc + "\", 0, true);");
script.AppendLine("var fso = WScript.CreateObject(\"Scripting.FileSystemObject\");");
script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(installerFilename) + "\", true); } catch (err) {}");
script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(updaterFilename) + "\", true); } catch (err) {}");
script.AppendLine("try { fso.DeleteFolder(\"" + HttpUtility.JavaScriptStringEncode(workingFolder.TrimEnd(Path.DirectorySeparatorChar)) + "\", true); } catch (err) {}");
writer.WriteCData(script.ToString());
writer.WriteEndElement(); // script
writer.WriteEndElement(); // job
writer.WriteEndElement(); // package
writer.WriteEndDoreplacedent();
writer.Flush();
// Prepare WSF launch parameters.
Trace.TraceInformation("Launching update script file {0}...", updaterFilename);
var process = new Process();
process.StartInfo.FileName = "wscript.exe";
process.StartInfo.Arguments = "\"" + updaterFilename + "\"";
process.StartInfo.WorkingDirectory = workingFolder;
// Close WSF and installer files as late as possible to narrow the attack window.
// If Windows supported executing files that are locked for writing, we could leave those files open.
updaterFile.Close();
installerFile.Close();
process.Start();
}
catch
{
// Close WSF file.
updaterFile.Close();
// Delete WSF file. If possible.
Trace.TraceInformation("Deleting file {0}...", updaterFilename);
try { File.Delete(updaterFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", updaterFilename, ex2.ToString()); }
throw;
}
}
catch
{
// Close installer file.
installerFile.Close();
// Delete installer file. If possible.
Trace.TraceInformation("Deleting file {0}...", installerFilename);
try { File.Delete(installerFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
throw;
}
}
catch
{
// Delete working folder. If possible.
try { Directory.Delete(workingFolder); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} folder failed: {1}", workingFolder, ex2.ToString()); }
throw;
}
};
// Self-update progress.
selfUpdate.ProgressChanged += (object sender, ProgressChangedEventArgs e) =>
{
Progress.Value = e.ProgressPercentage;
};
// Self-update complereplacedion.
selfUpdate.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
{
if (e.Error == null)
{
// Self-updating successfuly launched. Quit to release open files.
Wizard.OnQuitApplication(this);
}
else
Wizard.Error = e.Error;
// Self-dispose.
(sender as BackgroundWorker)?.Dispose();
};
selfUpdate.RunWorkerAsync();
}
19
Source : SelfUpdateProgressPage.cs
with GNU General Public License v3.0
from Amebis
with GNU General Public License v3.0
from Amebis
public override void OnActivate()
{
base.OnActivate();
// Setup self-update.
var selfUpdate = new BackgroundWorker() { WorkerReportsProgress = true };
selfUpdate.DoWork += (object sender, DoWorkEventArgs e) =>
{
selfUpdate.ReportProgress(0);
var random = new Random();
var tempFolder = Path.GetTempPath();
var workingFolder = tempFolder + Path.GetRandomFileName() + "\\";
Directory.CreateDirectory(workingFolder);
try
{
string installerFilename = null;
FileStream installerFile = null;
// Download installer.
while (DownloadUris.Count > 0)
{
Window.Abort.Token.ThrowIfCancellationRequested();
var uriIndex = random.Next(DownloadUris.Count);
try
{
var binaryUri = DownloadUris[uriIndex];
Trace.TraceInformation("Downloading installer file from {0}...", binaryUri.AbsoluteUri);
var request = WebRequest.Create(binaryUri);
request.Proxy = null;
using (var response = request.GetResponse())
{
// 1. Get installer filename from Content-Disposition header.
// 2. Get installer filename from the last segment of URI path.
// 3. Fallback to a predefined installer filename.
try { installerFilename = Path.GetFullPath(workingFolder + new ContentDisposition(request.Headers["Content-Disposition"]).FileName); }
catch
{
try { installerFilename = Path.GetFullPath(workingFolder + binaryUri.Segments[binaryUri.Segments.Length - 1]); }
catch { installerFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup.exe"); }
}
// Save response data to file.
installerFile = File.Open(installerFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
try
{
using (var stream = response.GetResponseStream())
{
installerFile.Seek(0, SeekOrigin.Begin);
var hash = new eduEd25519.SHA256();
var buffer = new byte[1048576];
long offset = 0, total = response.ContentLength;
for (; ; )
{
// Wait for the data to arrive.
Window.Abort.Token.ThrowIfCancellationRequested();
var bufferLength = stream.Read(buffer, 0, buffer.Length);
if (bufferLength == 0)
break;
//Window.Abort.Token.WaitHandle.WaitOne(100); // Mock a slow link for testing.
// Append it to the file and hash it.
Window.Abort.Token.ThrowIfCancellationRequested();
installerFile.Write(buffer, 0, bufferLength);
hash.TransformBlock(buffer, 0, bufferLength, buffer, 0);
// Report progress.
offset += bufferLength;
selfUpdate.ReportProgress((int)(offset * 100 / total));
}
hash.TransformFinalBlock(buffer, 0, 0);
if (!hash.Hash.SequenceEqual(Hash))
throw new DownloadedFileCorruptException(string.Format(Resources.Strings.ErrorDownloadedFileCorrupt, binaryUri.AbsoluteUri));
installerFile.SetLength(installerFile.Position);
break;
}
}
catch
{
// Close installer file.
installerFile.Close();
installerFile = null;
// Delete installer file. If possible.
Trace.TraceInformation("Deleting file {0}...", installerFilename);
try { File.Delete(installerFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
installerFilename = null;
throw;
}
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
Trace.TraceWarning("Error: {0}", ex.ToString());
DownloadUris.RemoveAt(uriIndex);
}
}
if (installerFilename == null || installerFile == null)
{
// The installer file is not ready.
throw new InstallerFileUnavailableException();
}
try
{
var updaterFilename = Path.GetFullPath(workingFolder + Properties.Settings.Default.Clientreplacedle + " Client Setup and Relaunch.wsf");
var updaterFile = File.Open(updaterFilename, FileMode.CreateNew, FileAccess.Write, FileShare.Read | FileShare.Inheritable);
try
{
// Prepare WSF file.
var writer = new XmlTextWriter(updaterFile, null);
writer.WriteStartDoreplacedent();
writer.WriteStartElement("package");
writer.WriteStartElement("job");
writer.WriteStartElement("reference");
writer.WriteAttributeString("object", "WScript.Shell");
writer.WriteEndElement(); // reference
writer.WriteStartElement("reference");
writer.WriteAttributeString("object", "Scripting.FileSystemObject");
writer.WriteEndElement(); // reference
writer.WriteStartElement("script");
writer.WriteAttributeString("language", "JScript");
var installerArgumentsEsc = string.IsNullOrEmpty(Arguments) ? "" : " " + HttpUtility.JavaScriptStringEncode(Arguments);
var argv = Environment.GetCommandLineArgs();
var arguments = new StringBuilder();
for (long i = 1, n = argv.LongLength; i < n; i++)
{
if (i > 1) arguments.Append(" ");
arguments.Append("\"");
arguments.Append(argv[i].Replace("\"", "\"\""));
arguments.Append("\"");
}
var script = new StringBuilder();
script.AppendLine("var wsh = WScript.CreateObject(\"WScript.Shell\");");
script.AppendLine("wsh.Run(\"\\\"" + HttpUtility.JavaScriptStringEncode(installerFilename.Replace("\"", "\"\"")) + "\\\"" + installerArgumentsEsc + "\", 0, true);");
script.AppendLine("var fso = WScript.CreateObject(\"Scripting.FileSystemObject\");");
script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(installerFilename) + "\", true); } catch (err) {}");
script.AppendLine("try { fso.DeleteFile(\"" + HttpUtility.JavaScriptStringEncode(updaterFilename) + "\", true); } catch (err) {}");
script.AppendLine("try { fso.DeleteFolder(\"" + HttpUtility.JavaScriptStringEncode(workingFolder.TrimEnd(Path.DirectorySeparatorChar)) + "\", true); } catch (err) {}");
writer.WriteCData(script.ToString());
writer.WriteEndElement(); // script
writer.WriteEndElement(); // job
writer.WriteEndElement(); // package
writer.WriteEndDoreplacedent();
writer.Flush();
// Prepare WSF launch parameters.
Trace.TraceInformation("Launching update script file {0}...", updaterFilename);
var process = new Process();
process.StartInfo.FileName = "wscript.exe";
process.StartInfo.Arguments = "\"" + updaterFilename + "\"";
process.StartInfo.WorkingDirectory = workingFolder;
// Close WSF and installer files as late as possible to narrow the attack window.
// If Windows supported executing files that are locked for writing, we could leave those files open.
updaterFile.Close();
installerFile.Close();
process.Start();
}
catch
{
// Close WSF file.
updaterFile.Close();
// Delete WSF file. If possible.
Trace.TraceInformation("Deleting file {0}...", updaterFilename);
try { File.Delete(updaterFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", updaterFilename, ex2.ToString()); }
throw;
}
}
catch
{
// Close installer file.
installerFile.Close();
// Delete installer file. If possible.
Trace.TraceInformation("Deleting file {0}...", installerFilename);
try { File.Delete(installerFilename); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} file failed: {1}", installerFilename, ex2.ToString()); }
throw;
}
}
catch
{
// Delete working folder. If possible.
try { Directory.Delete(workingFolder); }
catch (Exception ex2) { Trace.TraceWarning("Deleting {0} folder failed: {1}", workingFolder, ex2.ToString()); }
throw;
}
};
// Self-update progress.
selfUpdate.ProgressChanged += (object sender, ProgressChangedEventArgs e) =>
{
Progress.Value = e.ProgressPercentage;
};
// Self-update complereplacedion.
selfUpdate.RunWorkerCompleted += (object sender, RunWorkerCompletedEventArgs e) =>
{
if (e.Error == null)
{
// Self-updating successfuly launched. Quit to release open files.
Wizard.OnQuitApplication(this);
}
else
Wizard.Error = e.Error;
// Self-dispose.
(sender as BackgroundWorker)?.Dispose();
};
selfUpdate.RunWorkerAsync();
}
19
Source : ShaderIncludeHandler.cs
with MIT License
from amerkoleci
with MIT License
from amerkoleci
private string? GetFilePath(string fileName)
{
for (int i = 0; i < _includeDirectories.Length; i++)
{
var filePath = Path.GetFullPath(Path.Combine(_includeDirectories[i], fileName));
if (File.Exists(filePath))
return filePath;
}
return null;
}
19
Source : ShaderIncludeHandler.cs
with MIT License
from amerkoleci
with MIT License
from amerkoleci
private string? GetFilePath(string fileName)
{
if (File.Exists(fileName))
return fileName;
for (int i = 0; i < _includeDirectories.Count; i++)
{
var filePath = Path.GetFullPath(Path.Combine(_includeDirectories[i], fileName));
if (File.Exists(filePath))
{
var fileDirectory = Path.GetDirectoryName(filePath);
if (!_includeDirectories.Contains(fileDirectory))
_includeDirectories.Add(fileDirectory);
return filePath;
}
}
return null;
}
19
Source : Interface.cs
with MIT License
from Aminator
with MIT License
from Aminator
public static ValueTask<Gltf> LoadModelAsync(string filePath)
{
var path = Path.GetFullPath(filePath);
using Stream stream = File.OpenRead(path);
return LoadModelAsync(stream);
}
19
Source : MovieRenamerService.cs
with MIT License
from amoscardino
with MIT License
from amoscardino
public async Task RenameAsync(string inputPath, string outputPath, bool skipConfirmation, bool verbose)
{
_verbose = verbose;
inputPath = Path.GetFullPath(inputPath ?? Directory.GetCurrentDirectory());
outputPath = Path.GetFullPath(outputPath ?? inputPath);
if (!File.GetAttributes(inputPath).HasFlag(FileAttributes.Directory))
{
_console.WriteLine("Input path must be a directory, not a file.");
return;
}
if (_verbose)
{
_console.WriteLine($"* Using Input Path: {inputPath}");
_console.WriteLine($"* Using Output Path: {outputPath}");
_console.WriteLine();
}
var files = _fileService.GetFiles(inputPath);
if (!files.Any())
return;
await MatchFilesAsync(files, outputPath);
var anyToRename = files.Any(match => !match.NewPath.IsNullOrWhiteSpace());
if (anyToRename && (skipConfirmation || Prompt.GetYesNo("Look good?", true)))
_fileService.RenameFiles(files);
else
_console.WriteLine("Nothing has been changed.");
}
19
Source : ShowRenamerService.cs
with MIT License
from amoscardino
with MIT License
from amoscardino
public async Task RenameAsync(string inputPath, string outputPath, bool filesOnly, bool recurse, bool skipConfirmation, bool verbose)
{
_verbose = verbose;
inputPath = Path.GetFullPath(inputPath ?? Directory.GetCurrentDirectory());
outputPath = Path.GetFullPath(outputPath ?? inputPath);
if (!File.GetAttributes(inputPath).HasFlag(FileAttributes.Directory))
{
_console.WriteLine("Input path must be a directory, not a file.");
return;
}
if (_verbose)
{
_console.WriteLine($"* Using Input Path: {inputPath}");
_console.WriteLine($"* Using Output Path: {outputPath}");
_console.WriteLine();
}
var files = _fileService.GetFiles(inputPath, recurse);
if (!files.Any())
return;
await MatchFilesAsync(files, outputPath, filesOnly);
var anyToRename = files.Any(match => !match.NewPath.IsNullOrWhiteSpace());
if (anyToRename && (skipConfirmation || Prompt.GetYesNo("Look good?", true)))
_fileService.RenameFiles(files);
else
_console.WriteLine("Nothing has been changed.");
}
19
Source : SvnSccProvider.Enlistment.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
protected override void Translate_SolutionRenamed(string oldName, string newName)
{
string oldDir = Path.GetDirectoryName(oldName);
string newDir = Path.GetDirectoryName(newName);
string newNameU = newName.ToUpperInvariant();
if (oldDir == newDir)
return;
string oldDirRoot = Path.GetPathRoot(oldDir);
Dictionary<string, string> oldNameMap = new Dictionary<string, string>(_trueNameMap);
_trueNameMap.Clear();
foreach (KeyValuePair<string, string> kv in oldNameMap)
{
if (!IsSafeSccPath(kv.Key) || !IsSafeSccPath(kv.Value))
{
// Just copy translations like http://localhost
_trueNameMap.Add(kv.Key, kv.Value);
continue;
}
string newRel = SvnItem.MakeRelativeNoCase(newName, kv.Key);
if (IsSafeSccPath(newRel))
continue; // Not relative from .sln after
string newPath = Path.GetFullPath(Path.Combine(newDir, newRel));
if (newPath == kv.Key)
continue; // No translation necessary after the rename
_trueNameMap[kv.Key] = newPath;
}
}
19
Source : TestBase.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
protected string FindDirName( string baseName )
{
string dir = baseName;
int i = 1;
while ( Directory.Exists( dir ) )
{
dir = string.Format( "{0}-{1}", baseName, i );
++i;
}
return Path.GetFullPath( dir );
}
19
Source : BuildDeployTools.cs
with MIT License
from anderm
with MIT License
from anderm
public static bool BuildAppxFromSLN(string productName, string msBuildVersion, bool forceRebuildAppx, string buildConfig, string buildDirectory, bool incrementVersion, bool showDialog = true)
{
EditorUtility.DisplayProgressBar("Build AppX", "Building AppX Package...", 0);
string slnFilename = Path.Combine(buildDirectory, PlayerSettings.productName + ".sln");
if (!File.Exists(slnFilename))
{
Debug.LogError("Unable to find Solution to build from!");
EditorUtility.ClearProgressBar();
return false;
}
// Get and validate the msBuild path...
var vs = CalcMSBuildPath(msBuildVersion);
if (!File.Exists(vs))
{
Debug.LogError("MSBuild.exe is missing or invalid (path=" + vs + "). Note that the default version is " + DefaultMSBuildVersion);
EditorUtility.ClearProgressBar();
return false;
}
// Get the path to the NuGet tool
string unity = Path.GetDirectoryName(EditorApplication.applicationPath);
System.Diagnostics.Debug.replacedert(unity != null, "unity != null");
string storePath = Path.GetFullPath(Path.Combine(Path.Combine(Application.dataPath, ".."), buildDirectory));
string solutionProjectPath = Path.GetFullPath(Path.Combine(storePath, productName + @".sln"));
// Bug in Unity editor that doesn't copy project.json and project.lock.json files correctly if solutionProjectPath is not in a folder named UWP.
if (!File.Exists(storePath + "\\project.json"))
{
File.Copy(unity + @"\Data\PlaybackEngines\MetroSupport\Tools\project.json", storePath + "\\project.json");
}
string nugetPath = Path.Combine(unity, @"Data\PlaybackEngines\MetroSupport\Tools\NuGet.exe");
// Before building, need to run a nuget restore to generate a json.lock file. Failing to do
// this breaks the build in VS RTM
if (!RestoreNugetPackages(nugetPath, storePath) ||
!RestoreNugetPackages(nugetPath, storePath + "\\" + productName) ||
EditorUserBuildSettings.wsaGenerateReferenceProjects && !RestoreNugetPackages(nugetPath, storePath + "/GeneratedProjects/UWP/replacedembly-CSharp") ||
EditorUserBuildSettings.wsaGenerateReferenceProjects && !RestoreNugetPackages(nugetPath, storePath + "/GeneratedProjects/UWP/replacedembly-CSharp-firstpreplaced"))
{
Debug.LogError("Failed to restore nuget packages");
EditorUtility.ClearProgressBar();
return false;
}
EditorUtility.DisplayProgressBar("Build AppX", "Building AppX Package...", 25);
// Ensure that the generated .appx version increments by modifying
// Package.appxmanifest
if (incrementVersion)
{
IncrementPackageVersion();
}
// Now do the actual build
var pInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = vs,
CreateNoWindow = false,
Arguments = string.Format("\"{0}\" /t:{2} /p:Configuration={1} /p:Platform=x86 /verbosity:m",
solutionProjectPath,
buildConfig,
forceRebuildAppx ? "Rebuild" : "Build")
};
// Uncomment out to debug by copying into command window
//Debug.Log("\"" + vs + "\"" + " " + pInfo.Arguments);
var process = new System.Diagnostics.Process { StartInfo = pInfo };
try
{
if (!process.Start())
{
Debug.LogError("Failed to start Cmd process!");
EditorUtility.ClearProgressBar();
return false;
}
process.WaitForExit();
EditorUtility.ClearProgressBar();
if (process.ExitCode == 0 &&
showDialog &&
!EditorUtility.DisplayDialog("Build AppX", "AppX Build Successful!", "OK", "Open Project Folder"))
{
System.Diagnostics.Process.Start("explorer.exe", "/select," + storePath);
}
if (process.ExitCode != 0)
{
Debug.LogError("MSBuild error (code = " + process.ExitCode + ")");
EditorUtility.DisplayDialog(PlayerSettings.productName + " build Failed!", "Failed to build appx from solution. Error code: " + process.ExitCode, "OK");
return false;
}
process.Close();
process.Dispose();
}
catch (Exception e)
{
Debug.LogError("Cmd Process EXCEPTION: " + e);
EditorUtility.ClearProgressBar();
return false;
}
return true;
}
19
Source : BuildDeployWindow.cs
with MIT License
from anderm
with MIT License
from anderm
private void OnGUI()
{
GUILayout.Space(GUISectionOffset);
// Setup
int buttonWidth_Quarter = Screen.width / 4;
int buttonWidth_Half = Screen.width / 2;
int buttonWidth_Full = Screen.width - 25;
var locatorHasData = XdeGuestLocator.HasData;
var locatorIsSearching = XdeGuestLocator.IsSearching;
var xdeGuestIpAddress = XdeGuestLocator.GuestIpAddress;
// Quick Options
GUILayout.BeginVertical();
GUILayout.Label("Quick Options");
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
// Build & Run button...
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
GUI.enabled = ShouldBuildSLNBeEnabled;
if (GUILayout.Button((!locatorIsSearching && locatorHasData || HoloLensUsbConnected)
? "Build SLN, Build APPX, then Install"
: "Build SLN, Build APPX",
GUILayout.Width(buttonWidth_Half - 20)))
{
// Build SLN
EditorApplication.delayCall += () => { BuildAll(!locatorIsSearching && locatorHasData || HoloLensUsbConnected); };
}
GUI.enabled = true;
if (GUILayout.Button("Open Player Settings", GUILayout.Width(buttonWidth_Quarter)))
{
EditorApplication.ExecuteMenuItem("Edit/Project Settings/Player");
}
if (GUILayout.Button(string.IsNullOrEmpty(wsaCertPath) ? "Select Certificate" : wsaCertPath, GUILayout.Width(buttonWidth_Quarter)))
{
string path = EditorUtility.OpenFilePanel("Select Certificate", Application.dataPath, "pfx");
wsaCertPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal) + 1);
if (!string.IsNullOrEmpty(path))
{
CertificatePreplacedwordWindow.Show(path);
}
else
{
PlayerSettings.WSA.SetCertificate(string.Empty, string.Empty);
}
}
}
GUILayout.EndVertical();
// Build section
GUILayout.BeginVertical();
GUILayout.Label("SLN");
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
// Build directory (and save setting, if it's changed)
string curBuildDirectory = BuildDeployPrefs.BuildDirectory;
string newBuildDirectory = EditorGUILayout.TextField(GUIHorizSpacer + "Build directory", curBuildDirectory);
if (newBuildDirectory != curBuildDirectory)
{
BuildDeployPrefs.BuildDirectory = newBuildDirectory;
curBuildDirectory = newBuildDirectory;
}
// Build SLN button
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
float previousLabelWidth = EditorGUIUtility.labelWidth;
// Generate C# Project References
EditorGUIUtility.labelWidth = 105;
bool generateReferenceProjects = EditorUserBuildSettings.wsaGenerateReferenceProjects;
bool shouldGenerateProjects = EditorGUILayout.Toggle("Unity C# Projects", generateReferenceProjects);
if (shouldGenerateProjects != generateReferenceProjects)
{
EditorUserBuildSettings.wsaGenerateReferenceProjects = shouldGenerateProjects;
}
// Restore previous label width
EditorGUIUtility.labelWidth = previousLabelWidth;
GUI.enabled = ShouldOpenSLNBeEnabled;
if (GUILayout.Button("Open SLN", GUILayout.Width(buttonWidth_Quarter)))
{
// Open SLN
string slnFilename = Path.Combine(curBuildDirectory, PlayerSettings.productName + ".sln");
if (File.Exists(slnFilename))
{
var slnFile = new FileInfo(slnFilename);
Process.Start(slnFile.FullName);
}
else if (EditorUtility.DisplayDialog("Solution Not Found", "We couldn't find the solution. Would you like to Build it?", "Yes, Build", "No"))
{
// Build SLN
EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); };
}
}
GUI.enabled = ShouldBuildSLNBeEnabled;
if (GUILayout.Button("Build Visual Studio SLN", GUILayout.Width(buttonWidth_Half)))
{
// Build SLN
EditorApplication.delayCall += () => { BuildDeployTools.BuildSLN(curBuildDirectory); };
}
GUI.enabled = true;
}
// Appx sub-section
GUILayout.BeginVertical();
GUILayout.Label("APPX");
// SDK and MS Build Version(and save setting, if it's changed)
string curMSBuildVer = BuildDeployPrefs.MsBuildVersion;
string currentSDKVersion = EditorUserBuildSettings.wsaUWPSDK;
int currentSDKVersionIndex = 0;
int defaultMSBuildVersionIndex = 0;
for (var i = 0; i < windowsSdkPaths.Length; i++)
{
if (string.IsNullOrEmpty(currentSDKVersion))
{
currentSDKVersionIndex = windowsSdkPaths.Length - 1;
}
else
{
if (windowsSdkPaths[i].Equals(currentSDKVersion))
{
currentSDKVersionIndex = i;
}
if (windowsSdkPaths[i].Equals("10.0.14393.0"))
{
defaultMSBuildVersionIndex = i;
}
}
}
currentSDKVersionIndex = EditorGUILayout.Popup(GUIHorizSpacer + "SDK Version", currentSDKVersionIndex, windowsSdkPaths);
string newSDKVersion = windowsSdkPaths[currentSDKVersionIndex];
if (!newSDKVersion.Equals(currentSDKVersion))
{
EditorUserBuildSettings.wsaUWPSDK = newSDKVersion;
}
string newMSBuildVer = currentSDKVersionIndex <= defaultMSBuildVersionIndex ? BuildDeployTools.DefaultMSBuildVersion : "15.0";
EditorGUILayout.LabelField(GUIHorizSpacer + "MS Build Version", newMSBuildVer);
if (!newMSBuildVer.Equals(curMSBuildVer))
{
BuildDeployPrefs.MsBuildVersion = newMSBuildVer;
curMSBuildVer = newMSBuildVer;
}
// Build config (and save setting, if it's changed)
string curBuildConfigString = BuildDeployPrefs.BuildConfig;
BuildConfigEnum buildConfigOption;
if (curBuildConfigString.ToLower().Equals("master"))
{
buildConfigOption = BuildConfigEnum.MASTER;
}
else if (curBuildConfigString.ToLower().Equals("release"))
{
buildConfigOption = BuildConfigEnum.RELEASE;
}
else
{
buildConfigOption = BuildConfigEnum.DEBUG;
}
buildConfigOption = (BuildConfigEnum)EditorGUILayout.EnumPopup(GUIHorizSpacer + "Build Configuration", buildConfigOption);
string newBuildConfig = buildConfigOption.ToString();
if (newBuildConfig != curBuildConfigString)
{
BuildDeployPrefs.BuildConfig = newBuildConfig;
curBuildConfigString = newBuildConfig;
}
// Build APPX button
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
float previousLabelWidth = EditorGUIUtility.labelWidth;
// Force rebuild
EditorGUIUtility.labelWidth = 50;
bool curForceRebuildAppx = BuildDeployPrefs.ForceRebuild;
bool newForceRebuildAppx = EditorGUILayout.Toggle("Rebuild", curForceRebuildAppx);
if (newForceRebuildAppx != curForceRebuildAppx)
{
BuildDeployPrefs.ForceRebuild = newForceRebuildAppx;
curForceRebuildAppx = newForceRebuildAppx;
}
// Increment version
EditorGUIUtility.labelWidth = 110;
bool curIncrementVersion = BuildDeployPrefs.IncrementBuildVersion;
bool newIncrementVersion = EditorGUILayout.Toggle("Increment version", curIncrementVersion);
if (newIncrementVersion != curIncrementVersion)
{
BuildDeployPrefs.IncrementBuildVersion = newIncrementVersion;
curIncrementVersion = newIncrementVersion;
}
// Restore previous label width
EditorGUIUtility.labelWidth = previousLabelWidth;
// Build APPX
GUI.enabled = ShouldBuildAppxBeEnabled;
if (GUILayout.Button("Build APPX from SLN", GUILayout.Width(buttonWidth_Half)))
{
// Open SLN
string slnFilename = Path.Combine(curBuildDirectory, PlayerSettings.productName + ".sln");
if (File.Exists(slnFilename))
{
// Build APPX
EditorApplication.delayCall += () =>
BuildDeployTools.BuildAppxFromSLN(
PlayerSettings.productName,
curMSBuildVer,
curForceRebuildAppx,
curBuildConfigString,
curBuildDirectory,
curIncrementVersion);
}
else if (EditorUtility.DisplayDialog("Solution Not Found", "We couldn't find the solution. Would you like to Build it?", "Yes, Build", "No"))
{
// Build SLN then APPX
EditorApplication.delayCall += () => BuildAll(install: false);
}
}
GUI.enabled = true;
}
GUILayout.EndVertical();
GUILayout.EndVertical();
GUILayout.Space(GUISectionOffset);
// Deploy section
GUILayout.BeginVertical();
GUILayout.Label("Deploy");
// Target IPs (and save setting, if it's changed)
string curTargetIps = BuildDeployPrefs.TargetIPs;
if (!LocalIPsOnly)
{
string newTargetIPs = EditorGUILayout.TextField(
new GUIContent(GUIHorizSpacer + "IP Address(es)", "IP(s) of target devices (e.g. 127.0.0.1;10.11.12.13)"),
curTargetIps);
if (newTargetIPs != curTargetIps)
{
BuildDeployPrefs.TargetIPs = newTargetIPs;
curTargetIps = newTargetIPs;
}
}
else
{
// Queue up a repaint if we're still busy, or we'll get stuck
// in a disabled state.
if (locatorIsSearching)
{
Repaint();
}
var addressesToPresent = new List<string> { "127.0.0.1" };
if (!locatorIsSearching && locatorHasData)
{
addressesToPresent.Add(xdeGuestIpAddress.ToString());
}
var previouslySavedAddress = addressesToPresent.IndexOf(curTargetIps);
if (previouslySavedAddress == -1)
{
previouslySavedAddress = 0;
}
EditorGUILayout.BeginHorizontal();
if (locatorIsSearching && !locatorHasData)
{
GUI.enabled = false;
}
var selectedAddressIndex = EditorGUILayout.Popup(GUIHorizSpacer + "IP Address", previouslySavedAddress, addressesToPresent.ToArray());
if (GUILayout.Button(locatorIsSearching ? "Searching" : "Refresh", GUILayout.Width(buttonWidth_Quarter)))
{
UpdateXdeStatus();
}
GUI.enabled = true;
EditorGUILayout.EndHorizontal();
var selectedAddress = addressesToPresent[selectedAddressIndex];
if (curTargetIps != selectedAddress && !locatorIsSearching)
{
BuildDeployPrefs.TargetIPs = selectedAddress;
}
}
// Username/Preplacedword (and save seeings, if changed)
string curUsername = BuildDeployPrefs.DeviceUser;
string newUsername = EditorGUILayout.TextField(GUIHorizSpacer + "Username", curUsername);
string curPreplacedword = BuildDeployPrefs.DevicePreplacedword;
string newPreplacedword = EditorGUILayout.PreplacedwordField(GUIHorizSpacer + "Preplacedword", curPreplacedword);
bool curFullReinstall = BuildDeployPrefs.FullReinstall;
bool newFullReinstall = EditorGUILayout.Toggle(
new GUIContent(GUIHorizSpacer + "Uninstall first", "Uninstall application before installing"), curFullReinstall);
if (newUsername != curUsername ||
newPreplacedword != curPreplacedword ||
newFullReinstall != curFullReinstall)
{
BuildDeployPrefs.DeviceUser = newUsername;
BuildDeployPrefs.DevicePreplacedword = newPreplacedword;
BuildDeployPrefs.FullReinstall = newFullReinstall;
}
// Build list (with install buttons)
if (builds.Count == 0)
{
GUILayout.Label(GUIHorizSpacer + "*** No builds found in build directory", EditorStyles.boldLabel);
}
else
{
GUILayout.BeginVertical();
scrollPosition = GUILayout.BeginScrollView(scrollPosition, GUILayout.Width(buttonWidth_Full), GUILayout.Height(128));
foreach (var fullBuildLocation in builds)
{
int lastBackslashIndex = fullBuildLocation.LastIndexOf("\\", StringComparison.Ordinal);
var directoryDate = Directory.GetLastWriteTime(fullBuildLocation).ToString("yyyy/MM/dd HH:mm:ss");
string packageName = fullBuildLocation.Substring(lastBackslashIndex + 1);
EditorGUILayout.BeginHorizontal();
GUILayout.Space(GUISectionOffset + 15);
GUI.enabled = (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
if (GUILayout.Button("Install", GUILayout.Width(120.0f)))
{
string thisBuildLocation = fullBuildLocation;
string[] ipList = ParseIPList(curTargetIps);
EditorApplication.delayCall += () =>
{
InstallAppOnDevicesList(thisBuildLocation, ipList);
};
}
GUI.enabled = true;
GUILayout.Space(5);
GUILayout.Label(packageName + " (" + directoryDate + ")");
EditorGUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
EditorGUILayout.Separator();
}
GUILayout.EndVertical();
GUILayout.Space(GUISectionOffset);
// Utilities section
GUILayout.BeginVertical();
GUILayout.Label("Utilities");
// Open AppX packages location
using (new EditorGUILayout.HorizontalScope())
{
GUI.enabled = builds.Count > 0;
GUILayout.FlexibleSpace();
if (GUILayout.Button("Open APPX Packages Location", GUILayout.Width(buttonWidth_Full)))
{
Process.Start("explorer.exe", "/open," + Path.GetFullPath(curBuildDirectory + "/" + PlayerSettings.productName + "/AppPackages"));
}
GUI.enabled = true;
}
// Open web portal
using (new EditorGUILayout.HorizontalScope())
{
GUI.enabled = ShouldWebPortalBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
GUILayout.FlexibleSpace();
if (GUILayout.Button("Open Device Portal", GUILayout.Width(buttonWidth_Full)))
{
OpenWebPortalForIPs(curTargetIps);
}
GUI.enabled = true;
}
// Launch app..
using (new EditorGUILayout.HorizontalScope())
{
GUI.enabled = ShouldLaunchAppBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
GUILayout.FlexibleSpace();
if (GUILayout.Button("Launch Application", GUILayout.Width(buttonWidth_Full)))
{
// If already running, kill it (button is a toggle)
if (IsAppRunning_FirstIPCheck(PlayerSettings.productName, curTargetIps))
{
KillAppOnIPs(curTargetIps);
}
else
{
LaunchAppOnIPs(curTargetIps);
}
}
GUI.enabled = true;
}
// Log file
using (new EditorGUILayout.HorizontalScope())
{
GUI.enabled = ShouldLogViewBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
GUILayout.FlexibleSpace();
if (GUILayout.Button("View Log File", GUILayout.Width(buttonWidth_Full)))
{
OpenLogFileForIPs(curTargetIps);
}
GUI.enabled = true;
}
// Uninstall...
using (new EditorGUILayout.HorizontalScope())
{
GUI.enabled = ShouldLogViewBeEnabled && (!locatorIsSearching && locatorHasData || HoloLensUsbConnected);
GUILayout.FlexibleSpace();
if (GUILayout.Button("Uninstall Application", GUILayout.Width(buttonWidth_Full)))
{
EditorApplication.delayCall += () =>
{
UninstallAppOnDevicesList(ParseIPList(curTargetIps));
};
}
GUI.enabled = true;
}
//GUILayout.EndScrollView();
GUILayout.EndVertical();
}
19
Source : BuildDeployWindow.cs
with MIT License
from anderm
with MIT License
from anderm
private void UpdateBuilds()
{
builds.Clear();
try
{
var appPackageDirectories = new List<string>();
string[] buildList = Directory.GetDirectories(BuildDeployPrefs.AbsoluteBuildDirectory);
foreach (string appBuild in buildList)
{
string appPackageDirectory = appBuild + @"\AppPackages";
if (Directory.Exists(appPackageDirectory))
{
appPackageDirectories.AddRange(Directory.GetDirectories(appPackageDirectory));
}
}
IEnumerable<string> selectedDirectories =
from string directory in appPackageDirectories
orderby Directory.GetLastWriteTime(directory) descending
select Path.GetFullPath(directory);
builds.AddRange(selectedDirectories);
}
catch (DirectoryNotFoundException)
{
// unused
}
timeLastUpdatedBuilds = Time.realtimeSinceStartup;
}
See More Examples