Here are the examples of the csharp api System.IO.Directory.GetFiles(string, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1309 Examples
19
View Source File : XmlCommandsProvider.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
public void Load(string path, string pattern)
{
var files = System.IO.Directory.GetFiles(path, pattern);
foreach (var item in files)
{
Load(item);
}
}
19
View Source File : BeatmapConverter.cs
License : MIT License
Project Creator : 39M
License : MIT License
Project Creator : 39M
static void Convert()
{
Debug.Log(string.Format("Source path: {0}", beatmapPath));
// 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
foreach (string directoryPath in sourceDirectories)
{
Music music = new Music();
// 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
int count = 0;
foreach (string filepath in sourceFiles)
{
string[] lines = File.ReadAllLines(filepath);
Beatmap beatmap = new Beatmap();
music.beatmapList.Add(beatmap);
#region Set Difficulty
beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
count++;
#endregion
#region Processing file line by line
bool startProcessNotes = false;
foreach (string line in lines)
{
if (line.StartsWith("[HitObjects]"))
{
startProcessNotes = true;
continue;
}
if (!startProcessNotes)
{
// 处理谱面信息
int lastIndex = line.LastIndexOf(':');
if (lastIndex < 0)
{
// 如果不是有效信息行则跳过
continue;
}
string value = line.Substring(lastIndex + 1).Trim();
if (line.StartsWith("replacedle"))
{
music.replacedle = value;
}
else if (line.StartsWith("Artist"))
{
music.artist = value;
}
else if (line.StartsWith("AudioFilename"))
{
value = value.Remove(value.LastIndexOf('.'));
music.audioFilename = value;
music.bannerFilename = value;
music.soundEffectFilename = value;
}
else if (line.StartsWith("PreviewTime"))
{
music.previewTime = float.Parse(value) / 1000;
}
else if (line.StartsWith("Creator"))
{
beatmap.creator = value;
}
else if (line.StartsWith("Version"))
{
beatmap.version = value;
}
}
else
{
// 开始处理 HitObject
string[] noteInfo = line.Split(',');
int type = int.Parse(noteInfo[3]);
if ((type & 0x01) != 0)
{
// Circle
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Circle 相关的处理
});
}
else if ((type & 0x02) != 0)
{
// Slider
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Slider 相关的处理
});
}
else if ((type & 0x08) != 0)
{
// Spinner
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[2]) / 1000,
// 其他 Spinner 相关的处理
});
beatmap.noteList.Add(new Note
{
x = int.Parse(noteInfo[0]),
y = int.Parse(noteInfo[1]),
time = float.Parse(noteInfo[5]) / 1000,
// 其他 Spinner 相关的处理
});
}
}
}
#endregion
}
string targetPath = directoryPath + ".json";
if (File.Exists(targetPath))
{
File.Delete(targetPath);
}
File.WriteAllText(targetPath, music.ToJson());
Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
}
Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
}
19
View Source File : ExcelExportUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static void ExportExcelProtobuf(ConfigType configType)
{
string exportPath = PathUtil.GetPath(PathType.DataPath, GetProtobufPath(configType));
string clreplacedPath = PathUtil.GetPath(PathType.DataPath, GetClreplacedPath(configType));
string jsonPath = PathUtil.GetPath(PathType.DataPath, GetJsonPath(configType));
List<string> protoNameList = new List<string>();
foreach (string item in Directory.GetFiles(clreplacedPath, "*.cs"))
{
protoNameList.Add(Path.GetFileNameWithoutExtension(item));
}
foreach (string item in protoNameList)
{
string json = FileUtil.Getreplacedet($"{jsonPath}/{item}.txt").GetString();
object obj;
if (configType == ConfigType.Model)
{
obj = JsonUtil.ToObject(typeof(Manager).replacedembly.GetType($"{typeof(Manager).Namespace}.{item}Category"), json);
}
else
{
obj = JsonUtil.ToObject(typeof(LccHotfix.Manager).replacedembly.GetType($"{typeof(LccHotfix.Manager).Namespace}.{item}Category"), json);
}
FileUtil.Savereplacedet($"{exportPath}/{item}Category.bytes", ProtobufUtil.Serialize(obj));
}
}
19
View Source File : ExcelExportUtil.cs
License : MIT License
Project Creator : 404Lcc
License : MIT License
Project Creator : 404Lcc
public static void ExportClreplacedAndJson()
{
content = FileUtil.Getreplacedet(templatePath).GetString();
foreach (string item in Directory.GetFiles(excelPath, "*.xlsx"))
{
ExportExcelClreplaced(new XSSFWorkbook(item), Path.GetFileNameWithoutExtension(item), ConfigType.Model);
ExportExcelClreplaced(new XSSFWorkbook(item), Path.GetFileNameWithoutExtension(item), ConfigType.Hotfix);
ExportExcelJson(new XSSFWorkbook(item), Path.GetFileNameWithoutExtension(item), ConfigType.Model);
ExportExcelJson(new XSSFWorkbook(item), Path.GetFileNameWithoutExtension(item), ConfigType.Hotfix);
}
replacedetDatabase.Refresh();
}
19
View Source File : DynamicDNAConverterBehaviourEditor.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private void RecursiveScanFoldersForreplacedets(string path, Delegate callback, int addMethod)
{
var replacedetFiles = System.IO.Directory.GetFiles(path, "*.prefab");
foreach (var replacedetFile in replacedetFiles)
{
var tempDnaGO = replacedetDatabase.LoadreplacedetAtPath(replacedetFile, typeof(GameObject)) as GameObject;
DynamicDNAConverterBehaviour tempDnareplacedet = tempDnaGO.GetComponent<DynamicDNAConverterBehaviour>();
if (tempDnareplacedet)
{
callback.DynamicInvoke(tempDnareplacedet, addMethod);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'), callback, addMethod);
}
}
19
View Source File : SlotLibraryEditor.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private void RecursiveScanFoldersForreplacedets(string path)
{
var replacedetFiles = System.IO.Directory.GetFiles(path, "*.replacedet");
foreach (var replacedetFile in replacedetFiles)
{
var tempSlotDatareplacedet = replacedetDatabase.LoadreplacedetAtPath(replacedetFile, typeof(SlotDatareplacedet)) as SlotDatareplacedet;
if (tempSlotDatareplacedet)
{
AddSlotDatareplacedet(tempSlotDatareplacedet);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'));
}
}
19
View Source File : OverlayLibraryEditor.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
private void RecursiveScanFoldersForreplacedets(string path)
{
var replacedetFiles = System.IO.Directory.GetFiles(path, "*.replacedet");
foreach (var replacedetFile in replacedetFiles)
{
var tempOverlayData = replacedetDatabase.LoadreplacedetAtPath(replacedetFile, typeof(OverlayDatareplacedet)) as OverlayDatareplacedet;
if (tempOverlayData)
{
AddOverlayData(tempOverlayData);
}
}
foreach (var subFolder in System.IO.Directory.GetDirectories(path))
{
RecursiveScanFoldersForreplacedets(subFolder.Replace('\\', '/'));
}
}
19
View Source File : TestCustomizerDD.cs
License : Apache License 2.0
Project Creator : A7ocin
License : Apache License 2.0
Project Creator : A7ocin
public void ListLoadableFiles(ScrollRect ItemList)
{
var thisSubFolder = Avatar.loadPath.TrimStart('\\', '/').TrimEnd('\\', '/').Trim();//trim this at the start and the end of slashes. And then we may need to switch any slashes in the middle depending on the platform- for explode on them or something
//we can find things in resources/thisSubFolder and in persistentDataPath/thisSubFolder
//Clear the item list
ItemList.content.GetComponent<VerticalLayoutGroup>().enabled = false;//dont seem to be able to clear the content with this on...
foreach (Transform child in ItemList.content.transform)
{
Destroy(child.gameObject);
}
ItemList.content.GetComponent<VerticalLayoutGroup>().enabled = true;
//- I need to basically get rid of the other oprions in CharacterAvatars enumerator since they are effectively useless apart from in the editor
var persistentPath = Path.Combine(Application.persistentDataPath, thisSubFolder);
if (Directory.Exists(persistentPath))
{
string[] persistentDataFiles = Directory.GetFiles(persistentPath, "*.txt");
foreach (string path in persistentDataFiles)
{
GameObject thisLoadableItem = Instantiate(loadableItemPrefab) as GameObject;
thisLoadableItem.transform.SetParent(ItemList.content.transform, false);
thisLoadableItem.GetComponent<CSLoadableItem>().customizerScript = this;
thisLoadableItem.GetComponent<CSLoadableItem>().filepath = path;
thisLoadableItem.GetComponent<CSLoadableItem>().filename = Path.GetFileNameWithoutExtension(path);
thisLoadableItem.GetComponentInChildren<Text>().text = Path.GetFileNameWithoutExtension(path);
}
}
foreach (KeyValuePair<string, string> kp in (UMAContext.Instance.dynamicCharacterSystem as DynamicCharacterSystem).CharacterRecipes)
{
GameObject thisLoadableItem = Instantiate(loadableItemPrefab) as GameObject;
thisLoadableItem.transform.SetParent(ItemList.content.transform, false);
thisLoadableItem.GetComponent<CSLoadableItem>().customizerScript = this;
thisLoadableItem.GetComponent<CSLoadableItem>().filename = Path.GetFileNameWithoutExtension(kp.Key);
thisLoadableItem.GetComponentInChildren<Text>().text = Path.GetFileNameWithoutExtension(kp.Key);
}
}
19
View Source File : ResourceController.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
[Route("Photo/{type}/{name}")]
public async Task<IActionResult> Photo([FromRoute]string type, [FromRoute]string name)
{
if (type.EqualsIC("Tag") || type.EqualsIC("Object"))
{
var profilePhotoPath = [email protected]"{_contentRoot}\replacedets\Images\Profile\";
var files = Directory.GetFiles(profilePhotoPath, $"{name}.*");
if (!files.Any())
{
return StatusCode(new ErrorMessage
{
StatusCode = System.Net.HttpStatusCode.NotFound,
ErrorCode = "RESOURCE.PHOTO.NOT.FOUND",
Message = "The image you requested does not exists"
});
}
else
{
var file = System.IO.File.OpenRead(files.FirstOrDefault());
return File(file, "Image/jpeg");
}
}
else
{
return StatusCode(new ErrorMessage
{
StatusCode = System.Net.HttpStatusCode.NotFound,
ErrorCode = "RESOURCE.PHOTO.TYPE.NOT.FOUND",
Message = "The file you requested does not exists"
});
}
}
19
View Source File : ResourceController.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
[Route("Photo/{type}/{name}")]
public async Task<IActionResult> Photo([FromRoute]string type, [FromRoute]string name)
{
if (type.EqualsIC("Profile"))
{
var profilePhotoPath = [email protected]"{_contentRoot}\replacedets\Images\Profile\";
var files = Directory.GetFiles(profilePhotoPath, $"{name}.*");
if (!files.Any())
{
return StatusCode(new ErrorMessage
{
StatusCode = System.Net.HttpStatusCode.NotFound,
ErrorCode = "RESOURCE.PHOTO.NOT.FOUND",
Message = "The image you requested does not exists"
});
}
else
{
var file = System.IO.File.OpenRead(files.FirstOrDefault());
return File(file, "Image/jpeg");
}
}
else
{
return StatusCode(new ErrorMessage
{
StatusCode = System.Net.HttpStatusCode.NotFound,
ErrorCode = "RESOURCE.PHOTO.TYPE.NOT.FOUND",
Message = "The file you requested does not exists"
});
}
}
19
View Source File : OVRConfig.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
public string GetGradlePath(bool throwError = true)
{
string libPath = "";
#if UNITY_2019_1_OR_NEWER
// Check for use of embedded path or user defined
bool useEmbedded = EditorPrefs.GetBool("GradleUseEmbedded") || string.IsNullOrEmpty(EditorPrefs.GetString("GradlePath"));
if (useEmbedded)
{
libPath = Path.Combine(BuildPipeline.GetPlaybackEngineDirectory(BuildTarget.Android, BuildOptions.None), "Tools\\gradle\\lib");
}
else
{
libPath = Path.Combine(EditorPrefs.GetString("GradlePath"), "lib");
}
#else
libPath = Path.Combine(EditorApplication.applicationContentsPath, "PlaybackEngines\\AndroidPlayer\\Tools\\gradle\\lib");
#endif
libPath = libPath.Replace("/", "\\");
if (!string.IsNullOrEmpty(libPath) && Directory.Exists(libPath))
{
string[] gradleJar = Directory.GetFiles(libPath, "gradle-launcher-*.jar");
if (gradleJar.Length == 1)
{
gradlePath = gradleJar[0];
}
}
// Validate gradle path and notify user if path does not exist.
if (!File.Exists(gradlePath))
{
if (throwError)
{
EditorUtility.DisplayDialog("Gradle not Found",
"Gradle not found. Please ensure that the path is set correctly in (Edit -> Preferences -> External Tools) or that the Untiy Android module is installed correctly.",
"Ok");
}
return string.Empty;
}
EditorUtility.SetDirty(Instance);
return gradlePath;
}
19
View Source File : OVRSceneLoader.cs
License : MIT License
Project Creator : absurd-joy
License : MIT License
Project Creator : absurd-joy
private void LoadScene(SceneInfo sceneInfo)
{
replacedetBundle mainSceneBundle = null;
Debug.Log("[OVRSceneLoader] Loading main scene: " + sceneInfo.scenes[0] + " with version " + sceneInfo.version.ToString());
logTextBox.text += "Target Scene: " + sceneInfo.scenes[0] + "\n";
logTextBox.text += "Version: " + sceneInfo.version.ToString() + "\n";
// Load main scene and dependent additive scenes (if any)
Debug.Log("[OVRSceneLoader] Loading scene bundle files.");
// Fetch all files under scene cache path, excluding unnecessary files such as scene metadata file
string[] bundles = Directory.GetFiles(scenePath, "*_*");
logTextBox.text += "Loading " + bundles.Length + " bundle(s) . . . ";
string mainSceneBundleFileName = "scene_" + sceneInfo.scenes[0].ToLower();
try
{
foreach (string b in bundles)
{
var replacedetBundle = replacedetBundle.LoadFromFile(b);
if (replacedetBundle != null)
{
Debug.Log("[OVRSceneLoader] Loading file bundle: " + replacedetBundle.name == null ? "null" : replacedetBundle.name);
loadedreplacedetBundles.Add(replacedetBundle);
}
else
{
Debug.LogError("[OVRSceneLoader] Loading file bundle failed");
}
if (replacedetBundle.name == mainSceneBundleFileName)
{
mainSceneBundle = replacedetBundle;
}
if (replacedetBundle.name == resourceBundleName)
{
OVRResources.SetResourceBundle(replacedetBundle);
}
}
}
catch(Exception e)
{
logTextBox.text += "<color=red>" + e.Message + "</color>";
return;
}
logTextBox.text += "<color=green>DONE\n</color>";
if (mainSceneBundle != null)
{
logTextBox.text += "Loading Scene: {0:P0}\n";
formattedLogText = logTextBox.text;
string[] scenePaths = mainSceneBundle.GetAllScenePaths();
string sceneName = Path.GetFileNameWithoutExtension(scenePaths[0]);
loadSceneOperation = SceneManager.LoadSceneAsync(sceneName);
loadSceneOperation.completed += LoadSceneOperation_completed;
}
else
{
logTextBox.text += "<color=red>Failed to get main scene bundle.\n</color>";
}
}
19
View Source File : SmokeTests_ExampleWalkUsingBreadcrumbView.cs
License : MIT License
Project Creator : ABTSoftware
License : MIT License
Project Creator : ABTSoftware
private void RunExportExampleTest(ExampleStartTestCase testCase)
{
return;
// Useful UIAutomation Ids
// ExportExampleView
// ExportExampleView.ExportPathTextBox
// ExportExampleView.ExportButton
// ExportExampleView.CloseButton
// ExampleView.Export
// Toggle the export button, this shows ExportExampleView
var exportButton = _mainWindow.FindFirstDescendant("ExampleView.Export").AsToggleButton();
exportButton?.Toggle();
string exportPath = base.GetTemporaryDirectory();
try
{
var exampleExportView = WaitForElement(() => _mainWindow.FindFirstDescendant("ExportExampleView"));
var exampleExportTextBox = exampleExportView.FindFirstDescendant("ExportExampleView.ExportPathTextBox")
.AsTextBox();
var exampleExportButton =
exampleExportView.FindFirstDescendant("ExportExampleView.ExportButton").AsButton();
var exampleExportCloseButton =
exampleExportView.FindFirstDescendant("ExportExampleView.CloseButton").AsButton();
// Set output path and export
exampleExportTextBox.Text = exportPath;
exampleExportButton.Invoke();
// Get the messagebox, close it
var msg = WaitForElement(() => _mainWindow.ModalWindows.FirstOrDefault().AsWindow());
var yesButton = msg.FindFirstChild(cf => cf.ByName("OK")).AsButton();
yesButton.Invoke();
// Close example export view
exampleExportCloseButton?.Invoke();
// Now check the example
var subDir = Directory.GetDirectories(exportPath).First();
var projectFile = Directory.GetFiles(subDir, "*.sln").FirstOrDefault();
// MSBuild
//fs.WriteLine("@echo Building " + projectName);
//fs.WriteLine(@"call ""C:\Program Files (x86)\MSBuild\12.0\Bin\msbuild.exe"" /ToolsVersion:12.0 /p:Configuration=""Debug"" ""{0}/{0}.csproj"" /p:WarningLevel=0", projectName);
string msBuildPath = "C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Enterprise\\MSBuild\\Current\\Bin\\MSBuild.exe";
var msBuildProcess = Process.Start(new ProcessStartInfo(msBuildPath,
$"/ToolsVersion:Current /p:Configuration=\"Debug\" \"{projectFile}\" /t:Restore;Build /p:WarningLevel=0"));
msBuildProcess.WaitForExit(10000);
replacedert.That(msBuildProcess.ExitCode, Is.EqualTo(0), $"Failed to build example {testCase.Category}/{testCase.Group}/{testCase.Example}");
}
finally
{
Directory.Delete(exportPath, true);
}
}
19
View Source File : WhichUtil.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static string Which(string command, bool require = false, ITraceWriter trace = null, string prependPath = null)
{
ArgUtil.NotNullOrEmpty(command, nameof(command));
trace?.Info($"Which: '{command}'");
if (Path.IsPathFullyQualified(command) && File.Exists(command))
{
trace?.Info($"Fully qualified path: '{command}'");
return command;
}
string path = Environment.GetEnvironmentVariable(PathUtil.PathVariable);
if (string.IsNullOrEmpty(path))
{
trace?.Info("PATH environment variable not defined.");
path = path ?? string.Empty;
}
if (!string.IsNullOrEmpty(prependPath))
{
path = PathUtil.PrependPath(prependPath, path);
}
string[] pathSegments = path.Split(new Char[] { Path.PathSeparator }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < pathSegments.Length; i++)
{
pathSegments[i] = Environment.ExpandEnvironmentVariables(pathSegments[i]);
}
foreach (string pathSegment in pathSegments)
{
if (!string.IsNullOrEmpty(pathSegment) && Directory.Exists(pathSegment))
{
string[] matches = null;
#if OS_WINDOWS
string pathExt = Environment.GetEnvironmentVariable("PATHEXT");
if (string.IsNullOrEmpty(pathExt))
{
// XP's system default value for PATHEXT system variable
pathExt = ".com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh";
}
string[] pathExtSegments = pathExt.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
// if command already has an extension.
if (pathExtSegments.Any(ext => command.EndsWith(ext, StringComparison.OrdinalIgnoreCase)))
{
try
{
matches = Directory.GetFiles(pathSegment, command);
}
catch (UnauthorizedAccessException ex)
{
trace?.Info("Ignore UnauthorizedAccess exception during Which.");
trace?.Verbose(ex.ToString());
}
if (matches != null && matches.Length > 0)
{
trace?.Info($"Location: '{matches.First()}'");
return matches.First();
}
}
else
{
string searchPattern;
searchPattern = StringUtil.Format($"{command}.*");
try
{
matches = Directory.GetFiles(pathSegment, searchPattern);
}
catch (UnauthorizedAccessException ex)
{
trace?.Info("Ignore UnauthorizedAccess exception during Which.");
trace?.Verbose(ex.ToString());
}
if (matches != null && matches.Length > 0)
{
// add extension.
for (int i = 0; i < pathExtSegments.Length; i++)
{
string fullPath = Path.Combine(pathSegment, $"{command}{pathExtSegments[i]}");
if (matches.Any(p => p.Equals(fullPath, StringComparison.OrdinalIgnoreCase)))
{
trace?.Info($"Location: '{fullPath}'");
return fullPath;
}
}
}
}
#else
try
{
matches = Directory.GetFiles(pathSegment, command);
}
catch (UnauthorizedAccessException ex)
{
trace?.Info("Ignore UnauthorizedAccess exception during Which.");
trace?.Verbose(ex.ToString());
}
if (matches != null && matches.Length > 0)
{
trace?.Info($"Location: '{matches.First()}'");
return matches.First();
}
#endif
}
}
#if OS_WINDOWS
trace?.Info($"{command}: command not found. Make sure '{command}' is installed and its location included in the 'Path' environment variable.");
#else
trace?.Info($"{command}: command not found. Make sure '{command}' is installed and its location included in the 'PATH' environment variable.");
#endif
if (require)
{
throw new FileNotFoundException(
message: $"{command}: command not found",
fileName: command);
}
return null;
}
19
View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro
License : MIT License
Project Creator : Actipro
private void QueueFiles(List<string> queuedFiles, string path, string searchPattern) {
string[] files = Directory.GetFiles(path, searchPattern);
if (files != null) {
foreach (string file in files)
queuedFiles.Add(file);
}
}
19
View Source File : TypeFinder.cs
License : MIT License
Project Creator : ad313
License : MIT License
Project Creator : ad313
protected void Loadreplacedemblies(string path)
{
foreach (string file in Directory.GetFiles(path, "*.dll"))
{
if (Match(Path.GetFileName(file)) == false)
continue;
LoadreplacedemblyToAppDomain(file);
}
}
19
View Source File : CoverageService.cs
License : MIT License
Project Creator : ademanuele
License : MIT License
Project Creator : ademanuele
protected XmlNode GetRunSettings(Project testProject)
{
string solutionDirectoryPath = testProject.ParentSolution.BaseDirectory.ToString();
string[] runSettingsFiles = Directory.GetFiles(solutionDirectoryPath, "*.runsettings");
string runSettingsFile = runSettingsFiles.FirstOrDefault();
if (runSettingsFile == null) return null;
return ParseRunSettings(runSettingsFile);
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : AdriaandeJongh
License : GNU General Public License v3.0
Project Creator : AdriaandeJongh
static void ClearITMSPPackage()
{
// remove any previously copied replacedets
foreach (string file in Directory.GetFiles(itmspFilePath + "/", "*.png").Where(item => item.EndsWith(".png", StringComparison.CurrentCultureIgnoreCase)))
File.Delete(file);
foreach (string file in Directory.GetFiles(itmspFilePath + "/", "*.mp4").Where(item => item.EndsWith(".mp4", StringComparison.CurrentCultureIgnoreCase)))
File.Delete(file);
}
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr
License : GNU General Public License v2.0
Project Creator : adrifcastr
public void readxml()
{
statuslabel.Content = "Reading XML File...";
string xmldir = AppDomain.CurrentDomain.BaseDirectory + @"\\tmp";
string[] xmlfile = Directory.GetFiles(xmldir, "*.xml");
if (xmlfile.Length != 1)
{
System.Windows.MessageBox.Show("There is no file to patch within your NSP file!");
return;
}
XDoreplacedent xdoc = XDoreplacedent.Load(xmlfile[0]);
foreach (var order in xdoc.Descendants("ContentMeta"))
{
string mrmk = order.Element("KeyGenerationMin").Value;
{
keylabel.Content = mrmk;
}
string tid = order.Element("Id").Value;
{
tidlabel.Content = tid.Substring(2);
}
}
if (keylabel.Content.Equals(null))
{
fwlabel.Content = "???";
DialogResult uspg = System.Windows.Forms.MessageBox.Show("This NSP is not supported!",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
if (uspg == System.Windows.Forms.DialogResult.OK)
return;
}
if (keylabel.Content.Equals("0"))
{
fwlabel.Content = "all";
}
if (keylabel.Content.Equals("1"))
{
fwlabel.Content = "1.0.0";
}
if (keylabel.Content.Equals("2"))
{
fwlabel.Content = "3.0.0";
}
if (keylabel.Content.Equals("3"))
{
fwlabel.Content = "3.0.1";
}
if (keylabel.Content.Equals("4"))
{
fwlabel.Content = "4.0.0";
}
if (keylabel.Content.Equals("5"))
{
fwlabel.Content = "5.0.0";
}
if (keylabel.Content.Equals("6"))
{
fwlabel.Content = "???";
DialogResult uspg = System.Windows.Forms.MessageBox.Show("This NSP is not supported yet!",
"Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
if (uspg == System.Windows.Forms.DialogResult.OK)
return;
}
patchxml();
}
19
View Source File : MainWindow.xaml.cs
License : GNU General Public License v2.0
Project Creator : adrifcastr
License : GNU General Public License v2.0
Project Creator : adrifcastr
public void patchxml()
{
statuslabel.Content = "Patching XML File...";
string xmldir = AppDomain.CurrentDomain.BaseDirectory + @"\\tmp";
string[] xmlfile = Directory.GetFiles(xmldir, "*.xml");
XDoreplacedent xdoc = XDoreplacedent.Load(xmlfile[0]);
var patch = xdoc.Root.Descendants("RequiredSystemVersion").FirstOrDefault();
if (patch == null)
return;
patch.Value = "0";
string xmlname = String.Join(",", xmlfile);
xdoc.Save(xmlname);
repacknsp();
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private void GameLoop_GameLaunched(object sender, StardewModdingAPI.Events.GameLaunchedEventArgs e)
{
loadedDialogues = new Dictionary<string, DialogueTree>();
loadedQuestionStrings = new Dictionary<string, string>();
loadedResponseStrings = new Dictionary<string, string>();
loadedTopicNames = new Dictionary<string, string>();
foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
{
try
{
int add = 0;
Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}");
DialogueTreeData json = contentPack.ReadJsonFile<DialogueTreeData>("content.json");
foreach (DialogueTree dialogue in json.dialogues)
{
loadedDialogues.Add(dialogue.topicID, dialogue);
add++;
}
foreach (var kvp in json.standardQuestions)
{
loadedQuestionStrings[kvp.Key] = kvp.Value;
}
foreach (var kvp in json.playerResponses)
{
loadedResponseStrings[kvp.Key] = kvp.Value;
}
foreach (var kvp in json.topicNames)
{
loadedTopicNames[kvp.Key] = kvp.Value;
}
Monitor.Log($"Got {add} dialogues from content pack {contentPack.Manifest.Name}", LogLevel.Debug);
}
catch (Exception ex)
{
Monitor.Log($"Error processing content.json in content pack {contentPack.Manifest.Name} {ex}", LogLevel.Error);
}
}
foreach(string t in loadedDialogues.Keys)
{
if (!loadedTopicNames.ContainsKey(t))
loadedTopicNames[t] = t;
}
Monitor.Log($"Got {loadedDialogues.Count} dialogues total", LogLevel.Debug);
if(Directory.Exists(Path.Combine(Helper.DirectoryPath, "work")))
{
foreach(string file in Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "work"), "*.json"))
{
string name = Path.GetFileNameWithoutExtension(file);
if (File.ReadAllText(file).Length > 0)
continue;
if(name == "content")
{
Monitor.Log($"Building content.json for [DT] pack");
DialogueTreeData dtd = new DialogueTreeData();
foreach(DialogueTree dt in loadedDialogues.Values)
{
foreach(string id in dt.questionIDs)
{
if(!loadedQuestionStrings.ContainsKey(id))
dtd.standardQuestions[id] = "";
}
foreach(string id in dt.responseIDs)
{
dtd.playerResponses[id] = "";
}
}
Helper.Data.WriteJsonFile(Path.Combine("work",Path.GetFileName(file)), dtd);
}
else
{
Monitor.Log($"Building {name}.json for [CP] pack");
CharacterDataModel cdm = new CharacterDataModel(name);
foreach (DialogueTree dt in loadedDialogues.Values)
{
foreach (string id in dt.questionIDs)
{
cdm.Changes[0].Entries[$"DialogueTrees_question_{id}"] = "";
}
cdm.Changes[0].Entries[$"DialogueTrees_response_{dt.topicID}_1"] = "";
foreach (string id in dt.responseIDs)
{
cdm.Changes[0].Entries[$"DialogueTrees_reaction_{dt.topicID}_{id}_1"] = "";
cdm.Changes[0].Entries[$"DialogueTrees_friendship_{dt.topicID}_{id}_1"] = "0";
}
}
Helper.Data.WriteJsonFile(Path.Combine("work", Path.GetFileName(file)), cdm);
}
}
}
}
19
View Source File : MapActions.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static void GetMapCollectionData()
{
string modPath = ModEntry.SHelper.DirectoryPath;
ModEntry.mapCollectionData = new MapCollectionData();
var mapEdits = new List<MapCollectionData>();
if (ModEntry.Config.IncludeGlobalEdits && File.Exists(Path.Combine(modPath, "map_data.json")))
{
mapEdits.Add(GetMapEdits("map_data.json"));
}
if (Directory.Exists(Path.Combine(ModEntry.SHelper.DirectoryPath, "custom")))
{
foreach (string file in Directory.GetFiles(Path.Combine(ModEntry.SHelper.DirectoryPath, "custom"), "*.json"))
{
mapEdits.Add(GetMapEdits(Path.Combine("custom", Path.GetFileName(file))));
}
}
if (ModEntry.Config.UseSaveSpecificEdits)
{
if (!Directory.Exists(Path.Combine(modPath, "data")))
Directory.CreateDirectory(Path.Combine(modPath, "data"));
mapEdits.Add(GetMapEdits(Path.Combine("data", Constants.SaveFolderName + "_map_data.json")));
}
foreach(MapCollectionData data in mapEdits)
{
foreach(var map in data.mapDataDict)
{
if (!ModEntry.mapCollectionData.mapDataDict.ContainsKey(map.Key))
{
ModEntry.mapCollectionData.mapDataDict[map.Key] = map.Value;
}
else
{
foreach(var tile in map.Value.tileDataDict)
{
ModEntry.mapCollectionData.mapDataDict[map.Key].tileDataDict[tile.Key] = tile.Value;
}
}
}
}
ModEntry.SMonitor.Log($"Loaded map data for {ModEntry.mapCollectionData.mapDataDict.Count} maps");
}
19
View Source File : PhoneGameLoop.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static void GameLoop_GameLaunched(object sender, StardewModdingAPI.Events.GameLaunchedEventArgs e)
{
foreach (IContentPack contentPack in Helper.ContentPacks.GetOwned())
{
Monitor.Log($"Reading content pack: {contentPack.Manifest.Name} {contentPack.Manifest.Version} from {contentPack.DirectoryPath}");
try
{
MobilePhonePackJSON json = contentPack.ReadJsonFile<MobilePhonePackJSON>("content.json") ?? null;
if(json != null)
{
if (json.apps != null && json.apps.Any())
{
foreach (AppJSON app in json.apps)
{
Texture2D tex = contentPack.Loadreplacedet<Texture2D>(app.iconPath);
if (tex == null)
{
continue;
}
ModEntry.apps.Add(app.id, new MobileApp(app.name, app.keyPress, app.closePhone, tex));
Monitor.Log($"Added app {app.name} from {contentPack.DirectoryPath}");
}
}
else if (json.iconPath != null)
{
Texture2D icon = contentPack.Loadreplacedet<Texture2D>(json.iconPath);
if (icon == null)
{
continue;
}
ModEntry.apps.Add(json.id, new MobileApp(json.name, json.keyPress, json.closePhone, icon));
Monitor.Log($"Added app {json.name} from {contentPack.DirectoryPath}");
}
if (json.invites != null && json.invites.Any())
{
foreach (EventInvite invite in json.invites)
{
MobilePhoneCall.eventInvites.Add(invite);
Monitor.Log($"Added event invite {invite.name} from {contentPack.DirectoryPath}");
}
}
}
}
catch (Exception ex)
{
Monitor.Log($"error reading content.json file in content pack {contentPack.Manifest.Name}.\r\n{ex}", LogLevel.Error);
}
if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "events")))
{
Monitor.Log($"Adding events");
string[] events = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "events"), "*.json");
Monitor.Log($"CP has {events.Length} events");
foreach (string eventFile in events)
{
try
{
string eventPath = Path.Combine("replacedets", "events", Path.GetFileName(eventFile));
Monitor.Log($"Adding events {Path.GetFileName(eventFile)} from {contentPack.DirectoryPath}");
Reminiscence r = contentPack.ReadJsonFile<Reminiscence>(eventPath);
MobilePhoneCall.contentPackReminiscences.Add(Path.GetFileName(eventFile).Replace(".json", ""), r);
Monitor.Log($"Added event {Path.GetFileName(eventFile)} from {contentPack.DirectoryPath}");
}
catch { }
}
}
if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "skins")))
{
Monitor.Log($"Adding skins");
string[] skins = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "skins"), "*_landscape.png");
Monitor.Log($"CP has {skins.Length} skins");
foreach (string skinFile in skins)
{
try
{
string skinPath = Path.Combine("replacedets", "skins", Path.GetFileName(skinFile));
Monitor.Log($"Adding skin {Path.GetFileName(skinFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
Texture2D skin = contentPack.Loadreplacedet<Texture2D>(skinPath.Replace("_landscape.png", ".png"));
Texture2D skinl = contentPack.Loadreplacedet<Texture2D>(skinPath);
ThemeApp.skinList.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(skinFile).Replace("_landscape.png", ""));
ThemeApp.skinDict.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(skinFile).Replace("_landscape.png", ""), new Texture2D[] { skin, skinl});
Monitor.Log($"Added skin {Path.GetFileName(skinFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
}
catch { }
}
}
if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "backgrounds")))
{
Monitor.Log($"Adding backgrounds");
string[] backgrounds = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "backgrounds"), "*_landscape.png");
Monitor.Log($"CP has {backgrounds.Length} backgrounds");
foreach (string backFile in backgrounds)
{
try
{
string backPath = Path.Combine("replacedets", "backgrounds", Path.GetFileName(backFile));
Monitor.Log($"Adding background {Path.GetFileName(backFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
Texture2D back = contentPack.Loadreplacedet<Texture2D>(backPath.Replace("_landscape.png", ".png"));
Texture2D backl = contentPack.Loadreplacedet<Texture2D>(backPath);
ThemeApp.backgroundDict.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(backFile).Replace("_landscape.png", ""), new Texture2D[] { back, backl });
ThemeApp.backgroundList.Add(contentPack.Manifest.UniqueID + ":" + Path.GetFileName(backFile).Replace("_landscape.png", ""));
Monitor.Log($"Added background {Path.GetFileName(backFile).Replace("_landscape.png", "")} from {contentPack.DirectoryPath}");
}
catch { }
}
}
if (Directory.Exists(Path.Combine(contentPack.DirectoryPath, "replacedets", "ringtones")))
{
Monitor.Log($"Adding ringtones");
string[] rings = Directory.GetFiles(Path.Combine(contentPack.DirectoryPath, "replacedets", "ringtones"), "*.wav");
Monitor.Log($"CP has {rings.Length} ringtones");
foreach (string path in rings)
{
try
{
object ring;
try
{
var type = Type.GetType("System.Media.SoundPlayer, System");
ring = Activator.CreateInstance(type, new object[] { path });
}
catch
{
ring = SoundEffect.FromStream(new FileStream(path, FileMode.Open));
}
if (ring != null)
{
ThemeApp.ringDict.Add(string.Concat(contentPack.Manifest.UniqueID,":", Path.GetFileName(path).Replace(".wav", "")), ring);
ThemeApp.ringList.Add(string.Concat(contentPack.Manifest.UniqueID,":", Path.GetFileName(path).Replace(".wav", "")));
Monitor.Log($"loaded ring {path}");
}
else
Monitor.Log($"Couldn't load ring {path}");
}
catch (Exception ex)
{
Monitor.Log($"Couldn't load ring {path}:\r\n{ex}", LogLevel.Error);
}
}
}
}
ModEntry.listHeight = Config.IconMarginY + (int)Math.Ceiling(ModEntry.apps.Count / (float)ModEntry.gridWidth) * (Config.IconHeight + Config.IconMarginY);
PhoneVisuals.CreatePhoneTextures();
PhoneUtils.RefreshPhoneLayout();
if (Helper.ModRegistry.IsLoaded("purrplingcat.npcadventure"))
{
INpcAdventureModApi api = Helper.ModRegistry.GetApi<INpcAdventureModApi>("purrplingcat.npcadventure");
if (api != null)
{
Monitor.Log("Loaded NpcAdventureModApi successfully");
ModEntry.npcAdventureModApi = api;
}
}
}
19
View Source File : ThemeApp.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private static void CreateThemeLists()
{
if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "skins")))
{
string[] skins = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "skins"), "*_landscape.png");
foreach (string path in skins)
{
try
{
Texture2D skin = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "skins", Path.GetFileName(path).Replace("_landscape", "")));
Texture2D skinl = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "skins", Path.GetFileName(path)));
if (skin != null && skinl != null)
{
skinDict.Add(Path.Combine("replacedets", "skins", Path.GetFileName(path).Replace("_landscape", "")), new Texture2D[] { skin, skinl });
Monitor.Log($"loaded skin {path.Replace("_landscape", "")}");
}
else
Monitor.Log($"Couldn't load skin {path.Replace("_landscape", "")}: texture was null", LogLevel.Error);
}
catch (Exception ex)
{
Monitor.Log($"Couldn't load skin {path.Replace("_landscape", "")}: {ex}", LogLevel.Error);
}
}
}
if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "backgrounds")))
{
string[] papers = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "backgrounds"), "*_landscape.png");
foreach (string path in papers)
{
try
{
Texture2D back = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path).Replace("_landscape", "")));
Texture2D backl = Helper.Content.Load<Texture2D>(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path)));
if (back != null && backl != null)
{
backgroundDict.Add(Path.Combine("replacedets", "backgrounds", Path.GetFileName(path).Replace("_landscape", "")), new Texture2D[] { back, backl });
Monitor.Log($"loaded background {path.Replace("_landscape", "")}");
}
else
Monitor.Log($"Couldn't load background {path.Replace("_landscape", "")}: texture was null", LogLevel.Error);
}
catch (Exception ex)
{
Monitor.Log($"Couldn't load background {path.Replace("_landscape", "")}: {ex}", LogLevel.Error);
}
}
}
if (Directory.Exists(Path.Combine(Helper.DirectoryPath, "replacedets", "ringtones")))
{
string[] rings = Directory.GetFiles(Path.Combine(Helper.DirectoryPath, "replacedets", "ringtones"), "*.wav");
foreach (string path in rings)
{
try
{
object ring;
try
{
var type = Type.GetType("System.Media.SoundPlayer, System");
ring = Activator.CreateInstance(type, new object[] { path });
}
catch
{
ring = SoundEffect.FromStream(new FileStream(path, FileMode.Open));
}
if (ring != null)
{
ringDict.Add(Path.GetFileName(path).Replace(".wav", ""), ring);
Monitor.Log($"loaded ring {path}");
}
else
Monitor.Log($"Couldn't load ring {path}", LogLevel.Error);
}
catch (Exception ex)
{
Monitor.Log($"Couldn't load ring {path}:\r\n{ex}", LogLevel.Error);
}
}
rings = Config.BuiltInRingTones.Split(',');
foreach (string ring in rings)
{
ringDict.Add(ring, null);
}
}
ringList = ringDict.Keys.ToList();
skinList = skinDict.Keys.ToList();
backgroundList = backgroundDict.Keys.ToList();
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
private static void Furniture_placementAction_Prefix(Furniture __instance)
{
if(__instance.furniture_type == 6 && SHelper.Input.IsDown(Config.ModKey))
{
var paintingFiles = Directory.GetFiles(Path.Combine(SHelper.DirectoryPath, "paintings"), "*.*");
}
}
19
View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public override void Entry(IModHelper helper)
{
context = this;
Config = Helper.ReadConfig<ModConfig>();
if (!Config.EnableMod)
return;
string path = Path.Combine(Helper.DirectoryPath, "replacedets");
if (!Directory.Exists(path))
{
Monitor.Log($"replacedets folder not found. No videos will be loaded.", LogLevel.Warn);
return;
}
videoFiles = Directory.GetFiles(path, "*.wmv");
if (videoFiles.Length == 0)
{
Monitor.Log($"No videos found to play.", LogLevel.Warn);
return;
}
Monitor.Log($"Loaded {videoFiles.Length} videos.", LogLevel.Debug);
SetVideo(0);
MakeTextures();
Helper.Events.GameLoop.GameLaunched += GameLoop_GameLaunched;
Helper.Events.Input.ButtonPressed += Input_ButtonPressed;
Helper.Events.Display.Rendered += Display_Rendered;
}
19
View Source File : MapActions.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn
License : GNU General Public License v3.0
Project Creator : aedenthorn
public static void SaveMapTile(string map, Vector2 tileLoc, TileLayers tile)
{
if (tile == null)
{
ModEntry.mapCollectionData.mapDataDict[map].tileDataDict.Remove(tileLoc);
if (ModEntry.mapCollectionData.mapDataDict[map].tileDataDict.Count == 0)
ModEntry.mapCollectionData.mapDataDict.Remove(map);
}
else
{
if (!ModEntry.mapCollectionData.mapDataDict.ContainsKey(map))
ModEntry.mapCollectionData.mapDataDict[map] = new MapData();
ModEntry.mapCollectionData.mapDataDict[map].tileDataDict[Game1.currentCursorTile] = new TileLayers(ModEntry.currentTileDict);
}
string modPath = ModEntry.SHelper.DirectoryPath;
if (ModEntry.Config.IncludeGlobalEdits)
{
var mapData = GetMapEdits("map_data.json");
if (tile == null)
{
if (mapData.mapDataDict.ContainsKey(map) && mapData.mapDataDict[map].tileDataDict.ContainsKey(tileLoc))
{
mapData.mapDataDict[map].tileDataDict.Remove(tileLoc);
if (mapData.mapDataDict[map].tileDataDict.Count == 0)
mapData.mapDataDict.Remove(map);
SaveMapData(Path.Combine("map_data.json"), mapData);
}
}
else if (!ModEntry.Config.UseSaveSpecificEdits || (mapData.mapDataDict.ContainsKey(map) && mapData.mapDataDict[map].tileDataDict.ContainsKey(tileLoc))) // save new to global if not using save specific
{
if (!mapData.mapDataDict.ContainsKey(map))
mapData.mapDataDict[map] = new MapData();
mapData.mapDataDict[map].tileDataDict[tileLoc] = tile;
SaveMapData(Path.Combine("map_data.json"), mapData);
}
}
if (Directory.Exists(Path.Combine(modPath, "custom")))
{
foreach (string file in Directory.GetFiles(Path.Combine(modPath, "custom"), "*.json"))
{
string relPath = Path.Combine("custom", Path.GetFileName(file));
var mapData = GetMapEdits(relPath);
if (mapData.mapDataDict.ContainsKey(map) && mapData.mapDataDict[map].tileDataDict.ContainsKey(tileLoc)) // only edit if custom file contains this
{
if (tile == null)
{
mapData.mapDataDict[map].tileDataDict.Remove(tileLoc);
if (mapData.mapDataDict[map].tileDataDict.Count == 0)
mapData.mapDataDict.Remove(map);
}
else
{
mapData.mapDataDict[map].tileDataDict[tileLoc] = tile;
}
SaveMapData(relPath, mapData);
}
}
}
if (ModEntry.Config.UseSaveSpecificEdits)
{
string relPath = Path.Combine("data", Constants.SaveFolderName + "_map_data.json");
var mapData = new MapCollectionData();
if (!Directory.Exists(Path.Combine(modPath, "data")))
Directory.CreateDirectory(Path.Combine(modPath, "data"));
else
mapData = GetMapEdits(relPath);
if (tile == null)
{
if (mapData.mapDataDict.ContainsKey(map) && mapData.mapDataDict[map].tileDataDict.ContainsKey(tileLoc))
{
mapData.mapDataDict[map].tileDataDict.Remove(tileLoc);
if (mapData.mapDataDict[map].tileDataDict.Count == 0)
mapData.mapDataDict.Remove(map);
}
}
else // always save new to save specific
{
if (!mapData.mapDataDict.ContainsKey(map))
mapData.mapDataDict[map] = new MapData();
mapData.mapDataDict[map].tileDataDict[tileLoc] = tile;
}
SaveMapData(relPath, mapData);
}
ModEntry.cleanMaps.Remove(map);
}
19
View Source File : Build.cs
License : GNU General Public License v3.0
Project Creator : Aetsu
License : GNU General Public License v3.0
Project Creator : Aetsu
public static void Confuse(string folder)
{
string[] exeList = Directory.GetFiles(folder, "*.exe");
foreach (string exe in exeList)
{
string text = File.ReadAllText(Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "template_confuserEx.crproj" }));
text = text.Replace("{{BASE_DIR}}", folder);
text = text.Replace("{{OUTPUT_DIR}}", Path.Combine(new string[] { folder, "Confused" }));
text = text.Replace("{{EXE_FILE}}", exe);
string crprojPath = Path.Combine(new string[] { folder, exe + ".crproj" });
System.IO.File.WriteAllText(crprojPath, text);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(" Confusing " + exe + "...");
Console.ResetColor();
if (Helpers.ExecuteCommand(
Path.Combine(new string[] { Directory.GetCurrentDirectory(), "Resources", "ConfuserEx", "Confuser.CLI.exe" }) + " " + crprojPath) != 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" Error -> ConfuserEx: {0}", exe);
Console.ResetColor();
}
else
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(" No errors!");
Console.ResetColor();
}
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : Aetsu
License : GNU General Public License v3.0
Project Creator : Aetsu
static void replacedyzeTools()
{
string[] toolList = Directory.GetFiles("Tools", "*.yml");
foreach (string tool in toolList)
{
string outputFolder = string.Empty;
string toolPath = string.Empty;
string text = File.ReadAllText(tool);
var stringReader = new StringReader(text);
var yaml = new YamlStream();
yaml.Load(stringReader);
var mapping = (YamlMappingNode)yaml.Doreplacedents[0].RootNode;
foreach (var entry in mapping.Children)
{
var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("tool")];
foreach (YamlMappingNode item in items)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\n[+] Name: {0}", item.Children[new YamlScalarNode("name")]);
Console.ResetColor();
Console.WriteLine(" - Description: {0}\n - Git link: {1}\n - Solution file: {2}\n",
item.Children[new YamlScalarNode("description")],
item.Children[new YamlScalarNode("gitLink")],
item.Children[new YamlScalarNode("solutionPath")]);
try
{
toolPath = Build.DownloadRepository(item.Children[new YamlScalarNode("name")].ToString()
, item.Children[new YamlScalarNode("gitLink")].ToString());
outputFolder = Build.BuildTool(
item.Children[new YamlScalarNode("solutionPath")].ToString(),
item.Children[new YamlScalarNode("name")].ToString());
if (Helpers.ExecuteCommand("RMDIR \"" + toolPath + "\" /S /Q") != 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(" Error -> RMDIR: {0}", toolPath);
Helpers.LogToFile("replacedyzeTools", "ERROR", "RMDIR: <" + toolPath + ">");
Console.ResetColor();
}
Build.Confuse(outputFolder);
Helpers.CalculateMD5Files(outputFolder);
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine(" Output folder: {0}", outputFolder);
Console.ResetColor();
}
catch (Exception ex)
{
Console.WriteLine(" Error -> replacedyzing: <{0}> -> {1}", item.Children[new YamlScalarNode("name")], ex.ToString());
Helpers.LogToFile("replacedyzeTools", "ERROR", "replacedyzing: <" + item.Children[new YamlScalarNode("name")] + "> -> " + ex.ToString());
}
}
}
}
}
19
View Source File : Program.cs
License : GNU General Public License v3.0
Project Creator : Aetsu
License : GNU General Public License v3.0
Project Creator : Aetsu
static void ListTools()
{
string[] toolList = Directory.GetFiles("Tools", "*.yml");
foreach (string tool in toolList)
{
string text = File.ReadAllText(tool);
var stringReader = new StringReader(text);
var yaml = new YamlStream();
yaml.Load(stringReader);
var mapping = (YamlMappingNode)yaml.Doreplacedents[0].RootNode;
foreach (var entry in mapping.Children)
{
var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("tool")];
foreach (YamlMappingNode item in items)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\n [+] Name: {0}", item.Children[new YamlScalarNode("name")]);
Console.ResetColor();
Console.WriteLine(" - Description: {0}\n - Git: {1}",
item.Children[new YamlScalarNode("description")],
item.Children[new YamlScalarNode("gitLink")]);
}
}
}
Console.WriteLine();
}
19
View Source File : LayoutSelectionDialog.cs
License : GNU General Public License v2.0
Project Creator : afrantzis
License : GNU General Public License v2.0
Project Creator : afrantzis
void PopulateLayoutList()
{
// specify the column types
TreeStore ts = new TreeStore(typeof(string), typeof(string));
TreeIter ti = ts.AppendValues(Catalog.GetString("System-wide Layouts"), string.Empty);
// fill list from bless data dir
string dataDir = FileResourcePath.GetDataPath("data");
if (Directory.Exists(dataDir)) {
string[] files = Directory.GetFiles(dataDir, "*.layout");
foreach (string s in files) {
ts.AppendValues(ti, System.IO.Path.GetFileName(s), s);
}
}
ti = ts.AppendValues(Catalog.GetString("User Layouts"), string.Empty);
// fill list from user layout dir
if (Directory.Exists(layoutDir)) {
string[] files = Directory.GetFiles(layoutDir, "*.layout");
foreach (string s in files) {
ts.AppendValues(ti, System.IO.Path.GetFileName(s), s);
}
}
// Create the treeview
LayoutList.Model = ts;
LayoutList.AppendColumn("Layout", new CellRendererText (), "text", (int)LayoutColumn.Filename);
LayoutList.ExpandAll();
LayoutList.Selection.Changed += OnLayoutListSelectionChanged;
}
19
View Source File : IOHelper.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public static void CopyPath(string srcPath, string destPath, string ext = "*.*", bool child = true, bool replace = false, params string[] excludes)
{
if (!Directory.Exists(srcPath))
{
return;
}
CheckPath(destPath);
foreach (var ch in Directory.GetFiles(srcPath, ext))
{
if (excludes != null && excludes.Contains(Path.GetExtension(ch), StringComparer.OrdinalIgnoreCase))
{
continue;
}
var ch2 = Path.Combine(destPath, Path.GetFileName(ch));
if (replace || !File.Exists(ch2))
{
File.Copy(ch, ch2, true);
}
}
if (!child)
{
return;
}
foreach (var ch in Directory.GetDirectories(srcPath))
{
if (excludes != null && excludes.Contains(Path.GetFileName(ch), StringComparer.OrdinalIgnoreCase))
{
continue;
}
CopyPath(ch, Path.Combine(destPath, Path.GetFileName(ch) ?? throw new InvalidOperationException()), ext, true, replace, excludes);
}
}
19
View Source File : CacheManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public void RemoveSession(string sessionId)
{
try
{
string dir = Path.Combine(CachePath, sessionId);
int rdiCount = Directory.GetFiles(dir, "*.rdi").Length;
Debug.replacedert(rdiCount == 0);
if (rdiCount == 0)
Directory.Delete(dir, true);
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
View Source File : CacheManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public bool TryRemoveSession(string sessionId)
{
bool removed = false;
try
{
string dir = Path.Combine(CachePath, sessionId);
string rde = Path.Combine(dir, "0.rde");
int rdiCount = Directory.GetFiles(dir, "*.rdi").Length;
//Debug.replacedert(rdiCount == 0);
if (File.Exists(rde) && rdiCount == 0)
{
Directory.Delete(dir, true);
removed = true;
}
else if (Directory.GetLastWriteTime(dir).AddMinutes(30) < DateTime.Now)
{
Directory.Delete(dir, true);
removed = true;
}
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
return removed;
}
19
View Source File : CacheManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public bool TryRemoveSession(string sessionId)
{
bool removed = false;
try
{
string dir = Path.Combine(CachePath, sessionId);
string rde = Path.Combine(dir, "0.rde");
int rdiCount = Directory.GetFiles(dir, "*.rdi").Length;
//Debug.replacedert(rdiCount == 0);
if (File.Exists(rde) && rdiCount == 0)
{
Directory.Delete(dir, true);
removed = true;
}
else if (Directory.GetLastWriteTime(dir).AddMinutes(30) < DateTime.Now)
{
Directory.Delete(dir, true);
removed = true;
}
}
catch (Exception ex) { TraceLog.WriteException(ex); throw; }
return removed;
}
19
View Source File : CacheManager.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public void TryRemoveSession(string sessionId)
{
try
{
string dir = Path.Combine(CachePath, sessionId);
string rde = Path.Combine(dir, "0.rde");
int rdiCount = Directory.GetFiles(dir, "*.rdi").Length;
//Debug.replacedert(rdiCount == 0);
if (rdiCount == 0 && File.Exists(rde))
Directory.Delete(dir, true);
else if (Directory.GetLastWriteTime(dir).AddDays(1) < DateTime.Now)
Directory.Delete(dir, true);
}
catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
}
19
View Source File : Program.cs
License : MIT License
Project Creator : airbreather
License : MIT License
Project Creator : airbreather
private static CsvFile[] GetCsvFiles([CallerFilePath]string myLocation = null)
{
string csvFileDirectoryPath = Path.Combine(Path.GetDirectoryName(myLocation), "large-csv-files");
if (!Directory.Exists(csvFileDirectoryPath))
{
string tmpDirectoryPath = csvFileDirectoryPath + "-tmp";
if (Directory.Exists(tmpDirectoryPath))
{
Directory.Delete(tmpDirectoryPath, true);
}
string zipFilePath = csvFileDirectoryPath + ".zip";
Directory.CreateDirectory(tmpDirectoryPath);
ZipFile.ExtractToDirectory(zipFilePath, tmpDirectoryPath);
Directory.Move(tmpDirectoryPath, csvFileDirectoryPath);
}
return Array.ConvertAll(Directory.GetFiles(csvFileDirectoryPath, "*.csv"),
fullPath => new CsvFile(fullPath));
}
19
View Source File : CampaignGenerator.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
private void CreateImageFiles(CampaignTemplate campaignTemplate, DCSCampaign campaign, string baseFileName)
{
string allyFlagName = campaignTemplate.GetCoalition(campaignTemplate.ContextCoalitionPlayer);
string enemyFlagName = campaignTemplate.GetCoalition((Coalition)(1 - (int)campaignTemplate.ContextCoalitionPlayer));
using (ImageMaker imgMaker = new())
{
string theaterImage;
string[] theaterImages = Directory.GetFiles($"{BRPaths.INCLUDE_JPG}Theaters\\", $"{campaignTemplate.ContextTheater}*.jpg");
if (theaterImages.Length == 0)
theaterImage = "_default.jpg";
else
theaterImage = "Theaters\\" + Path.GetFileName(Toolbox.RandomFrom(theaterImages));
// Print the name of the campaign over the campaign "replacedle picture"
imgMaker.TextOverlay.Text = campaign.Name;
imgMaker.TextOverlay.Alignment = ContentAlignment.TopCenter;
campaign.AddMediaFile($"{baseFileName}_replacedle.jpg",
imgMaker.GetImageBytes(
new ImageMakerLayer(theaterImage),
new ImageMakerLayer($"Flags\\{enemyFlagName}.png", ContentAlignment.MiddleCenter, -32, -32),
new ImageMakerLayer($"Flags\\{allyFlagName}.png", ContentAlignment.MiddleCenter, 32, 32)));
// Reset background and text overlay
imgMaker.BackgroundColor = Color.Black;
imgMaker.TextOverlay.Text = "";
campaign.AddMediaFile($"{baseFileName}_Success.jpg", imgMaker.GetImageBytes("Sky.jpg", $"Flags\\{allyFlagName}.png"));
campaign.AddMediaFile($"{baseFileName}_Failure.jpg", imgMaker.GetImageBytes("Fire.jpg", $"Flags\\{allyFlagName}.png", "Burning.png"));
}
}
19
View Source File : MissionGeneratorImages.cs
License : GNU General Public License v3.0
Project Creator : akaAgar
License : GNU General Public License v3.0
Project Creator : akaAgar
internal void Generatereplacedle(DCSMission mission, MissionTemplate template)
{
ImageMaker.TextOverlay.Alignment = ContentAlignment.MiddleCenter;
ImageMaker.TextOverlay.Text = mission.Briefing.Name;
List<ImageMakerLayer> imageLayers = new List<ImageMakerLayer>();
string[] theaterImages = Directory.GetFiles($"{BRPaths.INCLUDE_JPG}Theaters\\", $"{Database.Instance.GetEntry<DBEntryTheater>(template.ContextTheater).DCSID}*.jpg");
if (theaterImages.Length == 0)
imageLayers.Add(new ImageMakerLayer("_default.jpg"));
else
imageLayers.Add(new ImageMakerLayer("Theaters\\" + Path.GetFileName(Toolbox.RandomFrom(theaterImages))));
imageLayers.Add(new ImageMakerLayer($"Flags\\{template.GetCoalitionID(template.ContextPlayerCoalition)}.png", ContentAlignment.TopLeft, 8, 8, 0, .5));
byte[] imageBytes = ImageMaker.GetImageBytes(imageLayers.ToArray());
mission.AddMediaFile($"l10n/DEFAULT/replacedle_{mission.UniqueID}.jpg", imageBytes);
}
19
View Source File : PluginsManager.cs
License : MIT License
Project Creator : alaabenfatma
License : MIT License
Project Creator : alaabenfatma
public bool LoadPlugins()
{
var newFilesList = new List<string>(Directory.GetFiles(@"./Plugins/", "*.dll"));
var same = true;
if (newFilesList.Count != _plugins.Count)
{
_plugins = new List<string>(newFilesList.GetRange(0, newFilesList.Count));
same = false;
}
if (same && _container != null) return false;
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new replacedemblyCatalog(typeof(Node).replacedembly));
catalog.Catalogs.Add(new DirectoryCatalog(@"./"));
_container = new CompositionContainer(catalog);
try
{
_container.ComposeExportedValue("host", _host);
_container.ComposeExportedValue("bool", false);
_container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
Hub.LoadedExternalNodes = LoadedNodes;
return true;
}
19
View Source File : WindowUtils.cs
License : MIT License
Project Creator : AlexanderPro
License : MIT License
Project Creator : AlexanderPro
private static string GetSelectedFileFromDesktop(IntPtr hwnd)
{
var processPointer = IntPtr.Zero;
var virtualAllocPointer = IntPtr.Zero;
try
{
var itemNames = new List<string>();
var processId = (uint)0;
NativeMethods.GetWindowThreadProcessId(hwnd, out processId);
var itemCount = NativeMethods.SendMessage(hwnd, NativeConstants.LVM_GEreplacedEMCOUNT, 0, 0);
processPointer = NativeMethods.OpenProcess(NativeConstants.PROCESS_VM_OPERATION | NativeConstants.PROCESS_VM_READ | NativeConstants.PROCESS_VM_WRITE, false, processId);
virtualAllocPointer = NativeMethods.VirtualAllocEx(processPointer, IntPtr.Zero, 4096, NativeConstants.MEM_RESERVE | NativeConstants.MEM_COMMIT, NativeConstants.PAGE_READWRITE);
for (int i = 0; i < itemCount; i++)
{
var buffer = new byte[256];
var item = new LVITEM[1];
item[0].mask = NativeConstants.LVIF_TEXT;
item[0].iItem = i;
item[0].iSubItem = 0;
item[0].cchTextMax = buffer.Length;
item[0].pszText = (IntPtr)((int)virtualAllocPointer + Marshal.SizeOf(typeof(LVITEM)));
var numberOfBytesRead = (uint)0;
NativeMethods.WriteProcessMemory(processPointer, virtualAllocPointer, Marshal.UnsafeAddrOfPinnedArrayElement(item, 0), Marshal.SizeOf(typeof(LVITEM)), ref numberOfBytesRead);
NativeMethods.SendMessage(hwnd, NativeConstants.LVM_GEreplacedEMW, i, virtualAllocPointer.ToInt32());
NativeMethods.ReadProcessMemory(processPointer, (IntPtr)((int)virtualAllocPointer + Marshal.SizeOf(typeof(LVITEM))), Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0), buffer.Length, ref numberOfBytesRead);
var text = Encoding.Unicode.GetString(buffer, 0, (int)numberOfBytesRead);
text = text.Substring(0, text.IndexOf('\0'));
var result = NativeMethods.SendMessage(hwnd, NativeConstants.LVM_GEreplacedEMSTATE, i, (int)NativeConstants.LVIS_SELECTED);
if (result == NativeConstants.LVIS_SELECTED)
{
itemNames.Add(text);
}
}
if (itemNames.Any())
{
var desktopDirectoryName = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
var commonDesktopDirectoryName = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
var itemName = itemNames[0];
var fileNames = Directory.GetFiles(desktopDirectoryName, itemName + ".*").ToList();
fileNames.AddRange(Directory.GetFiles(commonDesktopDirectoryName, itemName + ".*"));
if (fileNames.Any())
{
var fileName = fileNames[0];
if (Path.GetExtension(fileName).ToLower() == ".lnk")
{
WshShell shell = new WshShell();
IWshShortcut link = (IWshShortcut)shell.CreateShortcut(fileName);
return link.TargetPath;
}
return fileName;
}
}
return string.Empty;
}
finally
{
if (processPointer != IntPtr.Zero && virtualAllocPointer != IntPtr.Zero)
{
NativeMethods.VirtualFreeEx(processPointer, virtualAllocPointer, 0, NativeConstants.MEM_RELEASE);
}
if (processPointer != IntPtr.Zero)
{
NativeMethods.CloseHandle(processPointer);
}
}
}
19
View Source File : ArduinoThread.cs
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet
License : GNU General Public License v3.0
Project Creator : AlexandreDoucet
string[] GetPortNamesOSX() //Function retreived from : https://answers.unity.com/questions/643078/serialportsgetportnames-error.html
{
List<string> serial_ports = new List<string>();
string[] ttys = System.IO.Directory.GetFiles("/dev/", "tty.*");
foreach (string dev in ttys)
{
serial_ports.Add(dev);
}
return serial_ports.ToArray();
}
19
View Source File : PluginManager.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
public void LoadPlugins(string pluginsPath)
{
if (!Directory.Exists(pluginsPath))
{
return;
}
string[] dllFileNames = Directory.GetFiles(pluginsPath, "*.dll");
ICollection<replacedembly> replacedemblies = new List<replacedembly>(dllFileNames.Length);
foreach (string dllFile in dllFileNames)
{
replacedembly pluginreplacedembly = LoadPlugin(dllFile);
replacedemblies.Add(pluginreplacedembly);
}
Type pluginType = typeof(PluginBase);
ICollection<Type> pluginTypes = new List<Type>();
foreach (replacedembly replacedembly in replacedemblies)
{
try
{
if (replacedembly != null)
{
Type[] types = replacedembly.GetTypes();
foreach (Type type in types)
{
if (type.IsInterface || type.IsAbstract)
{
continue;
}
else
{
if (type.IsSubclreplacedOf(pluginType))
{
pluginTypes.Add(type);
}
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error loading plugin {0}. Error Code: {1}", replacedembly.FullName, ex.Message);
}
}
this.GroupChatPlugins.Clear();
this.MessageComposePlugins.Clear();
foreach (Type type in pluginTypes)
{
var plugin = (PluginBase)Activator.CreateInstance(type);
if (plugin is IMessageComposePlugin messageComposePlugin)
{
this.MessageComposePlugins.Add(messageComposePlugin);
}
else if (plugin is IGroupChatPlugin groupChatPlugin)
{
this.GroupChatPlugins.Add(groupChatPlugin);
}
else if (plugin is IGroupChatCachePlugin groupChatCachePlugin)
{
this.GroupChatCachePlugins.Add(groupChatCachePlugin);
}
}
}
19
View Source File : PluginManager.cs
License : GNU General Public License v3.0
Project Creator : alexdillon
License : GNU General Public License v3.0
Project Creator : alexdillon
public void LoadPlugins(string pluginsPath)
{
this.GroupChatPluginsAutoInstalled.Clear();
this.GroupChatPluginsBuiltIn.Clear();
this.GroupChatPluginsManuallyInstalled.Clear();
this.MessageComposePluginsAutoInstalled.Clear();
this.MessageComposePluginsBuiltIn.Clear();
this.MessageComposePluginsManuallyInstalled.Clear();
Directory.CreateDirectory(pluginsPath);
Directory.CreateDirectory(Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory));
if (Directory.Exists(pluginsPath))
{
// Handle staged removals
foreach (var file in Directory.GetFiles(Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory), "*.rm"))
{
if (Path.GetFileNameWithoutExtension(file).EndsWith(PluginInstaller.StagingSuffix))
{
var originalPluginName = Path.GetFileNameWithoutExtension(file).Replace(PluginInstaller.StagingSuffix, string.Empty);
var originalPluginFullPath = Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory, originalPluginName);
if (new FileInfo(file).Length == 0)
{
// Delete the zero-byte staging stub
File.Delete(file);
// Delete the staged installation directory
if (Directory.Exists(originalPluginFullPath))
{
Directory.Delete(originalPluginFullPath, true);
}
}
}
}
// Handle staged upgrades
foreach (var directory in Directory.GetDirectories(Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory)))
{
if (Path.GetFileNameWithoutExtension(directory).EndsWith(PluginInstaller.StagingSuffix))
{
var originalPluginName = Path.GetFileNameWithoutExtension(directory).Replace(PluginInstaller.StagingSuffix, string.Empty);
var originalPluginFullPath = Path.Combine(pluginsPath, PluginInstaller.PackagesDirectory, originalPluginName);
if (Directory.Exists(originalPluginFullPath))
{
Directory.Delete(originalPluginFullPath, true);
}
Directory.Move(directory, originalPluginFullPath);
}
}
var dllFileNames = Directory.GetFiles(pluginsPath, "*.dll", SearchOption.AllDirectories);
var replacedemblies = new List<replacedembly>(dllFileNames.Length);
foreach (string dllFile in dllFileNames)
{
var an = replacedemblyName.GetreplacedemblyName(dllFile);
var replacedembly = replacedembly.Load(an);
replacedemblies.Add(replacedembly);
}
var pluginType = typeof(PluginBase);
var pluginTypes = new List<Type>();
foreach (var replacedembly in replacedemblies)
{
if (replacedembly != null)
{
try
{
var types = replacedembly.GetTypes();
foreach (var type in types)
{
if (type.IsInterface || type.IsAbstract)
{
continue;
}
else
{
if (type.IsSubclreplacedOf(pluginType))
{
pluginTypes.Add(type);
}
}
}
}
catch (Exception)
{
Debug.WriteLine($"Failed to load plugin {replacedembly.FullName}");
}
}
}
var pluginInstaller = Ioc.Default.GetService<PluginInstaller>();
foreach (var type in pluginTypes)
{
var hostedreplacedemblyName = Path.GetFileNameWithoutExtension(Path.GetDirectoryName(type.Module.replacedembly.Location));
var installedPlugin = pluginInstaller.InstalledPlugins.FirstOrDefault(p => p.InstallationGuid == hostedreplacedemblyName);
var plugin = (PluginBase)Activator.CreateInstance(type);
if (plugin is IMessageComposePlugin messageComposePlugin)
{
if (installedPlugin == null)
{
this.MessageComposePluginsManuallyInstalled.Add(messageComposePlugin);
}
else
{
this.MessageComposePluginsAutoInstalled.Add(messageComposePlugin);
}
}
else if (plugin is IGroupChatPlugin groupChatPlugin)
{
if (installedPlugin == null)
{
this.GroupChatPluginsManuallyInstalled.Add(groupChatPlugin);
}
else
{
this.GroupChatPluginsAutoInstalled.Add(groupChatPlugin);
}
}
}
}
// Load plugins that ship directly in GMDC/Wpf
this.GroupChatPluginsBuiltIn.Add(new ImageGalleryPlugin());
}
19
View Source File : DiagnosticVerifier.Helper.cs
License : MIT License
Project Creator : AlexGhiondea
License : MIT License
Project Creator : AlexGhiondea
private static Project CreateProject(string[] sources, string language = LanguageNames.CSharp)
{
string fileNamePrefix = DefaultFilePathPrefix;
string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;
var projectId = ProjectId.CreateNewId(debugName: TestProjectName);
// we should get all the files in the shared framework loaded...
string pathToSharedFx = Path.GetDirectoryName(typeof(object).replacedembly.Location);
var files = Directory.GetFiles(pathToSharedFx, "System*dll");
List<MetadataReference> refs = new List<MetadataReference>();
foreach (var item in files)
{
refs.Add(MetadataReference.CreateFromFile(item));
}
// add netStandard.dll to the mix
var ns20 = Path.Combine(pathToSharedFx, "netstandard.dll");
refs.Add(MetadataReference.CreateFromFile(ns20));
var solution = new AdhocWorkspace()
.CurrentSolution
.AddProject(projectId, TestProjectName, TestProjectName, language)
.AddMetadataReference(projectId, CSharpSymbolsReference)
.AddMetadataReference(projectId, CodereplacedysisReference)
.AddMetadataReferences(projectId, refs)
.AddMetadataReference(projectId, PathToCommandLinereplacedemblyToReference);
//.AddMetadataReference(projectId, MetadataReference.CreateFromFile(@"D:\code\github\alexghiondea\OutputColorizer\bin\Debug\netstandard1.3\OutputColorizer.dll"));
int count = 0;
foreach (var source in sources)
{
var newFileName = fileNamePrefix + count + "." + fileExt;
var doreplacedentId = DoreplacedentId.CreateNewId(projectId, debugName: newFileName);
solution = solution.AddDoreplacedent(doreplacedentId, newFileName, SourceText.From(source));
count++;
}
return solution.GetProject(projectId);
}
19
View Source File : Style.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
License : GNU General Public License v3.0
Project Creator : alexgracianoarj
private static bool LoadStyles()
{
try
{
if (Directory.Exists(StylesDirectory))
{
string[] files = Directory.GetFiles(StylesDirectory, "*.dst");
foreach (string file in files)
Load(file);
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
19
View Source File : ProjectInfo.cs
License : MIT License
Project Creator : aliencube
License : MIT License
Project Creator : aliencube
private void SetProjectPath(string path)
{
if (path.IsNullOrWhiteSpace() || path == ".")
{
this._projectPath = Environment.CurrentDirectory.TrimEnd(directorySeparator);
var filepath = Directory.GetFiles(this._projectPath, "*.csproj").SingleOrDefault();
if (filepath.IsNullOrWhiteSpace())
{
throw new FileNotFoundException();
}
var csproj = new FileInfo(filepath);
this._filename = csproj.Name;
return;
}
var fqpath =
#if NETFRAMEWORK
System.IO.Path.IsPathRooted(path)
#else
System.IO.Path.IsPathFullyQualified(path)
#endif
? path
: $"{Environment.CurrentDirectory.TrimEnd(directorySeparator)}{directorySeparator}{path}";
if (fqpath.EndsWith(".csproj"))
{
var csproj = new FileInfo(fqpath);
this._projectPath = csproj.DirectoryName.TrimEnd(directorySeparator);
this._filename = csproj.Name;
return;
}
var di = new DirectoryInfo(fqpath);
this._projectPath = di.FullName.TrimEnd(directorySeparator);
var segments = di.FullName.Split(new[] { directorySeparator }, StringSplitOptions.RemoveEmptyEntries);
this._filename = $"{segments.Last()}.csproj";
}
19
View Source File : VideoMuxing.cs
License : MIT License
Project Creator : Alkl58
License : MIT License
Project Creator : Alkl58
public static async Task Concat()
{
// ══════════════════════════════════════ Chunk Parsing ══════════════════════════════════════
// Writes all ivf files into chunks.txt for later concat
IOrderedEnumerable<string> sorted = null;
if (MainWindow.EncodeMethod <= 4)
{
sorted = Directory.GetFiles(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks"), "*.webm").OrderBy(f => f);
}
else
{
// rav1e external only supports ivf
sorted = Directory.GetFiles(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks"), "*.ivf").OrderBy(f => f);
}
using (StreamWriter outputFile = new StreamWriter(Path.Combine(Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks"), "chunks.txt")))
{
foreach (string fileTemp in sorted)
{
string tempName = fileTemp.Replace("'", "'\\''");
outputFile.WriteLine("file '" + tempName + "'");
}
}
bool audio = !EncodeAudio.noaudio;
bool vfr = MainWindow.VFRVideo;
bool sub = MainWindow.subSoftSubEnabled;
string ffmpegCommand;
// Replace ' with "'", else muxing will fail with single quotes in filename
Global.temp_path_folder.Replace("'", "\"'\"");
// ═══════════════════════════════════════ Chunk Muxing ══════════════════════════════════════
if (!audio && !vfr && !sub)
{
ffmpegCommand = "/C ffmpeg.exe -y -f concat -safe 0 -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "chunks.txt") + '\u0022' + " -c copy " + '\u0022' + Global.Video_Output + '\u0022';
Helpers.Logging("Muxing: " + ffmpegCommand);
await Task.Run(() => SmallFunctions.ExecuteFfmpegTask(ffmpegCommand));
}
else
{
// First Concats the video to a temp.mkv file
ffmpegCommand = "/C ffmpeg.exe -y -f concat -safe 0 -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Chunks", "chunks.txt") + '\u0022' + " -c copy " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "temp.mkv") + '\u0022';
Helpers.Logging("Muxing: " + ffmpegCommand);
await Task.Run(() => SmallFunctions.ExecuteFfmpegTask(ffmpegCommand));
}
if (audio)
{
if (!sub)
{
if (!vfr)
{
// Muxes Video & Audio together (required for MP4 output)
ffmpegCommand = "/C ffmpeg.exe -y -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "temp.mkv") + '\u0022' + " -i " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Audio", "audio.mkv") + '\u0022' + " -map 0:v -map 1:a -c copy " + '\u0022' + Global.Video_Output + '\u0022';
Helpers.Logging("Muxing: " + ffmpegCommand);
await Task.Run(() => SmallFunctions.ExecuteFfmpegTask(ffmpegCommand));
}
else
{
// Run mkvmerge command - only supports mkv / webm
string mkvmergeCommand = "/C mkvmerge.exe --output " + '\u0022' + Global.Video_Output + '\u0022' + " " + MainWindow.VFRCMD + " --language 0:und --default-track 0:yes " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "temp.mkv") + '\u0022' + " --default-track 0:yes " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Audio", "audio.mkv") + '\u0022';
Helpers.Logging("Muxing: " + mkvmergeCommand);
await Task.Run(() => SmallFunctions.ExecuteMKVMergeTask(mkvmergeCommand));
}
}
else
{
// Muxes Video & Audio & Subreplacedles together - MP4 not supported - also supports VFR
string mkvmergeCommand = "/C mkvmerge.exe --output " + '\u0022' + Global.Video_Output + '\u0022' + " " + MainWindow.VFRCMD + " --language 0:und --default-track 0:yes " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "temp.mkv") + '\u0022' + " --default-track 0:yes " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "Audio", "audio.mkv") + '\u0022' + " " + MainWindow.SubCommand;
Helpers.Logging("Muxing: " + mkvmergeCommand);
await Task.Run(() => SmallFunctions.ExecuteMKVMergeTask(mkvmergeCommand));
}
}
else if (!audio)
{
if (!sub)
{
if (vfr)
{
// Run mkvmerge command with VFR Support
string mkvmergeCommand = "/C mkvmerge.exe --output " + '\u0022' + Global.Video_Output + '\u0022' + " " + MainWindow.VFRCMD + " --language 0:und --default-track 0:yes " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "temp.mkv") + '\u0022';
Helpers.Logging("Muxing: " + mkvmergeCommand);
await Task.Run(() => SmallFunctions.ExecuteMKVMergeTask(mkvmergeCommand));
}
}
else
{
// Muxes Video & Subreplacedles together
string mkvmergeCommand = "/C mkvmerge.exe --output " + '\u0022' + Global.Video_Output + '\u0022' + " " + MainWindow.VFRCMD + " --language 0:und --default-track 0:yes " + '\u0022' + Path.Combine(Global.temp_path, Global.temp_path_folder, "temp.mkv") + '\u0022' + " " + MainWindow.SubCommand;
Helpers.Logging("Muxing: " + mkvmergeCommand);
await Task.Run(() => SmallFunctions.ExecuteMKVMergeTask(mkvmergeCommand));
}
}
}
19
View Source File : PdfImageConverter.cs
License : MIT License
Project Creator : allantargino
License : MIT License
Project Creator : allantargino
private async Task<string[]> ConvertAsync(string input, string ratio = "102.4")
{
var filename = new FileInfo(input).Name.Replace(".pdf", "");
var outdir = new FileInfo(input).FullName.Replace(".pdf", "");
Directory.CreateDirectory(outdir);
string output = "", err = "";
try
{
int exitCode = await Task.Run(() =>
{
String args = [email protected]"-dNOPAUSE -sDEVICE=jpeg -r{ratio} -o""{outdir}/{filename}_%d.jpg"" ""{input}""";
Console.WriteLine($"GS command line: {args}");
Process proc = new Process();
proc.StartInfo.FileName = _gsPath;
proc.StartInfo.Arguments = args;
proc.StartInfo.UseShellExecute = false;
proc.Start();
proc.WaitForExit();
return proc.ExitCode;
});
Thread.Sleep(500);
File.Delete(input);
if (exitCode == 0)
{
Console.WriteLine($"outdir: {outdir}");
return Directory.GetFiles(outdir, "*.jpg");
}
else
{
Console.WriteLine($"ExitCode: {exitCode} gs: {_gsPath} out: {output} err: {err} ");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error generating image from pdf: {ex.Message}");
throw new Exception(ex.Message, ex);
}
return null;
}
19
View Source File : AssemblyExtensions.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
public static List<replacedembly> LoadAllFrom(this replacedembly replacedembly, string includedFilePattern, params string[] excludedFileNames)
{
string[] replacedemblyFiles = null;
try
{
replacedemblyFiles = Directory.GetFiles(GetExecutingreplacedemblyDirectoryName(), "ClreplacedifyBot.*.dll").ToArray();
}
catch (Exception e)
{
L.Error(e, "Exception thrown searching directory {0} for file pattern {1}.", Directory.GetCurrentDirectory(), includedFilePattern);
return null;
}
if (replacedemblyFiles == null)
{
L.Debug("No included files preplaceded to LoadAllFrom() method");
return null;
}
else
{
return LoadAllFrom(replacedembly, replacedemblyFiles, excludedFileNames);
}
}
See More Examples