System.Diagnostics.Debug.Assert(bool, string)

Here are the examples of the csharp api System.Diagnostics.Debug.Assert(bool, string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

4480 Examples 7

19 Source : WaveFileReader.cs
with MIT License
from 3wz

public static void ReadWaveHeader(Stream stream, out WaveFormat format, out long dataChunkPosition, out int dataChunkLength, List<RiffChunk> chunks)
        {
            dataChunkPosition = -1;
            format = null;
            BinaryReader br = new BinaryReader(stream);
            if (Encoding.ASCII.GetString(br.ReadBytes(4)) != "RIFF")//WaveInterop.mmioStringToFOURCC("RIFF", 0)
            {
                throw new FormatException("Not a WAVE file - no RIFF header");
            }
            uint fileSize = br.ReadUInt32(); // read the file size (minus 8 bytes)
            if (Encoding.ASCII.GetString(br.ReadBytes(4)) != "WAVE")//WaveInterop.mmioStringToFOURCC("WAVE", 0)
            {
                throw new FormatException("Not a WAVE file - no WAVE header");
            }
            int dataChunkID = BitConverter.ToInt32(Encoding.UTF8.GetBytes("data"), 0); ;//WaveInterop.mmioStringToFOURCC("data", 0)
            int formatChunkId = BitConverter.ToInt32(Encoding.UTF8.GetBytes("fmt "), 0); ;//WaveInterop.mmioStringToFOURCC("fmt ", 0)
            dataChunkLength = 0;

            // sometimes a file has more data than is specified after the RIFF header
            long stopPosition = Math.Min(fileSize + 8, stream.Length);

            // this -8 is so we can be sure that there are at least 8 bytes for a chunk id and length
            while (stream.Position <= stopPosition - 8)
            {
                Int32 chunkIdentifier = br.ReadInt32();
                Int32 chunkLength = br.ReadInt32();
                if (chunkIdentifier == dataChunkID)
                {
                    dataChunkPosition = stream.Position;
                    dataChunkLength = chunkLength;
                    stream.Position += chunkLength;
                }
                else if (chunkIdentifier == formatChunkId)
                {
                    format = WaveFormat.FromFormatChunk(br, chunkLength);
                }
                else
                {
                    // check for invalid chunk length
                    if (chunkLength < 0 || chunkLength > stream.Length - stream.Position)
                    {
                        Debug.replacedert(false, String.Format("Invalid chunk length {0}, pos: {1}. length: {2}",
                            chunkLength, stream.Position, stream.Length));
                        // an exception will be thrown further down if we haven't got a format and data chunk yet,
                        // otherwise we will tolerate this file despite it having corrupt data at the end
                        break;
                    }
                    if (chunks != null)
                    {
                        chunks.Add(new RiffChunk(chunkIdentifier, chunkLength, stream.Position));
                    }
                    stream.Position += chunkLength;
                }
            }

            if (format == null)
            {
                throw new FormatException("Invalid WAV file - No fmt chunk found");
            }
            if (dataChunkPosition == -1)
            {
                throw new FormatException("Invalid WAV file - No data chunk found");
            }
        }

19 Source : WaveFileReader.cs
with MIT License
from 3wz

protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                // Release managed resources.
                if (waveStream != null)
                {
                    // only dispose our source if we created it
                    if (ownInput)
                    {
                        waveStream.Close();
                    }
                    waveStream = null;
                }
            }
            else
            {
                System.Diagnostics.Debug.replacedert(false, "WaveFileReader was not disposed");
            }
            // Release unmanaged resources.
            // Set large fields to null.
            // Call Dispose on your base clreplaced.
            base.Dispose(disposing);
        }

19 Source : ByteBuffer.cs
with MIT License
from a1q123456

private void InvokeContinuation(Action<object> continuation, object state, bool forceAsync)
            {
                if (continuation == null)
                    return;

                object scheduler = this.scheduler;
                this.scheduler = null;
                if (scheduler != null)
                {
                    if (scheduler is SynchronizationContext sc)
                    {
                        sc.Post(s =>
                        {
                            var t = (Tuple<Action<object>, object>)s;
                            t.Item1(t.Item2);
                        }, Tuple.Create(continuation, state));
                    }
                    else
                    {
                        Debug.replacedert(scheduler is TaskScheduler, $"Expected TaskScheduler, got {scheduler}");
                        Task.Factory.StartNew(continuation, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach, (TaskScheduler)scheduler);
                    }
                }
                else if (forceAsync)
                {
                    ThreadPool.QueueUserWorkItem(continuation, state, preferLocal: true);
                }
                else
                {
                    continuation(state);
                }
            }

19 Source : LogEvent.cs
with MIT License
from Abc-Arbitrage

public void WriteToStringBuffer(StringBuffer stringBuffer, KeyValuePointerBuffer keyValuePointerBuffer)
        {
            var endOfData = _dataPointer;
            var dataPointer = _startOfBuffer;

            keyValuePointerBuffer.Clear();

            while (dataPointer < endOfData)
            {
                if (!ConsumeKeyValue(ref dataPointer, keyValuePointerBuffer))
                    stringBuffer.Append(ref dataPointer, StringView.Empty, _strings, _argPointers, _argCount);
            }

            Debug.replacedert(dataPointer == endOfData, "Buffer over-read");

            if (keyValuePointerBuffer.KeyPointerCount > 0)
                JsonWriter.WriteJsonToStringBuffer(stringBuffer, keyValuePointerBuffer, _strings);

            if (_isTruncated)
                stringBuffer.Append(LogManager.Config.TruncatedMessageSuffix);
        }

19 Source : LogEvent.cs
with MIT License
from Abc-Arbitrage

public void WriteToStringBufferUnformatted(StringBuffer stringBuffer)
        {
            var endOfData = _dataPointer;
            var dataPointer = _startOfBuffer;

            while (dataPointer < endOfData)
            {
                AppendArgumentToStringBufferUnformatted(stringBuffer, ref dataPointer);

                if (dataPointer < endOfData)
                    stringBuffer.Append(", ");
            }

            Debug.replacedert(dataPointer == endOfData, "Buffer over-read");

            if (_isTruncated)
                stringBuffer.Append(LogManager.Config.TruncatedMessageSuffix);
        }

19 Source : ProcessExtensions.cs
with Apache License 2.0
from abist-co-ltd

public static async Task<ProcessResult> StartProcessAsync(this Process process, ProcessStartInfo startInfo, bool showDebug = false, CancellationToken cancellationToken = default)
        {
            Debug.replacedert(!startInfo.UseShellExecute, "Process Start Info must not use shell execution.");
            Debug.replacedert(startInfo.RedirectStandardOutput, "Process Start Info must redirect standard output.");
            Debug.replacedert(startInfo.RedirectStandardError, "Process Start Info must redirect standard errors.");

            process.StartInfo = startInfo;
            process.EnableRaisingEvents = true;

            var processResult = new TaskCompletionSource<ProcessResult>();
            var errorCodeResult = new TaskCompletionSource<string[]>();
            var errorList = new List<string>();
            var outputCodeResult = new TaskCompletionSource<string[]>();
            var outputList = new List<string>();

            process.Exited += OnProcessExited;
            process.ErrorDataReceived += OnErrorDataReceived;
            process.OutputDataReceived += OnOutputDataReceived;

            async void OnProcessExited(object sender, EventArgs args)
            {
                processResult.TrySetResult(new ProcessResult(process.ExitCode, await errorCodeResult.Task, await outputCodeResult.Task));
                process.Close();
                process.Dispose();
            }

            void OnErrorDataReceived(object sender, DataReceivedEventArgs args)
            {
                if (args.Data != null)
                {
                    errorList.Add(args.Data);

                    if (!showDebug)
                    {
                        return;
                    }

                    UnityEngine.Debug.LogError(args.Data);
                }
                else
                {
                    errorCodeResult.TrySetResult(errorList.ToArray());
                }
            }

            void OnOutputDataReceived(object sender, DataReceivedEventArgs args)
            {
                if (args.Data != null)
                {
                    outputList.Add(args.Data);

                    if (!showDebug)
                    {
                        return;
                    }

                    UnityEngine.Debug.Log(args.Data);
                }
                else
                {
                    outputCodeResult.TrySetResult(outputList.ToArray());
                }
            }

            if (!process.Start())
            {
                if (showDebug)
                {
                    UnityEngine.Debug.LogError("Failed to start process!");
                }

                processResult.TrySetResult(new ProcessResult(process.ExitCode, new[] { "Failed to start process!" }, null));
            }
            else
            {
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                CancellationWatcher(process);
            }

            async void CancellationWatcher(Process _process)
            {
                await Task.Run(() =>
                {
                    try
                    {
                        while (!_process.HasExited)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                _process.Kill();
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                });
            }

            return await processResult.Task;
        }

19 Source : Trajectory.cs
with GNU General Public License v3.0
from ACEmulator

public static float ballistic_range(float speed, float gravity, float initial_height)
        {
            // Handling these cases is up to your project's coding standards
            Debug.replacedert(speed > 0 && gravity > 0 && initial_height >= 0, "fts.ballistic_range called with invalid data");

            // Derivation
            //   (1) x = speed * time * cos O
            //   (2) z = initial_height + (speed * time * sin O) - (.5 * gravity*time*time)
            //   (3) via quadratic: t = (speed*sin O)/gravity + sqrt(speed*speed*sin O + 2*gravity*initial_height)/gravity    [ignore smaller root]
            //   (4) solution: range = x = (speed*cos O)/gravity * sqrt(speed*speed*sin O + 2*gravity*initial_height)    [plug t back into x=speed*time*cos O]
            var angle = 45 * 0.0174533; // no air resistence, so 45 degrees provides maximum range
            var cos = Math.Cos(angle);
            var sin = Math.Sin(angle);

            var range = (speed * cos / gravity) * (speed * sin + Math.Sqrt(speed * speed * sin * sin + 2 * gravity * initial_height));
            return (float)range;
        }

19 Source : Identity.cs
with MIT License
from actions

internal static Idenreplacedy FromXml(IServiceProvider serviceProvider, XmlReader reader)
        {
            Idenreplacedy obj = new Idenreplacedy();
            Debug.replacedert(reader.NodeType == XmlNodeType.Element, "Expected a node.");

            bool empty = reader.IsEmptyElement;

            // Process the xml attributes
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    switch (reader.Name)
                    {
                        case "DisplayName":
                            obj.ProviderDisplayName = reader.Value;
                            break;
                        case "IsActive":
                            obj.IsActive = XmlConvert.ToBoolean(reader.Value);
                            break;
                        case "IsContainer":
                            obj.IsContainer = XmlConvert.ToBoolean(reader.Value);
                            break;
                        case "TeamFoundationId":
                            obj.Id = XmlConvert.ToGuid(reader.Value);
                            break;
                        case "UniqueName":
                            // We don't have this property on VSIdenreplacedy
                            //obj.UniqueName = reader.Value;
                            break;
                        case "UniqueUserId":
                            obj.UniqueUserId = XmlConvert.ToInt32(reader.Value);
                            break;
                        default:
                            // Allow attributes such as xsi:type to fall through
                            break;
                    }
                }
            }

            // Process the fields in Xml elements
            reader.Read();
            if (!empty)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "Attributes":
                            KeyValueOfStringString[] attributes = XmlUtility.ArrayOfObjectFromXml<KeyValueOfStringString>(serviceProvider, reader, "KeyValueOfStringString", false, KeyValueOfStringString.FromXml);
                            if (attributes != null && obj.Properties != null)
                            {
                                foreach (KeyValueOfStringString attribute in attributes)
                                {
                                    obj.Properties[attribute.Key] = attribute.Value;
                                }
                            }
                            break;
                        case "Descriptor":
                            obj.Descriptor = IdenreplacedyDescriptor.FromXml(serviceProvider, reader);
                            break;
                        case "LocalProperties":
                            // Since we're only using the SOAP serializer for bootstrap, we won't support properties
                            //obj.m_localPropertiesSet = Helper.ArrayOfPropertyValueFromXml(serviceProvider, reader, false);
                            reader.ReadOuterXml();
                            break;
                        case "MemberOf":
                            obj.MemberOf = XmlUtility.ArrayOfObjectFromXml<IdenreplacedyDescriptor>(serviceProvider, reader, "IdenreplacedyDescriptor", false, IdenreplacedyDescriptor.FromXml);
                            break;
                        case "Members":
                            obj.Members = XmlUtility.ArrayOfObjectFromXml<IdenreplacedyDescriptor>(serviceProvider, reader, "IdenreplacedyDescriptor", false, IdenreplacedyDescriptor.FromXml);
                            break;
                        case "Properties":
                            // Since we're only using the SOAP serializer for bootstrap, we won't support properties
                            //obj.m_propertiesSet = Helper.ArrayOfPropertyValueFromXml(serviceProvider, reader, false);
                            reader.ReadOuterXml();
                            break;
                        default:
                            // Make sure that we ignore XML node trees we do not understand
                            reader.ReadOuterXml();
                            break;
                    }
                }
                reader.ReadEndElement();
            }
            return obj;
        }

19 Source : LocationMapping.cs
with MIT License
from actions

internal static LocationMapping FromXml(IServiceProvider serviceProvider, XmlReader reader)
        {
            LocationMapping obj = new LocationMapping();
            Debug.replacedert(reader.NodeType == XmlNodeType.Element, "Expected a node.");

            Boolean empty = reader.IsEmptyElement;

            // Process the xml attributes
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    switch (reader.Name)
                    {
                        case "accessMappingMoniker":
                            obj.AccessMappingMoniker = reader.Value;
                            break;
                        case "location":
                            obj.Location = reader.Value;
                            break;
                        default:
                            // Allow attributes such as xsi:type to fall through
                            break;
                    }
                }
            }

            // Process the fields in Xml elements
            reader.Read();
            if (!empty)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        default:
                            // Make sure that we ignore XML node trees we do not understand
                            reader.ReadOuterXml();
                            break;
                    }
                }
                reader.ReadEndElement();
            }
            return obj;
        }

19 Source : ServiceDefinition.cs
with MIT License
from actions

internal static ServiceDefinition FromXml(IServiceProvider serviceProvider, XmlReader reader)
        {
            ServiceDefinition obj = new ServiceDefinition();
            Debug.replacedert(reader.NodeType == XmlNodeType.Element, "Expected a node.");

            Boolean empty = reader.IsEmptyElement;

            // Process the xml attributes
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    switch (reader.Name)
                    {
                        case "description":
                            obj.Description = reader.Value;
                            break;
                        case "displayName":
                            obj.DisplayName = reader.Value;
                            break;
                        case "identifier":
                            obj.Identifier = XmlConvert.ToGuid(reader.Value);
                            break;
                        case "isSingleton":
                            obj.m_isSingleton = XmlConvert.ToBoolean(reader.Value);
                            break;
                        case "relativePath":
                            obj.RelativePath = reader.Value;
                            break;
                        case "relativeToSetting":
                            obj.RelativeToSetting = (RelativeToSetting)XmlConvert.ToInt32(reader.Value);
                            break;
                        case "serviceType":
                            obj.ServiceType = reader.Value;
                            break;
                        case "toolId":
                            obj.ToolId = reader.Value;
                            break;
                        case "resourceVersion":
                            obj.ResourceVersion = XmlConvert.ToInt32(reader.Value);
                            break;
                        case "minVersion":
                            obj.MinVersionString = reader.Value;
                            break;
                        case "maxVersion":
                            obj.MaxVersionString = reader.Value;
                            break;
                        case "releasedVersion":
                            obj.ReleasedVersionString = reader.Value;
                            break;
                        default:
                            // Allow attributes such as xsi:type to fall through
                            break;
                    }
                }
            }

            // Process the fields in Xml elements
            reader.Read();
            if (!empty)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "LocationMappings":
                            obj.LocationMappings = new List<LocationMapping>(XmlUtility.ArrayOfObjectFromXml<LocationMapping>(serviceProvider, reader, "LocationMapping", false, LocationMapping.FromXml));
                            break;
                        case "Properties":
                            // Ignore properties
                            reader.ReadOuterXml();
                            break;
                        default:
                            // Make sure that we ignore XML node trees we do not understand
                            reader.ReadOuterXml();
                            break;
                    }
                }
                reader.ReadEndElement();
            }
            return obj;
        }

19 Source : ArrayUtility.cs
with MIT License
from actions

public unsafe static bool Equals(byte[] a1, byte[] a2)
        {
            Debug.replacedert(a1 != null, "a1 was null");
            Debug.replacedert(a2 != null, "a2 was null");
            
            // Check if the lengths are the same.
            if (a1.Length != a2.Length)
            {
                return false;
            }
            if (a1.Length == 0)
            {
                return true;
            }

            return Equals(a1, a2, a1.Length);
        }

19 Source : ArrayUtility.cs
with MIT License
from actions

public static int GetHashCode(byte[] array)
        {
            Debug.replacedert(array != null, "array was null");

            int hash = 0;
            // the C# compiler defaults to unchecked behavior, so this will
            // wrap silently.  Since this is a hash code and not a count, this
            // is fine with us.
            foreach (byte item in array)
            {
                hash += item;
            }

            return hash;
        }

19 Source : Identity.cs
with MIT License
from actions

internal static KeyValueOfStringString FromXml(IServiceProvider serviceProvider, XmlReader reader)
        {
            KeyValueOfStringString obj = new KeyValueOfStringString();
            Debug.replacedert(reader.NodeType == XmlNodeType.Element, "Expected a node.");

            bool empty = reader.IsEmptyElement;

            // Process the xml attributes
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    switch (reader.Name)
                    {
                        default:
                            // Allow attributes such as xsi:type to fall through
                            break;
                    }
                }
            }

            // Process the fields in Xml elements
            reader.Read();
            if (!empty)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "Key":
                            obj.Key = XmlUtility.StringFromXmlElement(reader);
                            break;
                        case "Value":
                            obj.Value = XmlUtility.StringFromXmlElement(reader);
                            break;
                        default:
                            // Make sure that we ignore XML node trees we do not understand
                            reader.ReadOuterXml();
                            break;
                    }
                }
                reader.ReadEndElement();
            }
            return obj;
        }

19 Source : IdentityDescriptor.cs
with MIT License
from actions

internal static IdenreplacedyDescriptor FromXml(IServiceProvider serviceProvider, XmlReader reader)
        {
            string identifier = string.Empty;
            string idenreplacedyType = string.Empty;

            Debug.replacedert(reader.NodeType == XmlNodeType.Element, "Expected a node.");

            bool empty = reader.IsEmptyElement;

            // Process the xml attributes
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    switch (reader.Name)
                    {
                        case "identifier":
                            identifier = reader.Value;
                            break;
                        case "idenreplacedyType":
                            idenreplacedyType = reader.Value;
                            break;
                        default:
                            // Allow attributes such as xsi:type to fall through
                            break;
                    }
                }
            }

            IdenreplacedyDescriptor obj = new IdenreplacedyDescriptor(idenreplacedyType, identifier);

            // Process the fields in Xml elements
            reader.Read();
            if (!empty)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        default:
                            // Make sure that we ignore XML node trees we do not understand
                            reader.ReadOuterXml();
                            break;
                    }
                }
                reader.ReadEndElement();
            }

            return obj;
        }

19 Source : AccessMapping.cs
with MIT License
from actions

internal static AccessMapping FromXml(IServiceProvider serviceProvider, XmlReader reader)
        {
            AccessMapping obj = new AccessMapping();
            Debug.replacedert(reader.NodeType == XmlNodeType.Element, "Expected a node.");

            Boolean empty = reader.IsEmptyElement;

            // Process the xml attributes
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    switch (reader.Name)
                    {
                        case "AccessPoint":
                            obj.AccessPoint = reader.Value;
                            break;
                        case "DisplayName":
                            obj.DisplayName = reader.Value;
                            break;
                        case "Moniker":
                            obj.Moniker = reader.Value;
                            break;
                        default:
                            // Allow attributes such as xsi:type to fall through
                            break;
                    }
                }
            }

            // Process the fields in Xml elements
            reader.Read();
            if (!empty)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        default:
                            // Make sure that we ignore XML node trees we do not understand
                            reader.ReadOuterXml();
                            break;
                    }
                }
                reader.ReadEndElement();
            }
            return obj;
        }

19 Source : ConnectionData.cs
with MIT License
from actions

internal static ConnectionData FromXml(IServiceProvider serviceProvider, XmlReader reader)
        {
            ConnectionData obj = new ConnectionData();
            Debug.replacedert(reader.NodeType == XmlNodeType.Element, "Expected a node.");

            Boolean empty = reader.IsEmptyElement;

            // Process the xml attributes
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    switch (reader.Name)
                    {
                        case "CatalogResourceId":
                            obj.m_catalogResourceId = XmlConvert.ToGuid(reader.Value);
                            break;
                        case "InstanceId":
                            obj.InstanceId = XmlConvert.ToGuid(reader.Value);
                            break;
                        case "ServerCapabilities":
                            obj.m_serverCapabilities = XmlConvert.ToInt32(reader.Value);
                            break;
                        case "WebApplicationRelativeDirectory":
                            obj.WebApplicationRelativeDirectory = reader.Value;
                            break;
                        default:
                            // Allow attributes such as xsi:type to fall through
                            break;
                    }
                }
            }

            // Process the fields in Xml elements
            reader.Read();
            if (!empty)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "AuthenticatedUser":
                            obj.AuthenticatedUser = IC.Idenreplacedy.FromXml(serviceProvider, reader);
                            break;
                        case "AuthorizedUser":
                            obj.AuthorizedUser = IC.Idenreplacedy.FromXml(serviceProvider, reader);
                            break;
                        case "LocationServiceData":
                            obj.LocationServiceData = LocationServiceData.FromXml(serviceProvider, reader);
                            break;
                        default:
                            // Make sure that we ignore XML node trees we do not understand
                            reader.ReadOuterXml();
                            break;
                    }
                }
                reader.ReadEndElement();
            }
            return obj;
        }

19 Source : ConnectionData.cs
with MIT License
from actions

internal static LocationServiceData FromXml(IServiceProvider serviceProvider, XmlReader reader)
        {
            LocationServiceData obj = new LocationServiceData();
            Debug.replacedert(reader.NodeType == XmlNodeType.Element, "Expected a node.");

            Boolean empty = reader.IsEmptyElement;

            // Process the xml attributes
            if (reader.HasAttributes)
            {
                while (reader.MoveToNextAttribute())
                {
                    switch (reader.Name)
                    {
                        case "AccessPointsDoNotIncludeWebAppRelativeDirectory":
                            obj.m_accessPointsDoNotIncludeWebAppRelativeDirectory = XmlConvert.ToBoolean(reader.Value);
                            break;
                        case "ClientCacheFresh":
                            obj.ClientCacheFresh = XmlConvert.ToBoolean(reader.Value);
                            break;
                        case "DefaultAccessMappingMoniker":
                            obj.DefaultAccessMappingMoniker = reader.Value;
                            break;
                        case "LastChangeId":
                            obj.LastChangeId = XmlConvert.ToInt32(reader.Value);
                            break;
                        case "ClientCacheTimeToLive":
                            obj.ClientCacheTimeToLive = XmlConvert.ToInt32(reader.Value);
                            break;
                        default:
                            // Allow attributes such as xsi:type to fall through
                            break;
                    }                    
                }
            }

            // Process the fields in Xml elements
            reader.Read();
            if (!empty)
            {
                while (reader.NodeType == XmlNodeType.Element)
                {
                    switch (reader.Name)
                    {
                        case "AccessMappings":
                            obj.AccessMappings = XmlUtility.ArrayOfObjectFromXml<AccessMapping>(serviceProvider, reader, "AccessMapping", false, AccessMapping.FromXml);
                            break;
                        case "ServiceDefinitions":
                            obj.ServiceDefinitions = XmlUtility.ArrayOfObjectFromXml<ServiceDefinition>(serviceProvider, reader, "ServiceDefinition", false, ServiceDefinition.FromXml);
                            break;
                        default:
                            // Make sure that we ignore XML node trees we do not understand
                            reader.ReadOuterXml();
                            break;
                    }
                }
                reader.ReadEndElement();
            }
            return obj;
        }

19 Source : SecretUtility.cs
with MIT License
from actions

private static string ScrubSecret(string message, string token, string mask, bool replacedertOnDetection, bool maskToken=false)
        {
            int startIndex = -1;

            do
            {
                startIndex = message.IndexOf(token, (startIndex < 0) ? 0 : startIndex, StringComparison.OrdinalIgnoreCase);
                if (startIndex < 0)
                {
                    // Common case, there is not a preplacedword.
                    break;
                }

                //Explicitly check for original preplacedword mask so code that uses the orignal doesn't replacedert
                if (!maskToken && (
                    message.IndexOf(token + mask, StringComparison.OrdinalIgnoreCase) == startIndex
                    || (message.IndexOf(token + PreplacedwordMask, StringComparison.OrdinalIgnoreCase) == startIndex)))
                {
                    // The preplacedword is already masked, move past this string.
                    startIndex += token.Length + mask.Length;
                    continue;
                }

                // At this point we detected a preplacedword that is not masked, remove it!
                try
                {
                    if (!maskToken)
                    {
                        startIndex += token.Length;
                    }
                    // Find the end of the preplacedword.
                    int endIndex = message.Length - 1;

                    if (message[startIndex] == '"' || message[startIndex] == '\'')
                    {
                        // The preplacedword is wrapped in quotes.  The end of the string will be the next unpaired quote. 
                        // Unless the message itself wrapped the connection string in quotes, in which case we may mask out the rest of the message.  Better to be safe than leak the connection string.
                        // Intentionally going to "i < message.Length - 1".  If the quote isn't the second to last character, it is the last character, and we delete to the end of the string anyway.
                        for (int i = startIndex + 1; i < message.Length - 1; i++)
                        {
                            if (message[startIndex] == message[i])
                            {
                                if (message[startIndex] == message[i + 1])
                                {
                                    // we found a pair of quotes. Skip over the pair and continue.
                                    i++;
                                    continue;
                                }
                                else
                                {
                                    // this is a single quote, and the end of the preplacedword.
                                    endIndex = i;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        // The preplacedword is not wrapped in quotes.
                        // The end is any whitespace, semi-colon, single, or double quote character.
                        for (int i = startIndex + 1; i < message.Length; i++)
                        {
                            if (Char.IsWhiteSpace(message[i]) || ((IList<Char>)s_validPreplacedwordEnding).Contains(message[i]))
                            {
                                endIndex = i - 1;
                                break;
                            }
                        }
                    }

                    message = message.Substring(0, startIndex) + mask + message.Substring(endIndex + 1);

                    // Bug 94478: We need to scrub the message before replacedert, otherwise we will fall into
                    // a recursive replacedert where the TeamFoundationServerException contains same message
                    if (replacedertOnDetection)
                    {
                        Debug.replacedert(false, String.Format(CultureInfo.InvariantCulture, "Message contains an unmasked secret. Message: {0}", message));
                    }

                    // Trace raw that we have scrubbed a message.
                    //FUTURE: We need a work item to add Tracing to the VSS Client replacedembly.
                    //TraceLevel traceLevel = replacedertOnDetection ? TraceLevel.Error : TraceLevel.Info;
                    //TeamFoundationTracingService.TraceRaw(99230, traceLevel, s_area, s_layer, "An unmasked preplacedword was detected in a message. MESSAGE: {0}. STACK TRACE: {1}", message, Environment.StackTrace);
                }
                catch (Exception /*exception*/)
                {
                    // With an exception here the message may still contain an unmasked preplacedword.
                    // We also do not want to interupt the current thread with this exception, because it may be constucting a message 
                    // for a different exception. Trace this exception and continue on using a generic exception message.
                    //TeamFoundationTracingService.TraceExceptionRaw(99231, s_area, s_layer, exception);
                }
                finally
                {
                    // Iterate to the next preplacedword (if it exists)
                    startIndex += mask.Length;
                }
            } while (startIndex < message.Length);

            return message;
        }

19 Source : FlagsEnum.cs
with MIT License
from actions

public static object ParseKnownFlags(Type enumType, string stringValue)
        {
            ArgumentUtility.CheckForNull(enumType, nameof(enumType));
            if (!enumType.IsEnum)
            {
                throw new ArgumentException(PipelinesWebApiResources.FlagEnumTypeRequired());
            }

            // Check for the flags attribute in debug. Skip this reflection in release.
            Debug.replacedert(enumType.GetCustomAttributes(typeof(FlagsAttribute), inherit: false).Any(), "FlagsEnum only intended for enums with the Flags attribute.");

            // The exception types below are based on Enum.TryParseEnum (http://index/?query=TryParseEnum&rightProject=mscorlib&file=system%5Cenum.cs&rightSymbol=bhaeh2vnegwo)
            if (stringValue == null)
            {
                throw new ArgumentNullException(stringValue);
            }

            if (String.IsNullOrWhiteSpace(stringValue))
            {
                throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
            }

            if (UInt64.TryParse(stringValue, NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out ulong ulongValue))
            {
                return Enum.Parse(enumType, stringValue);
            }

            var enumNames = Enum.GetNames(enumType).ToHashSet(name => name, StringComparer.OrdinalIgnoreCase);
            var enumMemberMappings = new Lazy<IDictionary<string, string>>(() =>
            {
                IDictionary<string, string> mappings = null;
                foreach (var field in enumType.GetFields())
                {
                    if (field.GetCustomAttributes(typeof(EnumMemberAttribute), false).FirstOrDefault() is EnumMemberAttribute enumMemberAttribute)
                    {
                        if (mappings == null)
                        {
                            mappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
                        }
                        mappings.Add(enumMemberAttribute.Value, field.GetValue(null).ToString());
                    }
                }

                return mappings;
            });

            var values = stringValue.Split(s_enumSeparatorCharArray);

            var matches = new List<string>();
            for (int i = 0; i < values.Length; i++)
            {
                string value = values[i].Trim();

                if (String.IsNullOrEmpty(value))
                {
                    throw new ArgumentException(PipelinesWebApiResources.NonEmptyEnumElementsRequired(stringValue));
                }

                if (enumNames.Contains(value))
                {
                    matches.Add(value);
                }
                else if (enumMemberMappings.Value != null && enumMemberMappings.Value.TryGetValue(value, out string matchingValue))
                {
                    matches.Add(matchingValue);
                }
            }

            if (!matches.Any())
            {
                return Enum.Parse(enumType, "0");
            }

            string matchesString = String.Join(", ", matches);
            return Enum.Parse(enumType, matchesString, ignoreCase: true);
        }

19 Source : ServerDataProvider.cs
with MIT License
from actions

public async Task<AccessMapping> GetClientAccessMappingAsync(
            CancellationToken cancellationToken = default(CancellationToken))
        {
            AccessMapping clientAccessMapping = m_locationDataCacheManager.ClientAccessMapping;

            // If definition is null we may not have the cache information yet, go to the server to get the information.
            if (clientAccessMapping == null)
            {
                await EnsureConnectedAsync(ConnectOptions.IncludeServices, cancellationToken).ConfigureAwait(false);
                clientAccessMapping = m_locationDataCacheManager.ClientAccessMapping;

                Debug.replacedert(clientAccessMapping != null, "clientAccessMapping should never be null");
            }

            return clientAccessMapping;
        }

19 Source : ServerDataProvider.cs
with MIT License
from actions

public Task<String> LocationForAccessMappingAsync(
            ServiceDefinition serviceDefinition,
            AccessMapping accessMapping,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            ArgumentUtility.CheckForNull(serviceDefinition, "serviceDefinition");
            ArgumentUtility.CheckForNull(accessMapping, "accessMapping");

            // If this is FullyQualified then look through our location mappings
            if (serviceDefinition.RelativeToSetting == RelativeToSetting.FullyQualified)
            {
                LocationMapping locationMapping = serviceDefinition.GetLocationMapping(accessMapping);

                if (locationMapping != null)
                {
                    return Task.FromResult<String>(locationMapping.Location);
                }

                // We weren't able to find the location for the access mapping.  Return null.
                return Task.FromResult<String>(null);
            }
            else
            {
                // Make sure the AccessMapping has a valid AccessPoint.
                if (String.IsNullOrEmpty(accessMapping.AccessPoint))
                {
                    throw new InvalidAccessPointException(WebApiResources.InvalidAccessMappingLocationServiceUrl());
                }

                String webApplicationRelativeDirectory = m_locationDataCacheManager.WebApplicationRelativeDirectory;

                if (accessMapping.VirtualDirectory != null)
                {
                    webApplicationRelativeDirectory = accessMapping.VirtualDirectory;
                }

                Uri uri = new Uri(accessMapping.AccessPoint);

                String properRoot = String.Empty;
                switch (serviceDefinition.RelativeToSetting)
                {
                    case RelativeToSetting.Context:
                        properRoot = PathUtility.Combine(uri.AbsoluteUri, webApplicationRelativeDirectory);
                        break;
                    case RelativeToSetting.WebApplication:
                        properRoot = accessMapping.AccessPoint;
                        break;
                    default:
                        Debug.replacedert(true, "Found an unknown RelativeToSetting");
                        break;
                }

                return Task.FromResult<String>(PathUtility.Combine(properRoot, serviceDefinition.RelativePath));
            }
        }

19 Source : VssRequestTimerTrace.cs
with MIT License
from actions

internal static void Trace(this HttpRequestMessage request)
        {
            Object tracerObj = null;
            VssRequestTimerTrace tracer = null;
            if (request.Properties.TryGetValue(tracerKey, out tracerObj))
            {
                tracer = tracerObj as VssRequestTimerTrace;
                Debug.replacedert(tracer != null, "Tracer object is the wrong type!");
            }
            else
            {
                tracer = new VssRequestTimerTrace();
                request.Properties[tracerKey] = tracer;
            }

            if (tracer != null)
            {
                tracer.TraceRequest(request);
            }
        }

19 Source : ServerDataProvider.cs
with MIT License
from actions

public async Task<AccessMapping> GetDefaultAccessMappingAsync(
            CancellationToken cancellationToken = default(CancellationToken))
        {
            AccessMapping defaultAccessMapping = m_locationDataCacheManager.DefaultAccessMapping;

            // If defaultAccessMapping is null we may not have the cache information yet, go to the server to get the information.
            if (defaultAccessMapping == null)
            {
                await EnsureConnectedAsync(ConnectOptions.IncludeServices, cancellationToken).ConfigureAwait(false);
                defaultAccessMapping = m_locationDataCacheManager.DefaultAccessMapping;

                Debug.replacedert(defaultAccessMapping != null, "defaultAccessMapping should never be null");
            }

            return defaultAccessMapping;
        }

19 Source : VssConnection.cs
with MIT License
from actions

private Type GetExtensibleType(Type managedType)
        {
            if (managedType.GetTypeInfo().IsAbstract || managedType.GetTypeInfo().IsInterface)
            {
                Type extensibleType = null;

                // We can add extensible type registration for the client later (app.config? windows registry?). For now it is based solely on the attribute
                if (!m_extensibleServiceTypes.TryGetValue(managedType.Name, out extensibleType))
                {
                    VssClientServiceImplementationAttribute[] attributes = (VssClientServiceImplementationAttribute[])managedType.GetTypeInfo().GetCustomAttributes<VssClientServiceImplementationAttribute>(true);
                    if (attributes.Length > 0)
                    {
                        if (attributes[0].Type != null)
                        {
                            extensibleType = attributes[0].Type;
                            m_extensibleServiceTypes[managedType.Name] = extensibleType;
                        }
                        else if (!String.IsNullOrEmpty(attributes[0].TypeName))
                        {
                            extensibleType = Type.GetType(attributes[0].TypeName);

                            if (extensibleType != null)
                            {
                                m_extensibleServiceTypes[managedType.Name] = extensibleType;
                            }
                            else
                            {
                                Debug.replacedert(false, "VssConnection: Could not load type from type name: " + attributes[0].TypeName);
                            }
                        }
                    }
                }

                if (extensibleType == null)
                {
                    throw new ExtensibleServiceTypeNotRegisteredException(managedType);
                }

                if (!managedType.GetTypeInfo().IsreplacedignableFrom(extensibleType.GetTypeInfo()))
                {
                    throw new ExtensibleServiceTypeNotValidException(managedType, extensibleType);
                }

                return extensibleType;
            }
            else
            {
                return managedType;
            }
        }

19 Source : VssRequestTimerTrace.cs
with MIT License
from actions

internal static void Trace(this HttpResponseMessage response)
        {
            Object tracerObj = null;
            VssRequestTimerTrace tracer = null;
            if (response.RequestMessage.Properties.TryGetValue(tracerKey, out tracerObj))
            {
                tracer = tracerObj as VssRequestTimerTrace;
                Debug.replacedert(tracer != null, "Tracer object is the wrong type!");
            }

            if (tracer != null)
            {
                tracer.TraceResponse(response);
            }
        }

19 Source : WrappedException.cs
with MIT License
from 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 Source : EntityActionController.cs
with MIT License
from Adoxio

[HttpPost]
		[JsonHandlerError]
		[AjaxValidateAntiForgeryToken, SuppressMessage("ASP.NET.MVC.Security", "CA5332:MarkVerbHandlersWithValidateAntiforgeryToken", Justification = "Handled with the custom attribute AjaxValidateAntiForgeryToken")]
		public ActionResult UpdatePipelinePhase(EnreplacedyReference enreplacedyReference, string stepName, int salesStage, string description)
		{
			var portal = PortalCrmConfigurationManager.CreatePortalContext();
			var serviceContext = portal.ServiceContext;

			var opportunity = serviceContext.CreateQuery("opportunity").FirstOrDefault(o => o.GetAttributeValue<Guid>("opportunityid") == enreplacedyReference.Id);

			Debug.replacedert(opportunity != null, "opportunity != null");

			opportunity.Attributes["stepname"] = stepName;
			opportunity.Attributes["salesstage"] = new OptionSetValue(salesStage);

			serviceContext.UpdateObject(opportunity);

			serviceContext.SaveChanges();

			var objNotes = new Enreplacedy();
			objNotes.LogicalName = "annotation";

			objNotes.Attributes["subject"] = "Updated Pipeline Phase: " + stepName;
			objNotes.Attributes["notetext"] = description;

			objNotes.Attributes["objectid"] = enreplacedyReference;

			//objNotes.Attributes["objecttypecode"] = 1084;

			serviceContext.AddObject(objNotes);

			serviceContext.SaveChanges();

			var enreplacedy = serviceContext.CreateQuery(enreplacedyReference.LogicalName).First(e => e.GetAttributeValue<Guid>("opportunityid") == enreplacedyReference.Id);

			enreplacedy.Attributes["stepname"] = stepName;

			serviceContext.UpdateObject(enreplacedy);

			serviceContext.SaveChanges();



			serviceContext.TryRemoveFromCache(enreplacedy);

			return new HttpStatusCodeResult(HttpStatusCode.NoContent);
		}

19 Source : StartupExtension.cs
with Apache License 2.0
from agoda-com

private static ServiceDescriptor CreateServiceDescriptor(
            RegistrationContext registrationContext, ServiceLifetime serviceLifetime, Type toType = null)
        {
            if (registrationContext.FactoryType != null)
            {
                return new ServiceDescriptor(registrationContext.FromType, (x) =>
                 {
                     var factoryInstance = Activator.CreateInstance(registrationContext.FactoryType);
                     var buildMethod = factoryInstance.GetType().GetMethod("Build");
                     Debug.replacedert(buildMethod != null, nameof(buildMethod) + " != null"); // type is checked by RegistrationInfo.Validate()

                     return buildMethod.Invoke(factoryInstance, new[] { new NetCoreComponentResolver(x) });

                 }, serviceLifetime);
            }
            _ = toType ?? throw new ArgumentNullException(nameof(toType));
            return new ServiceDescriptor(registrationContext.FromType, toType, serviceLifetime);
        }

19 Source : UnityContainerAttributeExtensions.cs
with Apache License 2.0
from agoda-com

private static void RegisterKeyedFactory(RegistrationContext reg)
        {
            var keyedFactoryInterfaceType = typeof(IKeyedComponentFactory<>).MakeGenericType(reg.FromType);
            var keyedFactoryImplementationType = typeof(KeyedComponentFactory<>).MakeGenericType(reg.FromType);

            // obtain the keyed factory for this type from the container, or create and register one if it does not yet exist
            object keyedFactoryInstance;
            if (_container.IsRegistered(keyedFactoryInterfaceType))
            {
                keyedFactoryInstance = _container.Resolve(keyedFactoryInterfaceType);
            }
            else
            {
                var componentResolverType = typeof(UnityKeyedComponentResolver<>).MakeGenericType(reg.FromType);
                var componentResolverInstance = Activator.CreateInstance(componentResolverType, _container);
                keyedFactoryInstance = Activator.CreateInstance(keyedFactoryImplementationType, componentResolverInstance);
                _container.RegisterInstance(keyedFactoryInterfaceType, keyedFactoryInstance);
            }

            // tell the keyed factory about the new key
            var registerKeyMethod = keyedFactoryInstance.GetType().GetMethod("RegisterKey");
            Debug.replacedert(registerKeyMethod != null, nameof(registerKeyMethod) + " != null");
            registerKeyMethod.Invoke(keyedFactoryInstance, new object[] { reg.Key });
        }

19 Source : CustomBatchFixAllProvider.cs
with Apache License 2.0
from agoda-com

public async virtual Task AddDoreplacedentFixesAsync(Doreplacedent doreplacedent, ImmutableArray<Diagnostic> diagnostics, Action<CodeAction> addFix, FixAllContext fixAllContext)
        {
            Debug.replacedert(!diagnostics.IsDefault, "!diagnostics.IsDefault");
            var cancellationToken = fixAllContext.CancellationToken;
            var fixerTasks = new Task[diagnostics.Length];
            var fixes = new List<CodeAction>[diagnostics.Length];

            for (var i = 0; i < diagnostics.Length; i++)
            {
                var currentFixIndex = i;
                cancellationToken.ThrowIfCancellationRequested();
                var diagnostic = diagnostics[i];
                fixerTasks[i] = Task.Run(async () =>
                {
                    var localFixes = new List<CodeAction>();
                    var context = new CodeFixContext(
                        doreplacedent,
                        diagnostic,
                        (a, d) =>
                        {
                            // TODO: Can we share code between similar lambdas that we preplaced to this API in BatchFixAllProvider.cs, CodeFixService.cs and CodeRefactoringService.cs?
                            // Serialize access for thread safety - we don't know what thread the fix provider will call this delegate from.
                            lock (localFixes)
                            {
                                localFixes.Add(a);
                            }
                        },
                        cancellationToken);

                    // TODO: Wrap call to ComputeFixesAsync() below in IExtensionManager.PerformFunctionAsync() so that
                    // a buggy extension that throws can't bring down the host?
                    var task = fixAllContext.CodeFixProvider.RegisterCodeFixesAsync(context) ?? SpecializedTasks.CompletedTask;
                    await task.ConfigureAwait(false);

                    cancellationToken.ThrowIfCancellationRequested();
                    localFixes.RemoveAll(action => action.EquivalenceKey != fixAllContext.CodeActionEquivalenceKey);
                    fixes[currentFixIndex] = localFixes;
                });
            }

            await Task.WhenAll(fixerTasks).ConfigureAwait(false);
            foreach (var fix in fixes)
            {
                if (fix == null)
                {
                    continue;
                }

                foreach (var action in fix)
                {
                    addFix(action);
                }
            }
        }

19 Source : SA1107CodeFixProvider.cs
with Apache License 2.0
from agoda-com

private static Task<Doreplacedent> GetTransformedDoreplacedentAsync(Doreplacedent doreplacedent, SyntaxNode root, SyntaxNode node)
        {
            var newSyntaxRoot = root;
            Debug.replacedert(!node.HasLeadingTrivia, "The trivia should be trailing trivia of the previous node");

            var newNode = node.WithLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
            newSyntaxRoot = newSyntaxRoot.ReplaceNode(node, newNode);

            return Task.FromResult(doreplacedent.WithSyntaxRoot(newSyntaxRoot));
        }

19 Source : UnityContainerAttributeExtensions.cs
with Apache License 2.0
from agoda-com

private static Func<IUnityContainer, object> BuildFactory(RegistrationContext reg)
        {
            var factoryInstance = Activator.CreateInstance(reg.FactoryType);
            var buildMethod = factoryInstance.GetType().GetMethod("Build");
            Debug.replacedert(buildMethod != null, nameof(buildMethod) + " != null"); // type is checked by RegistrationInfo.Validate()
            var fastBuildMethod = new FastMethodInfo(buildMethod);
            var componentResolverInstance = Activator.CreateInstance(typeof(UnityComponentResolver), _container);

            return c =>
            {
                var instance = fastBuildMethod.Invoke(factoryInstance, componentResolverInstance);
                return _interceptorWrapper.WrapInterceptors(instance, reg);
            };
        }

19 Source : MathUtils.cs
with GNU General Public License v3.0
from ahmed605

private static Matrix3D GetViewMatrix(ProjectionCamera camera)
        {
            Debug.replacedert(camera != null,
                         "Caller needs to ensure camera is non-null.");

            // This math is identical to what you find doreplacedented for
            // D3DXMatrixLookAtRH with the exception that WPF uses a
            // LookDirection vector rather than a LookAt point.

            Vector3D zAxis = -camera.LookDirection;
            zAxis.Normalize();

            Vector3D xAxis = Vector3D.CrossProduct(camera.UpDirection, zAxis);
            xAxis.Normalize();

            Vector3D yAxis = Vector3D.CrossProduct(zAxis, xAxis);

            Vector3D position = (Vector3D)camera.Position;
            double offsetX = -Vector3D.DotProduct(xAxis, position);
            double offsetY = -Vector3D.DotProduct(yAxis, position);
            double offsetZ = -Vector3D.DotProduct(zAxis, position);

            return new Matrix3D(
                xAxis.X, yAxis.X, zAxis.X, 0,
                xAxis.Y, yAxis.Y, zAxis.Y, 0,
                xAxis.Z, yAxis.Z, zAxis.Z, 0,
                offsetX, offsetY, offsetZ, 1);
        }

19 Source : MathUtils.cs
with GNU General Public License v3.0
from ahmed605

private static Matrix3D GetProjectionMatrix(OrthographicCamera camera, double aspectRatio)
        {
            Debug.replacedert(camera != null,
                         "Caller needs to ensure camera is non-null.");

            // This math is identical to what you find doreplacedented for
            // D3DXMatrixOrthoRH with the exception that in WPF only
            // the camera's width is specified.  Height is calculated
            // from width and the aspect ratio.

            double w = camera.Width;
            double h = w / aspectRatio;
            double zn = camera.NearPlaneDistance;
            double zf = camera.FarPlaneDistance;

            double m33 = 1 / (zn - zf);
            double m43 = zn * m33;

            return new Matrix3D(
                2 / w, 0, 0, 0,
                0, 2 / h, 0, 0,
                0, 0, m33, 0,
                0, 0, m43, 1);
        }

19 Source : MathUtils.cs
with GNU General Public License v3.0
from ahmed605

private static Matrix3D GetProjectionMatrix(PerspectiveCamera camera, double aspectRatio)
        {
            Debug.replacedert(camera != null,
                         "Caller needs to ensure camera is non-null.");

            // This math is identical to what you find doreplacedented for
            // D3DXMatrixPerspectiveFovRH with the exception that in
            // WPF the camera's horizontal rather the vertical
            // field-of-view is specified.

            double hFoV = MathUtils.DegreesToRadians(camera.FieldOfView);
            double zn = camera.NearPlaneDistance;
            double zf = camera.FarPlaneDistance;

            double xScale = 1 / Math.Tan(hFoV / 2);
            double yScale = aspectRatio * xScale;
            double m33 = (zf == double.PositiveInfinity) ? -1 : (zf / (zn - zf));
            double m43 = zn * m33;

            return new Matrix3D(
                xScale, 0, 0, 0,
                0, yScale, 0, 0,
                0, 0, m33, -1,
                0, 0, m43, 0);
        }

19 Source : CodeFormat.cs
with GNU General Public License v3.0
from ahmed605

protected override string MatchEval(Match match)
		{
			if(match.Groups[1].Success) //comment
			{
				StringReader reader = new StringReader(match.ToString());
				string line;
				StringBuilder sb = new StringBuilder();
				while ((line = reader.ReadLine()) != null)
				{
					if(sb.Length > 0)
					{
						sb.Append("\n");
					}
					sb.Append("<span clreplaced=\"rem\">");
					sb.Append(line);
					sb.Append("</span>");
				}
				return sb.ToString();
			}
			if(match.Groups[2].Success) //string literal
			{
				return "<span clreplaced=\"str\">" + match.ToString() + "</span>";
			}
			if(match.Groups[3].Success) //preprocessor keyword
			{
				return "<span clreplaced=\"preproc\">" + match.ToString() + "</span>";
			}
			if(match.Groups[4].Success) //keyword
			{
				return "<span clreplaced=\"kwrd\">" + match.ToString() + "</span>";
			}
			System.Diagnostics.Debug.replacedert(false, "None of the above!");
			return ""; //none of the above
		}

19 Source : DebugLog.cs
with GNU General Public License v3.0
from aiportal

[Conditional("DEBUG")]
		public static void replacedert(bool condition, string message) { Debug.replacedert(condition, message); }

19 Source : DebugLog.cs
with GNU General Public License v3.0
from aiportal

[Conditional("DEBUG")]
		public static void replacedert<T>(this T obj, bool condition) { Debug.replacedert(condition, typeof(T).FullName); }

19 Source : CsvReaderVisitorWithUTF8HeadersBase.cs
with MIT License
from airbreather

[MethodImpl(MethodImplOptions.NoInlining)]
        private unsafe void VisitPartialFieldContentsSlow(ReadOnlySpan<byte> chunk)
        {
            if (_headers.IsDefault)
            {
                if (_headersBuilder.Count == _maxHeaderCount)
                {
                    throw new CursivelyTooManyHeadersException(_maxHeaderCount);
                }

                fixed (byte* b = &MemoryMarshal.GetReference(chunk))
                {
                    VisitHeaderChunk(b, chunk.Length, false);
                }
            }
            else
            {
                Debug.replacedert(_currentFieldIndex >= _headers.Length, "Another condition brought us into VisitPartialFieldContentsSlow without updating this bit.");
                VisitUnexpectedDataField();
                VisitPartialDataFieldContents(chunk);
            }
        }

19 Source : CsvReaderVisitorWithUTF8HeadersBase.cs
with MIT License
from airbreather

[MethodImpl(MethodImplOptions.NoInlining)]
        private unsafe void VisitEndOfFieldSlow(ReadOnlySpan<byte> chunk)
        {
            if (_headers.IsDefault)
            {
                if (_headersBuilder.Count == _maxHeaderCount)
                {
                    throw new CursivelyTooManyHeadersException(_maxHeaderCount);
                }

                fixed (byte* b = &MemoryMarshal.GetReference(chunk))
                {
                    VisitHeaderChunk(b, chunk.Length, true);
                }

                int headerBufferOffset = 0;

                if (_headersBuilder.Count == 0 &&
                    _ignoreUTF8IdentifierOnFirstHeaderField &&
                    _headerBufferConsumed > 0 &&
                    _headerBuffer[0] == '\uFEFF')
                {
                    headerBufferOffset = 1;
                }

                _headersBuilder.Add(new string(_headerBuffer, headerBufferOffset, _headerBufferConsumed - headerBufferOffset));
                _headerBufferConsumed = 0;
                ++_currentFieldIndex;
            }
            else
            {
                Debug.replacedert(_currentFieldIndex >= _headers.Length, "Another condition brought us into VisitEndOfFieldSlow without updating this bit.");
                VisitUnexpectedDataField();
                VisitEndOfDataField(chunk);
                _currentFieldIndex = checked(_currentFieldIndex + 1);
            }
        }

19 Source : CsvReaderVisitorWithUTF8HeadersBase.cs
with MIT License
from airbreather

[MethodImpl(MethodImplOptions.NoInlining)]
        private void VisitEndOfRecordSlow()
        {
            if (_headers.IsDefault)
            {
                if (_headersBuilder.Count == 0)
                {
                    // the tokenizer will never do this, but an external caller might.
                    throw new InvalidOperationException("No fields were present in the header record.");
                }

                _headersBuilder.Capacity = _headersBuilder.Count;
                _headers = _headersBuilder.MoveToImmutable();
                _currentFieldIndex = _headers.Length;

                // we're done building headers, so free up our buffers.
                _headersBuilder = null;
                _headerBuffer = null;

                // let the subclreplaced know that the headers are ready, in case it wants to set up some
                // stuff before the field data starts rolling in.
                VisitEndOfHeaderRecord();
            }
            else
            {
                Debug.replacedert(_currentFieldIndex != _headers.Length, "Another condition brought us into VisitEndOfRecordSlow without updating this bit.");
                if (_currentFieldIndex < _headers.Length)
                {
                    VisitMissingDataFields();
                }

                VisitEndOfDataRecord();
            }

            _currentFieldIndex = 0;
        }

19 Source : HtmlFromXamlConverter.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private static bool ReadNextToken(XmlReader xamlReader)
		{
			while (xamlReader.Read())
			{
				Debug.replacedert(xamlReader.ReadState == ReadState.Interactive, "Reader is expected to be in Interactive state (" + xamlReader.ReadState + ")");
				switch (xamlReader.NodeType)
				{
				    case XmlNodeType.Element: 
				    case XmlNodeType.EndElement:
				    case XmlNodeType.None:
				    case XmlNodeType.CDATA:
				    case XmlNodeType.Text:
				    case XmlNodeType.SignificantWhitespace:
					    return true;

				    case XmlNodeType.Whitespace:
					    if (xamlReader.XmlSpace == XmlSpace.Preserve)
					    {
						    return true;
					    }
					    // ignore insignificant whitespace
					    break;

				    case XmlNodeType.EndEnreplacedy:
				    case XmlNodeType.EnreplacedyReference:
                        //  Implement enreplacedy reading
					    //xamlReader.ResolveEnreplacedy();
					    //xamlReader.Read();
					    //ReadChildNodes( parent, parentBaseUri, xamlReader, positionInfo);
                        break; // for now we ignore enreplacedies as insignificant stuff

                    case XmlNodeType.Comment:
                        return true;
                    case XmlNodeType.ProcessingInstruction:
				    case XmlNodeType.DoreplacedentType:
				    case XmlNodeType.XmlDeclaration:
				    default:
					    // Ignorable stuff
					    break;
				}
            }
            return false;
        }

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

private void Triangulate()
        {
            while (_convexPoints.Count != 0)
            {
                IEnumerator<Point> e = _convexPoints.GetEnumerator();
                e.MoveNext();
                Point ear = e.Current;

                _convexPoints.Remove(ear);
                Point a = ear.Prev;
                Point b = ear;
                Point c = ear.Next;
                List<Point> triangle = new List<Point>(3);
                triangle.Add(a);
                triangle.Add(b);
                triangle.Add(c);

                Triangles.Add(triangle);

                // Remove ear, update angles and convex list
                Remove(ear);
                if (Valid(a))
                    _convexPoints.Add(a);
                if (Valid(c))
                    _convexPoints.Add(c);
            }

            Debug.replacedert(_size <= 3, "Triangulation bug, please report");
        }

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

public static Vertices CreateArc(float radians, int sides, float radius)
        {
            Debug.replacedert(radians > 0, "The arc needs to be larger than 0");
            Debug.replacedert(sides > 1, "The arc needs to have more than 1 sides");
            Debug.replacedert(radius > 0, "The arc needs to have a radius larger than 0");

            Vertices vertices = new Vertices();

            float stepSize = radians / sides;
            for (int i = sides - 1; i > 0; i--)
            {
                vertices.Add(new Vector2(radius * (float)Math.Cos(stepSize * i),
                                         radius * (float)Math.Sin(stepSize * i)));
            }

            return vertices;
        }

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

public void Translate(ref Vector2 value)
        {
            Debug.replacedert(!AttachedToBody, "Translating vertices that are used by a Body can result in unstable behavior. Use Body.Position instead.");

            for (int i = 0; i < Count; i++)
                this[i] = Vector2.Add(this[i], value);

            if (Holes != null && Holes.Count > 0)
            {
                foreach (Vertices hole in Holes)
                {
                    hole.Translate(ref value);
                }
            }
        }

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

public void Scale(ref Vector2 value)
        {
            Debug.replacedert(!AttachedToBody, "Scaling vertices that are used by a Body can result in unstable behavior.");

            for (int i = 0; i < Count; i++)
                this[i] = Vector2.Multiply(this[i], value);

            if (Holes != null && Holes.Count > 0)
            {
                foreach (Vertices hole in Holes)
                {
                    hole.Scale(ref value);
                }
            }
        }

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

public void Rotate(float value)
        {
            Debug.replacedert(!AttachedToBody, "Rotating vertices that are used by a Body can result in unstable behavior.");

            float num1 = (float)Math.Cos(value);
            float num2 = (float)Math.Sin(value);

            for (int i = 0; i < Count; i++)
            {
                Vector2 position = this[i];
                this[i] = new Vector2((position.X * num1 + position.Y * -num2), (position.X * num2 + position.Y * num1));
            }

            if (Holes != null && Holes.Count > 0)
            {
                foreach (Vertices hole in Holes)
                {
                    hole.Rotate(value);
                }
            }
        }

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

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public bool Equals(ref T a, ref T b)
        {
            if (typeof(T) == typeof(bool))
            {
                return Unsafe.As<T, bool>(ref a) == Unsafe.As<T, bool>(ref b);
            }
            if (typeof(T) == typeof(byte))
            {
                return Unsafe.As<T, byte>(ref a) == Unsafe.As<T, byte>(ref b);
            }
            if (typeof(T) == typeof(sbyte))
            {
                return Unsafe.As<T, sbyte>(ref a) == Unsafe.As<T, sbyte>(ref b);
            }
            if (typeof(T) == typeof(short))
            {
                return Unsafe.As<T, short>(ref a) == Unsafe.As<T, short>(ref b);
            }
            if (typeof(T) == typeof(ushort))
            {
                return Unsafe.As<T, ushort>(ref a) == Unsafe.As<T, ushort>(ref b);
            }
            if (typeof(T) == typeof(int))
            {
                return Unsafe.As<T, int>(ref a) == Unsafe.As<T, int>(ref b);
            }
            if (typeof(T) == typeof(uint))
            {
                return Unsafe.As<T, uint>(ref a) == Unsafe.As<T, uint>(ref b);
            }
            if (typeof(T) == typeof(long))
            {
                return Unsafe.As<T, long>(ref a) == Unsafe.As<T, long>(ref b);
            }
            if (typeof(T) == typeof(ulong))
            {
                return Unsafe.As<T, ulong>(ref a) == Unsafe.As<T, ulong>(ref b);
            }
            if (typeof(T) == typeof(IntPtr))
            {
                return Unsafe.As<T, IntPtr>(ref a) == Unsafe.As<T, IntPtr>(ref b);
            }
            if (typeof(T) == typeof(UIntPtr))
            {
                return Unsafe.As<T, UIntPtr>(ref a) == Unsafe.As<T, UIntPtr>(ref b);
            }
            if (typeof(T) == typeof(char))
            {
                return Unsafe.As<T, char>(ref a) == Unsafe.As<T, char>(ref b);
            }
            if (typeof(T) == typeof(double))
            {
                return Unsafe.As<T, double>(ref a) == Unsafe.As<T, double>(ref b);
            }
            if (typeof(T) == typeof(float))
            {
                return Unsafe.As<T, float>(ref a) == Unsafe.As<T, float>(ref b);
            }
            Debug.replacedert(false, "Should only use the supported primitive types with the primitive comparer.");
            return false;
        }

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

[MethodImpl(MethodImplOptions.AggressiveInlining)]
        public int Hash(ref T item)
        {
            //Note: the jit is able to inline the GetHashCodes; no need for custom implementations.
            if (typeof(T) == typeof(bool))
            {
                return Unsafe.As<T, bool>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(byte))
            {
                return Unsafe.As<T, byte>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(sbyte))
            {
                return Unsafe.As<T, sbyte>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(short))
            {
                return Unsafe.As<T, short>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(ushort))
            {
                return Unsafe.As<T, ushort>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(int))
            {
                return Unsafe.As<T, int>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(uint))
            {
                return Unsafe.As<T, uint>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(long))
            {
                return Unsafe.As<T, long>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(ulong))
            {
                return Unsafe.As<T, ulong>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(IntPtr))
            {
                return Unsafe.As<T, IntPtr>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(UIntPtr))
            {
                return Unsafe.As<T, UIntPtr>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(char))
            {
                return Unsafe.As<T, char>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(double))
            {
                return Unsafe.As<T, double>(ref item).GetHashCode();
            }
            if (typeof(T) == typeof(float))
            {
                return Unsafe.As<T, float>(ref item).GetHashCode();
            }
            Debug.replacedert(false, "Should only use the supported primitive types with the primitive comparer.");
            return 0;
        }

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

[Conditional("DEBUG")]
        void ValidateIndex(int index)
        {
            Debug.replacedert(index >= 0 && index < Count, "Index must be nonnegative and less than the number of elements in the queue.");
        }

See More Examples