System.Enum.HasFlag(System.Enum)

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

1277 Examples 7

19 Source : ShowRenamerService.cs
with MIT License
from amoscardino

public async Task RenameAsync(string inputPath, string outputPath, bool filesOnly, bool recurse, bool skipConfirmation, bool verbose)
        {
            _verbose = verbose;

            inputPath = Path.GetFullPath(inputPath ?? Directory.GetCurrentDirectory());
            outputPath = Path.GetFullPath(outputPath ?? inputPath);

            if (!File.GetAttributes(inputPath).HasFlag(FileAttributes.Directory))
            {
                _console.WriteLine("Input path must be a directory, not a file.");
                return;
            }

            if (_verbose)
            {
                _console.WriteLine($"* Using Input Path: {inputPath}");
                _console.WriteLine($"* Using Output Path: {outputPath}");
                _console.WriteLine();
            }

            var files = _fileService.GetFiles(inputPath, recurse);

            if (!files.Any())
                return;

            await MatchFilesAsync(files, outputPath, filesOnly);

            var anyToRename = files.Any(match => !match.NewPath.IsNullOrWhiteSpace());

            if (anyToRename && (skipConfirmation || Prompt.GetYesNo("Look good?", true)))
                _fileService.RenameFiles(files);
            else
                _console.WriteLine("Nothing has been changed.");
        }

19 Source : ImageResizer.cs
with MIT License
from andrewlock

static string[] GetFilesToSquash(IConsole console, string path)
        {
            console.WriteLine($"Checking '{path}'...");
            if (File.GetAttributes(path).HasFlag(FileAttributes.Directory))
            {
                console.WriteLine($"Path '{path}' is a directory, squashing all files");
                return Directory.GetFiles(path);
            }
            else
            {
                console.WriteLine($"Path '{path}' is a file");
                return new[] { path };
            }
        }

19 Source : ChatPage.xaml.cs
with MIT License
from angelsix

private void MessageText_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // Get the text box
            var textbox = sender as TextBox;

            // Check if we have pressed enter
            if (e.Key == Key.Enter)
            {
                // If we have control pressed...
                if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
                {
                    // Add a new line at the point where the cursor is
                    var index = textbox.CaretIndex;

                    // Insert the new line
                    textbox.Text = textbox.Text.Insert(index, Environment.NewLine);

                    // Shift the caret forward to the newline
                    textbox.CaretIndex = index + Environment.NewLine.Length;

                    // Mark this key as handled by us
                    e.Handled = true;
                }
                else
                    // Send the message
                    ViewModel.Send();

                // Mark the key as handled
                e.Handled = true;
            }
        }

19 Source : ListManager.cs
with GNU Lesser General Public License v3.0
from angturil

public StringListManager ClearOldList(string request, TimeSpan delta, ListFlags flags = ListFlags.Unchanged)
            {
                string listfilename = Path.Combine(Plugin.DataPath, request);
                TimeSpan UpdatedAge = GetFileAgeDifference(listfilename);

                StringListManager list = OpenList(request, flags);

                if (File.Exists(listfilename) && UpdatedAge > delta) // BUG: There's probably a better way to handle this
                {
                    //RequestBot.Instance.QueueChatMessage($"Clearing old session {request}");
                    list.Clear();
                    if (!(flags.HasFlag(ListFlags.InMemory) | flags.HasFlag(ListFlags.ReadOnly))) list.Writefile(request);

                }

                return list;
            }

19 Source : ListManager.cs
with GNU Lesser General Public License v3.0
from angturil

public StringListManager OpenList(string request, ListFlags flags = ListFlags.Unchanged) // All lists are accessed through here, flags determine mode
            {
                StringListManager list;
                if (!ListCollection.TryGetValue(request, out list))
                {
                    list = new StringListManager();
                    ListCollection.Add(request, list);
                    if (!flags.HasFlag(ListFlags.InMemory)) list.Readfile(request); // If in memory, we never read from disk
                }
                else
                {
                    if (flags.HasFlag(ListFlags.Uncached)) list.Readfile(request); // If Cache is off, ALWAYS re-read file.
                }
                return list;
            }

19 Source : ListManager.cs
with GNU Lesser General Public License v3.0
from angturil

public bool add(ref string listname, ref string key, ListFlags flags = ListFlags.Unchanged)
            {
                try
                {
                    StringListManager list = OpenList(listname);

                    list.Add(key);


                    if (!(flags.HasFlag(ListFlags.InMemory) | flags.HasFlag(ListFlags.ReadOnly))) list.Writefile(listname);
                    return true;

                }
                catch (Exception ex) { Plugin.Log(ex.ToString()); }

                return false;
            }

19 Source : ListManager.cs
with GNU Lesser General Public License v3.0
from angturil

public bool remove(ref string listname, ref string key, ListFlags flags = ListFlags.Unchanged)
            {
                try
                {
                    StringListManager list = OpenList(listname);

                    list.Removeentry(key);

                    if (!(flags.HasFlag(ListFlags.InMemory) | flags.HasFlag(ListFlags.ReadOnly))) list.Writefile(listname);

                    return false;

                }
                catch (Exception ex) { Plugin.Log(ex.ToString()); } // Going to try this form, to reduce code verbosity.              

                return false;
            }

19 Source : ListManager.cs
with GNU Lesser General Public License v3.0
from angturil

public bool Readfile(string filename, bool ConvertToLower = false)
            {
                if (flags.HasFlag(ListFlags.InMemory)) return false;

                try
                {
                    string listfilename = Path.Combine(Plugin.DataPath, filename);
                    string fileContent = File.ReadAllText(listfilename);
                    if (listfilename.EndsWith(".script"))
                        list = fileContent.Split(lineseparator, StringSplitOptions.RemoveEmptyEntries).ToList();
                    else
                        list = fileContent.Split(anyseparator, StringSplitOptions.RemoveEmptyEntries).ToList();

                    if (ConvertToLower) LowercaseList();
                    return true;
                }
                catch
                {
                    // Ignoring this for now, I expect it to fail
                }

                return false;
            }

19 Source : PolygonBoundaryFinderHelper.cs
with MIT License
from AnnoDesigner

private static ((int x, int y), Direction) FindStart(bool[][] insidePoints, Direction[][] boundarySides)
        {
            if (boundarySides != null)
            {
                for (var x = 0; x < boundarySides.Length; x++)
                {
                    for (var y = 0; y < boundarySides[x].Length; y++)
                    {
                        if (boundarySides[x][y] != Direction.None)
                        {
                            var side = Direction.Up;
                            for (var i = 0; i < 4; i++)
                            {
                                if (boundarySides[x][y].HasFlag(side))
                                {
                                    return (GetStartPoint((x, y), side), GetStartDirection(side));
                                }

                                side = RotateClockwise(side);
                            }
                        }
                    }
                }
            }
            else
            {
                for (var x = 0; x < insidePoints.Length; x++)
                {
                    for (var y = 0; y < insidePoints[x].Length; y++)
                    {
                        if (insidePoints[x][y])
                        {
                            return ((x, y), Direction.Left);
                        }
                    }
                }
            }

            return ((0, 0), Direction.None);
        }

19 Source : Connector.cs
with Apache License 2.0
from apache

private bool ValidateServerCertificate(object sender, X509Certificate? certificate, X509Chain? chain, SslPolicyErrors sslPolicyErrors)
    {
        if (sslPolicyErrors == SslPolicyErrors.None)
            return true;

        if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable))
            return false;

        if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNameMismatch) && _verifyCertificateName)
            return false;

        if (sslPolicyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors) && _verifyCertificateAuthority)
        {
            if (_trustedCertificateAuthority is null || chain is null || certificate is null)
                return false;

            chain.ChainPolicy.ExtraStore.Add(_trustedCertificateAuthority);
            _ = chain.Build((X509Certificate2) certificate);

            for (var i = 0; i < chain.ChainElements.Count; i++)
            {
                if (chain.ChainElements[i].Certificate.Thumbprint == _trustedCertificateAuthority.Thumbprint)
                    return true;
            }

            return false;
        }

        return true;
    }

19 Source : RenderStreamingLegacyRPAutomator.cs
with Apache License 2.0
from araobp

static void SaveSettings(RenderStreamingSettings settings) {
        //Make sure the settings is not set as ReadOnly (might happen when importing sample in older versions of Unity)
        FileAttributes attributes = File.GetAttributes(m_settingsPath);
        if (attributes.HasFlag(FileAttributes.ReadOnly))
            File.SetAttributes(m_settingsPath, attributes & ~FileAttributes.ReadOnly);

        File.WriteAllText(m_settingsPath,JsonUtility.ToJson(settings));
    }

19 Source : MoveToViewModel.cs
with MIT License
from arasplm

private void OnFileFolderBrowserCommandClick(object window)
		{
			var selectPathDialog = dialogFactory.GetSelectPathDialog(DirectoryItemType.File, methodFolderPath);
			var selectPathDialogResult = selectPathDialog.ShowDialog();
			if (selectPathDialogResult.DialogOperationResult == true)
			{
				FileAttributes attributes = File.GetAttributes(selectPathDialogResult.SelectedFullPath);
				if (attributes.HasFlag(FileAttributes.Directory))
				{
					this.CodeItemPath = selectPathDialogResult.SelectedFullPath;
				}
				else
				{
					this.CodeItemPath = Path.GetDirectoryName(selectPathDialogResult.SelectedFullPath);
					this.FileName = Path.GetFileNameWithoutExtension(selectPathDialogResult.SelectedFullPath);
				}
			}
		}

19 Source : Shell.cs
with MIT License
from Archomeda

public static Task StartRead()
        {
            cancellationTokenSource = new CancellationTokenSource();
            return Task.Run(async () =>
            {
                while (!stopRequested)
                {
                    // Implement our own reader since Console.ReadLine sucks in async and breaks our CTRL+C interrupt
                    SConsole.Write(">");
                    readingInput = true;
                    int pos = 0;
                    while (true)
                    {
                        var key = SConsole.ReadKey(true);
                        if (key.Modifiers.HasFlag(ConsoleModifiers.Control) && (key.Key == ConsoleKey.C || key.Key == ConsoleKey.Pause))
                        {
                            logger.LogMessage("{verb}Stopping...");
                            Program.Exit();
                            return;
                        }
                        else if (key.Key == ConsoleKey.Backspace)
                        {
                            if (pos > 0)
                            {
                                inputBuffer.Remove(pos - 1, 1);
                                lock (consoleLock)
                                    SConsole.Write("\b \b");
                                pos--;
                            }
                        }
                        else if (key.Key == ConsoleKey.Delete)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                inputBuffer.Remove(pos, 1);
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos) + " " + new string('\b', inputBuffer.Length - pos + 1));
                            }
                        }
                        else if (key.Key == ConsoleKey.LeftArrow)
                        {
                            if (pos > 0)
                            {
                                lock (consoleLock)
                                    SConsole.Write("\b");
                                pos--;
                            }
                        }
                        else if (key.Key == ConsoleKey.RightArrow)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer[pos]);
                                pos++;
                            }
                        }
                        else if (key.Key == ConsoleKey.Home)
                        {
                            if (pos > 0)
                            {
                                lock (consoleLock)
                                    SConsole.Write(new string('\b', pos));
                                pos = 0;
                            }
                        }
                        else if (key.Key == ConsoleKey.End)
                        {
                            if (pos < inputBuffer.Length)
                            {
                                lock (consoleLock)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos));
                                pos = inputBuffer.Length;
                            }
                        }
                        else if (key.Key == ConsoleKey.Enter)
                        {
                            lock (consoleLock)
                                SConsole.WriteLine();
                            break;
                        }
                        else if (key.KeyChar != 0)
                        {
                            inputBuffer.Insert(pos, key.KeyChar);
                            pos++;
                            lock (consoleLock)
                            {
                                SConsole.Write(key.KeyChar);
                                if (pos < inputBuffer.Length)
                                    SConsole.Write(inputBuffer.ToString().Substring(pos) + new string('\b', inputBuffer.Length - pos));
                            }
                        }
                    }
                    readingInput = false;

                    var line = inputBuffer.ToString().Trim();
                    inputBuffer.Clear();
                    if (string.IsNullOrWhiteSpace(line))
                        continue;

                    var verb = line.Split(new[] { ' ' }, 2)[0];
                    var command = Commands.FirstOrDefault(c => c.Verb == verb);

                    if (command != null)
                    {
                        try
                        {
                            await command.RunAsync(line.Substring(verb.Length).Trim(), cancellationTokenSource.Token);
                        }
                        catch (OperationCanceledException)
                        {
                            // Fine...
                        }
                        catch (Exception ex)
                        {
                            logger.LogException(ex);
                        }
                    }
                    else
                        logger.LogCommandOutput("Unknown command, use {command}help{reset} to get the list of available commands.");
                    logger.LogCommandOutput("");
                }
            });
        }

19 Source : Kernel32.cs
with GNU General Public License v3.0
from Artentus

private static SafeFileHandle CreateFileInternal(string path, uint access, FileShare share, FileMode mode, uint attributes)
        {
            var securityAttributes = new SecurityAttributes();
            securityAttributes.Length = Marshal.SizeOf(securityAttributes);
            securityAttributes.SecurityDescriptor = IntPtr.Zero;
            securityAttributes.InheritHandle = false;

            if (share.HasFlag(FileShare.Inheritable))
            {
                share &= ~FileShare.Inheritable;
                securityAttributes.InheritHandle = true;
            }

            SafeFileHandle fileHandle = CreateFileNative(path, access, share, ref securityAttributes, mode, attributes, IntPtr.Zero);

            if (fileHandle.IsInvalid)
            {
                fileHandle.Close();

                int hResult = Marshal.GetHRForLastWin32Error();
                Marshal.ThrowExceptionForHR(hResult);
            }

            return fileHandle;
        }

19 Source : DDSImporter.cs
with GNU General Public License v3.0
from arycama

public static Texture ReadFile(BinaryReader reader)
	{
		// Read and check the magic string (Should be 'DDS ', or  0x20534444)
		var magic = reader.ReadInt32();
		if(magic != 0x20534444)
		{
			throw new Exception("DDS file invalid");
		}

		// Read the header
		var headerSize = reader.ReadInt32();
		var headerFlags = (HeaderFlags)reader.ReadInt32();
		var height = reader.ReadInt32();
		var width = reader.ReadInt32();
		var pitchOrLinearSize = reader.ReadInt32();
		var depth = reader.ReadInt32();
		var mipMapCount = reader.ReadInt32();
		var dwReserved1 = reader.ReadBytes(sizeof(int) * 11);

		// Read pixel format
		var formatSize = reader.ReadInt32();
		var formatFlags = (PixelFormatFlags)reader.ReadInt32();
		var fourCC = Encoding.ASCII.GetString(reader.ReadBytes(4));
		var rgbBitCount = reader.ReadInt32();
		var redBitMask = reader.ReadInt32();
		var greenBitMask = reader.ReadInt32();
		var blueBitMask = reader.ReadInt32();
		var alphaBitMask = reader.ReadInt32();

		var Caps = (HeaderCaps)reader.ReadInt32();
		var Caps2 = reader.ReadInt32();
		var Caps3 = reader.ReadInt32();
		var Caps4 = reader.ReadInt32();
		var Reserved2 = reader.ReadInt32();

		// Get the size of the top level of the texture from the header, and read it
		var dataSize = formatFlags.HasFlag(PixelFormatFlags.FourCC) ? pitchOrLinearSize : pitchOrLinearSize * height;
		int missingDataSize;

		int bytesPerBlock;
		GraphicsFormat textureFormat;
		switch (formatFlags)
		{
			case (PixelFormatFlags.AlphaPixels | PixelFormatFlags.Rgb):
				bytesPerBlock = rgbBitCount;
				textureFormat = GraphicsFormat.B8G8R8A8_SRGB;
				break;
			case PixelFormatFlags.FourCC:
				switch (fourCC)
				{
					case "DXT1":
						bytesPerBlock = 8;
						textureFormat = GraphicsFormat.RGBA_DXT1_SRGB;
						break;
					case "DXT3":
						bytesPerBlock = 16;
						textureFormat = GraphicsFormat.RGBA_DXT3_SRGB;
						break;
					case "DXT5":
						bytesPerBlock = 16;
						textureFormat = GraphicsFormat.RGBA_DXT5_SRGB;
						break;
					default:
						throw new NotImplementedException(fourCC);
				}
				break;
			default:
				throw new NotImplementedException(formatFlags.ToString());
		}

		var hasMipMaps = Caps.HasFlag(HeaderCaps.Complex) || Caps.HasFlag(HeaderCaps.Mipmap);
		var data2Size = GetData2Size(width, height, bytesPerBlock, dataSize, mipMapCount, hasMipMaps, out missingDataSize);

		var data = new byte[dataSize + data2Size + missingDataSize];
		reader.Read(data, 0, dataSize + data2Size);

		var flags = hasMipMaps ? TextureCreationFlags.MipChain : TextureCreationFlags.None;
		var texture = new Texture2D(width, height, textureFormat, mipMapCount, flags);
		texture.LoadRawTextureData(data);
		texture.Apply(false, true);

		return texture;
	}

19 Source : NiZBufferProperty.cs
with GNU General Public License v3.0
from arycama

public override void ProcessNiObject(NiObjectNet niObject)
		{
			var zWrite = flags.HasFlag(ZBufferFlags.Enabled);
			niObject.Material.SetInt("_ZWrite", zWrite ? 1 : 0);

			var compareOp = (CompareOp)((int)flags >> 2);

			switch (compareOp)
			{
				case CompareOp.Always:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.Always);
					break;
				case CompareOp.Less:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.Less);
					break;
				case CompareOp.Equal:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.Equal);
					break;
				case CompareOp.LessOrEqual:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.Greater);
					break;
				case CompareOp.Greater:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.Greater);
					break;
				case CompareOp.NotEqual:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.NotEqual);
					break;
				case CompareOp.GreaterOrEqual:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.GreaterEqual);
					break;
				case CompareOp.Never:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.Never);
					break;
				default:
					niObject.Material.SetInt("_ZTest", (int)CompareFunction.Disabled);
					break;
			}
		}

19 Source : NiAVObject.cs
with GNU General Public License v3.0
from arycama

public override void ProcessNiObject(NiObjectNet niObject)
		{
			// Process properties first, as some NiNodes such as NiGeomControl will add a mesh renderer which needs the material
			if (propertyCount > 0)
			{
				// Create a new material for the properties to modify
				
				//Material = new Material(material);
				foreach (var property in properties)
				{
					niFile.NiObjects[property].NiParent = this;
				}
			}

			base.ProcessNiObject(niObject);

			if(NiParent != null)
			{
				GameObject.tag = NiParent.GameObject.tag;
				GameObject.layer = NiParent.GameObject.layer;
			}


			if (flags.HasFlag(Flags.Hidden))
			{
				GameObject.tag = "Hidden"; // Set tag and layer, so we can easily check if an object is hidden/marker etc by checking it's tag
				GameObject.layer = LayerMask.NameToLayer("Hidden");
				//GameObject.hideFlags = HideFlags.HideInHierarchy;
			}

			if (flags.HasFlag(Flags.Shadow))
			{
				GameObject.tag = "Shadow";
			}

			// Set transform (Use localPosition/rotation as this may be already parented)
			GameObject.transform.localPosition = position;
			GameObject.transform.localRotation = rotation;
			GameObject.transform.localScale = new Vector3(scale, scale, scale);

			if (hasBoundingBox)
			{
				boundingBox.AddCollider(GameObject);
			}
		}

19 Source : TerrainFactory.cs
with GNU General Public License v3.0
from arycama

private static int[,] GetBorderIndices(Directions cellDirections, TextureData[,] borderCells)
	{
		// Get the first row/column
		var borderIndices = new int[18, 18];
		var currentIndices = borderCells[1, 1].TextureIndices;

		// Copy the existing indices into a new array, starting at 1,1
		for (var y = 0; y < 16; y++)
		{
			for (var x = 0; x < 16; x++)
			{
				borderIndices[x + 1, y + 1] = currentIndices[x, y];
			}
		}

		// Now do each of the directions
		// Try and figure out a way to reduce this code
		// Southwest (Zero)
		if (cellDirections.HasFlag(Directions.SW))
		{
			borderIndices[0, 0] = borderCells[0, 0].TextureIndices[15, 15];
		}
		else
		{
			// Technically, this should check the West and South cells too, and see if one of those has a texture, but eh. 
			borderIndices[0, 0] = borderIndices[1, 1];
		}

		// South (One)
		if (cellDirections.HasFlag(Directions.S))
		{
			for (var i = 0; i < 16; i++)
			{
				borderIndices[i + 1, 0] = borderCells[1, 0].TextureIndices[i, 15];
			}
		}
		else
		{
			// If no south cell, duplicate the bottom layer
			for (var i = 0; i < 16; i++)
			{
				borderIndices[i + 1, 0] = borderIndices[i + 1, 1];
			}
		}

		// SouthEast (Two)
		if (cellDirections.HasFlag(Directions.SE))
		{
			borderIndices[17, 0] = borderCells[2, 0].TextureIndices[0, 15];
		}
		else
		{
			borderIndices[17, 0] = borderIndices[16, 1];
		}

		// West (Three)
		if (cellDirections.HasFlag(Directions.W))
		{
			for (var i = 0; i < 16; i++)
			{
				borderIndices[0, i + 1] = borderCells[0, 1].TextureIndices[15, i];
			}
		}
		else
		{
			// If no west cell, duplicate the leftmost column
			for (var i = 0; i < 16; i++)
			{
				borderIndices[0, i + 1] = borderIndices[1, i + 1];
			}
		}

		// East (Four (or five?)
		if (cellDirections.HasFlag(Directions.E))
		{
			for (var i = 0; i < 16; i++)
			{
				borderIndices[17, i + 1] = borderCells[2, 1].TextureIndices[15, i];
			}
		}
		else
		{
			// If no east cell, duplicate the rightmost column
			for (var i = 0; i < 16; i++)
			{
				borderIndices[17, i + 1] = borderIndices[16, i + 1];
			}
		}

		// Northwest (Six?)
		if (cellDirections.HasFlag(Directions.NW))
		{
			borderIndices[0, 17] = borderCells[0, 2].TextureIndices[15, 0];
		}
		else
		{
			// Technically, this should check the West and South cells too, and see if one of those has a texture, but eh. 
			borderIndices[0, 17] = borderIndices[1, 16];
		}

		// North (Seven?)
		if (cellDirections.HasFlag(Directions.N))
		{
			for (var i = 0; i < 16; i++)
			{
				borderIndices[i + 1, 17] = borderCells[1, 2].TextureIndices[i, 0];
			}
		}
		else
		{
			// If no North cell, duplicate the bottom layer
			for (var i = 0; i < 16; i++)
			{

				borderIndices[i + 1, 17] = borderIndices[i + 1, 16];
			}
		}

		// NorthEast (Eight)
		if (cellDirections.HasFlag(Directions.NE))
		{
			borderIndices[17, 17] = borderCells[2, 2].TextureIndices[0, 0];
		}
		else
		{
			borderIndices[17, 17] = borderIndices[16, 16];
		}

		return borderIndices;
	}

19 Source : Form1.cs
with MIT License
from atenfyr

private void listView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (ModifierKeys == Keys.Shift)
            {
                TreeNode newNode = null;
                if (e.KeyCode.HasFlag(Keys.Up)) // SHIFT + UP = navigate to previous node @ same level
                {
                    newNode = listView1.SelectedNode.PrevNode;
                    e.Handled = true;
                }
                else if (e.KeyCode.HasFlag(Keys.Down)) // SHIFT + DOWN = navigate to next node @ same level
                {
                    newNode = listView1.SelectedNode.NextNode;
                    e.Handled = true;
                }

                if (newNode != null)
                {
                    listView1.SelectedNode = newNode;
                    listView1.SelectedNode.EnsureVisible();
                }
            }
        }

19 Source : DeployTask.cs
with GNU General Public License v3.0
from AtomCrafty

protected override void Execute() {
			// init patch directory
			if(flags.Has("init")) {
				string deployDirectory = Helpers.AbsolutePath(arguments.Length > 0 ? arguments[0] : "autopatch");
				string deployFilePath = Path.ChangeExtension(deployDirectory, Constants.ydr);
				Dictionary<string, string> targets = new Dictionary<string, string>();
				for(int i = 1; i < arguments.Length; i++) {
					// parse targets in format name:path or just path
					string[] tmp = arguments[i].Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries);
					string name = tmp.Length > 1 && tmp[0].Length > 1 ? tmp[0] : Path.GetFileName(tmp[0]);
					string path = Helpers.AbsolutePath(tmp.Length > 1 && tmp[0].Length > 1 ? tmp[1] : tmp[0]);
					targets.Add(name, path);
				}
				if(targets.Count == 0) Fail("No target directories specified");

				Directory.CreateDirectory(deployDirectory);

				int fileCount = 0;

				dynamic info = new JObject();
				info.build = 0;
				info.nameschema = "inc.{buildno}.{target}.patch.ykc";
				info.deploydir = deployDirectory;
				info.targets = new JArray();
				foreach(var targetInfo in targets) {
					string targetName = targetInfo.Key;
					string targetPath = targetInfo.Value;
					string[] files = Directory.GetFiles(targetPath, "*", SearchOption.AllDirectories);

					dynamic target = new JObject();
					{
						target.name = targetName;
						target.path = targetPath;
						target.files = new JArray();
						foreach(string file in files) {
							// ignore unknown file types and hidden files
							if(!DataTypes.ForExtension(DataTypes.BaseExtension(Path.GetExtension(file))).IncludeInArchive()) continue;
							if(new FileInfo(file).Attributes.HasFlag(FileAttributes.Hidden)) continue;

							dynamic entry = new JObject();
							{
								entry.name = Helpers.RelativePath(file, targetPath);
								entry.size = Helpers.FileSize(file);
								entry.hash = Helpers.FileHash(file);
								entry.version = 0;
							}
							target.files.Add(entry);

							fileCount++;
						}
					}
					info.targets.Add(target);
					Log("Added target '" + targetName + "' (" + target.files.Count + " files) [" + targetPath + "]", ConsoleColor.Yellow);
				}
				Log("Successfully added " + fileCount + " file in " + info.targets.Count + " targets", ConsoleColor.Green);

				File.WriteAllText(deployFilePath, JsonConvert.SerializeObject(info, Formatting.Indented));
			}

			else {
				if(arguments.Length == 0) Fail("No target file specified");
				string deployFilePath = Helpers.AbsolutePath(arguments[0]);

				int changedFiles = 0, newFiles = 0;

				if(deployFilePath.EndsWith(Constants.ydr, StringComparison.OrdinalIgnoreCase)) {
					dynamic info = JsonConvert.DeserializeObject(File.ReadAllText(deployFilePath));
					info.build = (int)info.build + 1;

					foreach(var target in info.targets) {
						List<string> includedFiles = new List<string>();
						string[] files = Directory.GetFiles((string)target.path, "*", SearchOption.AllDirectories);
						foreach(string file in files) {
							string localName = Helpers.RelativePath(file, (string)target.path);

							// ignore unknown file types and hidden files
							if(!DataTypes.ForExtension(DataTypes.BaseExtension(Path.GetExtension(localName))).IncludeInArchive()) continue;
							if(new FileInfo(file).Attributes.HasFlag(FileAttributes.Hidden)) continue;

							bool include = true, exists = false;
							foreach(var localFile in target.files) {
								if(localName.Equals((string)localFile.name, StringComparison.OrdinalIgnoreCase)) {
									exists = true;
									string hash = Helpers.FileHash(file);
									long size = Helpers.FileSize(file);

									if(size != (long)localFile.size || !hash.Equals((string)localFile.hash)) {
										// update file entry if files differ
										localFile.size = size;
										localFile.hash = hash;
										localFile.version = (int)localFile.version + 1;
									}
									else include = false;
									break;
								}
							}
							if(!exists) {
								Log("[New file]   " + localName, ConsoleColor.Green);
								dynamic entry = new JObject();
								{
									entry.name = localName;
									entry.size = Helpers.FileSize(file);
									entry.hash = Helpers.FileHash(file);
									entry.version = 1;
								}
								target.files.Add(entry);
								newFiles++;
							}
							if(include) {
								string mainFile = Path.ChangeExtension(localName, DataTypes.BaseExtension(Path.GetExtension(localName)));
								if(!includedFiles.Contains(mainFile)) {
									includedFiles.Add(mainFile);
									if(exists) Log("[Changed]    " + localName, ConsoleColor.Yellow);
									if(exists) changedFiles++;
								}
							}
							else {
								Log("[Up to date] " + localName, ConsoleColor.Red);
							}
							// Log(include ? exists ? "Changed" : "New file" : "Up to date", ConsoleColor.Cyan);
						}

						if(includedFiles.Count > 0) {
							bool verbose = flags.Has('v');
							flags.Unset('v');
							YukaArchive archive = new YukaArchive();
							foreach(string file in includedFiles) {
								dynamic factory = FileFactory.ForExtension(Path.GetExtension(file));
								if(factory != null) {
									string realname = Path.ChangeExtension(file, DataTypes.ForExtension(Path.GetExtension(file)).BinaryExtension());
									Console.WriteLine(realname);
									dynamic data = factory.FromSource(Path.Combine((string)target.path, file));
									MemoryStream ms = new MemoryStream();
									factory.ToBinary(data, ms);
									archive.files[realname] = ms;
								}
							}
							string name = (string)info.nameschema;

							name = name.Replace("{buildno}", ((int)info.build).ToString("D3"));
							name = name.Replace("{target}", ((string)target.name));
							name = name.Replace("{date}", DateTime.Now.ToString("yyyy-MM-dd"));
							name = name.Replace("{time}", DateTime.Now.ToString("HH-mm-ss"));

							ArchiveFactory.Instance.ToSource(archive, Path.Combine((string)info.deploydir, name));
							if(verbose) flags.Set('v');
						}
					}

					Log("Deployed " + newFiles + " new files and " + changedFiles + " updates", ConsoleColor.Green);

					File.WriteAllText(deployFilePath, JsonConvert.SerializeObject(info, Formatting.Indented));
				}
			}

			if(flags.Has('w')) {
				Console.ReadLine();
			}
		}

19 Source : PackTask.cs
with GNU General Public License v3.0
from AtomCrafty

protected override void Execute() {
			if(arguments.Length == 0) Fail("No source directory specified");

			string sourceBasePath = Helpers.AbsolutePath(arguments[0]);
			string targetBasePath = arguments.Length > 1 ? Helpers.AbsolutePath(arguments[1]) : Path.ChangeExtension(sourceBasePath.TrimEnd('\\'), "ykc");

			string[] files = null;
			if(Directory.Exists(sourceBasePath)) {
				files = Directory.GetFiles(sourceBasePath, "*", SearchOption.AllDirectories);
			}
			else {
				Fail("The specified source directory does not exist");
			}

			YukaArchive archive = new YukaArchive();

			for(int i = 0; i < files.Length; i++) {
				string sourcePath = files[i];
				string localPath = Helpers.RelativePath(sourcePath, sourceBasePath);
				string extension = Path.GetExtension(localPath);
				DataType type = DataTypes.ForExtension(extension);

				// ignore unknown file types and hidden files
				if(!type.IncludeInArchive()) continue;
				if(new FileInfo(sourcePath).Attributes.HasFlag(FileAttributes.Hidden)) continue;

				currentFile = localPath;

				if(flags.Has('v')) {
					Console.WriteLine();
					Console.WriteLine("SourceBase: " + sourceBasePath);
					Console.WriteLine("TargetBase: " + targetBasePath);
					Console.WriteLine("Source:     " + sourcePath);
					Console.WriteLine("Local:      " + localPath);
				}

				if(DataTypes.ConvertOnPack(extension)) {
					// File needs to be converted
					string realPath = Path.ChangeExtension(localPath, type.BinaryExtension());
					MemoryStream ms = archive.GetOutputStream(realPath);
					dynamic factory = FileFactory.ForDataType(type);
					dynamic data = factory.FromSource(sourcePath);
					factory.ToBinary(data, ms);
				}
				else {
					MemoryStream ms = archive.GetOutputStream(localPath);
					FileStream fs = new FileStream(sourcePath, FileMode.Open);
					fs.CopyTo(ms);
					fs.Close();
				}
			}
			currentFile = "";

			ArchiveFactory.Instance.ToSource(archive, targetBasePath);

			if(flags.Has('w')) {
				Console.ReadLine();
			}
		}

19 Source : Swap.cs
with GNU General Public License v3.0
from atomex-me

public bool IsStatusSet(SwapStatus status, Enum flag) =>
            !Status.HasFlag(flag) && status.HasFlag(flag);

19 Source : ProgressProcessor.cs
with GNU General Public License v3.0
from audiamus

private string buildInfoLabel (EVerbosity verbosity, int maxStrLen) {
        bool doLog = Level >= 3;
        var sbLbl = new StringBuilder ();
        var sbLog = new StringBuilder ();

        sbLbl.Append ($"{R.MsgProgStep} {_progbar.AccuValue}/{_progbar.Acreplacedaximum}");
        sbLog.Append ($"{R.MsgProgStep} .../{_progbar.Acreplacedaximum}");

        foreach (var kvp in _books) {
          var bi = kvp.Value;

          string s = $"; \"{bi.replacedle.Shorten (maxStrLen)}\"";
          sbLbl.Append (s);
          if (doLog)
            sbLog.Append (s);

          if (verbosity.HasFlag (EVerbosity.counters)) {
            if (bi.PartNumber.HasValue) {
              s = $", {R.MsgProgPt} {bi.PartNumber}";
              sbLbl.Append (s);
              if (doLog)
                sbLog.Append (s);
            }

            if (bi.NumberOfChapters.HasValue) {
              s = $", {bi.NumberOfChapters} {R.MsgProgCh}";
              sbLbl.Append (s);
              if (doLog)
                sbLog.Append (s);
            }

            if (bi.NumberOfTracks.HasValue) {
              s = $", {bi.NumberOfTracks} {R.MsgProgTr}";
              sbLbl.Append (s);
              if (doLog)
                sbLog.Append (s);
            }
          }

          if (bi.Phase != EProgressPhase.none && verbosity.HasFlag (EVerbosity.phase)) {
            s = $", {R.ResourceManager.GetStringEx (bi.Phase.ToString ())}";
            sbLbl.Append (s);
            if (doLog)
              sbLog.Append (s);
          }

          if (verbosity.HasFlag (EVerbosity.chapters)) {
            buildInfoLabelSequence (sbLbl, bi.Parts, R.MsgProgPt);
            buildInfoLabelSequence (sbLbl, bi.Chapters, R.MsgProgCh);
            buildInfoLabelSequence (sbLbl, bi.Tracks, R.MsgProgTr);
          }
        }

        if (doLog) {
          string sLog = sbLog.ToString (); 
          if (!string.Equals (sLog, _logString)) {
            _logString = sLog;
            Log (3, this, sLog);
          }
        }

        return sbLbl.ToString();
      }

19 Source : FFmpeg.cs
with GNU General Public License v3.0
from audiamus

public bool Transcode (string filenameOut, ETranscode modifiers, string actBytes = null, TimeSpan? from = null, TimeSpan? to = null) {
      _error = false;
      _success = false;
      _aborted = false;
      _matchedDuration = false;
      AudioMeta.Time.Duration = TimeSpan.Zero;

      string param = FFMPEG_TRANSCODE;
      if (!(_filenameMeta is null))
        param = FFMPEG_TRANSCODE2;
      if (actBytes is null)
        param = param.Replace (ACTIVATION, string.Empty);
      else {
        param = param.Replace (ACTIVATION, ACTIVATION_PARAM);
        param = param.Replace (ACT_BYTES, actBytes);
      }

      if (from.HasValue) {
        param = param.Replace (BEGIN, BEGIN_PARAM);
        string secs = from.Value.TotalSeconds.ToString ("f3");
        param = param.Replace (TS_FROM, secs);
        AudioMeta.Time.Begin = from.Value;
      } else
        param = param.Replace (BEGIN, string.Empty);

      if (to.HasValue) {
        param = param.Replace (END, END_PARAM);
        string secs = to.Value.TotalSeconds.ToString ("f3");
        param = param.Replace (TS_TO, secs);
        AudioMeta.Time.End = to.Value;
      } else
        param = param.Replace (END, string.Empty);

      param = param.Replace (INPUT, _filenameIn);
      param = param.Replace (OUTPUT, filenameOut);

      if (!_bitrateParam.IsNullOrWhiteSpace ())
        param = param.Replace (BITRATE, _bitrateParam);
      else
        param = param.Replace (BITRATE, string.Empty);

      if (modifiers.HasFlag(ETranscode.copy) && _bitrateParam.IsNullOrWhiteSpace ())
        param = param.Replace (COPY, COPY_PARAM);
      else
        param = param.Replace (COPY, string.Empty);

      if (!(_filenameMeta is null))
        param = param.Replace (INPUT2, _filenameMeta);

      Log (4, this, () => ID + param.SubsreplacedUser ().SubsreplacedActiv ());
      string result = runProcess (FFmpegExePath, param, true, ffMpegAsyncHandlerTranscode);

      return _success && !_aborted && !_error;
    }

19 Source : AudibleAppContentMetadata.cs
with GNU General Public License v3.0
from audiamus

public void GetContentMetadata (Book.Part part, EFlags flags = default) {
      var filename = part.AaxFileItem.FileName;
      Log (3, this, () => $"\"{filename.SubsreplacedUser ()}\", flags={flags}");

      try {
        var contentMetadataFile = findContentMetadataFile (filename);
        if (contentMetadataFile is null || contentMetadataFile.Filename is null) {
          part.AaxFileItem.ContentMetadataFile = new AsinJsonFile (null, null);
          return;
        }

        part.AaxFileItem.ContentMetadataFile = contentMetadataFile;
        string metafile = contentMetadataFile.Filename;
        Log (3, this, () => $"\"{metafile.SubsreplacedUser ()}\"");

        if (flags.HasFlag (EFlags.fileOnly))
          return;

        getContentMetaChapters (part, metafile, flags.HasFlag (EFlags.skuOnly));
      } catch (Exception exc ) {
        Log (1, this, () => exc.ToShortString ());
      }
    }

19 Source : ElementTypeHelper.cs
with MIT License
from AutoMapper

public static Type[] GetElementTypes(Type enumerableType, System.Collections.IEnumerable enumerable,
            ElementTypeFlags flags = ElementTypeFlags.None)
        {
            if (enumerableType.HasElementType)
            {
                return new[] { enumerableType.GetElementType() };
            }

            var iDictionaryType = enumerableType.GetDictionaryType();
            if (iDictionaryType != null && flags.HasFlag(ElementTypeFlags.BreakKeyValuePair))
            {
                return iDictionaryType.GetTypeInfo().GenericTypeArguments;
            }

            var iReadOnlyDictionaryType = enumerableType.GetReadOnlyDictionaryType();
            if (iReadOnlyDictionaryType != null && flags.HasFlag(ElementTypeFlags.BreakKeyValuePair))
            {
                return iReadOnlyDictionaryType.GetTypeInfo().GenericTypeArguments;
            }

            var iEnumerableType = enumerableType.GetIEnumerableType();
            if (iEnumerableType != null)
            {
                return iEnumerableType.GetTypeInfo().GenericTypeArguments;
            }

            if (typeof(System.Collections.IEnumerable).IsreplacedignableFrom(enumerableType))
            {
                var first = enumerable?.Cast<object>().FirstOrDefault();

                return new[] { first?.GetType() ?? typeof(object) };
            }

            throw new ArgumentException($"Unable to find the element type for type '{enumerableType}'.",
                nameof(enumerableType));
        }

19 Source : Wildcard.cs
with MIT License
from Avanade

public bool Validate(WildcardSelection selection)
        {
            if ((selection.HasFlag(WildcardSelection.None) && !Supported.HasFlag(WildcardSelection.None)) ||
                (selection.HasFlag(WildcardSelection.Equal) && !Supported.HasFlag(WildcardSelection.Equal)) ||
                (selection.HasFlag(WildcardSelection.Single) && !Supported.HasFlag(WildcardSelection.Single)) ||
                (selection.HasFlag(WildcardSelection.StartsWith) && !Supported.HasFlag(WildcardSelection.StartsWith)) ||
                (selection.HasFlag(WildcardSelection.EndsWith) && !Supported.HasFlag(WildcardSelection.EndsWith)) ||
                (selection.HasFlag(WildcardSelection.Contains) && !Supported.HasFlag(WildcardSelection.Contains)) ||
                (selection.HasFlag(WildcardSelection.Embedded) && !Supported.HasFlag(WildcardSelection.Embedded)) ||
                (selection.HasFlag(WildcardSelection.MultiWildcard) && !Supported.HasFlag(WildcardSelection.MultiWildcard)) ||
                (selection.HasFlag(WildcardSelection.SingleWildcard) && !Supported.HasFlag(WildcardSelection.SingleWildcard)) ||
                (selection.HasFlag(WildcardSelection.AdjacentWildcards) && !Supported.HasFlag(WildcardSelection.AdjacentWildcards)) ||
                (selection.HasFlag(WildcardSelection.InvalidCharacter)))
                return false;
            else
                return true;
        }

19 Source : Wildcard.cs
with MIT License
from Avanade

public WildcardResult Parse(string? text)
        {
            text = Cleaner.Clean(text, StringTrim.Both, Transform);
            if (string.IsNullOrEmpty(text))
                return new WildcardResult(this) { Selection = WildcardSelection.None, Text = text };

            var sb = new StringBuilder();
            var wr = new WildcardResult(this) { Selection = WildcardSelection.Undetermined };

            if (CharactersNotAllowed != null && CharactersNotAllowed.Count > 0 && text.IndexOfAny(CharactersNotAllowed.ToArray()) >= 0)
                wr.Selection |= WildcardSelection.InvalidCharacter;

            var hasMulti = SpaceTreatment == WildcardSpaceTreatment.MultiWildcardWhenOthers && Supported.HasFlag(WildcardSelection.MultiWildcard) && text.IndexOf(MultiWildcardCharacter, StringComparison.InvariantCulture) >= 0;
            var hasTxt = false;

            for (int i = 0; i < text.Length; i++)
            {
                var c = text[i];
                var isMulti = c == MultiWildcard;
                var isSingle = c == SingleWildcard;

                if (isMulti)
                {
                    wr.Selection |= WildcardSelection.MultiWildcard;

                    // Skip adjacent multi's as they are redundant.
                    for (int j = i + 1; j < text.Length; j++)
                    {
                        if (text[j] == MultiWildcard)
                        {
                            i = j;
                            continue;
                        }

                        break;
                    }
                }

                if (isSingle)
                    wr.Selection |= WildcardSelection.SingleWildcard;

                if (isMulti || isSingle)
                {
                    if (text.Length == 1)
                        wr.Selection |= WildcardSelection.Single;
                    else if (i == 0)
                        wr.Selection |= WildcardSelection.EndsWith;
                    else if (i == text.Length - 1)
                        wr.Selection |= WildcardSelection.StartsWith;
                    else
                    {
                        if (hasTxt || isSingle)
                            wr.Selection |= WildcardSelection.Embedded;
                        else
                            wr.Selection |= WildcardSelection.EndsWith;
                    }

                    if (i < text.Length - 1 && (text[i + 1] == MultiWildcard || text[i + 1] == SingleWildcard))
                        wr.Selection |= WildcardSelection.AdjacentWildcards;
                }
                else
                {
                    hasTxt = true;
                    if (c == SpaceCharacter && (SpaceTreatment == WildcardSpaceTreatment.Compress || SpaceTreatment == WildcardSpaceTreatment.MultiWildcardAlways || SpaceTreatment == WildcardSpaceTreatment.MultiWildcardWhenOthers))
                    {
                        // Compress adjacent spaces.
                        bool skipChar = SpaceTreatment != WildcardSpaceTreatment.Compress && text[i - 1] == MultiWildcardCharacter;
                        for (int j = i + 1; j < text.Length; j++)
                        {
                            if (text[j] == SpaceCharacter)
                            {
                                i = j;
                                continue;
                            }

                            break;
                        }

                        if (skipChar || (SpaceTreatment != WildcardSpaceTreatment.Compress && text[i + 1] == MultiWildcardCharacter))
                            continue;

                        if (SpaceTreatment == WildcardSpaceTreatment.MultiWildcardAlways || (SpaceTreatment == WildcardSpaceTreatment.MultiWildcardWhenOthers && hasMulti))
                        {
                            c = MultiWildcardCharacter;
                            wr.Selection |= WildcardSelection.MultiWildcard;
                            wr.Selection |= WildcardSelection.Embedded;
                        }
                    }
                }

                sb.Append(c);
            }

            if (!hasTxt && wr.Selection == (WildcardSelection.StartsWith | WildcardSelection.MultiWildcard))
            {
                wr.Selection |= WildcardSelection.Single;
                wr.Selection ^= WildcardSelection.StartsWith;
            }

            if (hasTxt && wr.Selection.HasFlag(WildcardSelection.StartsWith) && wr.Selection.HasFlag(WildcardSelection.EndsWith) && !wr.Selection.HasFlag(WildcardSelection.Embedded))
            {
                wr.Selection |= WildcardSelection.Contains;
                wr.Selection ^= WildcardSelection.StartsWith;
                wr.Selection ^= WildcardSelection.EndsWith;
            }

            if (wr.Selection == WildcardSelection.Undetermined)
                wr.Selection |= WildcardSelection.Equal;

            wr.Text = sb.Length == 0 ? null : sb.ToString();
            return wr;
        }

19 Source : Wildcard.cs
with MIT License
from Avanade

public string? GetTextWithoutWildcards()
        {
            var s = Text;
            if (Selection.HasFlag(WildcardSelection.MultiWildcard))
                s = s!.Replace(new string(Wildcard.MultiWildcard, 1), string.Empty, StringComparison.InvariantCulture);

            if (Selection.HasFlag(WildcardSelection.SingleWildcard))
                s = s!.Replace(new string(Wildcard.SingleWildcard, 1), string.Empty, StringComparison.InvariantCulture);

            return s;
        }

19 Source : Wildcard.cs
with MIT License
from Avanade

public Regex CreateRegex(bool ignoreCase = true)
        {
            ThrowOnError();

            if (Selection.HasFlag(WildcardSelection.Single))
                return CreateRegex(Selection.HasFlag(WildcardSelection.MultiWildcard) ? "^.*$" : "^.$", ignoreCase);

            var p = Regex.Escape(Text);
            if (Selection.HasFlag(WildcardSelection.MultiWildcard))
                p = p.Replace("\\*", ".*", StringComparison.InvariantCulture);

            if (Selection.HasFlag(WildcardSelection.SingleWildcard))
                p = p.Replace("\\?", ".", StringComparison.InvariantCulture);

            return CreateRegex($"^{p}$", ignoreCase);
        }

19 Source : Wildcard.cs
with MIT License
from Avanade

public string GetRegexPattern()
        {
            ThrowOnError();

            if (Selection.HasFlag(WildcardSelection.Single))
                return Selection.HasFlag(WildcardSelection.MultiWildcard) ? "^.*$" : "^.$";

            var p = Regex.Escape(Text);
            if (Selection.HasFlag(WildcardSelection.MultiWildcard))
                p = p.Replace("\\*", ".*", StringComparison.InvariantCulture);

            if (Selection.HasFlag(WildcardSelection.SingleWildcard))
                p = p.Replace("\\?", ".", StringComparison.InvariantCulture);

            return $"^{p}$";
        }

19 Source : DefaultRepositoryMonitor.cs
with MIT License
from awaescher

private void OnCheckKnownRepository(string file, KnownRepositoryNotifications notification)
		{
			var repo = _repositoryReader.ReadRepository(file);
			if (repo.WasFound)
			{
				if (notification.HasFlag(KnownRepositoryNotifications.WhenFound))
					OnRepositoryChangeDetected(repo);
			}
			else
			{
				if (notification.HasFlag(KnownRepositoryNotifications.WhenNotFound))
					OnRepositoryDeletionDetected(file);
			}
		}

19 Source : DefaultRepositoryMonitorTests.cs
with MIT License
from awaescher

private static void NormalizeReadOnlyFiles(string rootPath)
		{
			// set readonly git files to "normal" 
			// otherwise we get UnauthorizedAccessExceptions
			var readOnlyFiles = Directory.GetFiles(rootPath, "*.*", SearchOption.AllDirectories)
				.Where(f => File.GetAttributes(f).HasFlag(FileAttributes.ReadOnly));

			foreach (var file in readOnlyFiles)
				File.SetAttributes(file, FileAttributes.Normal);
		}

19 Source : AsyncDirectorySource.cs
with Apache License 2.0
from awslabs

private bool ShouldSkip(string fullPath)
        {
            if (!File.Exists(fullPath) || File.GetAttributes(fullPath).HasFlag(FileAttributes.Directory))
            {
                return true;
            }
            if (_subDirFilters is null)
            {
                // include all subdirectories
                return false;
            }

            var dirPath = Path.GetDirectoryName(fullPath);

            return !_subDirFilters.Any(s => dirPath.StartsWith(s,
                OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal));
        }

19 Source : FileSystemDirectory.cs
with MIT License
from azist

private void deepCopyTo(FileSystemDirectory target, DirCopyFlags flags, byte[] buffer, Func<FileSystemSessionItem, bool> filter, Func<FileSystemSessionItem, bool> cancel = null)
        {
            target.CheckCanChange();

            if (flags.HasFlag(DirCopyFlags.Directories))
            {
              foreach(var sdn in this.SubDirectoryNames)
                using(var sdir = this.GetSubDirectory(sdn))
                 if (filter==null||filter(sdir))
                 {
                    if (cancel != null && cancel(sdir)) return;

                    using(var newSDir = target.CreateDirectory(sdn))
                    {
                      copyCommonAttributes(sdir, newSDir, buffer, flags);


                      if (flags.HasFlag(DirCopyFlags.Readonly) &&
                          this.FileSystem.InstanceCapabilities.SupportsReadonlyDirectories &&
                          target.FileSystem.InstanceCapabilities.SupportsReadonlyDirectories) newSDir.ReadOnly = sdir.ReadOnly;

                      sdir.deepCopyTo(newSDir, flags, buffer, filter, cancel);
                    }
                 }//if
            }

            if (flags.HasFlag(DirCopyFlags.Files))
            {
              foreach(var fn in this.FileNames)
                using(var file = this.GetFile(fn))
                  if (filter==null||filter(file))
                  {
                    if (cancel != null && cancel(file)) return;

                    using(var newFile = target.CreateFile(fn))
                    {
                      copyCommonAttributes(file, newFile, buffer, flags);

                      if (flags.HasFlag(DirCopyFlags.Readonly) &&
                          this.FileSystem.InstanceCapabilities.SupportsReadonlyFiles &&
                          target.FileSystem.InstanceCapabilities.SupportsReadonlyFiles) newFile.ReadOnly = file.ReadOnly;

                      copyStream(file.FileStream, newFile.FileStream, buffer);
                    }
                  }
            }


        }

19 Source : FileSystemDirectory.cs
with MIT License
from azist

private void copyCommonAttributes(FileSystemSessionItem source, FileSystemSessionItem target, byte[] buffer, DirCopyFlags flags)
        {
          if (flags.HasFlag(DirCopyFlags.Security) &&
              this.FileSystem.InstanceCapabilities.SupportsSecurity &&
              target.FileSystem.InstanceCapabilities.SupportsSecurity) copyStream(source.PermissionsStream, target.PermissionsStream, buffer);

          if (flags.HasFlag(DirCopyFlags.Metadata) &&
              this.FileSystem.InstanceCapabilities.SupportsCustomMetadata &&
              target.FileSystem.InstanceCapabilities.SupportsCustomMetadata) copyStream(source.MetadataStream, target.MetadataStream, buffer);

          if (flags.HasFlag(DirCopyFlags.Timestamps))
          {
            if (this.FileSystem.InstanceCapabilities.SupportsCreationTimestamps &&
                target.FileSystem.InstanceCapabilities.SupportsCreationTimestamps) target.CreationTimestamp = source.CreationTimestamp;

            if (this.FileSystem.InstanceCapabilities.SupportsModificationTimestamps &&
                target.FileSystem.InstanceCapabilities.SupportsModificationTimestamps) target.ModificationTimestamp = source.ModificationTimestamp;

            if (this.FileSystem.InstanceCapabilities.SupportsLastAccessTimestamps &&
                target.FileSystem.InstanceCapabilities.SupportsLastAccessTimestamps) target.LastAccessTimestamp = source.LastAccessTimestamp;
          }
        }

19 Source : Protocol.cs
with MIT License
from azist

public static void CheckReplyDataForErrors(ReplyData reply)
          {
            if (reply.Flags.HasFlag(ResponseFlags.QueryFailure))
            {
              var err = (reply.Doreplacedents!=null && reply.Doreplacedents.Length>0) ? reply.Doreplacedents[0].ToString() : NOT_AVAIL;
              throw new MongoDbConnectorServerException(StringConsts.SERVER_QUERY_FAILURE_ERROR + err);
            }

            if (reply.Flags.HasFlag(ResponseFlags.CursorNotFound))
              throw new MongoDbConnectorServerException(StringConsts.SERVER_CURSOR_NOT_FOUND_ERROR);
          }

19 Source : Utils.cs
with MIT License
from Azure

internal static void CleanupGlobalVariables(PowerShell pwsh)
        {
            List<string> varsToRemove = null;
            ICollection<PSVariable> globalVars = GetGlobalVariables(pwsh);

            foreach (PSVariable var in globalVars)
            {
                // The variable is one of the built-in global variables.
                if (s_globalVariables.Contains(var.Name)) { continue; }

                // We cannot remove a constant variable, so leave it as is.
                if (var.Options.HasFlag(ScopedItemOptions.Constant)) { continue; }

                // The variable is exposed by a module. We don't remove modules, so leave it as is.
                if (var.Module != null) { continue; }

                // The variable is not a regular PSVariable.
                // It's likely not created by the user, so leave it as is.
                if (var.GetType() != typeof(PSVariable)) { continue; }

                if (varsToRemove == null)
                {
                    // Create a list only if it's needed.
                    varsToRemove = new List<string>();
                }

                // Add the variable path.
                varsToRemove.Add($"{VariableDriveRoot}{var.Name}");
            }

            if (varsToRemove != null)
            {
                // Remove the global variable added by the function invocation.
                pwsh.Runspace.SessionStateProxy.InvokeProvider.Item.Remove(
                    varsToRemove.ToArray(),
                    recurse: true,
                    force: true,
                    literalPath: true);
            }
        }

19 Source : Program.cs
with MIT License
from badamczewski

static KeyBuffer ProcessKeyEvents(string prompt, char breakKey, char multiLineKey, bool wasMultiline = false)
        {
            XConsole.Write(prompt);
            StringBuilder statementBuilder = new StringBuilder();
            XConsole.ForegroundColor = Colors.Green;

            var keyInfo = new ConsoleKeyInfo();
            int bufferIndex = 0;
            int baseIndex = prompt.Length;
            bool isTerminated = false;
            bool isMultiLine = wasMultiline;

            while (keyInfo.KeyChar != breakKey)
            {
                keyInfo = Console.ReadKey(true);
                            
                if (keyInfo.Key == ConsoleKey.UpArrow)
                {
                    if (historyIndex > 0) historyIndex--;
                    var historyStatement = history[historyIndex];

                    if (historyStatement != null)
                    {
                        Console.SetCursorPosition(baseIndex, Console.CursorTop);
                        XConsole.Write(new string(' ', statementBuilder.Length + historyStatement.Length));
                        Console.SetCursorPosition(baseIndex, Console.CursorTop);

                        if (keyInfo.Modifiers.HasFlag(ConsoleModifiers.Shift))
                        {
                            XConsole.Write(statementBuilder.ToString() + historyStatement);
                            statementBuilder.Append(statementBuilder.ToString() + historyStatement);
                        }
                        else
                        {
                            //
                            // The statement needs to be colorized.
                            //
                            ColorizeExpression(historyStatement);
                            statementBuilder.Clear();
                            statementBuilder.Append(historyStatement);
                        }
                    }

                    bufferIndex = statementBuilder.Length;

                }
                else if (keyInfo.Key == ConsoleKey.DownArrow)
                {
                    if (historyIndex < history.Length) historyIndex++;
                    var historyStatement = history[historyIndex & history.Length];

                    Console.SetCursorPosition(baseIndex, Console.CursorTop);
                    XConsole.Write(new string(' ', statementBuilder.Length));
                    Console.SetCursorPosition(baseIndex, Console.CursorTop);

                    ColorizeExpression(historyStatement);
                    statementBuilder.Clear();
                    statementBuilder.Append(historyStatement);
                    bufferIndex = statementBuilder.Length;
                }
                else if (keyInfo.Key == ConsoleKey.LeftArrow)
                {
                    if (bufferIndex == 0)
                        continue;

                    Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                    bufferIndex--;

                }
                else if (keyInfo.Key == ConsoleKey.RightArrow)
                {
                    if (bufferIndex >= statementBuilder.Length)
                        continue;

                    Console.SetCursorPosition(Console.CursorLeft + 1, Console.CursorTop);
                    bufferIndex++;
                }
                else if (keyInfo.Key == ConsoleKey.Backspace)
                {
                    if (bufferIndex == 0)
                        continue;

                    if (bufferIndex >= statementBuilder.Length)
                    {
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);
                        XConsole.Write(" ");
                        Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop);

                        statementBuilder.Remove(statementBuilder.Length - 1, 1);
                    }
                    else
                    {
                        RemoveBetween(statementBuilder, keyInfo.KeyChar, bufferIndex);
                    }

                    bufferIndex--;

                }
                else if(keyInfo.KeyChar == breakKey)
                {
                    //
                    // This is not an empty key so we need to display it.
                    //
                    if (keyInfo.Key != ConsoleKey.Enter)
                    {
                        statementBuilder.Append(keyInfo.KeyChar);
                        XConsole.Write(keyInfo.KeyChar.ToString());
                    }

                    isTerminated = true;
                    break;
                }
                //
                // Enable multiline mode.
                //
                else if(keyInfo.KeyChar == multiLineKey)
                {
                    statementBuilder.Append(multiLineKey + Environment.NewLine);
                    XConsole.WriteLine(multiLineKey.ToString());

                    isMultiLine = true;
                    break;
                }
                //
                // Move to new line and break here.
                //
                else if (isMultiLine && keyInfo.Key == ConsoleKey.Enter)
                {
                    statementBuilder.Append(Environment.NewLine);
                    XConsole.WriteLine();
                    break;
                }
                else
                {
                    Colorize(keyInfo.KeyChar);

                    if (bufferIndex >= statementBuilder.Length)
                    {
                        statementBuilder.Append(keyInfo.KeyChar);
                    }
                    else
                    {
                        InsertBetween(statementBuilder, keyInfo.KeyChar, bufferIndex);
                    }

                    bufferIndex++;

                    foreach (var command in Definitions.Commands)
                    {
                        var clsIdx = IndexOf(statementBuilder, command);

                        if (clsIdx >= 0 && bufferIndex <= clsIdx + command.Length)
                        {
                            Console.SetCursorPosition(prompt.Length + clsIdx, Console.CursorTop);
                            XConsole.Write(command, Colors.Blue);
                        }
                    }

                }
            }

            return new KeyBuffer() { Statement = statementBuilder.ToString(), IsTerminated = isTerminated, IsMultiLine = isMultiLine};
        }

19 Source : Parser.cs
with MIT License
from badamczewski

private AST_Node ParseBinaryExpression(ref int index, ref bool isEnd, int level, ParsingMode mode = ParsingMode.None)
        {
            AST_Node left = null;

            for (; index < tokens.Count; index++)
            {
                var token = tokens[index];

                //
                // Check if we're dealing with Unary Expression: (-1 -2 etc)
                // The Left Hand side needs to be unset for this to be true
                // since otherwise we would match against any substraction.
                // But since we descent on every oprtator unary expressions will be 
                // correctly matched.
                //
                if (IsLiteralWithOperator(index) && left == null)
                {
                    UnaryExpression unary = new UnaryExpression();
                    unary.Operator = token.GetValue();
                    Move(ref index);

                    unary.Left = ParseLiteralsAndIdentifiers(ref index);
                    left = unary;
                }
                else if (IsParrenWithOperator(index) && left == null)
                {
                    UnaryExpression unary = new UnaryExpression();
                    unary.Operator = token.GetValue();

                    Move(ref index);
                    Move(ref index);

                    unary.Left = ParseBinaryExpression(ref index, 0);
                    left = unary;
                }
                else if (IsOperator(index))
                {
                    var @operator = (OperatorToken)token;
                    var isValid = ValidateBinaryExpressionOperator(@operator, index);

                    // 
                    // Check if we should descent deeper, if the operator has a
                    // higher level value we simply call parse binary again.
                    //
                    if (@operator.Level > level)
                    {
                        Move(ref index);
                        var right = ParseBinaryExpression(ref index, ref isEnd, @operator.Level, mode);
                        left = new BinaryExpression() { Left = left, Operator = @operator.GetValue(), Right = right };

                        if (isEnd) return left;
                    }
                    else
                    {
                        //
                        // Move back to the operator
                        // This could be improved by explicit itteration control 
                        // but it's not needed for now.
                        //
                        if (isValid) index--;
                        return left;
                    }
                }

                //
                // @IDEA:
                // Indexing Access is used in replacedembly instructions
                // Perhaps we should preplaced it as a mode argument to recursive descent.
                //
                else if (IsIndexingAccessOpen(index))
                {
                    Move(ref index);
                    return ParseBinaryExpression(ref index, 0, mode);

                }
                else if (mode.HasFlag(ParsingMode.Indexing) && IsIndexingAccessClose(index))
                {
                    isEnd = true;
                    return left;
                }
                // For replacedembly index addressing we need to 
                // exit when we encouter a comma.
                //
                else if (mode.HasFlag(ParsingMode.Separator) && IsComma(index))
                {
                    isEnd = true;
                    return left;
                }
                else if (IsOpenBracket(index))
                {
                    Move(ref index);
                    return ParseBinaryExpression(ref index, 0);
                }
                else if (IsCloseBracket(index))
                {
                    return left;
                }
                else if (IsLiteralsOrVars(index))
                {
                    left = ParseLiteralsAndIdentifiers(ref index);
                }
                //
                // IF we are parsing a block we need to check for block temrination
                //
                else if (mode.HasFlag(ParsingMode.Block) && IsCloseBlock(index))
                {
                    isEnd = true;
                    return left;
                }
                else if (mode.HasFlag(ParsingMode.Block) && IsEndOfStatement(index))
                {
                    isEnd = true;
                    return left;
                }
                else
                {
                    return ParsingError("Unexpected sub-expression.", index);
                }
            }

            return left;
        }

19 Source : SmartFormattedText.cs
with The Unlicense
from BAndysc

private static void AllowOnlyString(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TextBlock tb)
            {
                var text = GetText(d);
                var paramStyle = GetParamStyle(d);
                var sourceStyle = GetSourceStyle(d);
                var contextArray = GetContextArray(d);

                tb.Inlines.Clear();
                if (text == null)
                    return;

                bool changeRun = false;
                int start = 0;
                State state = State.Text;
                Styles currentStyle = Styles.Normal;
                int currentContextIndex = -1;
                Run? lastRun = null;

                void Append(string s)
                {
                    if (lastRun != null && !changeRun)
                    {
                        lastRun.Text += s;
                        return;
                    }

                    lastRun = new Run(s);

                    if (contextArray != null && currentContextIndex >= 0 && currentContextIndex < contextArray.Count)
                        lastRun.DataContext = contextArray[currentContextIndex];
                    else
                        lastRun.DataContext = null;

                    if (currentStyle.HasFlag(Styles.Parameter) && paramStyle != null)
                        lastRun.Style = paramStyle;

                    if (currentStyle.HasFlag(Styles.Source) && sourceStyle != null)
                        lastRun.Style = sourceStyle;

                    changeRun = false;

                    tb.Inlines.Add(lastRun);
                }

                for (int i = 0; i < text.Length; i++)
                {
                    char l = text[i];
                    if (l == '\\' && state == State.Text)
                    {
                        Append(text.Substring(start, i - start));
                        start = i + 1;
                        state = State.Slash;
                    }
                    else if (l == '[' && state == State.Text)
                    {
                        Append(text.Substring(start, i - start));
                        changeRun = true;
                        currentContextIndex = -1;
                        start = i + 1;
                        state = State.OpeningTag;
                    }
                    else if (l == '/' && state == State.OpeningTag)
                    {
                        start = i + 1;
                        state = State.InClosingTag;
                    }
                    else if (l != ']' && state == State.OpeningTag)
                    {
                        state = State.InTag;
                    }
                    else if (l == ']' && state == State.InTag)
                    {
                        if (text[start] == 'p')
                        {
                            currentStyle = currentStyle | Styles.Parameter;
                        }
                        else if (text[start] == 's')
                        {
                            currentStyle = currentStyle | Styles.Source;
                        }

                        if (text[start + 1] == '=' && char.IsDigit(text[start + 2]))
                            currentContextIndex = text[start + 2] - '0';

                        start = i + 1;
                        state = State.Text;
                    }
                    else if (l == ']' && state == State.InClosingTag)
                    {
                        if (text[start] == 'p')
                            currentStyle = currentStyle & ~Styles.Parameter;
                        else if (text[start] == 's')
                            currentStyle = currentStyle & ~Styles.Source;

                        start = i + 1;
                        state = State.Text;
                    }
                    else if (state == State.Slash)
                    {
                        state = State.Text;
                    }
                }

                if (state == State.Text)
                    Append(text.Substring(start));
            }
        }

19 Source : State_Test.cs
with MIT License
from Bannerlord-Coop-Team

[Fact]
        private void EnumGenerics()
        {
            Enum Connected = ConnectionStates.Connected;
            Enum Disconnected = ConnectionStates.Disconnected;
            Enum Playing = GameStates.Playing;
            bool has = Connected.HasFlag(ConnectionStates.Disconnected);

            replacedert.NotEqual(Connected, Disconnected);

            replacedert.Equal((int)ConnectionStates.Connected, (int)GameStates.Playing);
            replacedert.NotEqual(Playing, Disconnected);

            Type csType = Connected.GetType();
            Type csType2 = Connected.GetType();
            
            replacedert.Equal(csType, csType2);
            replacedert.True(has);

            Type gsType = GameStates.MainMenu.GetType();
            replacedert.NotEqual(gsType, csType);
        }

19 Source : VideoCutterTimeline.cs
with MIT License
from bartekmotyl

protected override void OnMouseWheel(MouseEventArgs e)
        {
            base.OnMouseWheel(e);

            var delta = e.Delta * (ModifierKeys.HasFlag(Keys.Shift) ? 10 : 1);
            var hoveredPosition = HoverPosition;

            HoverPosition = null;

            if (ModifierKeys.HasFlag(Keys.Control))
            {
                float newScale = scale + (delta / SystemInformation.MouseWheelScrollDelta * 0.25f);

                if (newScale < 1)
                    newScale = 1;

                if (newScale > scale)
                {
                    var zoomCenter = ClientRectangle.Width / 2.0f;
                    
                    if (hoveredPosition != null)
                        zoomCenter = PositionToPixel(hoveredPosition);

                    var currPosZoomCenter = PixelToPosition(zoomCenter);
                    var newPosZoomCenter = PixelToPosition(zoomCenter, newScale);

                    offset = offset + (currPosZoomCenter - newPosZoomCenter);
                    offset = Math.Max(offset, 0);
                }
                else if (newScale < scale)
                {
                    var zoomCenter = ClientRectangle.Width / 2.0f;

                    if (hoveredPosition != null)
                        zoomCenter = PositionToPixel(hoveredPosition);

                    var currPosZoomCenter = PixelToPosition(zoomCenter);
                    var newPosZoomCenter = PixelToPosition(zoomCenter, newScale);

                    offset = offset + (currPosZoomCenter - newPosZoomCenter);
                    offset = Math.Max(offset, 0);
                }

                scale = newScale;
            }
            else
            {
                var step = (ClientRectangle.Width * MillisecondsPerPixels()) / 10.0f;
                
                long newOffset = offset - (int)(delta / SystemInformation.MouseWheelScrollDelta * step);

                newOffset = Math.Max(newOffset, 0);

                this.offset = newOffset;
            }

            EnsureOffsetInBounds();

            Refresh();

        }

19 Source : MediaDeviceExtentions.cs
with MIT License
from Bassman2

public static void UploadFolder(this MediaDevice device, string source, string destination, bool recursive = true)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (!MediaDevice.IsPath(source))
            {
                throw new ArgumentException("source");
            }
            if (destination == null)
            {
                throw new ArgumentNullException("destination");
            }
            if (!MediaDevice.IsPath(destination))
            {
                throw new ArgumentException("destination");
            }
            if (!device.IsConnected)
            {
                throw new NotConnectedException("Not connected");
            }

            device.CreateDirectory(destination);

            if (recursive)
            {
                DirectoryInfo di = new DirectoryInfo(source);
                foreach (var e in di.EnumerateFileSystemInfos("*", SearchOption.AllDirectories))
                {
                    string path = Path.Combine(destination, GetLocalPath(source, e.FullName));
                    if (e.Attributes.HasFlag(FileAttributes.Directory))
                    {
                        device.CreateDirectory(path);
                    }
                    else
                    {
                        FileInfo fi = e as FileInfo;
                        using (FileStream stream = fi.OpenRead())
                        {
                            device.UploadFile(stream, path);
                        }
                    }
                }
            }
            else
            {
                DirectoryInfo di = new DirectoryInfo(source);
                foreach (FileInfo fi in di.EnumerateFiles())
                {
                    string path = Path.Combine(destination, GetLocalPath(source, fi.FullName));
                    using (FileStream stream = fi.OpenRead())
                    {
                        device.UploadFile(stream, path);
                    }
                }
            }
        }

19 Source : TypeExtensions.cs
with Apache License 2.0
from bcgov

public static bool IsAnonymousType(this Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            // HACK: The only way to detect anonymous types right now.
            return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
                && type.IsGenericType && type.Name.Contains("AnonymousType")
                && (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
                && type.Attributes.HasFlag(TypeAttributes.NotPublic);
        }

19 Source : ChestInfo.cs
with MIT License
from bdfzchen2015

public void AddPending(ServerPlayer player, Pending pending, ServerPlayer friend = null)
		{

			if (_pendings.ContainsKey(player.UUID))
				_pendings[player.UUID] |= pending;
			else
				_pendings.Add(player.UUID, pending);
			if (pending.HasFlag(Pending.AddFriend) || pending.HasFlag(Pending.RemoveFriend))
				SetFriendP(player, friend);
		}

19 Source : ChestInfo.cs
with MIT License
from bdfzchen2015

public void SetPendings(ServerPlayer player, Pending pending, ServerPlayer friend = null)
		{
			if (_pendings.ContainsKey(player.UUID))
				_pendings[player.UUID] = pending;
			else
				_pendings.Add(player.UUID, pending);
			if (pending.HasFlag(Pending.AddFriend) || pending.HasFlag(Pending.RemoveFriend))
				SetFriendP(player, friend);

		}

19 Source : ChestInfo.cs
with MIT License
from bdfzchen2015

public void RemovePending(ServerPlayer player, Pending pending)
		{
			if (_pendings.ContainsKey(player.UUID))
				_pendings[player.UUID] &= ~pending;
			if (pending.HasFlag(Pending.AddFriend) || pending.HasFlag(Pending.RemoveFriend))
				SetFriendP(player, null);
		}

19 Source : Config.cs
with GNU General Public License v3.0
from belowaverage-org

public static bool CanSaveConfig()
        {
            try
            {
                File.OpenWrite(@".\SuperGrate.xml").Close();
                FileAttributes fa = File.GetAttributes(@".\SuperGrate.xml");
                if (fa.HasFlag(FileAttributes.Hidden)) return false;
                return true;
            }
            catch(Exception)
            {
                return false;
            }
        }

19 Source : FileOperations.cs
with GNU General Public License v3.0
from belowaverage-org

public static Task<double> GetFolderSize(DirectoryInfo Directory)
        {
            return Task.Run(() => {
                if (Main.Canceled) return 0;
                double folderSize = 0;
                if (Directory.Attributes.HasFlag(FileAttributes.ReparsePoint)) return 0;
                try
                {
                    List<Task> childTasks = new List<Task>();
                    foreach (DirectoryInfo subDir in Directory.EnumerateDirectories())
                    {
                        if (Main.Canceled) return 0;
                        childTasks.Add(GetFolderSize(subDir));
                    }
                    foreach (FileInfo file in Directory.EnumerateFiles())
                    {
                        if (Main.Canceled) return 0;
                        folderSize += file.Length;
                    }
                    Task.WaitAll(childTasks.ToArray());
                    foreach (Task<double> childTask in childTasks)
                    {
                        folderSize += childTask.Result;
                    }
                    return folderSize;
                }
                catch (Exception e)
                {
                    Logger.Exception(e, "Failed to get folder size!");
                    return 0;
                }
            });
        }

See More Examples