System.IO.Path.GetFileNameWithoutExtension(string)

Here are the examples of the csharp api System.IO.Path.GetFileNameWithoutExtension(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

5709 Examples 7

19 Source : DiskAccess.cs
with MIT License
from AiursoftWeb

public string[] GetAllFileNamesInHardware()
        {
            if (!Directory.Exists(_path))
            {
                Directory.CreateDirectory(_path);
            }
            return Directory.GetFiles(_path).Select(t => Path.GetFileNameWithoutExtension(t)).ToArray();
        }

19 Source : ImageCompressor.cs
with MIT License
from AiursoftWeb

public async Task<string> Compress(string path, int width, int height)
        {
            width = _sizeCalculator.Ceiling(width);
            height = _sizeCalculator.Ceiling(height);
            try
            {
                var compressedFolder = _tempFilePath + $"{Path.DirectorySeparatorChar}Compressed{Path.DirectorySeparatorChar}";
                if (Directory.Exists(compressedFolder) == false)
                {
                    Directory.CreateDirectory(compressedFolder);
                }
                var compressedImagePath = $"{compressedFolder}probe_compressed_w{width}_h{height}_fileId_{Path.GetFileNameWithoutExtension(path)}.dat";
                await SaveCompressedImage(path, compressedImagePath, width, height);
                return compressedImagePath;
            }
            catch (ImageFormatException)
            {
                return path;
            }
        }

19 Source : ImageCompressor.cs
with MIT License
from AiursoftWeb

public async Task<string> ClearExif(string path)
        {
            try
            {
                var clearedFolder = _tempFilePath + $"{Path.DirectorySeparatorChar}ClearedEXIF{Path.DirectorySeparatorChar}";
                if (Directory.Exists(clearedFolder) == false)
                {
                    Directory.CreateDirectory(clearedFolder);
                }
                var clearedImagePath = $"{clearedFolder}probe_cleared_file_id_{Path.GetFileNameWithoutExtension(path)}.dat";
                await ClearImage(path, clearedImagePath);
                return clearedImagePath;
            }
            catch (ImageFormatException)
            {
                return path;
            }
        }

19 Source : SteamVR_SkyboxEditor.cs
with MIT License
from ajayyy

public override void OnInspectorGUI()
	{
		DrawDefaultInspector();

		EditorGUILayout.HelpBox(helpText, MessageType.Info);

		if (GUILayout.Button("Take snapshot"))
		{
			var directions = new Quaternion[] {
				Quaternion.LookRotation(Vector3.forward),
				Quaternion.LookRotation(Vector3.back),
				Quaternion.LookRotation(Vector3.left),
				Quaternion.LookRotation(Vector3.right),
				Quaternion.LookRotation(Vector3.up, Vector3.back),
				Quaternion.LookRotation(Vector3.down, Vector3.forward)
			};

			Camera tempCamera = null;
			foreach (SteamVR_Skybox target in targets)
			{
				var targetScene = target.gameObject.scene;
                var sceneName = Path.GetFileNameWithoutExtension(targetScene.path);
				var scenePath = Path.GetDirectoryName(targetScene.path);
				var replacedetPath = scenePath + "/" + sceneName;
				if (!replacedetDatabase.IsValidFolder(replacedetPath))
				{
					var guid = replacedetDatabase.CreateFolder(scenePath, sceneName);
					replacedetPath = replacedetDatabase.GUIDToreplacedetPath(guid);
				}

				var camera = target.GetComponent<Camera>();
				if (camera == null)
				{
					if (tempCamera == null)
						tempCamera = new GameObject().AddComponent<Camera>();
					camera = tempCamera;
				}

				var targetTexture = camera.targetTexture;
				if (camera.targetTexture == null)
				{
					targetTexture = new RenderTexture(1024, 1024, 24);
					targetTexture.antiAliasing = 8;
					camera.targetTexture = targetTexture;
				}

				var oldPosition = target.transform.localPosition;
				var oldRotation = target.transform.localRotation;
				var baseRotation = target.transform.rotation;

				var t = camera.transform;
				t.position = target.transform.position;
				camera.orthographic = false;
				camera.fieldOfView = 90;

				for (int i = 0; i < directions.Length; i++)
				{
					t.rotation = baseRotation * directions[i];
					camera.Render();

					// Copy to texture and save to disk.
					RenderTexture.active = targetTexture;
					var texture = new Texture2D(targetTexture.width, targetTexture.height, TextureFormat.ARGB32, false);
					texture.ReadPixels(new Rect(0, 0, texture.width, texture.height), 0, 0);
					texture.Apply();
					RenderTexture.active = null;

					var replacedetName = string.Format(nameFormat, replacedetPath, target.name, i);
					System.IO.File.WriteAllBytes(replacedetName, texture.EncodeToPNG());
				}
	
				if (camera != tempCamera)
				{
					target.transform.localPosition = oldPosition;
					target.transform.localRotation = oldRotation;
				}
			}

			if (tempCamera != null)
			{
				Object.DestroyImmediate(tempCamera.gameObject);
			}

			// Now that everything has be written out, reload the replacedociated replacedets and replacedign them.
			replacedetDatabase.Refresh();
			foreach (SteamVR_Skybox target in targets)
			{
				var targetScene = target.gameObject.scene;
				var sceneName = Path.GetFileNameWithoutExtension(targetScene.path);
				var scenePath = Path.GetDirectoryName(targetScene.path);
				var replacedetPath = scenePath + "/" + sceneName;

				for (int i = 0; i < directions.Length; i++)
				{
					var replacedetName = string.Format(nameFormat, replacedetPath, target.name, i);
					var importer = replacedetImporter.GetAtPath(replacedetName) as TextureImporter;
#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
					importer.textureFormat = TextureImporterFormat.RGB24;
#else
					importer.textureCompression = TextureImporterCompression.Uncompressed;
#endif
					importer.wrapMode = TextureWrapMode.Clamp;
					importer.mipmapEnabled = false;
					importer.SaveAndReimport();

					var texture = replacedetDatabase.LoadreplacedetAtPath<Texture>(replacedetName);
					target.SetTextureByIndex(i, texture);
				}
			}
		}
		else if (GUILayout.Button("Take stereo snapshot"))
		{
			const int width = 4096;
			const int height = width / 2;
			const int halfHeight = height / 2;

			var textures = new Texture2D[] {
				new Texture2D(width, height, TextureFormat.ARGB32, false),
				new Texture2D(width, height, TextureFormat.ARGB32, false) };

			var timer = new System.Diagnostics.Stopwatch();

			Camera tempCamera = null;
			foreach (SteamVR_Skybox target in targets)
			{
				timer.Start();

				var targetScene = target.gameObject.scene;
				var sceneName = Path.GetFileNameWithoutExtension(targetScene.path);
				var scenePath = Path.GetDirectoryName(targetScene.path);
				var replacedetPath = scenePath + "/" + sceneName;
				if (!replacedetDatabase.IsValidFolder(replacedetPath))
				{
					var guid = replacedetDatabase.CreateFolder(scenePath, sceneName);
					replacedetPath = replacedetDatabase.GUIDToreplacedetPath(guid);
				}

				var camera = target.GetComponent<Camera>();
				if (camera == null)
				{
					if (tempCamera == null)
						tempCamera = new GameObject().AddComponent<Camera>();
					camera = tempCamera;
				}

				var fx = camera.gameObject.AddComponent<SteamVR_SphericalProjection>();

				var oldTargetTexture = camera.targetTexture;
				var oldOrthographic = camera.orthographic;
				var oldFieldOfView = camera.fieldOfView;
				var oldAspect = camera.aspect;

				var oldPosition = target.transform.localPosition;
				var oldRotation = target.transform.localRotation;
				var basePosition = target.transform.position;
				var baseRotation = target.transform.rotation;

				var transform = camera.transform;

				int cellSize = int.Parse(target.StereoCellSize.ToString().Substring(1));
	            float ipd = target.StereoIpdMm / 1000.0f;
				int vTotal = halfHeight / cellSize;
				float dv = 90.0f / vTotal; // vertical degrees per segment
				float dvHalf = dv / 2.0f;

				var targetTexture = new RenderTexture(cellSize, cellSize, 24);
				targetTexture.wrapMode = TextureWrapMode.Clamp;
				targetTexture.antiAliasing = 8;

				camera.fieldOfView = dv;
				camera.orthographic = false;
				camera.targetTexture = targetTexture;

				// Render sections of a sphere using a rectilinear projection
				// and resample using a sphereical projection into a single panorama
				// texture per eye.  We break into sections in order to keep the eye
				// separation similar around the sphere.  Rendering alternates between
				// top and bottom sections, sweeping horizontally around the sphere,
				// alternating left and right eyes.
				for (int v = 0; v < vTotal; v++)
				{
					var pitch = 90.0f - (v * dv) - dvHalf;
					var uTotal = width / targetTexture.width;
                    var du = 360.0f / uTotal; // horizontal degrees per segment
					var duHalf = du / 2.0f;

					var vTarget = v * halfHeight / vTotal;

					for (int i = 0; i < 2; i++) // top, bottom
					{
						if (i == 1)
						{
							pitch = -pitch;
							vTarget = height - vTarget - cellSize;
                        }

						for (int u = 0; u < uTotal; u++)
						{
							var yaw = -180.0f + (u * du) + duHalf;

							var uTarget = u * width / uTotal;

							var xOffset = -ipd / 2 * Mathf.Cos(pitch * Mathf.Deg2Rad);

							for (int j = 0; j < 2; j++) // left, right
							{
								var texture = textures[j];

								if (j == 1)
								{
									xOffset = -xOffset;
								}

								var offset = baseRotation * Quaternion.Euler(0, yaw, 0) * new Vector3(xOffset, 0, 0);
								transform.position = basePosition + offset;

								var direction = Quaternion.Euler(pitch, yaw, 0.0f);
								transform.rotation = baseRotation * direction;

								// vector pointing to center of this section
								var N = direction * Vector3.forward;

								// horizontal span of this section in degrees
								var phi0 = yaw - (du / 2);
								var phi1 = phi0 + du;

								// vertical span of this section in degrees
								var theta0 = pitch + (dv / 2);
								var theta1 = theta0 - dv;

								var midPhi = (phi0 + phi1) / 2;
								var baseTheta = Mathf.Abs(theta0) < Mathf.Abs(theta1) ? theta0 : theta1;

								// vectors pointing to corners of image closes to the equator
								var V00 = Quaternion.Euler(baseTheta, phi0, 0.0f) * Vector3.forward;
								var V01 = Quaternion.Euler(baseTheta, phi1, 0.0f) * Vector3.forward;

								// vectors pointing to top and bottom midsection of image
								var V0M = Quaternion.Euler(theta0, midPhi, 0.0f) * Vector3.forward;
								var V1M = Quaternion.Euler(theta1, midPhi, 0.0f) * Vector3.forward;

								// intersection points for each of the above
								var P00 = V00 / Vector3.Dot(V00, N);
								var P01 = V01 / Vector3.Dot(V01, N);
								var P0M = V0M / Vector3.Dot(V0M, N);
								var P1M = V1M / Vector3.Dot(V1M, N);

								// calculate basis vectors for plane
								var P00_P01 = P01 - P00;
								var P0M_P1M = P1M - P0M;

								var uMag = P00_P01.magnitude;
								var vMag = P0M_P1M.magnitude;

								var uScale = 1.0f / uMag;
								var vScale = 1.0f / vMag;

								var uAxis = P00_P01 * uScale;
								var vAxis = P0M_P1M * vScale;

								// update material constant buffer
								fx.Set(N, phi0, phi1, theta0, theta1,
									uAxis, P00, uScale,
									vAxis, P0M, vScale);

								camera.aspect = uMag / vMag;
								camera.Render();

								RenderTexture.active = targetTexture;
								texture.ReadPixels(new Rect(0, 0, targetTexture.width, targetTexture.height), uTarget, vTarget);
								RenderTexture.active = null;
							}
						}
					}
                }

				// Save textures to disk.
				for (int i = 0; i < 2; i++)
				{
					var texture = textures[i];

					texture.Apply();
					var replacedetName = string.Format(nameFormat, replacedetPath, target.name, i);
					File.WriteAllBytes(replacedetName, texture.EncodeToPNG());
				}

				// Cleanup.
				if (camera != tempCamera)
				{
					camera.targetTexture = oldTargetTexture;
					camera.orthographic = oldOrthographic;
					camera.fieldOfView = oldFieldOfView;
					camera.aspect = oldAspect;

					target.transform.localPosition = oldPosition;
					target.transform.localRotation = oldRotation;
                }
				else
				{
					tempCamera.targetTexture = null;
				}

				DestroyImmediate(targetTexture);
				DestroyImmediate(fx);

				timer.Stop();
				Debug.Log(string.Format("Screenshot took {0} seconds.", timer.Elapsed));
			}

			if (tempCamera != null)
			{
				DestroyImmediate(tempCamera.gameObject);
			}

			DestroyImmediate(textures[0]);
			DestroyImmediate(textures[1]);

			// Now that everything has be written out, reload the replacedociated replacedets and replacedign them.
			replacedetDatabase.Refresh();
			foreach (SteamVR_Skybox target in targets)
			{
				var targetScene = target.gameObject.scene;
				var sceneName = Path.GetFileNameWithoutExtension(targetScene.path);
				var scenePath = Path.GetDirectoryName(targetScene.path);
				var replacedetPath = scenePath + "/" + sceneName;

				for (int i = 0; i < 2; i++)
				{
					var replacedetName = string.Format(nameFormat, replacedetPath, target.name, i);
					var importer = replacedetImporter.GetAtPath(replacedetName) as TextureImporter;
					importer.mipmapEnabled = false;
					importer.wrapMode = TextureWrapMode.Repeat;
#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
					importer.SetPlatformTextureSettings("Standalone", width, TextureImporterFormat.RGB24);
#else
					var settings = importer.GetPlatformTextureSettings("Standalone");
					settings.textureCompression = TextureImporterCompression.Uncompressed;
					settings.maxTextureSize = width;
					importer.SetPlatformTextureSettings(settings);
#endif
					importer.SaveAndReimport();

					var texture = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(replacedetName);
					target.SetTextureByIndex(i, texture);
				}
			}
		}
	}

19 Source : Database.cs
with GNU General Public License v3.0
from akaAgar

private void LoadEntries<T>(string subDirectory) where T : DBEntry, new()
        {
            BriefingRoom.PrintToLog($"Loading {subDirectory.ToLowerInvariant()}...");

            string directory = $"{BRPaths.DATABASE}{subDirectory}";
            if (!Directory.Exists(directory))
                throw new Exception($"Directory {directory} not found.");

            Type dbType = typeof(T);
            string shortTypeName = dbType.Name.Substring(7).ToLowerInvariant();

            if (!DBEntries.ContainsKey(dbType))
                DBEntries.Add(dbType, new Dictionary<string, DBEntry>(StringComparer.InvariantCultureIgnoreCase));

            DBEntries[dbType].Clear();

            foreach (string filePath in Directory.EnumerateFiles(directory, "*.ini", SearchOption.AllDirectories))
            {
                string id = Path.GetFileNameWithoutExtension(filePath).Replace(",", "").Trim(); // No commas in file names, so we don't break comma-separated arrays

                if (DBEntries[dbType].ContainsKey(id)) continue;
                T entry = new T();
                if (!entry.Load(this, id, filePath)) continue;
                DBEntries[dbType].Add(id, entry);
                BriefingRoom.PrintToLog($"Loaded {shortTypeName} \"{id}\"");
            }
            BriefingRoom.PrintToLog($"Found {DBEntries[dbType].Count} database entries of type \"{typeof(T).Name}\"");

            bool mustHaveAtLeastOneEntry = true;
            if ((dbType == typeof(DBEntryDefaultUnitList)) ||
                (dbType == typeof(DBEntryFeatureMission)) ||
                (dbType == typeof(DBEntryFeatureObjective)))
                mustHaveAtLeastOneEntry = false;

            // If a required database type has no entries, raise an error.
            if ((DBEntries[dbType].Count == 0) && mustHaveAtLeastOneEntry)
                BriefingRoom.PrintToLog($"No valid database entries found in the \"{subDirectory}\" directory", LogMessageErrorLevel.Error);
        }

19 Source : Database.cs
with GNU General Public License v3.0
from akaAgar

private void LoadCustomUnitEntries(string subDirectory)
        {
            BriefingRoom.PrintToLog($"Custom Loading {subDirectory.ToLowerInvariant()}...");

            string directory = $"{BRPaths.CUSTOMDATABASE}{subDirectory}";
            if (!Directory.Exists(directory))
                return;

            Type dbType = typeof(DBEntryUnit);
            string shortTypeName = dbType.Name.Substring(7).ToLowerInvariant();

            foreach (string filePath in Directory.EnumerateFiles(directory, "*.ini", SearchOption.AllDirectories))
            {
                string id = Path.GetFileNameWithoutExtension(filePath).Replace(",", "").Trim(); // No commas in file names, so we don't break comma-separated arrays

                var entry = new DBEntryUnit();
                if (!entry.Load(this, id, filePath)) continue;
                if (DBEntries[dbType].ContainsKey(id))
                {
                    ((DBEntryUnit)DBEntries[dbType][id]).Merge(entry);
                    BriefingRoom.PrintToLog($"Updated {shortTypeName} \"{id}\"");

                } else {
                    DBEntries[dbType].Add(id, entry);
                    BriefingRoom.PrintToLog($"Loaded {shortTypeName} \"{id}\"");
                }
            }
            BriefingRoom.PrintToLog($"Found {DBEntries[dbType].Count} custom database entries of type \"{typeof(DBEntryUnit).Name}\"");

            bool mustHaveAtLeastOneEntry = true;
            if ((dbType == typeof(DBEntryDefaultUnitList)) ||
                (dbType == typeof(DBEntryFeatureMission)) ||
                (dbType == typeof(DBEntryFeatureObjective)))
                mustHaveAtLeastOneEntry = false;

            // If a required database type has no entries, raise an error.
            if ((DBEntries[dbType].Count == 0) && mustHaveAtLeastOneEntry)
                BriefingRoom.PrintToLog($"No valid database entries found in the \"{subDirectory}\" directory", LogMessageErrorLevel.Error);
        }

19 Source : MissionGenerator.cs
with GNU General Public License v3.0
from akaAgar

internal DCSMission Generate(MissionTemplate template, bool useObjectivePresets)
        {
            int i;

            // Check for missing entries in the database
            if (!GeneratorTools.CheckDBForMissingEntry<DBEntryCoalition>(template.ContextCoalitionBlue) ||
                !GeneratorTools.CheckDBForMissingEntry<DBEntryCoalition>(template.ContextCoalitionRed) ||
                !GeneratorTools.CheckDBForMissingEntry<DBEntryWeatherPreset>(template.EnvironmentWeatherPreset, true) ||
                !GeneratorTools.CheckDBForMissingEntry<DBEntryTheater>(template.ContextTheater))
                return null;

            // Create mission clreplaced and other fields
            DCSMission mission = new DCSMission();
            
            List<Waypoint> waypoints = new List<Waypoint>();
            List<int> immediateActivationAircraftGroupsIDs = new List<int>();
            List<int> lateActivationAircraftGroupsIDs = new List<int>();

            // Get required database entries here, so we don't have to look for them each time they're needed.
            DBEntryTheater theaterDB = Database.Instance.GetEntry<DBEntryTheater>(template.ContextTheater);
            DBEntryCoalition[] coalitionsDB = new DBEntryCoalition[]
            {
                Database.Instance.GetEntry<DBEntryCoalition>(template.ContextCoalitionBlue),
                Database.Instance.GetEntry<DBEntryCoalition>(template.ContextCoalitionRed)
            };

            // Copy values from the template
            mission.SetValue("BriefingAllyCoalition", coalitionsDB[(int)template.ContextPlayerCoalition].UIDisplayName);
            mission.SetValue("BriefingEnemyCoalition", coalitionsDB[(int)template.ContextPlayerCoalition.GetEnemy()].UIDisplayName);
            mission.SetValue("EnableAudioRadioMessages", !template.OptionsMission.Contains(MissionOption.RadioMessagesTextOnly));
            mission.SetValue("LuaPlayerCoalition", $"coalition.side.{template.ContextPlayerCoalition.ToString().ToUpperInvariant()}");
            mission.SetValue("LuaEnemyCoalition", $"coalition.side.{template.ContextPlayerCoalition.GetEnemy().ToString().ToUpperInvariant()}");
            mission.SetValue("TheaterID", theaterDB.DCSID);
            mission.SetValue("AircraftActivatorCurrentQueue", ""); // Just to make sure aircraft groups spawning queues are empty
            mission.SetValue("AircraftActivatorReserveQueue", "");
            mission.SetValue("MissionPlayerSlots", template.GetPlayerSlotsCount() == 1 ? "Single-player mission" : $"{template.GetPlayerSlotsCount()}-players mission");

            // Add common media files
            foreach (string oggFile in Database.Instance.Common.CommonOGG)
                mission.AddMediaFile($"l10n/DEFAULT/{Toolbox.AddMissingFileExtension(oggFile, ".ogg")}", $"{BRPaths.INCLUDE_OGG}{Toolbox.AddMissingFileExtension(oggFile, ".ogg")}");

            Country[][] coalitionsCountries;
            // Generate list of countries for each coalition
            using (MissionGeneratorCountries countriesGenerator = new MissionGeneratorCountries())
                coalitionsCountries = countriesGenerator.GenerateCountries(mission, template);

            // Create unit maker
            UnitMaker unitMaker = new UnitMaker(mission, template, coalitionsDB, theaterDB, template.ContextPlayerCoalition, coalitionsCountries, template.GetPlayerSlotsCount() == 1);

            DrawingMaker drawingMaker = new DrawingMaker(mission, template, theaterDB);

            // Generate mission date and time
            Month month;
            BriefingRoom.PrintToLog("Generating mission date and time...");
            using (MissionGeneratorDateTime dateTimeGenerator = new MissionGeneratorDateTime())
            {
                dateTimeGenerator.GenerateMissionDate(mission, template, out month);
                dateTimeGenerator.GenerateMissionTime(mission, template, theaterDB, month);
            }

            // Generate weather and wind
            BriefingRoom.PrintToLog("Generating mission weather...");
            double windSpeedAtSeaLevel, windDirectionAtSeaLevel;
            using (MissionGeneratorWeather weatherGenerator = new MissionGeneratorWeather())
            {
                weatherGenerator.GenerateWeather(mission, template, theaterDB, month, out int turbulenceFromWeather);
                weatherGenerator.GenerateWind(mission, template, turbulenceFromWeather, out windSpeedAtSeaLevel, out windDirectionAtSeaLevel);
            }

            // Setup airbases
            DBEntryAirbase playerAirbase;
            BriefingRoom.PrintToLog("Setting up airbases...");
            using (MissionGeneratorAirbases airbasesGenerator = new MissionGeneratorAirbases())
            {
                playerAirbase = airbasesGenerator.SelectStartingAirbase(mission, template, template.FlightPlanTheaterStartingAirbase);
                if (playerAirbase == null) throw new BriefingRoomException("No valid airbase was found for the player(s).");
                airbasesGenerator.SetupAirbasesCoalitions(mission, template, playerAirbase);
                airbasesGenerator.SelectStartingAirbaseForPackages(mission, template, playerAirbase);
                mission.SetValue("PlayerAirbaseName", playerAirbase.Name);
                mission.SetValue("MissionAirbaseX", playerAirbase.Coordinates.X);
                mission.SetValue("MissionAirbaseY", playerAirbase.Coordinates.Y);
                mission.Briefing.AddItem(DCSMissionBriefingItemType.Airbase, $"{playerAirbase.Name}\t{playerAirbase.Runways}\t{playerAirbase.ATC}\t{playerAirbase.ILS}\t{playerAirbase.TACAN}");
            }

            // Generate objectives
            BriefingRoom.PrintToLog("Generating objectives...");
            List<Coordinates> objectiveCoordinates = new List<Coordinates>();
            List<UnitFamily> objectiveTargetUnitFamilies = new List<UnitFamily>();
            Coordinates lastObjectiveCoordinates = playerAirbase.Coordinates;
            using (MissionGeneratorObjectives objectivesGenerator = new MissionGeneratorObjectives(unitMaker, drawingMaker))
                for (i = 0; i < template.Objectives.Count; i++)
                {
                    lastObjectiveCoordinates = objectivesGenerator.GenerateObjective(mission, template, theaterDB, i, lastObjectiveCoordinates, playerAirbase, useObjectivePresets, out string objectiveName, out UnitFamily objectiveTargetUnitFamily);
                    objectiveCoordinates.Add(lastObjectiveCoordinates);
                    waypoints.Add(objectivesGenerator.GenerateObjectiveWaypoint(template.Objectives[i], lastObjectiveCoordinates, objectiveName, template));
                    objectiveTargetUnitFamilies.Add(objectiveTargetUnitFamily);
                }
            Coordinates objectivesCenter = (objectiveCoordinates.Count == 0) ? playerAirbase.Coordinates : Coordinates.Sum(objectiveCoordinates) / objectiveCoordinates.Count;
            mission.SetValue("MissionCenterX", objectivesCenter.X);
            mission.SetValue("MissionCenterY", objectivesCenter.Y);

            // Generate carrier groups
            BriefingRoom.PrintToLog("Generating carrier groups...");
            Dictionary<string, UnitMakerGroupInfo> carrierDictionary;
            using (MissionGeneratorCarrierGroup carrierGroupGenerator = new MissionGeneratorCarrierGroup(unitMaker))
                carrierDictionary = carrierGroupGenerator.GenerateCarrierGroup(mission, template, playerAirbase.Coordinates, objectivesCenter, windSpeedAtSeaLevel, windDirectionAtSeaLevel);
            Coordinates averageInitialPosition = playerAirbase.Coordinates;
            if (carrierDictionary.Count > 0) averageInitialPosition = (averageInitialPosition + carrierDictionary.First().Value.Coordinates) / 2.0;

            // Generate extra flight plan info
            using (MissionGeneratorFlightPlan flightPlanGenerator = new MissionGeneratorFlightPlan())
            {
                flightPlanGenerator.GenerateBullseyes(mission, objectivesCenter);
                flightPlanGenerator.GenerateObjectiveWPCoordinatesLua(template, mission, waypoints);
                flightPlanGenerator.GenerateAircraftPackageWaypoints(template,waypoints, averageInitialPosition, objectivesCenter);
                flightPlanGenerator.GenerateIngressAndEgressWaypoints(template, waypoints, averageInitialPosition, objectivesCenter);
            }

            // Generate surface-to-air defenses
            using (MissionGeneratorAirDefense airDefenseGenerator = new MissionGeneratorAirDefense(unitMaker))
                airDefenseGenerator.GenerateAirDefense(template, averageInitialPosition, objectivesCenter);

            // Generate combat air patrols
            using (MissionGeneratorCombatAirPatrols capGenerator = new MissionGeneratorCombatAirPatrols(unitMaker))
            {
                int[] capGroupsID = capGenerator.GenerateCAP(template, averageInitialPosition, objectivesCenter);
                foreach (int capGroupID in capGroupsID) // Add 50% of CAP groups to the list of A/C activated on takeoff, the other 50% to the list of A/C activated later.
                    if (Toolbox.RandomChance(2))
                        immediateActivationAircraftGroupsIDs.Add(capGroupID);
                    else
                        lateActivationAircraftGroupsIDs.Add(capGroupID);
            }

            // Generate player flight groups
            BriefingRoom.PrintToLog("Generating player flight groups...");
            using (MissionGeneratorPlayerFlightGroups playerFlightGroupsGenerator = new MissionGeneratorPlayerFlightGroups(unitMaker))
                for (i = 0; i < template.PlayerFlightGroups.Count; i++)
                    playerFlightGroupsGenerator.GeneratePlayerFlightGroup(mission, template, i, playerAirbase, waypoints, carrierDictionary, averageInitialPosition, objectivesCenter);

            // Generate mission features
            BriefingRoom.PrintToLog("Generating mission features...");
            mission.AppendValue("ScriptMissionFeatures", ""); // Just in case there's no features
            using (MissionGeneratorFeaturesMission missionFeaturesGenerator = new MissionGeneratorFeaturesMission(unitMaker))
                for (i = 0; i < template.MissionFeatures.Count; i++)
                    missionFeaturesGenerator.GenerateMissionFeature(mission, template.MissionFeatures[i], i, playerAirbase.Coordinates, objectivesCenter);

            // Add ogg files to the media files dictionary
            foreach (string mediaFile in mission.GetMediaFileNames())
            {
                if (!mediaFile.ToLowerInvariant().EndsWith(".ogg")) continue; // Not an .ogg file
                mission.AppendValue("MapResourcesFiles", $"[\"ResKey_Snd_{Path.GetFileNameWithoutExtension(mediaFile)}\"] = \"{Path.GetFileName(mediaFile)}\",\n");
            }

            // Get unit tables from the unit maker (MUST BE DONE AFTER ALL UNITS ARE GENERATED)
            mission.SetValue("CountriesBlue", unitMaker.GetUnitsLuaTable(Coalition.Blue));
            mission.SetValue("CountriesRed", unitMaker.GetUnitsLuaTable(Coalition.Red));
            mission.SetValue("Drawings", drawingMaker.GetLuaDrawings());

            // Generate briefing and additional mission info
            BriefingRoom.PrintToLog("Generating briefing...");
            using (MissionGeneratorBriefing briefingGenerator = new MissionGeneratorBriefing())
            {
                string missionName = GeneratorTools.GenerateMissionName(template.BriefingMissionName);
                mission.Briefing.Name = missionName;
                mission.SetValue("MISSIONNAME", missionName);
                
                briefingGenerator.GenerateMissionBriefingDescription(mission, template, objectiveTargetUnitFamilies);
                mission.SetValue("DescriptionText", mission.Briefing.GetBriefingAsRawText("\\\n"));
            }

            // Generate mission options
            BriefingRoom.PrintToLog("Generating options...");
            using (MissionGeneratorOptions optionsGenerator = new MissionGeneratorOptions())
                optionsGenerator.GenerateForcedOptions(mission, template);

            // Generate warehouses
            BriefingRoom.PrintToLog("Generating warehouses...");
            using (MissionGeneratorWarehouses warehousesGenerator = new MissionGeneratorWarehouses())
                warehousesGenerator.GenerateWarehouses(mission);

            // Generate image files
            BriefingRoom.PrintToLog("Generating images...");
            using (MissionGeneratorImages imagesGenerator = new MissionGeneratorImages()) {
                imagesGenerator.Generatereplacedle(mission, template);
                imagesGenerator.GenerateKneeboardImage(mission);
            }

            return mission;
        }

19 Source : CommandLine.cs
with GNU General Public License v3.0
from akaAgar

public bool DoCommandLine(string[] args)
        {
            string[] templateFiles = (from string arg in args where File.Exists(arg) select arg).ToArray();
            string[] invalidTemplateFiles = (from string arg in args where !File.Exists(arg) select arg).ToArray();

            foreach (string filePath in invalidTemplateFiles)
                WriteToDebugLog($"Template file {filePath} doesn't exist.", LogMessageErrorLevel.Warning);

            if (templateFiles.Length == 0)
            {
                WriteToDebugLog("No valid mission template files given as parameters.", LogMessageErrorLevel.Error);
                WriteToDebugLog("");
                WriteToDebugLog("Command-line format is BriefingRoomCommandLine.exe <MissionTemplate.brt> [<MissionTemplate2.brt> <MissionTemplate3.brt>...]");
                return false;
            }

            foreach (string t in templateFiles)
            {
                if (Path.GetExtension(t).ToLowerInvariant() == ".cbrt") // Template file is a campaign template
                {
                    DCSCampaign campaign = BriefingRoomGenerator.GenerateCampaign(t);
                    if (campaign == null)
                    {
                        Console.WriteLine($"Failed to generate a campaign from template {Path.GetFileName(t)}");
                        continue;
                    }

                    string campaignDirectory;
                    if (templateFiles.Length == 1) // Single template file provided, use  campaign name as campaign path.
                        campaignDirectory = Path.Combine(Application.StartupPath, RemoveInvalidPathCharacters(campaign.Name));
                    else // Multiple template files provided, use the template name as campaign name so we know from which template campaign was generated.
                        campaignDirectory = Path.Combine(Application.StartupPath, Path.GetFileNameWithoutExtension(t));
                    campaignDirectory = GetUnusedFileName(campaignDirectory);

                    if (!campaign.ExportToDirectory(Application.StartupPath))
                    {
                        WriteToDebugLog($"Failed to export campaign directory from template {Path.GetFileName(t)}", LogMessageErrorLevel.Warning);
                        continue;
                    }
                    else
                        WriteToDebugLog($"Campaign {Path.GetFileName(campaignDirectory)} exported to directory from template {Path.GetFileName(t)}");
                }
                else // Template file is a mission template
                {
                    DCSMission mission = BriefingRoomGenerator.GenerateMission(t);
                    if (mission == null)
                    {
                        Console.WriteLine($"Failed to generate a mission from template {Path.GetFileName(t)}");
                        continue;
                    }

                    string mizFileName;
                    if (templateFiles.Length == 1) // Single template file provided, use "theater + mission name" as file name.
                        mizFileName = Path.Combine(Application.StartupPath, $"{mission.TheaterID} - {RemoveInvalidPathCharacters(mission.Briefing.Name)}.miz");
                    else // Multiple template files provided, use the template name as file name so we know from which template mission was generated.
                        mizFileName = Path.Combine(Application.StartupPath, Path.GetFileNameWithoutExtension(t) + ".miz");
                    mizFileName = GetUnusedFileName(mizFileName);

                    if (!mission.SaveToMizFile(mizFileName))
                    {
                        WriteToDebugLog($"Failed to export .miz file from template {Path.GetFileName(t)}", LogMessageErrorLevel.Warning);
                        continue;
                    }
                    else
                        WriteToDebugLog($"Mission {Path.GetFileName(mizFileName)} exported to .miz file from template {Path.GetFileName(t)}");
                }
            }

            return true;
        }

19 Source : CommandLine.cs
with GNU General Public License v3.0
from akaAgar

private string GetUnusedFileName(string filePath)
        {
            if (!File.Exists(filePath)) return filePath; // File doesn't exist, use the desired name

            string newName;
            int extraNameCount = 2;

            do
            {
                newName = Path.Combine(Path.GetDirectoryName(filePath), $"{Path.GetFileNameWithoutExtension(filePath)} ({extraNameCount}){Path.GetExtension(filePath)}");
                extraNameCount++;
            } while (File.Exists(newName));

            return newName;
        }

19 Source : BlobInfo.cs
with MIT License
from akasarto

private static string GetRawId(string blobName)
		{
			return Path.GetFileName(path: Path.GetFileNameWithoutExtension(Sanitize(blobName)));
		}

19 Source : PlaylistManager.cs
with GNU Affero General Public License v3.0
from akira0245

internal static async Task AddAsync(string[] filePaths, bool reload = false)
    {
        if (reload)
        {
            FilePathList.Clear();
            MidiBard.config.Playlist.Clear();
        }

        var count = filePaths.Length;
        var success = 0;

        await foreach (var path in GetPathsAvailable(filePaths))
        {
            MidiBard.config.Playlist.Add(path);
            string fileName = Path.GetFileNameWithoutExtension(path);
            FilePathList.Add((path, fileName, SwitchInstrument.ParseSongName(fileName, out _, out _)));
            success++;
        }

        PluginLog.Information($"File import all complete! success: {success} total: {count}");
    }

19 Source : AssetTreeModel.cs
with MIT License
from akof1314

public virtual void SetDataPaths(string refPathStr, string pathStr, string commonPathStr)
        {
            data = null;
            ResetAutoId();
            replacedetPaths = pathStr;
            refPaths = replacedetDanshariUtility.PathStrToArray(refPathStr);
            resPaths = replacedetDanshariUtility.PathStrToArray(pathStr);
            commonPaths = replacedetDanshariUtility.PathStrToArray(commonPathStr);
            m_DataPathLen = Application.dataPath.Length - 6;

            commonDirs = new List<replacedetInfo>();
            foreach (var commonPath in commonPaths)
            {
                if (!Directory.Exists(commonPath))
                {
                    continue;
                }

                var commonName = Path.GetFileNameWithoutExtension(commonPath);
                var commonLen = commonPath.Length - commonName.Length;
                commonDirs.Add(new replacedetInfo(GetAutoId(), commonPath, commonName));

                var allDirs = Directory.GetDirectories(commonPath, "*", SearchOption.AllDirectories);
                foreach (var allDir in allDirs)
                {
                    var dirInfo = GenreplacedetInfo(PathToStandardized(allDir));
                    dirInfo.displayName = dirInfo.fileRelativePath.Substring(commonLen);
                    commonDirs.Add(dirInfo);
                }
            }
        }

19 Source : AssetBundleFilesAnalyzeObject.cs
with MIT License
from akof1314

private static void ExportTexture2D(Texture2D tex, string rootPath, string name)
        {
            if (!replacedetBundleFilesreplacedyze.replacedyzeExport)
            {
                return;
            }

            string dirPath = Path.Combine(Path.GetDirectoryName(rootPath), Path.GetFileNameWithoutExtension(rootPath) + "Export");
            dirPath = Path.Combine(dirPath, name);
            dirPath = Path.Combine(dirPath, replacedetFileInfoType.texture2D);
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            RenderTexture rt = RenderTexture.GetTemporary(tex.width, tex.height, 0);
            Graphics.Blit(tex, rt);

            RenderTexture active = RenderTexture.active;
            RenderTexture.active = rt;
            Texture2D cont = new Texture2D(tex.width, tex.height);
            cont.hideFlags = HideFlags.HideAndDontSave;
            cont.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0);
            cont.Apply();
            RenderTexture.active = active;
            RenderTexture.ReleaseTemporary(rt);

            File.WriteAllBytes(Path.Combine(dirPath, tex.name + ".png"), cont.EncodeToPNG());
        }

19 Source : EmployeeService.cs
with MIT License
from aksoftware98

public async Task<EnreplacedyApiResponse<EmployeeDetail>> CreateEmployeeAsync(EmployeeDetail employeeDetail, string currentUserId)
        {
            if (employeeDetail is null)
                throw new ArgumentNullException(nameof(employeeDetail));

            var org = await _orgRepository.GetByIdAsync(employeeDetail.OrganizationId);

            if (org is null)
                return new EnreplacedyApiResponse<EmployeeDetail>(error: "Organization does not exist");

            if (employeeDetail.Preplacedword != employeeDetail.ConfirmPreplacedword)
                return new EnreplacedyApiResponse<EmployeeDetail>(error: "Preplacedwords do not match");

            var uploadedFile = !(employeeDetail.ProfileImage is null);

            var usersImagesFolderPath = Path.Combine(_envProvider.WebRootPath, "Images", "Users");

            var profileImageFileName = "default.png";

            if (uploadedFile)
            {
                var extension = Path.GetExtension(employeeDetail.ProfileImage.FileName);

                if (!_settings.SupportedExtensions.Contains(extension))
                    return new EnreplacedyApiResponse<EmployeeDetail>(error: "File extension is not supported");

                if (employeeDetail.ProfileImage.Length > _settings.MaxImageSize)
                    return new EnreplacedyApiResponse<EmployeeDetail>(error: "File size is too large");

                profileImageFileName = $"{Path.GetFileNameWithoutExtension(employeeDetail.ProfileImage.FileName)}_{Guid.NewGuid()}{extension}";
            }

            var createUserResponse = await _userService.CreateUserAsync(new CreateApplicationUser
            {
                FirstName = employeeDetail.FirstName?.Trim(),
                LastName = employeeDetail.LastName?.Trim(),
                Email = employeeDetail.Email,
                Preplacedword = employeeDetail.Preplacedword,
                ProfilePicture = Path.Combine(usersImagesFolderPath, profileImageFileName).Replace("\\","/"),
                RoleId = employeeDetail.RoleId,
                OrganizationId = org.Id
            });

            if (!createUserResponse.IsSuccess)
                return new EnreplacedyApiResponse<EmployeeDetail>(error: createUserResponse.Error);

            var newEmployee = new Employee
            {
                Address = employeeDetail.Address?.Trim(),
                StreetAddress = employeeDetail.StreetAddress?.Trim(),
                City = employeeDetail.City?.Trim(),
                Description = employeeDetail.Description?.Trim(),
                BirthDate = employeeDetail.Birthdate.ToUniversalTime(),
                UserId = createUserResponse.Enreplacedy.Id,
                CreatedById = currentUserId,
                ModifiedById = currentUserId,
                OrganizationId = org.Id
            };

            await _employeeRepository.InsertAsync(newEmployee);
            newEmployee.User = createUserResponse.Enreplacedy;

            if (uploadedFile)
                using (Stream stream = new FileStream(createUserResponse.Enreplacedy.ProfilePicture, FileMode.Create))
                    await employeeDetail.ProfileImage.CopyToAsync(stream);

            return new EnreplacedyApiResponse<EmployeeDetail>(enreplacedy: new EmployeeDetail(newEmployee));
        }

19 Source : AzureBlobStorageService.cs
with MIT License
from aksoftware98

public async Task<string> SaveBlobAsync(IFormFile file, BlobType blobType)
        {
            string extension = Path.GetExtension(file.FileName);
            string fileName = file.FileName;
            string newFileName = $"{Path.GetFileNameWithoutExtension(fileName)}-{Guid.NewGuid()}{extension}";
            ValidateExtension(extension, blobType);

            string url = _config["AzureBlobSettings:BlobEndpoint"];

            await _container.CreateIfNotExistsAsync();
            var blob = _container.GetBlobClient(newFileName);
            using (var stream = file.OpenReadStream())
            {
                var result = await blob.UploadAsync(file.OpenReadStream());
                return $"{url}/{_container.Name}/{newFileName}";
            }
        }

19 Source : EmployeeService.cs
with MIT License
from aksoftware98

public async Task<EnreplacedyApiResponse<EmployeeDetail>> UpdateEmployeeAsync(EmployeeDetail employeeDetail, string currentUserId)
        {
            if (employeeDetail is null)
                throw new ArgumentNullException(nameof(employeeDetail));

            var employee = await _employeeRepository.GetByIdAsync(employeeDetail.Id);

            if (employee is null)
                return new EnreplacedyApiResponse<EmployeeDetail>(error: "Employee does not exist");

            var uploadedFile = !(employeeDetail.ProfileImage is null);

            var profileImageFileName = Path.GetFileName(employee.User.ProfilePicture);

            // Keep a copy in case of updating to delete the old image
            var oldProfilePictureFileName = profileImageFileName;

            var usersImagesFolderPath = Path.Combine(_envProvider.WebRootPath, "Images", "Users");

            if (uploadedFile)
            {
                var extension = Path.GetExtension(employeeDetail.ProfileImage.FileName);

                if (!_settings.SupportedExtensions.Contains(extension))
                    return new EnreplacedyApiResponse<EmployeeDetail>(error: "File extension is not supported");

                if (employeeDetail.ProfileImage.Length > _settings.MaxImageSize)
                    return new EnreplacedyApiResponse<EmployeeDetail>(error: "File size is too large");

                profileImageFileName = $"{Path.GetFileNameWithoutExtension(employeeDetail.ProfileImage.FileName)}_{Guid.NewGuid()}{extension}";
            }

            var updateUserResponse = await _userService.UpdateUserAsync(employee.UserId, new UpdateApplicationUser
            {
                FirstName = employeeDetail.FirstName?.Trim(),
                LastName = employeeDetail.LastName?.Trim(),
                ProfilePicture = Path.Combine(usersImagesFolderPath, profileImageFileName).Replace("\\", "/"),
            });

            if (!updateUserResponse.IsSuccess)
                return new EnreplacedyApiResponse<EmployeeDetail>(error: updateUserResponse.Error);

            employee.Address = employeeDetail.Address?.Trim();
            employee.StreetAddress = employeeDetail.StreetAddress?.Trim();
            employee.City = employeeDetail.City?.Trim();
            employee.Description = employeeDetail.Description?.Trim();
            employee.BirthDate = employeeDetail.Birthdate.ToUniversalTime();
            employee.ModifiedById = currentUserId;
            employee.LastModifiedDate = DateTime.UtcNow;

            await _employeeRepository.UpdateAsync(employee);
            employee.User = updateUserResponse.Enreplacedy;

            if (uploadedFile)
            {
                using (Stream stream = new FileStream(updateUserResponse.Enreplacedy.ProfilePicture, FileMode.Create))
                    await employeeDetail.ProfileImage.CopyToAsync(stream);

                if (oldProfilePictureFileName != "default.png")
                {
                    var fileToDelete = Path.Combine(usersImagesFolderPath, oldProfilePictureFileName);
                    File.Delete(fileToDelete);
                }
            }

            return new EnreplacedyApiResponse<EmployeeDetail>(enreplacedy: new EmployeeDetail(employee));
        }

19 Source : NodeEditorUtilities.cs
with MIT License
from aksyr

internal static UnityEngine.Object CreateScript(string pathName, string templatePath) {
            string clreplacedName = Path.GetFileNameWithoutExtension(pathName).Replace(" ", string.Empty);
            string templateText = string.Empty;

            UTF8Encoding encoding = new UTF8Encoding(true, false);

            if (File.Exists(templatePath)) {
                /// Read procedures.
                StreamReader reader = new StreamReader(templatePath);
                templateText = reader.ReadToEnd();
                reader.Close();

                templateText = templateText.Replace("#SCRIPTNAME#", clreplacedName);
                templateText = templateText.Replace("#NOTRIM#", string.Empty);
                /// You can replace as many tags you make on your templates, just repeat Replace function
                /// e.g.:
                /// templateText = templateText.Replace("#NEWTAG#", "MyText");

                /// Write procedures.

                StreamWriter writer = new StreamWriter(Path.GetFullPath(pathName), false, encoding);
                writer.Write(templateText);
                writer.Close();

                replacedetDatabase.Importreplacedet(pathName);
                return replacedetDatabase.LoadreplacedetAtPath(pathName, typeof(Object));
            } else {
                Debug.LogError(string.Format("The template file was not found: {0}", templatePath));
                return null;
            }
        }

19 Source : PipelineTool.cs
with MIT License
from Alan-FGR

protected string GenerateClreplacedCodeForFileList(string[] finalFiles, string extraMembers = "")
         {
            var c = new StringBuilder();
            
            c.AppendLine($"public static clreplaced {Id} {{");
            foreach (string finalFile in finalFiles)
            {
               var name = Path.GetFileNameWithoutExtension(finalFile);

               string ext = exportExtension;
               if (exportExtension == null)
                  ext = Path.GetExtension(finalFile).Replace(".","");

               c.AppendLine($" public const string {name} = \"{name}.{ext}\";");
            }
            c.AppendLine(extraMembers);
            c.AppendLine("}");

            return c.ToString();
         }

19 Source : PipelineTool.cs
with MIT License
from Alan-FGR

public string RunProcessor(string input)
         {
            return 
               Sanitize(
                  methodInfo_.Invoke(instance_, new object[]
                  {
                     Path.GetDirectoryName(input),
                     Path.GetFileNameWithoutExtension(input),
                     new DirectoryInfo(Path.GetDirectoryName(input)).Name,
                  }) as string);
         }

19 Source : Program.cs
with MIT License
from Alan-FGR

static void Main(string[] args)
    {
        String[] files = {"Registry", "ArchetypePool"};
        string path = "Archetypes";

        Console.WriteLine("C# VARIADIC GENERATOR. VALID TAGS:");
        foreach (var modeFunction in modeFunctions)
        {
            Console.WriteLine($"  {modeFunction.Key}");
            Console.WriteLine($"    Description: {modeFunction.Value.descr}");
        }

        foreach (string file in Directory.GetFiles(path, "*.cs", SearchOption.AllDirectories))
        {
            var pathElements = file.Split(Path.DirectorySeparatorChar, StringSplitOptions.RemoveEmptyEntries);
            if (pathElements.Contains("obj"))
                continue;
            if (!files.Contains(Path.GetFileName(file)) && !files.Contains(Path.GetFileNameWithoutExtension(file)))
                continue;
            
            var code = File.ReadAllLines(file);
            var generatedCode = new StringWriter();

            Console.WriteLine($"PARSING FILE: {file}...");

            var regions = new List<(int qty, List<string> lines)>();

            List<string> currentRegion = null;

            foreach (string line in code)
            {
                if (line.ToLowerInvariant().Contains("#region variadic"))
                {
                    currentRegion = new List<string>();
                    regions.Add((int.Parse(line.Trim().Split(' ')[2]), currentRegion));
                    continue;
                }

                if (line.ToLowerInvariant().Contains("#endregion"))
                {
                    currentRegion = null;
                    continue;
                }

                currentRegion?.Add(line);
            }

            foreach (var tuple in regions)
            {
                curRegion = tuple.lines;
                for (int qti = 2; qti <= tuple.qty; qti++)
                {
                    curQty = qti;
                    for (var i = 0; i < tuple.lines.Count; i++)
                    {
                        string line = tuple.lines[i];

                        var trimmed = line.TrimStart(' ');
                        if (trimmed.Length >= 2)
                        {
                            string substring = trimmed.Substring(0, 2);
                            if (substring == "//")
                                continue;
                            if (substring == "/*")
                                Console.WriteLine($"MULTILINE COMMENT BLOCKS (DETECTED ON LINE {i}) NOT SUPPORTED." +
                                                  "YOU CAN USE THEM FOR COMMENTS AS USUAL BUT MAKE SURE THERE ARE NO TAGS IN THEM.");
                        }

                        if (line.ToLowerInvariant().Contains("genvariadic"))
                        {
                            var pars = line.Split("genvariadic")[1].Split(' ', StringSplitOptions.RemoveEmptyEntries);
                            Console.WriteLine(
                                $"found variadic on line {i}, {pars.Length} parameters: {string.Join(", ", pars)}");

                            if (pars.Length < 1)
                            {
                                Console.WriteLine("NO PARAMETERS!");
                                continue;
                            }

                            var mode = pars.First();
                            var options = pars.Skip(1).ToArray();

                            if (modeFunctions.TryGetValue(mode, out var value))
                            {
                                var str = value.Item2(options, i);
                                generatedCode.WriteLine(str);
                            }
                            else
                            {
                                string err = $"INVALID MODE: {mode}";
                                Console.WriteLine(err);
                                generatedCode.WriteLine(err);
                            }
                        }
                        else
                        {
                            generatedCode.WriteLine(line);
                        }
                    }
                }
            }

            Console.WriteLine($"PARSED FILE: {file}\n");


            var allcode = "";
            foreach (string line in code)
            {
                var trimmed = (line.Trim());
                if (trimmed.Length > 6)
                    if (trimmed.Substring(0, 5) == "using")
                        allcode += line+"\r\n";
            }

            allcode += $"public unsafe partial clreplaced {Path.GetFileNameWithoutExtension(file)} {{";

            allcode += generatedCode.ToString();

            allcode += "}";

            File.WriteAllText(Path.Combine(path, Path.GetFileNameWithoutExtension(file)+"GeneratedVariadic.cs"), allcode);

        }

        //Console.ReadKey();
    }

19 Source : PipelineTool.cs
with MIT License
from Alan-FGR

protected string GenerateClreplacedCodeForTypedreplacedet(string[] values)
         {
            var c = new StringBuilder();

            c.AppendLine($"using {typeImport_};");
            c.AppendLine($"public static clreplaced {Id} {{");
            c.AppendLine("public static clreplaced Cache {");
            foreach (string finalFile in values)
            {
               var name = Path.GetFileNameWithoutExtension(finalFile);

               string ext = exportExtension;
               if (exportExtension == null)
                  ext = Path.GetExtension(finalFile).Replace(".", "");

               c.AppendLine($"  public static {typeName_} {name} = Pipelinereplacedets.Loadreplacedet<{typeName_}>(\"{name}.{ext}\");");
            }
            c.AppendLine("}");
            foreach (string finalFile in values)
            {
               var name = Path.GetFileNameWithoutExtension(finalFile);

               string ext = exportExtension;
               if (exportExtension == null)
                  ext = Path.GetExtension(finalFile).Replace(".", "");

               c.AppendLine($" public static string {name} = \"{name}.{ext}\";");
            }
            c.AppendLine("}");
            return c.ToString();
         }

19 Source : TxtMapExporter.cs
with MIT License
from Alan-FGR

public void Save(string filename, Dictionary<string, Rectangle> map)
		{
			// copy the files list and sort alphabetically
			string[] keys = new string[map.Count];
			map.Keys.CopyTo(keys, 0);
			List<string> outputFiles = new List<string>(keys);
			outputFiles.Sort();

			using (StreamWriter writer = new StreamWriter(filename))
			{
				foreach (var image in outputFiles)
				{
					// get the destination rectangle
					Rectangle destination = map[image];

					// write out the destination rectangle for this bitmap
					writer.WriteLine(string.Format(
	                 	"{0} = {1} {2} {3} {4}", 
	                 	Path.GetFileNameWithoutExtension(image), 
	                 	destination.X, 
	                 	destination.Y, 
	                 	destination.Width, 
	                 	destination.Height));
				}
			}
		}

19 Source : MainProgram.cs
with MIT License
from AlbertMN

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        [STAThread]
        static void Main(string[] args) {
            Console.WriteLine("Log location; " + logFilePath);
            CheckSettings();

            var config = new NLog.Config.LoggingConfiguration();
            var logfile = new NLog.Targets.FileTarget("logfile") { FileName = logFilePath };
            var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
            config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
            config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);
            NLog.LogManager.Configuration = config;

            void ActualMain() {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                //Upgrade settings
                if (Properties.Settings.Default.UpdateSettings) {
                    /* Copy old setting-files in case the Evidence type and Evidence Hash has changed (which it does sometimes) - easier than creating a whole new settings system */
                    try {
                        Configuration accConfiguration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
                        string currentFolder = new DirectoryInfo(accConfiguration.FilePath).Parent.Parent.FullName;
                        string[] directories = Directory.GetDirectories(new DirectoryInfo(currentFolder).Parent.FullName);

                        foreach (string dir in directories) {
                            if (dir != currentFolder.ToString()) {
                                var directoriesInDir = Directory.GetDirectories(dir);
                                foreach (string childDir in directoriesInDir) {
                                    string checkPath = Path.Combine(currentFolder, Path.GetFileName(childDir));
                                    if (!Directory.Exists(checkPath)) {
                                        string checkFile = Path.Combine(childDir, "user.config");
                                        if (File.Exists(checkFile)) {
                                            bool xmlHasError = false;
                                            try {
                                                XmlDoreplacedent xml = new XmlDoreplacedent();
                                                xml.Load(checkFile);

                                                xml.Validate(null);
                                            } catch {
                                                xmlHasError = true;
                                                DoDebug("XML doreplacedent validation failed (is invalid): " + checkFile);
                                            }

                                            if (!xmlHasError) {
                                                Directory.CreateDirectory(checkPath);
                                                File.Copy(checkFile, Path.Combine(checkPath, "user.config"), true);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } catch (Exception e) {
                        Console.WriteLine("Error getting settings from older versions of ACC; " + e.Message);
                    }
                    /* End "copy settings" */

                    try {
                        Properties.Settings.Default.Upgrade();
                        Properties.Settings.Default.UpdateSettings = false;
                        Properties.Settings.Default.Save();
                    } catch {
                        DoDebug("Failed to upgrade from old settings file.");
                    }

                    Console.WriteLine("Upgraded settings to match last version");
                }

                if (Properties.Settings.Default.LastUpdated == DateTime.MinValue) {
                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                }

                //Create action mod path
                if (!Directory.Exists(actionModsPath)) {
                    Directory.CreateDirectory(actionModsPath);
                }

                //Translator
                string tempDir = Path.Combine(currentLocation, "Translations");
                if (Directory.Exists(tempDir)) {
                    Translator.translationFolder = Path.Combine(currentLocation, "Translations");
                    Translator.languagesArray = Translator.GetLanguages();
                } else {
                    MessageBox.Show("Missing the translations folder. Reinstall the software to fix this issue.", messageBoxreplacedle);
                }

                string lang = Properties.Settings.Default.ActiveLanguage;
                if (Array.Exists(Translator.languagesArray, element => element == lang)) {
                    DoDebug("ACC running with language \"" + lang + "\"");

                    Translator.SetLanguage(lang);
                } else {
                    DoDebug("Invalid language chosen (" + lang + ")");

                    Properties.Settings.Default.ActiveLanguage = "English";
                    Translator.SetLanguage("English");
                }
                //End translator
                sysIcon = new SysTrayIcon();

                Properties.Settings.Default.TimesOpened += 1;
                Properties.Settings.Default.Save();

                SetupDataFolder();
                if (File.Exists(logFilePath)) {
                    try {
                        File.WriteAllText(logFilePath, string.Empty);
                    } catch {
                        // Don't let this being DENIED crash the software
                        Console.WriteLine("Failed to empty the log");
                    }
                } else {
                    Console.WriteLine("Trying to create log");
                    CreateLogFile();
                }

                //Check if software already runs, if so kill this instance
                var otherACCs = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(currentLocationFull));
                if (otherACCs.Length > 1) {
                    //Try kill the _other_ process instead
                    foreach (Process p in otherACCs) {
                        if (p.Id != Process.GetCurrentProcess().Id) {
                            try {
                                p.Kill();
                                DoDebug("Other ACC instance was running. Killed it.");
                            } catch {
                                DoDebug("Could not kill other process of ACC; access denied");
                            }
                        }
                    }
                }

                Application.EnableVisualStyles();

                DoDebug("[ACC begun (v" + softwareVersion + ")]");

                if (Properties.Settings.Default.CheckForUpdates) {
                    if (HasInternet()) {
                        new Thread(() => {
                            new SoftwareUpdater().Check();
                        }).Start();
                    } else {
                        DoDebug("Couldn't check for new update as PC does not have access to the internet");
                    }
                }

                //On console close: hide NotifyIcon
                Application.ApplicationExit += new EventHandler(OnApplicationExit);
                handler = new ConsoleEventDelegate(ConsoleEventCallback);
                SetConsoleCtrlHandler(handler, true);

                //Create shortcut folder if doesn't exist
                if (!Directory.Exists(shortcutLocation)) {
                    Directory.CreateDirectory(shortcutLocation);
                }
                if (!File.Exists(Path.Combine(shortcutLocation, @"example.txt"))) {
                    //Create example-file
                    try {
                        using (StreamWriter sw = File.CreateText(Path.Combine(shortcutLocation, @"example.txt"))) {
                            sw.WriteLine("This is an example file.");
                            sw.WriteLine("If you haven't already, make your replacedistant open this file!");
                        }
                    } catch {
                        DoDebug("Could not create or write to example file");
                    }
                }

                //Delete all old action files
                if (Directory.Exists(CheckPath())) {
                    DoDebug("Deleting all files in action folder");
                    foreach (string file in Directory.GetFiles(CheckPath(), "*." + Properties.Settings.Default.ActionFileExtension)) {
                        int timeout = 0;

                        if (File.Exists(file)) {
                            while (ActionChecker.FileInUse(file) && timeout < 5) {
                                timeout++;
                                Thread.Sleep(500);
                            }
                            if (timeout >= 5) {
                                DoDebug("Failed to delete file at " + file + " as file appears to be in use (and has been for 2.5 seconds)");
                            } else {
                                try {
                                    File.Delete(file);
                                } catch (Exception e) {
                                    DoDebug("Failed to delete file at " + file + "; " + e.Message);
                                }
                            }
                        }
                    }
                    DoDebug("Old action files removed - moving on...");
                }

                //SetupListener();
                watcher = new FileSystemWatcher() {
                    Path = CheckPath(),
                    NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                                        | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                    Filter = "*." + Properties.Settings.Default.ActionFileExtension,
                    EnableRaisingEvents = true
                };
                watcher.Changed += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Created += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Renamed += new RenamedEventHandler(new ActionChecker().FileFound);
                watcher.Deleted += new FileSystemEventHandler(new ActionChecker().FileFound);
                watcher.Error += delegate { DoDebug("Something wen't wrong"); };

                DoDebug("\n[" + messageBoxreplacedle + "] Initiated. \nListening in: \"" + CheckPath() + "\" for \"." + Properties.Settings.Default.ActionFileExtension + "\" extensions");

                sysIcon.TrayIcon.Icon = Properties.Resources.ACC_icon_light;

                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                if (Registry.GetValue(key.Name + @"\replacedistantComputerControl", "FirstTime", null) == null) {
                    SetStartup(true);

                    key.CreateSubKey("replacedistantComputerControl");
                    key = key.OpenSubKey("replacedistantComputerControl", true);
                    key.SetValue("FirstTime", false);

                    ShowGettingStarted();

                    DoDebug("Starting setup guide (first time opening ACC - wuhu!)");
                } else {
                    if (!Properties.Settings.Default.HasCompletedTutorial) {
                        ShowGettingStarted();
                        DoDebug("Didn't finish setup guide last time, opening again");
                    }
                }
                SetRegKey("ActionFolder", CheckPath());
                SetRegKey("ActionExtension", Properties.Settings.Default.ActionFileExtension);

                testActionWindow = new TestActionWindow();

                //If newly updated
                if (Properties.Settings.Default.LastKnownVersion != softwareVersion) {
                    //Up(or down)-grade, display version notes
                    DoDebug("ACC has been updated");

                    if (Properties.Settings.Default.LastKnownVersion != "" && new System.Version(Properties.Settings.Default.LastKnownVersion) < new System.Version("1.4.3")) {
                        //Had issues before; fixed now
                        DoDebug("Upgraded to 1.4.3, fixed startup - now starting with Windows");

                        try {
                            RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
                            rk.DeleteValue(appName, false);
                        } catch {
                            DoDebug("Failed to remove old start with win run");
                        }

                        SetStartup(true);
                    } else {
                        if (ACCStartsWithWindows()) {
                            SetStartup(true);
                        }
                    }

                    Properties.Settings.Default.LastUpdated = DateTime.Now;
                    if (gettingStarted != null) {
                        DoDebug("'AboutVersion' window awaits, as 'Getting Started' is showing");
                        aboutVersionAwaiting = true;
                    } else {
                        Properties.Settings.Default.LastKnownVersion = softwareVersion;
                        new NewVersion().Show();
                    }
                    Properties.Settings.Default.Save();
                }

                //Check if software starts with Windows
                if (!ACCStartsWithWindows())
                    sysIcon.AddOpenOnStartupMenu();

                /* 'Evalufied' user feedback implementation */
                if ((DateTime.Now - Properties.Settings.Default.LastUpdated).TotalDays >= 7 && Properties.Settings.Default.TimesOpened >= 7
                    && gettingStarted == null
                    && !Properties.Settings.Default.HasPromptedFeedback) {
                    //User has had the software/update for at least 7 days, and has opened the software more than 7 times - time to ask for feedback
                    //(also the "getting started" window is not showing)
                    if (HasInternet()) {
                        try {
                            WebRequest request = WebRequest.Create("https://evalufied.dk/");
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                            if (response == null || response.StatusCode != HttpStatusCode.OK) {
                                DoDebug("'Evalufied' is down - won't show faulty feedback window");
                            } else {
                                DoDebug("Showing 'User Feedback' window");
                                Properties.Settings.Default.HasPromptedFeedback = true;
                                Properties.Settings.Default.Save();
                                new UserFeedback().Show();
                            }
                        } catch {
                            DoDebug("Failed to check for 'Evalufied'-availability");
                        }
                    } else {
                        DoDebug("No internet connection, not showing user feedback window");
                    }
                }

                //Action mods implementation
                ActionMods.CheckMods();
                TaskSchedulerSetup();

                hreplacedtarted = true;
                SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); //On wake up from sleep

                Application.Run();
            }

            if (sentryToken != "super_secret") {
                //Tracking issues with Sentry.IO - not forked from GitHub (official version)
                bool sentryOK = false;
                try {
                    if (Properties.Settings.Default.UID != "") {
                        Properties.Settings.Default.UID = Guid.NewGuid().ToString();
                        Properties.Settings.Default.Save();
                    }

                    if (Properties.Settings.Default.UID != "") {
                        SentrySdk.ConfigureScope(scope => {
                            scope.User = new Sentry.Protocol.User {
                                Id = Properties.Settings.Default.UID
                            };
                        });
                    }

                    using (SentrySdk.Init(sentryToken)) {
                        sentryOK = true;
                    }
                } catch {
                    //Sentry failed. Error sentry's side or invalid key - don't let this stop the app from running
                    DoDebug("Sentry initiation failed");
                    ActualMain();
                }

                if (sentryOK) {
                    try {
                        using (SentrySdk.Init(sentryToken)) {
                            DoDebug("Sentry initiated");
                            ActualMain();
                        }
                    } catch {
                        ActualMain();
                    }
                }
            } else {
                //Code is (most likely) forked - skip issue tracking
                ActualMain();
            }
        }

19 Source : Translator.cs
with MIT License
from AlbertMN

public static string[] GetLanguages() {
            if (!String.IsNullOrEmpty(translationFolder)) {
                List<string> stringList = new List<string>();
                DirectoryInfo d = new DirectoryInfo(translationFolder);
                foreach (var file in d.GetFiles("*.json")) {
                    string fileContent = ReadLanguage(file.FullName);
                    if (fileContent != null) {
                        try {
                            dynamic jsonTest = JsonConvert.DeserializeObject<dynamic>(fileContent);
                            if (jsonTest["translations"] != null) {
                                stringList.Add(Path.GetFileNameWithoutExtension(file.FullName));
                            } else {
                                MainProgram.DoDebug("Invalid translation; " + (jsonTest));
                            }
                        } catch {
                            MainProgram.DoDebug("Could not validate language from file " + file.Name);
                        }
                    }
                }

                string[] theArr = stringList.ToArray<string>();
                return theArr;
            }
            return new string[0];
        }

19 Source : SKBitmapExtensions.cs
with MIT License
from albyho

public static string[] CreateThumbnails(Stream imageStream, string folder, string fileName, IEnumerable<int> widths)
        {
            Directory.CreateDirectory(folder);
            var displayName = Path.GetFileNameWithoutExtension(fileName);
            var ext = Path.GetExtension(fileName);
            var format = GetFormat(fileName);

            var result = new List<string>();
            using (var inputStream = new SKManagedStream(imageStream))
            using (var codec = SKCodec.Create(inputStream))
            using (var original = SKBitmap.Decode(codec))
            using (var image = HandleOrientation(original, codec.EncodedOrigin))
            {
                foreach (var width in widths)
                {
                    int height = (int)Math.Round(width * ((float)image.Height / image.Width));

                    string thumbnailPath = Path.Combine(folder, $"{displayName}-{width}x{height}{ext}");
                    result.Add(thumbnailPath);
                    var info = new SKImageInfo(width, height);

                    using (var resized = image.Resize(info, SKFilterQuality.Medium))
                    using (var thumb = SKImage.FromBitmap(resized))
                    using (var fs = new FileStream(thumbnailPath, FileMode.CreateNew, FileAccess.ReadWrite))
                    {
                        thumb.Encode(format, Quality)
                             .SaveTo(fs);
                    }
                }
            }
            return result.ToArray();
        }

19 Source : BuildPostProcessor.cs
with MIT License
from aleab

[PostProcessBuild(1)]
        public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject)
        {
            // Only Windows x86 and x86_64 atm.
            if (target != BuildTarget.StandaloneWindows && target != BuildTarget.StandaloneWindows64)
                return;

            ////////////////////////////////////////////////////////////////
            // COPY EVERY FILE IN THE PLUGIN DIRECTORY TO THE BUILD PATH. //
            ////////////////////////////////////////////////////////////////

            // Get the source directory (replacedets/Plugins or replacedets/Plugins/x86 or replacedets/Plugins/x86_64).
            string srcPluginsFolder = string.Format("{0}/{1}", Application.dataPath, "Plugins");
            switch (target)
            {
                case BuildTarget.StandaloneWindows:
                    if (Directory.Exists(srcPluginsFolder + "/x86"))
                        srcPluginsFolder += "/x86";
                    break;

                case BuildTarget.StandaloneWindows64:
                    if (Directory.Exists(srcPluginsFolder + "/x86_64"))
                        srcPluginsFolder += "/x86_64";
                    break;

                default:
                    break;
            }

            // Get the destination directory (<BUILT_EXE_PATH>/<EXE_NAME>_Data/Plugins).
            int splitIndex = pathToBuiltProject.LastIndexOf('/');
            string buildPath = pathToBuiltProject.Substring(0, splitIndex);
            string executableName = pathToBuiltProject.Substring(splitIndex + 1);
            string buildPluginsPath = string.Format("{0}/{1}_Data/Plugins", buildPath, Path.GetFileNameWithoutExtension(executableName));

            DirectoryInfo srcPluginsFolderInfo = new DirectoryInfo(srcPluginsFolder);
            DirectoryInfo buildPluginsPathInfo = new DirectoryInfo(buildPluginsPath);

            // Exclude some files (.dlls should already be there!)
            var srcPluginsFolderFiles = srcPluginsFolderInfo.GetFiles("*.*", SearchOption.TopDirectoryOnly)
                                                            .Where(fi => !fi.Name.EndsWith(".meta") && !fi.Name.EndsWith(".dll") &&
                                                                         !fi.Name.EndsWith(".pdb") && !fi.Name.EndsWith(".lib") &&
                                                                         !fi.Name.EndsWith(".mdb") && !fi.Name.EndsWith(".xml"));
            var srcPluginsFolderDirectories = srcPluginsFolderInfo.GetDirectories();

            // Copy selected files and sub-directories.
            foreach (var dir in srcPluginsFolderDirectories)
                DirectoryCopy(dir.FullName, string.Format("{0}/{1}", buildPluginsPathInfo.FullName, dir.Name), true);
            foreach (var file in srcPluginsFolderFiles)
                File.Copy(file.FullName, string.Format("{0}/{1}", buildPluginsPathInfo.FullName, file.Name), false);
        }

19 Source : MixtureGraphicTestRunner.cs
with MIT License
from alelievr

public static IEnumerable<MixtureTestCase> GetMixtureTestCases()
        {
            foreach (var replacedetPath in Directory.GetFiles(mixtureTestFolder, "*.replacedet", SearchOption.AllDirectories))
            {
                var graph = MixtureEditorUtils.GetGraphAtPath(replacedetPath);
                string graphName = Path.GetFileNameWithoutExtension(replacedetPath);
                string referenceImagePath = Path.Combine(referenceImagesFolder, graphName + ".png");
                var expectedImage = replacedetDatabase.LoadreplacedetAtPath<Texture2D>(referenceImagePath);

                if (graph != null)
                {
                    yield return new MixtureTestCase
                    {
                        graph = graph,
                        expected = expectedImage
                    };
                }
            }
        }

19 Source : MixtureCallbacks.cs
with MIT License
from alelievr

public static void CreateMixtureVariant(MixtureGraph targetGraph, MixtureVariant parentVariant)
		{
			string path;

			if (targetGraph != null)
				path = replacedetDatabase.GetreplacedetPath(targetGraph);
			else
			{
				targetGraph = parentVariant.parentGraph;
				path = replacedetDatabase.GetreplacedetPath(parentVariant);
			}

			// Patch path name to add Variant
			string fileName = Path.GetFileNameWithoutExtension(path) + " Variant";
			path = Path.Combine(Path.GetDirectoryName(path), fileName + Path.GetExtension(path));
			path = replacedetDatabase.GenerateUniquereplacedetPath(path);

			var action = ScriptableObject.CreateInstance< MixtureVariantAction >();
			action.targetGraph = targetGraph;
			action.parentVariant = parentVariant;
            ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, action,
            	Path.GetFileName(path), targetGraph.type == MixtureGraphType.Realtime ? MixtureUtils.realtimeVariantIcon : MixtureUtils.iconVariant, null);
		}

19 Source : MixtureCallbacks.cs
with MIT License
from alelievr

public override void Action(int instanceId, string pathName, string resourceFile)
			{
				var mixture = CreateMixtureGraphreplacedet();
				mixture.name = Path.GetFileNameWithoutExtension(pathName);
				mixture.hideFlags = HideFlags.HideInHierarchy;

				replacedetDatabase.Createreplacedet(mixture, pathName);

				// Generate the output texture:
				mixture.outputTextures.Clear();
				if (mixture.type == MixtureGraphType.Realtime)
				{
					mixture.UpdateRealtimereplacedetsOnDisk();
				}
				else
				{
					MixtureGraphProcessor.RunOnce(mixture);
					mixture.SaveAllTextures(false);
				}

				ProjectWindowUtil.ShowCreatedreplacedet(mixture.mainOutputTexture);
				Selection.activeObject = mixture.mainOutputTexture;
				EditorApplication.delayCall += () => EditorGUIUtility.PingObject(mixture.mainOutputTexture);
			}

19 Source : MixtureCallbacks.cs
with MIT License
from alelievr

public override void Action(int instanceId, string pathName, string resourceFile)
			{
				var variant = ScriptableObject.CreateInstance<MixtureVariant>();
				if (parentVariant != null)
					variant.SetParent(parentVariant);
				else
					variant.SetParent(targetGraph);

				variant.name = Path.GetFileNameWithoutExtension(pathName);
				variant.hideFlags = HideFlags.HideInHierarchy;

				replacedetDatabase.Createreplacedet(variant, pathName);

				if (parentVariant != null)
					variant.CopyTexturesFromParentVariant();
				else
					variant.CopyTexturesFromGraph();

				replacedetDatabase.Savereplacedets();
				replacedetDatabase.Refresh();

				EditorApplication.delayCall += () => {
					var mainreplacedet = replacedetDatabase.LoadreplacedetAtPath<Texture>(pathName);
					Selection.activeObject = mainreplacedet;
					EditorGUIUtility.PingObject(mainreplacedet);
				};
			}

19 Source : MixtureEditorUtils.cs
with MIT License
from alelievr

static string       GetMixturereplacedetFolderPath(MixtureGraph graph)
        {
            var path = replacedetDatabase.GetreplacedetPath(graph);

            return Path.GetDirectoryName(path) + "/" + Path.GetFileNameWithoutExtension(path);
        }

19 Source : NodeProvider.cs
with MIT License
from alelievr

static MonoScript FindScriptFromClreplacedName(string clreplacedName)
		{
			var scriptGUIDs = replacedetDatabase.Findreplacedets($"t:script {clreplacedName}");

			if (scriptGUIDs.Length == 0)
				return null;

			foreach (var scriptGUID in scriptGUIDs)
			{
				var replacedetPath = replacedetDatabase.GUIDToreplacedetPath(scriptGUID);
				var script = replacedetDatabase.LoadreplacedetAtPath<MonoScript>(replacedetPath);

				if (script != null && String.Equals(clreplacedName, Path.GetFileNameWithoutExtension(replacedetPath), StringComparison.OrdinalIgnoreCase))
					return script;
			}

			return null;
		}

19 Source : DoCreatePWNodeScript.cs
with MIT License
from alelievr

public override void Action(int instanceId, string pathName, string resourceFile)
		{
			string name = Path.GetFileNameWithoutExtension(pathName);

			if (!File.Exists(nodeTemplate))
				TryFindEditorPath();
			
			//Node editor file replacedet
			createScriptreplacedet.Invoke(null, new object[]{ pathName, nodeEditorTemplate });
			File.Move(Path.GetFullPath(pathName), Application.dataPath + ProceduralWorldsEditorPath + "/" + name + "Editor.cs");
			
			//then node file replacedet
			createScriptreplacedet.Invoke(null, new object[]{ pathName, nodeTemplate });

			var replacedet = replacedetDatabase.LoadreplacedetAtPath(pathName, typeof(MonoScript));
			ProjectWindowUtil.ShowCreatedreplacedet(replacedet);

			replacedetDatabase.Refresh();
		}

19 Source : WorldPresetScreen.cs
with MIT License
from alelievr

List< BiomeGraph > CopyBiomesFromPreset(string biomeFolder)
		{
			List< BiomeGraph > biomes = new List< BiomeGraph >();

			string graphPath = worldGraph.replacedetFilePath;
			string biomeTargetPath = Path.GetDirectoryName(graphPath) + "/" + GraphFactory.baseGraphBiomeFolderName + "/";
			
			var biomeGraphs = Resources.LoadAll< BiomeGraph >(biomereplacedetPrefix + biomeFolder);
			for (int i = 0; i < biomeGraphs.Length; i++)
			{
				string name = Path.GetFileNameWithoutExtension(replacedetDatabase.GetreplacedetPath(biomeGraphs[i]));
				var bg = biomeGraphs[i].Clone() as BiomeGraph;
				string path = biomeTargetPath + name + ".replacedet";

				replacedetDatabase.Createreplacedet(bg, path);
				foreach (var node in bg.allNodes)
					replacedetDatabase.AddObjectToreplacedet(node, bg);
				
				//Set our graph into biome graph input
				(bg.inputNode as NodeBiomeGraphInput).previewGraph = worldGraph;

				biomes.Add(bg);
			}
			
			return biomes;
		}

19 Source : MixtureGraphWindow.cs
with MIT License
from alelievr

protected override void InitializeWindow(BaseGraph graph)
		{
            if (view != null)
            {
                view.Dispose();
                MixtureUpdater.RemoveGraphToProcess(view);
            }

            var mixture = (graph as MixtureGraph);
            bool realtime = mixture.type == MixtureGraphType.Realtime;
			var fileName = Path.GetFileNameWithoutExtension(mixture.mainreplacedetPath);
			replacedleContent = new GUIContent($"Mixture {(realtime ? "(RT) " : "")}- {fileName}", MixtureUtils.windowIcon);

			view = new MixtureGraphView(this);

			rootView.Add(view);

			view.Add(new MixtureToolbar(view));
		}

19 Source : CubeLutAssetImporter.cs
with MIT License
from alelievr

static void OnPostprocessAllreplacedets(string[] imported, string[] deleted, string[] moved, string[] movedFrom)
        {
            foreach (string path in imported)
            {
                string ext = Path.GetExtension(path);
                string filename = Path.GetFileNameWithoutExtension(path);

                if (string.IsNullOrEmpty(ext) || s_Excluded.Contains(filename))
                    continue;

                ext = ext.ToLowerInvariant();
                if (ext.Equals(".cube"))
                    ImportCubeLut(path);
            }
        }

19 Source : Assets.cs
with MIT License
from alelievr

public static Texture2DArray	GenerateOrLoadTexture2DArray(string fName, IEnumerable< Texture2D > texs, bool forceReload = false)
		{
			Texture2DArray	ret;

			if (String.IsNullOrEmpty(fName) || texs == null)
			{
				Debug.LogError("replacedet file null or empty !");
				return null;
			}

			ret = Resources.Load< Texture2DArray >(Path.GetFileNameWithoutExtension(fName));
			if (ret == null)
				Debug.LogError("Texture2DArray not found: " + fName);
			if (ret != null && ret.depth == texs.Count() && !forceReload)
				return ret;
				
			#if UNITY_EDITOR
				ret = GenerateTexture2DArray(texs);
				if (ret == null)
				{
					Debug.LogError("Can't create texture array, no albedo found in any biomes");
					return null;
				}
				replacedetDatabase.Createreplacedet(ret, fName + ".replacedet");
				replacedetDatabase.Savereplacedets();
			#else
				Debug.LogError("Cannot save TextureArray in play mode !");
				return null;
			#endif
			return ret;
		}

19 Source : BiomeSurfaceMapsObjectInspector.cs
with MIT License
from alelievr

void TryCompleteOtherMaps()
		{
			if (maps.albedo == null)
				return ;
	
			var name = Path.GetFileNameWithoutExtension(replacedetDatabase.GetreplacedetPath(maps.albedo));
	
			Texture2D tex;
	
			if ((tex = Texture2DExists(name, "nm", "normal", "_N")) != null)
				maps.normal = tex;
			if ((tex = Texture2DExists(name, "met", "metalic", "_MT")) != null)
				maps.metallic = tex;
		}

19 Source : ViewManager.cs
with MIT License
from AlexanderPro

public bool LoadSettings()
        {
            var settingsFileName = Path.GetFileNameWithoutExtension(replacedemblyUtils.replacedemblyLocation) + ".xml";
            settingsFileName = Path.Combine(replacedemblyUtils.replacedemblyDirectoryName, settingsFileName);
            if (File.Exists(settingsFileName))
            {
                try
                {
                    var xml = File.ReadAllText(settingsFileName, Encoding.UTF8);
                    Settings = SerializeUtils.Deserialize<ProgramSettings>(xml);
                    return true;
                }
                catch (Exception e)
                {
                    MessageBox.Show($"Failed to load settings from the file {settingsFileName}{Environment.NewLine}{e.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    return false;
                }
            }
            else
            {
                Settings.VideoFileExtensions = new List<string> { "*.mp4", "*.mp3", "*.mpg", "*.mpeg", "*.avi" };
                Settings.GalleryFileExtensions = new List<string> { "*.bmp", "*.jpg", "*.jpeg", "*.png", "*.gif", "*.tiff" };
                return true;
            }
        }

19 Source : ViewManager.cs
with MIT License
from AlexanderPro

private void SaveSettings()
        {
            var settingsFileName = Path.GetFileNameWithoutExtension(replacedemblyUtils.replacedemblyLocation) + ".xml";
            settingsFileName = Path.Combine(replacedemblyUtils.replacedemblyDirectoryName, settingsFileName);
            try
            {
                File.WriteAllText(settingsFileName, SerializeUtils.Serialize(Settings), Encoding.UTF8);
            }
            catch (Exception e)
            {
                MessageBox.Show($"Failed to save settings to the file {settingsFileName}{Environment.NewLine}{e.Message}", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

19 Source : WindowUtils.cs
with MIT License
from AlexanderPro

private static string GetSelectedFileFromExplorer(IntPtr hwnd)
        {
            var fileNames = new List<string>();
            var shellAppType = Type.GetTypeFromProgID("Shell.Application");
            var shellObject = Activator.CreateInstance(shellAppType);
            var shellWindows = (SHDocVw.ShellWindows)shellAppType.InvokeMember("Windows", BindingFlags.InvokeMethod, null, shellObject, new object[] { });
            foreach (SHDocVw.InternetExplorer window in shellWindows)
            {
                if (window.HWND == hwnd.ToInt32())
                {
                    var fileName = Path.GetFileNameWithoutExtension(window.FullName).ToLower();
                    if (fileName.ToLowerInvariant() == "explorer")
                    {
                        var items = ((Shell32.IShellFolderViewDual2)window.Doreplacedent).SelectedItems();
                        fileNames = items.Cast<Shell32.FolderItem>().Select(x => x.Path).ToList();
                    }
                }
            }
            return fileNames.Any() ? fileNames[0] : string.Empty;
        }

19 Source : TempFileUtils.cs
with GNU General Public License v3.0
from alexdillon

public static string GetTempFileName(string originalFileName)
        {
            var extension = Path.GetExtension(originalFileName);
            var tempFileName = Path.GetFileNameWithoutExtension(Path.GetTempFileName());
            var tempFile = Path.Combine(Path.GetTempPath(), "GroupMeDesktopClient", tempFileName + extension);

            return tempFile;
        }

19 Source : PatreonCrawledUrlProcessor.cs
with MIT License
from AlexCSDev

public async Task<bool> ProcessCrawledUrl(ICrawledUrl udpCrawledUrl, string downloadDirectory)
        {
            PatreonCrawledUrl crawledUrl = (PatreonCrawledUrl)udpCrawledUrl;

            bool skipChecks = false; //skip sanitization, duplicate and other checks, do not preplaced filename to download path
            if (crawledUrl.Url.IndexOf("dropbox.com/", StringComparison.Ordinal) != -1)
            {
                if (!crawledUrl.Url.EndsWith("?dl=1"))
                {
                    if (crawledUrl.Url.EndsWith("?dl=0"))
                        crawledUrl.Url = crawledUrl.Url.Replace("?dl=0", "?dl=1");
                    else
                        crawledUrl.Url = $"{crawledUrl.Url}?dl=1";
                }

                _logger.Debug($"[{crawledUrl.PostId}] This is a dropbox entry: {crawledUrl.Url}");
            }
            else if (crawledUrl.Url.StartsWith("https://mega.nz/"))
            {
                _logger.Debug($"[{crawledUrl.PostId}] mega found: {crawledUrl.Url}");
                skipChecks = true; //mega plugin expects to see only path to the folder where everything will be saved
            }
            else if (_googleDriveRegex.Match(crawledUrl.Url).Success)
            {
                _logger.Debug($"[{crawledUrl.PostId}] google drive found: {crawledUrl.Url}");
                skipChecks = true; //no need for checks if we use google drive plugin
            }
            else if (crawledUrl.Url.IndexOf("youtube.com/watch?v=", StringComparison.Ordinal) != -1 ||
                     crawledUrl.Url.IndexOf("youtu.be/", StringComparison.Ordinal) != -1)
            {
                //TODO: YOUTUBE SUPPORT?
                _logger.Fatal($"[{crawledUrl.PostId}] [NOT SUPPORTED] YOUTUBE link found: {crawledUrl.Url}");
            }
            else if (crawledUrl.Url.IndexOf("imgur.com/", StringComparison.Ordinal) != -1)
            {
                //TODO: IMGUR SUPPORT
                _logger.Fatal($"[{crawledUrl.PostId}] [NOT SUPPORTED] IMGUR link found: {crawledUrl.Url}");
            }

            string filename = crawledUrl.Filename;

            if (!skipChecks)
            {
                if (!_patreonDownloaderSettings.UseSubDirectories)
                    filename = $"{crawledUrl.PostId}_";
                else
                    filename = "";

                switch (crawledUrl.UrlType)
                {
                    case PatreonCrawledUrlType.PostFile:
                        filename += "post";
                        break;
                    case PatreonCrawledUrlType.PostAttachment:
                        filename += "attachment";
                        break;
                    case PatreonCrawledUrlType.PostMedia:
                        filename += "media";
                        break;
                    case PatreonCrawledUrlType.AvatarFile:
                        filename += "avatar";
                        break;
                    case PatreonCrawledUrlType.CoverFile:
                        filename += "cover";
                        break;
                    case PatreonCrawledUrlType.ExternalUrl:
                        filename += "external";
                        break;
                    default:
                        throw new ArgumentException($"Invalid url type: {crawledUrl.UrlType}");
                }

                if (crawledUrl.Filename == null)
                {
                    _logger.Debug($"No filename for {crawledUrl.Url}, trying to retrieve...");
                    string remoteFilename =
                        await _remoteFilenameRetriever.RetrieveRemoteFileName(crawledUrl.Url);

                    if (remoteFilename == null)
                    {
                        throw new DownloadException(
                            $"[{crawledUrl.PostId}] Unable to retrieve name for external entry of type {crawledUrl.UrlType}: {crawledUrl.Url}");
                    }

                    filename += $"_{remoteFilename}";
                }
                else
                {
                    filename += $"_{crawledUrl.Filename}";
                }

                _logger.Debug($"Filename for {crawledUrl.Url} is {filename}");

                _logger.Debug($"Sanitizing filename: {filename}");
                filename = PathSanitizer.SanitizePath(filename);
                _logger.Debug($"Sanitized filename: {filename}");

                if (filename.Length > _patreonDownloaderSettings.MaxFilenameLength)
                {
                    _logger.Debug($"Filename is too long, will be truncated: {filename}");
                    string extension = Path.GetExtension(filename);
                    if (extension.Length > 4)
                    {
                        _logger.Warn($"File extension for file {filename} is longer 4 characters and won't be appended to truncated filename!");
                        extension = "";
                    }
                    filename = filename.Substring(0, _patreonDownloaderSettings.MaxFilenameLength) + extension;
                    _logger.Debug($"Truncated filename: {filename}");
                }

                string key = $"{crawledUrl.PostId}_{filename.ToLowerInvariant()}";
                if (!_fileCountDict.ContainsKey(key))
                    _fileCountDict.Add(key, 0);

                _fileCountDict[key]++;

                if (_fileCountDict[key] > 1)
                {
                    _logger.Warn($"Found more than a single file with the name {filename} in the same folder in post {crawledUrl.PostId}, sequential number will be appended to its name.");

                    string appendStr = _fileCountDict[key].ToString();

                    if (crawledUrl.UrlType != PatreonCrawledUrlType.ExternalUrl)
                    {
                        MatchCollection matches = _fileIdRegex.Matches(crawledUrl.Url);

                        if (matches.Count == 0)
                            throw new DownloadException($"[{crawledUrl.PostId}] Unable to retrieve file id for {crawledUrl.Url}, contact developer!");
                        if (matches.Count > 1)
                            throw new DownloadException($"[{crawledUrl.PostId}] More than 1 media found in URL {crawledUrl.Url}");

                        appendStr = matches[0].Groups[5].Value;
                    }

                    filename = $"{Path.GetFileNameWithoutExtension(filename)}_{appendStr}{Path.GetExtension(filename)}";
                }
            }

            if (_patreonDownloaderSettings.UseSubDirectories && 
                crawledUrl.UrlType != PatreonCrawledUrlType.AvatarFile &&
                crawledUrl.UrlType != PatreonCrawledUrlType.CoverFile)
                downloadDirectory = Path.Combine(downloadDirectory, PostSubdirectoryHelper.CreateNameFromPattern(crawledUrl, _patreonDownloaderSettings.SubDirectoryPattern));

            crawledUrl.DownloadPath = !skipChecks ? Path.Combine(downloadDirectory, filename) : downloadDirectory + Path.DirectorySeparatorChar;

            return true;
        }

19 Source : PluginManager.cs
with GNU General Public License v3.0
from 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 Source : PluginManager.cs
with GNU General Public License v3.0
from alexdillon

private static replacedembly LoadPlugin(string relativePath)
        {
            // Navigate up to the solution root
            string root = Path.GetFullPath(Path.Combine(
                Path.GetDirectoryName(
                    Path.GetDirectoryName(
                        Path.GetDirectoryName(
                            Path.GetDirectoryName(
                                Path.GetDirectoryName(typeof(Program).replacedembly.Location)))))));

            string pluginLocation = Path.GetFullPath(Path.Combine(root, relativePath.Replace('\\', Path.DirectorySeparatorChar)));
            Console.WriteLine($"Loading commands from: {pluginLocation}");
            PluginLoadContext loadContext = new PluginLoadContext(pluginLocation);
            return loadContext.LoadFromreplacedemblyName(new replacedemblyName(Path.GetFileNameWithoutExtension(pluginLocation)));
        }

19 Source : FileAttachmentControlViewModel.cs
with GNU General Public License v3.0
from alexdillon

private async Task ClickedAction(PointerPressedEventArgs e)
        {
            if (e == null || e.GetCurrentPoint(null).Properties.IsLeftButtonPressed)
            {
                this.IsLoading = true;
                var data = await this.FileAttachment.DownloadFileAsync(this.MessageContainer.Messages.First());
                var extension = System.IO.Path.GetExtension(this.FileData.FileName);
                var tempFileName = Path.GetFileNameWithoutExtension(Path.GetTempFileName());
                var tempFile = Path.Combine(Path.GetTempPath(), "GroupMeDesktopClientAvalonia", tempFileName + extension);
                File.WriteAllBytes(tempFile, data);
                var psInfo = new ProcessStartInfo()
                {
                    FileName = tempFile,
                    UseShellExecute = true,
                };
                System.Diagnostics.Process.Start(psInfo);
                this.IsLoading = false;
            }
        }

19 Source : WpfThemeService.cs
with GNU General Public License v3.0
from alexdillon

public void Initialize()
        {
            // Add default theme style
            this.ThemeStyles.Add(this.DefaultThemeStyle, (null, null));

            // Load custom theme style
            if (Directory.Exists(App.ThemesPath))
            {
                var files = Directory.GetFiles(App.ThemesPath, "*.xaml");
                var themes = files
                    .Select(f => Path.GetFileNameWithoutExtension(f))
                    .Where(f => f.EndsWith(".Light", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".Dark", StringComparison.OrdinalIgnoreCase))
                    .Select(f => f.Substring(0, f.LastIndexOf(".")))
                    .Distinct();

                foreach (var theme in themes)
                {
                    var lightThemePath = Path.Combine(App.ThemesPath, $"{theme}.Light.xaml");
                    var darkThemePath = Path.Combine(App.ThemesPath, $"{theme}.Dark.xaml");
                    ResourceDictionary lightDictionary = null;
                    ResourceDictionary darkDictionary = null;

                    if (File.Exists(lightThemePath))
                    {
                        lightDictionary = new ResourceDictionary() { Source = new Uri(lightThemePath) };
                    }

                    if (File.Exists(darkThemePath))
                    {
                        darkDictionary = new ResourceDictionary() { Source = new Uri(darkThemePath) };
                    }

                    if (!this.ThemeStyles.ContainsKey(theme))
                    {
                        this.ThemeStyles.Add(theme, (lightDictionary, darkDictionary));
                    }
                }
            }
        }

19 Source : Project.cs
with GNU General Public License v3.0
from alexgracianoarj

public static Project Load(string fileName)
		{
			if (string.IsNullOrEmpty(fileName))
				throw new ArgumentException(Strings.ErrorBlankFilename, "fileName");

			if (!File.Exists(fileName))
				throw new FileNotFoundException(Strings.ErrorFileNotFound);

			XmlDoreplacedent doreplacedent = new XmlDoreplacedent();
			try
			{
				doreplacedent.Load(fileName);
			}
			catch (Exception ex)
			{
				throw new IOException(Strings.ErrorCouldNotLoadFile, ex);
			}

			XmlElement root = doreplacedent["Project"];
			if (root == null)
			{
				root = doreplacedent["ClreplacedProject"]; // Old file format
				if (root == null)
				{
					throw new InvalidDataException(Strings.ErrorCorruptSaveFile);
				}
				else
				{
					Project oldProject = LoadWithPreviousFormat(root);
					oldProject.FilePath = fileName;
					oldProject.name = Path.GetFileNameWithoutExtension(fileName);
					oldProject.isUnreplacedled = false;
					return oldProject;
				}
			}

			Project project = new Project();
			project.loading = true;
			try
			{
				project.Deserialize(root);
			}
			catch (Exception ex)
			{
				throw new InvalidDataException(Strings.ErrorCorruptSaveFile, ex);
			}
			project.loading = false;
			project.FilePath = fileName;
			project.isReadOnly = project.projectFile.IsReadOnly;

			return project;
		}

19 Source : OptionsDialog.cs
with GNU General Public License v3.0
from alexgracianoarj

private void btnSave_Click(object sender, EventArgs e)
		{
			using (SaveFileDialog dialog = new SaveFileDialog())
			{
				dialog.FileName = Style.CurrentStyle.Name;
				dialog.InitialDirectory = Style.StylesDirectory;
				dialog.Filter = Strings.DiagramStyle + " (*.dst)|*.dst";

				if (dialog.ShowDialog() == DialogResult.OK)
				{
					if (Style.CurrentStyle.IsUnreplacedled)
					{
						Style.CurrentStyle.Name = Path.GetFileNameWithoutExtension(dialog.FileName);
					}

					if (!Style.CurrentStyle.Save(dialog.FileName))
					{
						MessageBox.Show(
							Strings.ErrorCouldNotSaveFile, Strings.Save,
							MessageBoxButtons.OK, MessageBoxIcon.Error);
					}
					else
					{
						LoadStyles();
					}
				}
			}
		}

19 Source : FunctionNode.cs
with MIT License
from alexismorin

public override void ReadFromString( ref string[] nodeParams )
		{
			base.ReadFromString( ref nodeParams );
			m_filename = GetCurrentParam( ref nodeParams );
			m_orderIndex = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
			m_headerreplacedle = GetCurrentParam( ref nodeParams );

			if( UIUtils.CurrentShaderVersion() > 7203 )
			{
				m_functionGraphId = Convert.ToInt32( GetCurrentParam( ref nodeParams ) );
			}

			if( UIUtils.CurrentShaderVersion() > 13704 )
			{
				m_functionGUID = GetCurrentParam( ref nodeParams );
			}

			AmplifyShaderFunction loaded = replacedetDatabase.LoadreplacedetAtPath<AmplifyShaderFunction>( replacedetDatabase.GUIDToreplacedetPath( m_functionGUID ) );
			if( loaded != null )
			{
				CommonInit( loaded, UniqueId );
			}
			else
			{
				string[] guids = replacedetDatabase.Findreplacedets( "t:AmplifyShaderFunction " + m_filename );
				if( guids.Length > 0 )
				{
					string sfGuid = null;

					foreach( string guid in guids )
					{
						string replacedetPath = replacedetDatabase.GUIDToreplacedetPath( guid );
						string name = System.IO.Path.GetFileNameWithoutExtension( replacedetPath );
						if( name.Equals( m_filename, StringComparison.OrdinalIgnoreCase ) )
						{
							sfGuid = guid;
							break;
						}
					}
					loaded = replacedetDatabase.LoadreplacedetAtPath<AmplifyShaderFunction>( replacedetDatabase.GUIDToreplacedetPath( sfGuid ) );

					if( loaded != null )
					{
						CommonInit( loaded, UniqueId );
					}
					else
					{
						SetreplacedleText( "ERROR" );
						UIUtils.ShowMessage( string.Format( "Error loading {0} shader function from project folder", m_filename ), MessageSeverity.Error );
					}
				}
				else
				{
					SetreplacedleText( "Missing Function" );
					UIUtils.ShowMessage( string.Format( "Missing {0} shader function on project folder", m_filename ), MessageSeverity.Error );
				}
			}
			if( UIUtils.CurrentShaderVersion() > 14203 )
			{
				ReadOptionsHelper = GetCurrentParam( ref nodeParams ).Split( ',' );
			}
		}

See More Examples