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 View Source File : LineClipper.cs
License : MIT License
Project Creator : AliFlux

private static Point CalculateIntersection(Rect r, Point p1, Point p2, OutCode clipTo)
        {
            var dx = (p2.X - p1.X);
            var dy = (p2.Y - p1.Y);

            var slopeY = dx / dy; // slope to use for possibly-vertical lines
            var slopeX = dy / dx; // slope to use for possibly-horizontal lines

            if (clipTo.HasFlag(OutCode.Top))
            {
                return new Point(
                    p1.X + slopeY * (r.Top - p1.Y),
                    r.Top
                    );
            }
            if (clipTo.HasFlag(OutCode.Bottom))
            {
                return new Point(
                    p1.X + slopeY * (r.Bottom - p1.Y),
                    r.Bottom
                    );
            }
            if (clipTo.HasFlag(OutCode.Right))
            {
                return new Point(
                    r.Right,
                    p1.Y + slopeX * (r.Right - p1.X)
                    );
            }
            if (clipTo.HasFlag(OutCode.Left))
            {
                return new Point(
                    r.Left,
                    p1.Y + slopeX * (r.Left - p1.X)
                    );
            }
            throw new ArgumentOutOfRangeException("clipTo = " + clipTo);
        }

19 View Source File : OverlayBase`1.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

public static Keys RemoveModifiers(Keys keyCode, Keys modifiers)
            {
                Keys keys1 = keyCode;
                foreach (Keys keys2 in new List<Keys>()
      {
        Keys.ControlKey,
        Keys.LControlKey,
        Keys.Alt,
        Keys.ShiftKey,
        Keys.Shift,
        Keys.LShiftKey,
        Keys.RShiftKey,
        Keys.Control,
        Keys.LWin,
        Keys.RWin
      })
                {
                    if (keys1.HasFlag((Enum)keys2) && keys1 == keys2)
                        keys1 &= ~keys2;
                }
                return keys1;
            }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DoesNotFollowDirectoryReparsePoint()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //   randomDir/linkDir -> targetDir
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string linkDir = Path.Combine(randomDir, "linkDir");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir));
                    replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(linkDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(linkDir));
                    replacedert.True(Directory.Exists(targetDir));
                    replacedert.True(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : NpcPlugin.cs
License : MIT License
Project Creator : AkiniKites

public bool NpcFilter(object obj)
        {
            if (ApplyToAll)
                return obj == AllNpcStub;
            if (obj != AllNpcStub)
            {
                var model = (CharacterModel)((ValuePair<Model>)obj).Default;
                if (FilterValue.HasFlag(ModelFilter.MainCharacters))
                    return model.UniqueCharacter;
                return true;
            }

            return false;
        }

19 View Source File : MethodExtensions.cs
License : MIT License
Project Creator : adrianoc

public static string Modifiers(this IMethodSymbol method)
        {
            var bindingFlags = method.IsStatic ? BindingFlags.Static : BindingFlags.Instance;
            bindingFlags |= method.DeclaredAccessibility == Accessibility.Public ? BindingFlags.Public : BindingFlags.NonPublic;

            var res = "";
            var enumType = typeof(BindingFlags);
            foreach (BindingFlags flag in Enum.GetValues(enumType))
            {
                if (bindingFlags.HasFlag(flag))
                {
                    res = res + "|" + enumType.FullName + "." + flag;
                }
            }

            return res.Length > 0 ? res.Substring(1) : string.Empty;
        }

19 View Source File : WrappedException.cs
License : MIT License
Project Creator : actions

public Exception Unwrap(IDictionary<String, Type> typeMapping)
        {
            Exception innerException = null;
            if (InnerException != null)
            {
                innerException = InnerException.Unwrap(typeMapping);
                UnwrappedInnerException = innerException;
            }

            Exception exception = null;

            // if they have bothered to map type, use that first.
            if (!String.IsNullOrEmpty(TypeKey))
            {
                Type type;
                if (typeMapping != null && typeMapping.TryGetValue(TypeKey, out type) ||
                    baseTranslatedExceptions.TryGetValue(TypeKey, out type))
                {
                    try
                    {
                        this.Type = type;
                        exception = Activator.CreateInstance(this.Type, Message, innerException) as Exception;
                    }
                    catch (Exception)
                    {
                        // do nothing
                    }
                }
            }

            if (exception == null)
            {
                //no standard mapping, fallback to 
                exception = UnWrap(innerException);
            }

            if (exception is VssException)
            {
                ((VssException)exception).EventId = this.EventId;
                ((VssException)exception).ErrorCode = this.ErrorCode;
            }

            if (exception == null && !String.IsNullOrEmpty(Message))
            {
                // NOTE: We can get exceptions that we can't create, IE. SqlException, AzureExceptions.
                // This is not a failure, we will just wrap the exception in a VssServiceException
                // since the type is not available.
                exception = new VssServiceException(Message, innerException);
            }

            if (exception == null && !string.IsNullOrEmpty(TypeName))
            {
                Debug.replacedert(false, string.Format("Server exception cannot be resolved. Type name: {0}", TypeName));
            }

            if (exception != null
                && !string.IsNullOrEmpty(HelpLink))
            {
                exception.HelpLink = HelpLink;
            }

            if (exception != null
                && !string.IsNullOrEmpty(this.StackTrace))
            {
                FieldInfo stackTraceField = typeof(Exception).GetTypeInfo().GetDeclaredField("_stackTraceString");
                if (stackTraceField != null && !stackTraceField.Attributes.HasFlag(FieldAttributes.Public) && !stackTraceField.Attributes.HasFlag(FieldAttributes.Static))
                {
                    stackTraceField.SetValue(exception, this.StackTrace);
                }
            }

            if (exception != null && exception.GetType() == this.Type)
            {
                TryUnWrapCustomProperties(exception);
            }

            return exception;
        }

19 View Source File : DarkFlags.cs
License : MIT License
Project Creator : Alprog

public static bool IsSealed(this DarkFlags flags) => flags.HasFlag(DarkFlags.Sealed);

19 View Source File : ObjectInfo.cs
License : GNU General Public License v3.0
Project Creator : ACEmulator

public TransitionState ValidateWalkable(Sphere checkPos, Plane contactPlane, bool isWater, float waterDepth, Transition transition, uint landCellID)
        {
            var path = transition.SpherePath;
            var collision = transition.CollisionInfo;

            if (State.HasFlag(ObjectInfoState.IsViewer))
            {
                var dist = Vector3.Dot(checkPos.Center, contactPlane.Normal) + contactPlane.D - checkPos.Radius;
                if (dist > -PhysicsGlobals.EPSILON && path.BeginPos != null && (path.BeginPos.ObjCellID & 0xFFFF) >= 0x100)
                    return TransitionState.OK;

                var offset = checkPos.Center - path.GlobalCurrCenter[0].Center;
                var angle = dist / Vector3.Dot(offset, contactPlane.Normal);
                if ((angle <= 0.0f || angle > 1.0f) && path.BeginPos != null && (path.BeginPos.ObjCellID & 0xFFFF) >= 0x100)
                    return TransitionState.OK;

                path.AddOffsetToCheckPos(offset * -angle);
                collision.SetCollisionNormal(contactPlane.Normal);
                collision.CollidedWithEnvironment = true;
                return TransitionState.Adjusted;
            }
            else
            {
                var dist = Vector3.Dot(checkPos.Center - new Vector3(0, 0, checkPos.Radius), contactPlane.Normal) + contactPlane.D + waterDepth;
                if (dist >= -PhysicsGlobals.EPSILON)
                {
                    if (dist > PhysicsGlobals.EPSILON)
                        return TransitionState.OK;

                    if (path.StepDown || !State.HasFlag(ObjectInfoState.OnWalkable) || Object.is_valid_walkable(contactPlane.Normal))
                    {
                        collision.SetContactPlane(contactPlane, isWater);
                        collision.ContactPlaneCellID = landCellID;
                    }
                    if (!State.HasFlag(ObjectInfoState.Contact) && !path.StepDown)
                    {
                        collision.SetCollisionNormal(contactPlane.Normal);
                        collision.CollidedWithEnvironment = true;
                    }
                    return TransitionState.OK;
                }
                else
                {
                    if (path.CheckWalkable) return TransitionState.Collided;
                    var zDist = dist / contactPlane.Normal.Z;

                    if (path.StepDown || !State.HasFlag(ObjectInfoState.OnWalkable) || Object.is_valid_walkable(contactPlane.Normal))
                    {
                        collision.SetContactPlane(contactPlane, isWater);
                        collision.ContactPlaneCellID = landCellID;
                        if (path.StepDown)
                        {
                            var interp = (1.0f - -1.0f / (path.StepDownAmt * path.WalkInterp) * zDist) * path.WalkInterp;
                            if (interp >= path.WalkInterp || interp < -0.1f)
                                return TransitionState.Collided;

                            path.WalkInterp = interp;
                        }

                        var offset = new Vector3(0, 0, -zDist);
                        path.AddOffsetToCheckPos(offset);
                    }

                    if (!State.HasFlag(ObjectInfoState.Contact) && !path.StepDown)
                    {
                        collision.SetCollisionNormal(contactPlane.Normal);
                        collision.CollidedWithEnvironment = true;
                    }
                    return TransitionState.Adjusted;
                }
            }
        }

19 View Source File : MovieRenamerService.cs
License : MIT License
Project Creator : amoscardino

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

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

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

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

            var files = _fileService.GetFiles(inputPath);

            if (!files.Any())
                return;

            await MatchFilesAsync(files, outputPath);

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

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

19 View Source File : CmdLineActions.cs
License : MIT License
Project Creator : action-bi-toolkit

[ArgActionMethod, ArgShortcut("export-bim"), ArgDescription("Converts the Model artifacts to a TMSL/BIM file.")]
        public void ExportBim(
            [ArgRequired, ArgExistingDirectory, ArgDescription("The PbixProj folder to export the BIM file from.")] string folder,
            [ArgDescription("Generate model data sources. Only required for deployment to Azure replacedysis Services, but not for Power BI Premium via the XMLA endpoint.")] bool generateDataSources,
            [ArgDescription("List transformations to be applied to TMSL doreplacedent.")] ExportTransforms transforms
        )
        {
            using (var rootFolder = new FileSystem.ProjectRootFolder(folder))
            {
                var serializer = new Serialization.TabularModelSerializer(rootFolder, ProjectSystem.PbixProject.FromFolder(rootFolder).Settings.Model);
                if (serializer.TryDeserialize(out var db))  // throws for V1 models
                {
                    if (generateDataSources)
                    {
#if NETFRAMEWORK
                        var dataSources = TabularModel.TabularModelConversions.GenerateDataSources(db);
                        db["model"]["dataSources"] = dataSources;
#elif NET
                        throw new PlatformNotSupportedException("Generating DataSources is not supported by the pbi-tools Core version.");
#endif
                    }

                    if (transforms.HasFlag(ExportTransforms.RemovePBIDataSourceVersion))
                    {
                        db["model"]["defaultPowerBIDataSourceVersion"]?.Parent.Remove();
                    }

                    var path = Path.GetFullPath(Path.Combine(folder, "..", $"{Path.GetFileName(folder)}.bim"));
                    using (var writer = new JsonTextWriter(File.CreateText(path)))
                    {
                        writer.Formatting = Formatting.Indented;
                        db.WriteTo(writer);
                    }

                    Console.WriteLine($"BIM file written to: {path}");
                }
                else
                {
                    throw new PbiToolsCliException(ExitCode.UnspecifiedError, "A BIM file could not be exported.");
                }
            }
        }

19 View Source File : WindowMemory.cs
License : MIT License
Project Creator : AkiniKites

public static void ActivateWindow(Window window, string name, 
            WindowMemoryType memoryType = WindowMemoryType.All, bool attachEvents = true)
        {
            var win = new TrackingWindow()
            {
                Window = window,
                Name = name
            };

            if (Windows.ContainsKey(name))
                throw new WindowMemoryException($"Window already activated: {name}");
            Windows.Add(name, win);
            
            if (IoC.Settings.Windows.TryGetValue(win.Name, out Rectangle rect))
            {
                if (memoryType.HasFlag(WindowMemoryType.Size))
                {
                    window.Width = rect.Width;
                    window.Height = rect.Height;
                }
                if (memoryType.HasFlag(WindowMemoryType.Position))
                {
                    var area = new Rectangle(rect.Left, rect.Top, (int)window.Width, (int)window.Height);
                    if (Screen.AllScreens.Any(s => s.WorkingArea.IntersectsWith(area)))
                    {
                        window.WindowStartupLocation = WindowStartupLocation.Manual;
                        window.Top = rect.Top;
                        window.Left = rect.Left;
                    }
                }
            }

            if (attachEvents)
                win.AttachEvents();
        }

19 View Source File : ConsoleObservable.cs
License : MIT License
Project Creator : afucher

public bool IsNormalKey(ConsoleKeyInfo key)
        {
            var hreplacedhift = key.Modifiers.HasFlag(ConsoleModifiers.Shift);
            if (!hreplacedhift) return true;

            return !ConsoleUtils.isDigit(key.Key);
        }

19 View Source File : TypeExtensionMethods.cs
License : MIT License
Project Creator : actions

private static PropertyInfo GetPublicInstancePropertyInfo(Type type, string name)
        {
            Type typeToCheck = type;
            PropertyInfo propertyInfo = null;
            while (propertyInfo == null && typeToCheck != null)
            {
                TypeInfo typeInfo = typeToCheck.GetTypeInfo();
                propertyInfo = typeInfo.DeclaredProperties.FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase) && p.GetMethod.Attributes.HasFlag(MethodAttributes.Public) && !p.GetMethod.Attributes.HasFlag(MethodAttributes.Static));
                typeToCheck = typeInfo.BaseType;
            }
            return propertyInfo;
        }

19 View Source File : BaseOnScreenKeyboardWatcher.cs
License : MIT License
Project Creator : AlexeiScherbakov

protected void CheckKeyboard()
		{
			DisplayMode displayMode = Interop.DisplayMode.NotSupported;
			var raiseEvents = OnScreenKeyboardWatcherRaiseEvents.None;
			Rect location = default;
	
			int retry = 1;
			do
			{
				if (ReferenceEquals(_inputHostManagerBroker, null))
				{
					if (!GetInputHostManagerBroker())
					{
						// cannot detect
						return;
					}
				}
				try
				{
					_inputHostManagerBroker.Instance.GetIhmLocation(out location, out displayMode);
					retry = -1;
				}
				catch (Exception e)
				{
					retry--;
					Disposer.Dispose(ref _inputHostManagerBroker);
				}
			} while (retry >= 0);

			if (!_location.Equals(location))
			{
				_location = location;
				raiseEvents |= OnScreenKeyboardWatcherRaiseEvents.LocationChanged;
			}
			raiseEvents |= SetDisplayMode(displayMode);

			// raising events
			if (raiseEvents== OnScreenKeyboardWatcherRaiseEvents.None)
			{
				return;
			}
			else
			{
				OnParametersChanged();
			}

			if (raiseEvents.HasFlag(OnScreenKeyboardWatcherRaiseEvents.KeyboardOpened))
			{
				OnKeyboardOpened();
			}
			else if (raiseEvents.HasFlag(OnScreenKeyboardWatcherRaiseEvents.KeyboardClosed))
			{
				OnKeyboardClosed();
			}
		}

19 View Source File : MovementParamFlags.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Set(MovementParameters mvp, MovementParamFlags flags)
        {
            mvp.CanWalk = flags.HasFlag(MovementParamFlags.CanWalk);
            mvp.CanRun = flags.HasFlag(MovementParamFlags.CanRun);
            mvp.CanSidestep = flags.HasFlag(MovementParamFlags.CanSidestep);
            mvp.CanWalkBackwards = flags.HasFlag(MovementParamFlags.CanWalkBackwards);
            mvp.CanCharge = flags.HasFlag(MovementParamFlags.CanCharge);
            mvp.FailWalk = flags.HasFlag(MovementParamFlags.FailWalk);
            mvp.UseFinalHeading = flags.HasFlag(MovementParamFlags.UseFinalHeading);
            mvp.Sticky = flags.HasFlag(MovementParamFlags.Sticky);
            mvp.MoveAway = flags.HasFlag(MovementParamFlags.MoveAway);
            mvp.MoveTowards = flags.HasFlag(MovementParamFlags.MoveTowards);
            mvp.UseSpheres = flags.HasFlag(MovementParamFlags.UseSpheres);
            mvp.SetHoldKey = flags.HasFlag(MovementParamFlags.SetHoldKey);
            mvp.Autonomous = flags.HasFlag(MovementParamFlags.Autonomous);
            mvp.ModifyRawState = flags.HasFlag(MovementParamFlags.ModifyRawState);
            mvp.ModifyInterpretedState = flags.HasFlag(MovementParamFlags.ModifyInterpretedState);
            mvp.CancelMoveTo = flags.HasFlag(MovementParamFlags.CancelMoveTo);
            mvp.StopCompletely = flags.HasFlag(MovementParamFlags.StopCompletely);
            mvp.DisableJumpDuringLink = flags.HasFlag(MovementParamFlags.DisableJumpDuringLink);
        }

19 View Source File : DarkFlags.cs
License : MIT License
Project Creator : Alprog

public static bool IsAbstract(this DarkFlags flags) => flags.HasFlag(DarkFlags.Abstract);

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DeletesDirectoryReparsePointChain()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/<guid 1> -> <guid 2>
                //   randomDir/<guid 2> -> <guid 3>
                //   randomDir/<guid 3> -> <guid 4>
                //   randomDir/<guid 4> -> <guid 5>
                //   randomDir/<guid 5> -> targetDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //
                // The purpose of this test is to verify that DirectoryNotFoundException is gracefully handled when
                // deleting a chain of reparse point directories. Since the reparse points are named in a random order,
                // the DirectoryNotFoundException case is likely to be encountered.
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string linkDir1 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir1");
                    string linkDir2 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir2");
                    string linkDir3 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir3");
                    string linkDir4 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir4");
                    string linkDir5 = Path.Combine(randomDir, $"{Guid.NewGuid()}_linkDir5");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir1, target: linkDir2);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir2, target: linkDir3);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir3, target: linkDir4);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir4, target: linkDir5);
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir5, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir1));
                    replacedert.True(new DirectoryInfo(linkDir1).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir1, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(randomDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(linkDir1));
                    replacedert.False(Directory.Exists(targetDir));
                    replacedert.False(File.Exists(file));
                    replacedert.False(Directory.Exists(randomDir));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : DarkFlags.cs
License : MIT License
Project Creator : Alprog

public static bool IsSkipReading(this DarkFlags flags) => flags.HasFlag(DarkFlags.SkipReading);

19 View Source File : SimpleZoomInOutModifier.cs
License : MIT License
Project Creator : ABTSoftware

public override void OnModifierKeyDown(ModifierKeyArgs e)
        {
            base.OnModifierKeyDown(e);

            double factor = 0;

            if ((e.Key == Key.Add || e.Key == Key.OemPlus) && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
            {
                // On CTRL+, Zoom In
                factor = -ZoomFraction;
            }
            if ((e.Key == Key.Subtract || e.Key == Key.OemMinus) && Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
            {
                // On CTRL-, Zoom Out
                factor = ZoomFraction;
            }

            using (ParentSurface.SuspendUpdates())
            {
                // Zoom the XAxis by the required factor
                XAxis.ZoomBy(factor, factor, TimeSpan.FromMilliseconds(500));

                // Zoom the YAxis by the required factor
                YAxis.ZoomBy(factor, factor, TimeSpan.FromMilliseconds(500));

                // Note.. can be extended for multiple YAxis XAxis, just iterate over all axes on the parent surface
            }
        }

19 View Source File : FileSystemProvider.cs
License : MIT License
Project Creator : Aminator

public async Task<Stream> OpenStreamAsync(string path, FileMode mode, FileAccess access)
        {
            if (access.HasFlag(FileAccess.Write))
            {
                return await ReadWriteRootFolder.OpenStreamForWriteAsync(path, ToCreationCollisionOption(mode));
            }
            else
            {
                if (mode != FileMode.Open) throw new ArgumentException("File mode has to be FileMode.Open when FileAccess.Read is specified.");

                if (await ExistsAsync(ReadWriteRootFolder, path))
                {
                    return await ReadWriteRootFolder.OpenStreamForReadAsync(path);
                }

                if (RootFolder != ReadWriteRootFolder && await ExistsAsync(RootFolder, path))
                {
                    return await RootFolder.OpenStreamForReadAsync(path);
                }

                throw new FileNotFoundException();
            }
        }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DoesNotFollowNestLevel1DirectoryReparsePoint()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //   randomDir/subDir
                //   randomDir/subDir/linkDir -> ../targetDir
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string subDir = Directory.CreateDirectory(Path.Combine(randomDir, "subDir")).FullName;
                    string linkDir = Path.Combine(subDir, "linkDir");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir));
                    replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(subDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(subDir));
                    replacedert.True(Directory.Exists(targetDir));
                    replacedert.True(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : ObjectExtenders.cs
License : MIT License
Project Creator : adoconnection

public static bool IsAnonymous(this object obj)
        {
            Type type = obj.GetType();

            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 View Source File : ShardDatabase.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public virtual Biota GetBiota(ShardDbContext context, uint id, bool doNotAddToCache = false)
        {
            var biota = context.Biota
                .FirstOrDefault(r => r.Id == id);

            if (biota == null)
                return null;

            PopulatedCollectionFlags populatedCollectionFlags = (PopulatedCollectionFlags)biota.PopulatedCollectionFlags;

            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesAnimPart)) biota.BiotaPropertiesAnimPart = context.BiotaPropertiesAnimPart.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesAttribute)) biota.BiotaPropertiesAttribute = context.BiotaPropertiesAttribute.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesAttribute2nd)) biota.BiotaPropertiesAttribute2nd = context.BiotaPropertiesAttribute2nd.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesBodyPart)) biota.BiotaPropertiesBodyPart = context.BiotaPropertiesBodyPart.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesBook)) biota.BiotaPropertiesBook = context.BiotaPropertiesBook.FirstOrDefault(r => r.ObjectId == biota.Id);
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesBookPageData)) biota.BiotaPropertiesBookPageData = context.BiotaPropertiesBookPageData.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesBool)) biota.BiotaPropertiesBool = context.BiotaPropertiesBool.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesCreateList)) biota.BiotaPropertiesCreateList = context.BiotaPropertiesCreateList.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesDID)) biota.BiotaPropertiesDID = context.BiotaPropertiesDID.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesEmote)) biota.BiotaPropertiesEmote = context.BiotaPropertiesEmote.Include(r => r.BiotaPropertiesEmoteAction).Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesEnchantmentRegistry)) biota.BiotaPropertiesEnchantmentRegistry = context.BiotaPropertiesEnchantmentRegistry.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesEventFilter)) biota.BiotaPropertiesEventFilter = context.BiotaPropertiesEventFilter.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesFloat)) biota.BiotaPropertiesFloat = context.BiotaPropertiesFloat.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesGenerator)) biota.BiotaPropertiesGenerator = context.BiotaPropertiesGenerator.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesIID)) biota.BiotaPropertiesIID = context.BiotaPropertiesIID.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesInt)) biota.BiotaPropertiesInt = context.BiotaPropertiesInt.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesInt64)) biota.BiotaPropertiesInt64 = context.BiotaPropertiesInt64.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesPalette)) biota.BiotaPropertiesPalette = context.BiotaPropertiesPalette.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesPosition)) biota.BiotaPropertiesPosition = context.BiotaPropertiesPosition.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesSkill)) biota.BiotaPropertiesSkill = context.BiotaPropertiesSkill.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesSpellBook)) biota.BiotaPropertiesSpellBook = context.BiotaPropertiesSpellBook.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesString)) biota.BiotaPropertiesString = context.BiotaPropertiesString.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesTextureMap)) biota.BiotaPropertiesTextureMap = context.BiotaPropertiesTextureMap.Where(r => r.ObjectId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.HousePermission)) biota.HousePermission = context.HousePermission.Where(r => r.HouseId == biota.Id).ToList();
            if (populatedCollectionFlags.HasFlag(PopulatedCollectionFlags.BiotaPropertiesAllegiance)) biota.BiotaPropertiesAllegiance = context.BiotaPropertiesAllegiance.Where(r => r.AllegianceId == biota.Id).ToList();

            return biota;
        }

19 View Source File : ConsoleObservable.cs
License : MIT License
Project Creator : afucher

private void ImplementKeysBehaviours(ConsoleKeyInfo cki)
        {
            var key = cki.Key;
            switch (key)
            {
                case ConsoleKey.Backspace:
                    console.Write(" \b");
                    break;
            };
            var hreplacedhift = cki.Modifiers.HasFlag(ConsoleModifiers.Shift);
            if (hreplacedhift && ConsoleUtils.isDigit(key)) console.Write("\b");
        }

19 View Source File : IOUtil.cs
License : MIT License
Project Creator : actions

public static void DeleteDirectory(string path, bool contentsOnly, bool continueOnContentDeleteError, CancellationToken cancellationToken)
        {
            ArgUtil.NotNullOrEmpty(path, nameof(path));
            DirectoryInfo directory = new DirectoryInfo(path);
            if (!directory.Exists)
            {
                return;
            }

            if (!contentsOnly)
            {
                // Remove the readonly flag.
                RemoveReadOnly(directory);

                // Check if the directory is a reparse point.
                if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                {
                    // Delete the reparse point directory and short-circuit.
                    directory.Delete();
                    return;
                }
            }

            // Initialize a concurrent stack to store the directories. The directories
            // cannot be deleted until the files are deleted.
            var directories = new ConcurrentStack<DirectoryInfo>();

            if (!contentsOnly)
            {
                directories.Push(directory);
            }

            // Create a new token source for the parallel query. The parallel query should be
            // canceled after the first error is encountered. Otherwise the number of exceptions
            // could get out of control for a large directory with access denied on every file.
            using (var tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
            {
                try
                {
                    // Recursively delete all files and store all subdirectories.
                    Enumerate(directory, tokenSource)
                        .AsParallel()
                        .WithCancellation(tokenSource.Token)
                        .ForAll((FileSystemInfo item) =>
                        {
                            bool success = false;
                            try
                            {
                                // Remove the readonly attribute.
                                RemoveReadOnly(item);

                                // Check if the item is a file.
                                if (item is FileInfo)
                                {
                                    // Delete the file.
                                    item.Delete();
                                }
                                else
                                {
                                    // Check if the item is a directory reparse point.
                                    var subdirectory = item as DirectoryInfo;
                                    ArgUtil.NotNull(subdirectory, nameof(subdirectory));
                                    if (subdirectory.Attributes.HasFlag(FileAttributes.ReparsePoint))
                                    {
                                        try
                                        {
                                            // Delete the reparse point.
                                            subdirectory.Delete();
                                        }
                                        catch (DirectoryNotFoundException)
                                        {
                                            // The target of the reparse point directory has been deleted.
                                            // Therefore the item is no longer a directory and is now a file.
                                            //
                                            // Deletion of reparse point directories happens in parallel. This case can occur
                                            // when reparse point directory FOO points to some other reparse point directory BAR,
                                            // and BAR is deleted after the DirectoryInfo for FOO has already been initialized.
                                            File.Delete(subdirectory.FullName);
                                        }
                                    }
                                    else
                                    {
                                        // Store the directory.
                                        directories.Push(subdirectory);
                                    }
                                }

                                success = true;
                            }
                            catch (Exception) when (continueOnContentDeleteError)
                            {
                                // ignore any exception when continueOnContentDeleteError is true.
                                success = true;
                            }
                            finally
                            {
                                if (!success)
                                {
                                    tokenSource.Cancel(); // Cancel is thread-safe.
                                }
                            }
                        });
                }
                catch (Exception)
                {
                    tokenSource.Cancel();
                    throw;
                }
            }

            // Delete the directories.
            foreach (DirectoryInfo dir in directories.OrderByDescending(x => x.FullName.Length))
            {
                cancellationToken.ThrowIfCancellationRequested();
                dir.Delete();
            }
        }

19 View Source File : ManualMap.cs
License : MIT License
Project Creator : Akaion

private static ProtectionType CalculateSectionProtection(SectionCharacteristics sectionCharacteristics)
        {
            if (sectionCharacteristics.HasFlag(SectionCharacteristics.MemExecute))
            {
                if (sectionCharacteristics.HasFlag(SectionCharacteristics.MemWrite))
                {
                    return ProtectionType.ExecuteReadWrite;
                }

                return sectionCharacteristics.HasFlag(SectionCharacteristics.MemRead) ? ProtectionType.ExecuteRead : ProtectionType.Execute;
            }

            if (sectionCharacteristics.HasFlag(SectionCharacteristics.MemWrite))
            {
                return ProtectionType.ReadWrite;
            }

            return sectionCharacteristics.HasFlag(SectionCharacteristics.MemRead) ? ProtectionType.ReadOnly : ProtectionType.NoAccess;
        }

19 View Source File : EnumSample.cs
License : The Unlicense
Project Creator : ahotko

public override void Execute()
        {
            replacedle("EnumSampleExecute");

            Section("Simple Enum");
            //'This must be Thursday,' said Arthur to himself, sinking low over his beer. 'I never could get the hang of Thursdays.'
            WeekDay weekDay = WeekDay.Thursday; 
            Console.WriteLine($"weekDay Enum value: default={weekDay.ToString()}, string={weekDay.ToString("g")}, decimal={weekDay.ToString("d")}, hex=0x{weekDay.ToString("x")}");
            var enumValues = Enum.GetNames(typeof(WeekDay));
            Console.WriteLine("WeekDays Enum values:");
            foreach (string value in enumValues)
            {
                Console.WriteLine(value);
            }
            LineBreak();

            Section("Typed Enum (short)");
            Priority priority = Priority.Low;
            Console.WriteLine($"Priority Enum values: default={priority.ToString()}, string={priority.ToString("g")}, decimal={priority.ToString("d")}, hex=0x{priority.ToString("x")}");
            priority = Priority.Normal;
            Console.WriteLine($"Priority Enum values: default={priority.ToString()}, string={priority.ToString("g")}, decimal={priority.ToString("d")}, hex=0x{priority.ToString("x")}");
            priority = Priority.Highest;
            Console.WriteLine($"Priority Enum values: default={priority.ToString()}, string={priority.ToString("g")}, decimal={priority.ToString("d")}, hex=0x{priority.ToString("x")}");


            Section("Enum Flags");
            SidesAndCorners sidesAndCorners = SidesAndCorners.Bottom;
            OutputSidesAndCorners(sidesAndCorners);
            sidesAndCorners = SidesAndCorners.Full;
            OutputSidesAndCorners(sidesAndCorners);
            sidesAndCorners = SidesAndCorners.Top | SidesAndCorners.Bottom;
            OutputSidesAndCorners(sidesAndCorners);
            sidesAndCorners = SidesAndCorners.TopLeft;
            OutputSidesAndCorners(sidesAndCorners);

            //checking flags
            Console.WriteLine($"sidesAndCorners.Top is set={sidesAndCorners.HasFlag(SidesAndCorners.Top)}");
            Console.WriteLine($"sidesAndCorners.TopLeft is set={sidesAndCorners.HasFlag(SidesAndCorners.TopLeft)}");
            Console.WriteLine($"sidesAndCorners.Full is set={sidesAndCorners.HasFlag(SidesAndCorners.Full)}");
            Console.WriteLine($"sidesAndCorners.Bottom is set={sidesAndCorners.HasFlag(SidesAndCorners.Bottom)}");

            Section("Enum with Description");
            Status status= Status.NotCompleted;
            Console.WriteLine($"status value: default={status.ToString()}, string={status.ToString("g")}, decimal={status.ToString("d")}, hex=0x{status.ToString("x")}");
            var statusValues = Enum.GetValues(typeof(Status));
            Console.WriteLine("Status Enum values:");
            foreach (Status value in statusValues)
            {
                Console.WriteLine($"ordinal={(int)value}, value={value.ToString()}, description={value.GetDescription<Status>()}");
            }
            LineBreak();

            Finish();
        }

19 View Source File : IOUtil.cs
License : MIT License
Project Creator : actions

private static void RemoveReadOnly(FileSystemInfo item)
        {
            ArgUtil.NotNull(item, nameof(item));
            if (item.Attributes.HasFlag(FileAttributes.ReadOnly))
            {
                item.Attributes = item.Attributes & ~FileAttributes.ReadOnly;
            }
        }

19 View Source File : NpcPlugin.cs
License : MIT License
Project Creator : AkiniKites

public bool Filter(object obj)
        {
            var model = (CharacterModel)obj;
            if (FilterValue.HasFlag(ModelFilter.MainCharacters))
                return model.UniqueCharacter;
            return true;
        }

19 View Source File : BodyPart.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static List<BodyPart> GetFlags(BodyPart bodyParts)
        {
            return Enum.GetValues(typeof(BodyPart)).Cast<BodyPart>().Where(p => bodyParts.HasFlag(p)).ToList();
        }

19 View Source File : SchemaBuilder.cs
License : Apache License 2.0
Project Creator : AlexandreDaSilva

public string Build()
        {
            var sb = new StringBuilder();
            sb.Append($"{_name}:");
            sb.Append(" ");

            if (_list) sb.Append("[");
            sb.Append(_type.ToString().ToLowerInvariant());
            if (_list) sb.Append("]");

            if (_index)
            {
                sb.Append(" ");
                sb.Append("@index");

                if (_type == PredicateType.String)
                {
                    var selected = Enum
                        .GetValues(typeof(StringIndexType))
                        .Cast<StringIndexType>()
                        .Where(v => _stringIndexType.HasFlag(v))
                        .Select(x => x.ToString().ToLowerInvariant());

                    var selectedStr = string.Join(", ", selected);

                    sb.Append("(");
                    sb.Append(selectedStr);
                    sb.Append(")");
                }
                else if (_type == PredicateType.DateTime)
                {
                    sb.Append("(");
                    sb.Append(_dateTimeIndexType.ToString().ToLowerInvariant());
                    sb.Append(")");
                }
                else
                {
                    sb.Append("(");
                    sb.Append(_type.ToString().ToLowerInvariant());
                    sb.Append(")");
                }
            }

            if (_count)
            {
                sb.Append(" ");
                sb.Append("@count");
            }

            if (_upsert)
            {
                sb.Append(" ");
                sb.Append("@upsert");
            }

            sb.Append(" ");
            sb.Append(".");

            return sb.ToString();
        }

19 View Source File : VssHttpUriUtility.cs
License : MIT License
Project Creator : actions

[EditorBrowsable(EditorBrowsableState.Never)]
        public static String ReplaceRouteValues(
            String routeTemplate,
            Dictionary<String, Object> routeValues,
            RouteReplacementOptions routeReplacementOptions)
        {
            StringBuilder sbResult = new StringBuilder();
            StringBuilder sbCurrentPathPart = new StringBuilder();
            int paramStart = -1, paramLength = 0;
            bool insideParam = false;
            HashSet<string> unusedValues = new HashSet<string>(routeValues.Keys, StringComparer.OrdinalIgnoreCase);
            Dictionary<string, object> caseIncensitiveRouteValues = new Dictionary<string, object>(routeValues, StringComparer.OrdinalIgnoreCase);

            for (int i = 0; i < routeTemplate.Length; i++)
            {
                char c = routeTemplate[i];

                if (insideParam)
                {
                    if (c == '}')
                    {
                        insideParam = false;
                        String paramName = routeTemplate.Substring(paramStart, paramLength);
                        paramLength = 0;
                        if (paramName.StartsWith("*"))
                        {
                            if (routeReplacementOptions.HasFlag(RouteReplacementOptions.WildcardAsQueryParams))
                            {
                                continue;
                            }
                            // wildcard route
                            paramName = paramName.Substring(1);
                        }

                        Object paramValue;
                        if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue))
                        {
                            if (paramValue != null)
                            {
                                sbCurrentPathPart.Append(paramValue.ToString());
                                unusedValues.Remove(paramName);
                            }
                        }
                        else if (routeReplacementOptions.HasFlag(RouteReplacementOptions.RequireExplicitRouteParams))
                        {
                            throw new ArgumentException("Missing route param " + paramName);
                        }
                    }
                    else
                    {
                        paramLength++;
                    }
                }
                else
                {
                    if (c == '/')
                    {
                        if (sbCurrentPathPart.Length > 0)
                        {
                            sbResult.Append('/');
                            sbResult.Append(sbCurrentPathPart.ToString());
                            sbCurrentPathPart.Clear();
                        }
                    }
                    else if (c == '{')
                    {
                        if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '{')
                        {
                            // Escaped '{'
                            sbCurrentPathPart.Append(c);
                            i++;
                        }
                        else
                        {
                            insideParam = true;
                            paramStart = i + 1;
                        }
                    }
                    else if (c == '}')
                    {
                        sbCurrentPathPart.Append(c);
                        if ((i + 1) < routeTemplate.Length && routeTemplate[i + 1] == '}')
                        {
                            // Escaped '}'
                            i++;
                        }
                    }
                    else
                    {
                        sbCurrentPathPart.Append(c);
                    }
                }
            }

            if (sbCurrentPathPart.Length > 0)
            {
                sbResult.Append('/');
                sbResult.Append(sbCurrentPathPart.ToString());
            }

            if (routeReplacementOptions.HasFlag(RouteReplacementOptions.EscapeUri))
            {
                sbResult = new StringBuilder(Uri.EscapeUriString(sbResult.ToString()));
            }

            if (routeReplacementOptions.HasFlag(RouteReplacementOptions.AppendUnusedAsQueryParams) && unusedValues.Count > 0)
            {
                bool isFirst = true;

                foreach (String paramName in unusedValues)
                {
                    Object paramValue;
                    if (caseIncensitiveRouteValues.TryGetValue(paramName, out paramValue) && paramValue != null)
                    {
                        sbResult.Append(isFirst ? '?' : '&');
                        isFirst = false;
                        sbResult.Append(Uri.EscapeDataString(paramName));
                        sbResult.Append('=');
                        sbResult.Append(Uri.EscapeDataString(paramValue.ToString()));
                    }
                }
            }

            return sbResult.ToString();
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Alexx999

private static bool IsReadable(MemoryProtection protect)
        {
            return (protect.HasFlag(MemoryProtection.ReadOnly) || protect.HasFlag(MemoryProtection.ReadWrite) ||
                   protect.HasFlag(MemoryProtection.ExecuteRead) || protect.HasFlag(MemoryProtection.ExecuteReadWrite) ||
                   protect.HasFlag(MemoryProtection.ExecuteWriteCopy)) && !protect.HasFlag(MemoryProtection.Guard);
        }

19 View Source File : DigitalAnalyzerScrollBehavior.cs
License : MIT License
Project Creator : ABTSoftware

private void ScrollViewer_OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift))
            {
                if (ChangeChannelHeightCommand?.CanExecute(null) != true) return;
                ChangeChannelHeightCommand.Execute(e.Delta > 0 ? ChannelHeightDelta : -ChannelHeightDelta);
                e.Handled = true;
            }
            else if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control))
            {
                if (!(sender is ScrollViewer scroll)) return;
                scroll.ScrollToVerticalOffset(scroll.VerticalOffset - e.Delta);
                e.Handled = true;
            }
        }

19 View Source File : DarkFlags.cs
License : MIT License
Project Creator : Alprog

public static bool IsStatic(this DarkFlags flags) => flags.HasFlag(DarkFlags.Static);

19 View Source File : WrappedException.cs
License : MIT License
Project Creator : actions

private IEnumerable<PropertyInfo> GetCustomPropertiesInfo()
        {
            return this.Type.GetTypeInfo().DeclaredProperties.Where(p => p.GetMethod.Attributes.HasFlag(MethodAttributes.Public)
                && !p.GetMethod.Attributes.HasFlag(MethodAttributes.Static)
                && p.CustomAttributes.Any(a => a.AttributeType.GetTypeInfo().IsreplacedignableFrom(typeof(DataMemberAttribute).GetTypeInfo())));
        }

19 View Source File : DarkFlags.cs
License : MIT License
Project Creator : Alprog

public static bool IsSerializable(this DarkFlags flags) => flags.HasFlag(DarkFlags.Serializable);

19 View Source File : ObjectInfo.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public TransitionState ValidateWalkable(Sphere checkPos, Plane contactPlane, bool isWater, float waterDepth, Transition transition, uint landCellID)
        {
            var path = transition.SpherePath;
            var collision = transition.CollisionInfo;

            if (State.HasFlag(ObjectInfoState.IsViewer))
            {
                var dist = Vector3.Dot(checkPos.Center, contactPlane.Normal) + contactPlane.D - checkPos.Radius;
                if (dist > -PhysicsGlobals.EPSILON && path.BeginPos != null && (path.BeginPos.ObjCellID & 0xFFFF) >= 0x100)
                    return TransitionState.OK;

                var offset = checkPos.Center - path.GlobalCurrCenter[0].Center;
                var angle = dist / Vector3.Dot(offset, contactPlane.Normal);
                if ((angle <= 0.0f || angle > 1.0f) && path.BeginPos != null && (path.BeginPos.ObjCellID & 0xFFFF) >= 0x100)
                    return TransitionState.OK;

                path.AddOffsetToCheckPos(offset * -angle);
                collision.SetCollisionNormal(contactPlane.Normal);
                collision.CollidedWithEnvironment = true;
                return TransitionState.Adjusted;
            }
            else
            {
                var dist = Vector3.Dot(checkPos.Center - new Vector3(0, 0, checkPos.Radius), contactPlane.Normal) + contactPlane.D + waterDepth;
                if (dist >= -PhysicsGlobals.EPSILON)
                {
                    if (dist > PhysicsGlobals.EPSILON)
                        return TransitionState.OK;

                    if (path.StepDown || !State.HasFlag(ObjectInfoState.OnWalkable) || PhysicsObj.is_valid_walkable(contactPlane.Normal))
                    {
                        collision.SetContactPlane(contactPlane, isWater);
                        collision.ContactPlaneCellID = landCellID;
                    }
                    if (!State.HasFlag(ObjectInfoState.Contact) && !path.StepDown)
                    {
                        collision.SetCollisionNormal(contactPlane.Normal);
                        collision.CollidedWithEnvironment = true;
                    }
                    return TransitionState.OK;
                }
                else
                {
                    if (path.CheckWalkable) return TransitionState.Collided;
                    var zDist = dist / contactPlane.Normal.Z;

                    if (path.StepDown || !State.HasFlag(ObjectInfoState.OnWalkable) || PhysicsObj.is_valid_walkable(contactPlane.Normal))
                    {
                        collision.SetContactPlane(contactPlane, isWater);
                        collision.ContactPlaneCellID = landCellID;
                        if (path.StepDown)
                        {
                            var interp = (1.0f - -1.0f / (path.StepDownAmt * path.WalkInterp) * zDist) * path.WalkInterp;
                            if (interp >= path.WalkInterp || interp < -0.1f)
                                return TransitionState.Collided;

                            path.WalkInterp = interp;
                        }

                        var offset = new Vector3(0, 0, -zDist);
                        path.AddOffsetToCheckPos(offset);
                    }

                    if (!State.HasFlag(ObjectInfoState.Contact) && !path.StepDown)
                    {
                        collision.SetCollisionNormal(contactPlane.Normal);
                        collision.CollidedWithEnvironment = true;
                    }
                    return TransitionState.Adjusted;
                }
            }
        }

19 View Source File : DarkFlags.cs
License : MIT License
Project Creator : Alprog

public static bool IsInline(this DarkFlags flags) => flags.HasFlag(DarkFlags.Inline);

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DeletesDirectoryReparsePointsBeforeDirectories()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/linkDir -> targetDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //
                // The accuracy of this test relies on an replacedumption that IOUtil sorts the directories in
                // descending order before deleting them - either by length or by default sort order.
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string linkDir = Path.Combine(randomDir, "linkDir");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir));
                    replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(randomDir, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(linkDir));
                    replacedert.False(Directory.Exists(targetDir));
                    replacedert.False(File.Exists(file));
                    replacedert.False(Directory.Exists(randomDir));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : DarkFlags.cs
License : MIT License
Project Creator : Alprog

public static bool IsSkipWriting(this DarkFlags flags) => flags.HasFlag(DarkFlags.SkipWriting);

19 View Source File : ObjectManipulator.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void ReleaseRigidBody(Vector3 velocity, Vector3 angularVelocity)
        {
            if (rigidBody != null)
            {
                rigidBody.isKinematic = wasKinematic;

                if (releaseBehavior.HasFlag(ReleaseBehaviorType.KeepVelocity))
                {
                    rigidBody.velocity = velocity;
                }

                if (releaseBehavior.HasFlag(ReleaseBehaviorType.KeepAngularVelocity))
                {
                    rigidBody.angularVelocity = angularVelocity;
                }
            }
        }

19 View Source File : Util.cs
License : GNU General Public License v2.0
Project Creator : AmanoTooko

public static Keys RemoveModifiers(Keys keyCode, Keys modifiers)
    {
      Keys keys1 = keyCode;
      foreach (Keys keys2 in new List<Keys>()
      {
        Keys.ControlKey,
        Keys.LControlKey,
        Keys.Alt,
        Keys.ShiftKey,
        Keys.Shift,
        Keys.LShiftKey,
        Keys.RShiftKey,
        Keys.Control,
        Keys.LWin,
        Keys.RWin
      })
      {
        if (keys1.HasFlag((Enum) keys2) && keys1 == keys2)
          keys1 &= ~keys2;
      }
      return keys1;
    }

19 View Source File : IOUtilL0.cs
License : MIT License
Project Creator : actions

[Fact]
        [Trait("Level", "L0")]
        [Trait("Category", "Common")]
        public async Task DeleteDirectory_DoesNotFollowNestLevel2DirectoryReparsePoint()
        {
            using (TestHostContext hc = new TestHostContext(this))
            {
                Tracing trace = hc.GetTrace();

                // Arrange: Create the following structure:
                //   randomDir
                //   randomDir/targetDir
                //   randomDir/targetDir/file.txt
                //   randomDir/subDir1
                //   randomDir/subDir1/subDir2
                //   randomDir/subDir1/subDir2/linkDir -> ../../targetDir
                string randomDir = Path.Combine(hc.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
                try
                {
                    string targetDir = Directory.CreateDirectory(Path.Combine(randomDir, "targetDir")).FullName;
                    string file = Path.Combine(targetDir, "file.txt");
                    File.WriteAllText(path: file, contents: "some contents");
                    string subDir1 = Directory.CreateDirectory(Path.Combine(randomDir, "subDir1")).FullName;
                    string subDir2 = Directory.CreateDirectory(Path.Combine(subDir1, "subDir2")).FullName;
                    string linkDir = Path.Combine(subDir2, "linkDir");
                    await CreateDirectoryReparsePoint(context: hc, link: linkDir, target: targetDir);

                    // Sanity check to verify the link was created properly:
                    replacedert.True(Directory.Exists(linkDir));
                    replacedert.True(new DirectoryInfo(linkDir).Attributes.HasFlag(FileAttributes.ReparsePoint));
                    replacedert.True(File.Exists(Path.Combine(linkDir, "file.txt")));

                    // Act.
                    IOUtil.DeleteDirectory(subDir1, CancellationToken.None);

                    // replacedert.
                    replacedert.False(Directory.Exists(subDir1));
                    replacedert.True(Directory.Exists(targetDir));
                    replacedert.True(File.Exists(file));
                }
                finally
                {
                    // Cleanup.
                    if (Directory.Exists(randomDir))
                    {
                        Directory.Delete(randomDir, recursive: true);
                    }
                }
            }
        }

19 View Source File : AssetDatabaseExt.cs
License : MIT License
Project Creator : acoppes

public static List<GameObject> FindPrefabs(IEnumerable<Type> types, FindOptions options, string[] folders)
        {
            var considerChildren = options.HasFlag(FindOptions.ConsiderChildren);

            var guids = replacedetDatabase.Findreplacedets("t:Prefab", folders);

            var prefabs = guids.Select(g => replacedetDatabase.LoadreplacedetAtPath<GameObject>(
                replacedetDatabase.GUIDToreplacedetPath(g))).ToList();

            if (considerChildren)
            {
                IEnumerable<GameObject> result = prefabs;
                // By default is the AND of all specified Types
                foreach (var type in types)
                {
                    result = result.Where(p => p.GetComponentInChildren(type) != null);
                }
                return result.ToList();
            }
            else
            {
                IEnumerable<GameObject> result = prefabs;
                // By default is the AND of all specified Types
                foreach (var type in types)
                {
                    result = result.Where(p => p.GetComponent(type) != null);
                }
                return result.ToList();
            }
        }

19 View Source File : MouseWatcher.cs
License : MIT License
Project Creator : a1xd

public void ReadMouseMove(Message message)
        {
            RawInput rawInput;
            int size = Marshal.SizeOf(typeof(RawInput));
            _ = GetRawInputData(message.LParam, RawInputCommand.Input, out rawInput, ref size, Marshal.SizeOf(typeof(RAWINPUTHEADER)));

            bool relative = !rawInput.Data.Mouse.Flags.HasFlag(RawMouseFlags.MoveAbsolute);

            bool deviceMatch = false;
            foreach (var (handle, normalized) in SettingsManager.ActiveNormTaggedHandles)
            {
                if (handle == rawInput.Header.Device)
                {
                    deviceMatch = true;

                    if (normalized != LastMoveNormalized)
                    {
                        LastMoveDisplayFormat = normalized ?
                                                Constants.MouseMoveNormalizedFormat :
                                                Constants.MouseMoveDefaultFormat;
                        LastMoveNormalized = normalized;
                    }

                    break;
                }
            }

            if (relative && deviceMatch && (rawInput.Data.Mouse.LastX != 0 || rawInput.Data.Mouse.LastY != 0))
            {
                var time = Stopwatch.Elapsed.TotalMilliseconds;
                Stopwatch.Restart();
                time = time > 100 ? 100 : time;
                time = time > (PollTime * 0.8) ? time : (PollTime * 0.8);

                double x = rawInput.Data.Mouse.LastX;
                double y = rawInput.Data.Mouse.LastY;

                // strip negative directional multipliers, charts calculated from positive input

                Vec2<double> dirMults = new Vec2<double>
                {
                    x = SettingsManager.ActiveProfile.lrSensRatio,
                    y = SettingsManager.ActiveProfile.udSensRatio
                };

                if (dirMults.x > 0 && x < 0)
                {
                    x /= dirMults.x;
                }

                if (dirMults.y > 0 && y < 0)
                {
                    y /= dirMults.y;
                }

                MouseData.Set(rawInput.Data.Mouse.LastX, rawInput.Data.Mouse.LastY);
                AccelCharts.MakeDots(x, y, time);
            }

        }

19 View Source File : ManipulationHandler.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private void ReleaseRigidBody()
        {
            if (rigidBody != null)
            {
                rigidBody.isKinematic = wasKinematic;

                if (releaseBehavior.HasFlag(ReleaseBehaviorType.KeepVelocity))
                {
                    rigidBody.velocity = GetPointersVelocity();
                }

                if (releaseBehavior.HasFlag(ReleaseBehaviorType.KeepAngularVelocity))
                {
                    rigidBody.angularVelocity = GetPointersAngularVelocity();
                }

                rigidBody = null;
            }
        }

19 View Source File : CreatureProfile.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static void Write(this BinaryWriter writer, CreatureProfile profile)
        {
            writer.Write((uint)profile.Flags);
            writer.Write(profile.Health);
            writer.Write(profile.HealthMax);

            // has flags & 0x8?
            if (profile.Flags.HasFlag(CreatureProfileFlags.ShowAttributes))
            {
                writer.Write(profile.Strength);
                writer.Write(profile.Endurance);
                writer.Write(profile.Quickness);
                writer.Write(profile.Coordination);
                writer.Write(profile.Focus);
                writer.Write(profile.Self);

                writer.Write(profile.Stamina);
                writer.Write(profile.Mana);
                writer.Write(profile.StaminaMax);
                writer.Write(profile.ManaMax);
            }

            // has flags & 0x1?
            if (profile.Flags.HasFlag(CreatureProfileFlags.HasBuffsDebuffs))
            {
                writer.Write((ushort)profile.AttributeHighlights);
                writer.Write((ushort)profile.AttributeColors);
            }
        }

19 View Source File : IOUtil.cs
License : MIT License
Project Creator : actions

private static IEnumerable<FileSystemInfo> Enumerate(DirectoryInfo directory, CancellationTokenSource tokenSource)
        {
            ArgUtil.NotNull(directory, nameof(directory));
            ArgUtil.Equal(false, directory.Attributes.HasFlag(FileAttributes.ReparsePoint), nameof(directory.Attributes.HasFlag));

            // Push the directory onto the processing stack.
            var directories = new Stack<DirectoryInfo>(new[] { directory });
            while (directories.Count > 0)
            {
                // Pop the next directory.
                directory = directories.Pop();
                foreach (FileSystemInfo item in directory.GetFileSystemInfos())
                {
                    // Push non-reparse-point directories onto the processing stack.
                    directory = item as DirectoryInfo;
                    if (directory != null &&
                        !item.Attributes.HasFlag(FileAttributes.ReparsePoint))
                    {
                        directories.Push(directory);
                    }

                    // Then yield the directory. Otherwise there is a race condition when this method attempts to initialize
                    // the Attributes and the caller is deleting the reparse point in parallel (FileNotFoundException).
                    yield return item;
                }
            }
        }

19 View Source File : Permission.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public static bool HasPermission(this Permissions p, Permissions permission)
            => p.HasFlag(Permissions.Administrator) || (p & permission) == permission;

See More Examples