context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Text; using System.Threading; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; namespace System.Diagnostics { /// <summary> /// Provides interaction with Windows event logs. /// </summary> [DefaultEvent("EntryWritten")] public class EventLog : Component, ISupportInitialize { private const string EventLogKey = "SYSTEM\\CurrentControlSet\\Services\\EventLog"; internal const string DllName = "EventLogMessages.dll"; private const string eventLogMutexName = "netfxeventlog.1.0"; private const int DefaultMaxSize = 512 * 1024; private const int DefaultRetention = 7 * SecondsPerDay; private const int SecondsPerDay = 60 * 60 * 24; private EventLogInternal _underlyingEventLog; public EventLog() : this(string.Empty, ".", string.Empty) { } public EventLog(string logName) : this(logName, ".", string.Empty) { } public EventLog(string logName, string machineName) : this(logName, machineName, string.Empty) { } public EventLog(string logName, string machineName, string source) { _underlyingEventLog = new EventLogInternal(logName, machineName, source, this); } /// <summary> /// The contents of the log. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public EventLogEntryCollection Entries { get { return _underlyingEventLog.Entries; } } [Browsable(false)] public string LogDisplayName { get { return _underlyingEventLog.LogDisplayName; } } /// <summary> /// Gets or sets the name of the log to read from and write to. /// </summary> [ReadOnly(true)] [DefaultValue("")] [SettingsBindable(true)] public string Log { get { return _underlyingEventLog.Log; } set { EventLogInternal newLog = new EventLogInternal(value, _underlyingEventLog.MachineName, _underlyingEventLog.Source, this); EventLogInternal oldLog = _underlyingEventLog; if (oldLog.EnableRaisingEvents) { newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler; newLog.EnableRaisingEvents = true; } _underlyingEventLog = newLog; oldLog.Close(); } } /// <summary> /// The machine on which this event log resides. /// </summary> [ReadOnly(true)] [DefaultValue(".")] [SettingsBindable(true)] public string MachineName { get { return _underlyingEventLog.MachineName; } set { EventLogInternal newLog = new EventLogInternal(_underlyingEventLog.logName, value, _underlyingEventLog.sourceName, this); EventLogInternal oldLog = _underlyingEventLog; if (oldLog.EnableRaisingEvents) { newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler; newLog.EnableRaisingEvents = true; } _underlyingEventLog = newLog; oldLog.Close(); } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Browsable(false)] public long MaximumKilobytes { get => _underlyingEventLog.MaximumKilobytes; set => _underlyingEventLog.MaximumKilobytes = value; } [Browsable(false)] public OverflowAction OverflowAction { get => _underlyingEventLog.OverflowAction; } [Browsable(false)] public int MinimumRetentionDays { get => _underlyingEventLog.MinimumRetentionDays; } internal bool ComponentDesignMode { get => this.DesignMode; } internal object ComponentGetService(Type service) { return GetService(service); } /// <summary> /// Indicates if the component monitors the event log for changes. /// </summary> [Browsable(false)] [DefaultValue(false)] public bool EnableRaisingEvents { get => _underlyingEventLog.EnableRaisingEvents; set => _underlyingEventLog.EnableRaisingEvents = value; } /// <summary> /// The object used to marshal the event handler calls issued as a result of an EventLog change. /// </summary> [Browsable(false)] [DefaultValue(null)] public ISynchronizeInvoke SynchronizingObject { get => _underlyingEventLog.SynchronizingObject; set => _underlyingEventLog.SynchronizingObject = value; } /// <summary> /// The application name (source name) to use when writing to the event log. /// </summary> [ReadOnly(true)] [DefaultValue("")] [SettingsBindable(true)] public string Source { get => _underlyingEventLog.Source; set { EventLogInternal newLog = new EventLogInternal(_underlyingEventLog.Log, _underlyingEventLog.MachineName, CheckAndNormalizeSourceName(value), this); EventLogInternal oldLog = _underlyingEventLog; if (oldLog.EnableRaisingEvents) { newLog.onEntryWrittenHandler = oldLog.onEntryWrittenHandler; newLog.EnableRaisingEvents = true; } _underlyingEventLog = newLog; oldLog.Close(); } } /// <summary> /// Raised each time any application writes an entry to the event log. /// </summary> public event EntryWrittenEventHandler EntryWritten { add { _underlyingEventLog.EntryWritten += value; } remove { _underlyingEventLog.EntryWritten -= value; } } public void BeginInit() { _underlyingEventLog.BeginInit(); } public void Clear() { _underlyingEventLog.Clear(); } public void Close() { _underlyingEventLog.Close(); } public static void CreateEventSource(string source, string logName) { CreateEventSource(new EventSourceCreationData(source, logName, ".")); } [Obsolete("This method has been deprecated. Please use System.Diagnostics.EventLog.CreateEventSource(EventSourceCreationData sourceData) instead. https://go.microsoft.com/fwlink/?linkid=14202")] public static void CreateEventSource(string source, string logName, string machineName) { CreateEventSource(new EventSourceCreationData(source, logName, machineName)); } public static void CreateEventSource(EventSourceCreationData sourceData) { if (sourceData == null) throw new ArgumentNullException(nameof(sourceData)); string logName = sourceData.LogName; string source = sourceData.Source; string machineName = sourceData.MachineName; Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Checking arguments"); if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } if (logName == null || logName.Length == 0) logName = "Application"; if (!ValidLogName(logName, false)) throw new ArgumentException(SR.BadLogName); if (source == null || source.Length == 0) throw new ArgumentException(SR.Format(SR.MissingParameter, nameof(source))); if (source.Length + EventLogKey.Length > 254) throw new ArgumentException(SR.Format(SR.ParameterTooLong, nameof(source), 254 - EventLogKey.Length)); Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex); Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Calling SourceExists"); if (SourceExists(source, machineName, true)) { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: SourceExists returned true"); if (".".Equals(machineName)) throw new ArgumentException(SR.Format(SR.LocalSourceAlreadyExists, source)); else throw new ArgumentException(SR.Format(SR.SourceAlreadyExists, source, machineName)); } Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting DllPath"); RegistryKey baseKey = null; RegistryKey eventKey = null; RegistryKey logKey = null; RegistryKey sourceLogKey = null; RegistryKey sourceKey = null; try { Debug.WriteLineIf(CompModSwitches.EventLog.TraceVerbose, "CreateEventSource: Getting local machine regkey"); if (machineName == ".") baseKey = Registry.LocalMachine; else baseKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machineName); eventKey = baseKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\EventLog", true); if (eventKey == null) { if (!".".Equals(machineName)) throw new InvalidOperationException(SR.Format(SR.RegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source, machineName)); else throw new InvalidOperationException(SR.Format(SR.LocalRegKeyMissing, "SYSTEM\\CurrentControlSet\\Services\\EventLog", logName, source)); } logKey = eventKey.OpenSubKey(logName, true); if (logKey == null) { if (logName.Length == 8 && ( string.Equals(logName, "AppEvent", StringComparison.OrdinalIgnoreCase) || string.Equals(logName, "SecEvent", StringComparison.OrdinalIgnoreCase) || string.Equals(logName, "SysEvent", StringComparison.OrdinalIgnoreCase))) throw new ArgumentException(SR.Format(SR.InvalidCustomerLogName, logName)); } bool createLogKey = (logKey == null); if (createLogKey) { if (SourceExists(logName, machineName, true)) { if (".".Equals(machineName)) throw new ArgumentException(SR.Format(SR.LocalLogAlreadyExistsAsSource, logName)); else throw new ArgumentException(SR.Format(SR.LogAlreadyExistsAsSource, logName, machineName)); } logKey = eventKey.CreateSubKey(logName); SetSpecialLogRegValues(logKey, logName); // A source with the same name as the log has to be created // by default. It is the behavior expected by EventLog API. sourceLogKey = logKey.CreateSubKey(logName); SetSpecialSourceRegValues(sourceLogKey, sourceData); } if (logName != source) { if (!createLogKey) { SetSpecialLogRegValues(logKey, logName); } sourceKey = logKey.CreateSubKey(source); SetSpecialSourceRegValues(sourceKey, sourceData); } } finally { baseKey?.Close(); eventKey?.Close(); logKey?.Close(); sourceLogKey?.Close(); sourceKey?.Close(); } } finally { mutex?.ReleaseMutex(); mutex?.Close(); } } public static void Delete(string logName) { Delete(logName, "."); } public static void Delete(string logName, string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameterFormat, nameof(machineName)), nameof(machineName)); if (logName == null || logName.Length == 0) throw new ArgumentException(SR.NoLogName); if (!ValidLogName(logName, false)) throw new InvalidOperationException(SR.BadLogName); RegistryKey eventlogkey = null; Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex); try { eventlogkey = GetEventLogRegKey(machineName, true); if (eventlogkey == null) { throw new InvalidOperationException(SR.Format(SR.RegKeyNoAccess, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog", machineName)); } using (RegistryKey logKey = eventlogkey.OpenSubKey(logName)) { if (logKey == null) throw new InvalidOperationException(SR.Format(SR.MissingLog, logName, machineName)); //clear out log before trying to delete it //that way, if we can't delete the log file, no entries will persist because it has been cleared EventLog logToClear = new EventLog(logName, machineName); try { logToClear.Clear(); } finally { logToClear.Close(); } string filename = null; try { //most of the time, the "File" key does not exist, but we'll still give it a whirl filename = (string)logKey.GetValue("File"); } catch { } if (filename != null) { try { File.Delete(filename); } catch { } } } // now delete the registry entry eventlogkey.DeleteSubKeyTree(logName); } finally { eventlogkey?.Close(); } } finally { mutex?.ReleaseMutex(); } } public static void DeleteEventSource(string source) { DeleteEventSource(source, "."); } public static void DeleteEventSource(string source, string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } Mutex mutex = null; RuntimeHelpers.PrepareConstrainedRegions(); try { NetFrameworkUtils.EnterMutex(eventLogMutexName, ref mutex); RegistryKey key = null; // First open the key read only so we can do some checks. This is important so we get the same // exceptions even if we don't have write access to the reg key. using (key = FindSourceRegistration(source, machineName, true)) { if (key == null) { if (machineName == null) throw new ArgumentException(SR.Format(SR.LocalSourceNotRegistered, source)); else throw new ArgumentException(SR.Format(SR.SourceNotRegistered, source, machineName, "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\EventLog")); } // Check parent registry key (Event Log Name) and if it's equal to source, then throw an exception. // The reason: each log registry key must always contain subkey (i.e. source) with the same name. string keyname = key.Name; int index = keyname.LastIndexOf('\\'); if (string.Compare(keyname, index + 1, source, 0, keyname.Length - index, StringComparison.Ordinal) == 0) throw new InvalidOperationException(SR.Format(SR.CannotDeleteEqualSource, source)); } try { key = FindSourceRegistration(source, machineName, false); key.DeleteSubKeyTree(source); } finally { key?.Close(); } } finally { mutex?.ReleaseMutex(); } } protected override void Dispose(bool disposing) { _underlyingEventLog?.Dispose(disposing); base.Dispose(disposing); } public void EndInit() { _underlyingEventLog.EndInit(); } public static bool Exists(string logName) { return Exists(logName, "."); } public static bool Exists(string logName, string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) throw new ArgumentException(SR.Format(SR.InvalidParameterFormat, nameof(machineName))); if (logName == null || logName.Length == 0) return false; RegistryKey eventkey = null; RegistryKey logKey = null; try { eventkey = GetEventLogRegKey(machineName, false); if (eventkey == null) return false; logKey = eventkey.OpenSubKey(logName, false); // try to find log file key immediately. return (logKey != null); } finally { eventkey?.Close(); logKey?.Close(); } } private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly) { return FindSourceRegistration(source, machineName, readOnly, false); } private static RegistryKey FindSourceRegistration(string source, string machineName, bool readOnly, bool wantToCreate) { if (source != null && source.Length != 0) { RegistryKey eventkey = null; try { eventkey = GetEventLogRegKey(machineName, !readOnly); if (eventkey == null) { // there's not even an event log service on the machine. // or, more likely, we don't have the access to read the registry. return null; } StringBuilder inaccessibleLogs = null; // Most machines will return only { "Application", "System", "Security" }, // but you can create your own if you want. string[] logNames = eventkey.GetSubKeyNames(); for (int i = 0; i < logNames.Length; i++) { // see if the source is registered in this log. // NOTE: A source name must be unique across ALL LOGS! RegistryKey sourceKey = null; try { RegistryKey logKey = eventkey.OpenSubKey(logNames[i], /*writable*/!readOnly); if (logKey != null) { sourceKey = logKey.OpenSubKey(source, /*writable*/!readOnly); if (sourceKey != null) { // found it return logKey; } else { logKey.Close(); } } // else logKey is null, so we don't need to Close it } catch (UnauthorizedAccessException) { if (inaccessibleLogs == null) { inaccessibleLogs = new StringBuilder(logNames[i]); } else { inaccessibleLogs.Append(", "); inaccessibleLogs.Append(logNames[i]); } } catch (SecurityException) { if (inaccessibleLogs == null) { inaccessibleLogs = new StringBuilder(logNames[i]); } else { inaccessibleLogs.Append(", "); inaccessibleLogs.Append(logNames[i]); } } finally { sourceKey?.Close(); } } if (inaccessibleLogs != null) throw new SecurityException(SR.Format(wantToCreate ? SR.SomeLogsInaccessibleToCreate : SR.SomeLogsInaccessible, inaccessibleLogs)); } finally { eventkey?.Close(); } } return null; } public static EventLog[] GetEventLogs() { return GetEventLogs("."); } public static EventLog[] GetEventLogs(string machineName) { if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } string[] logNames = null; RegistryKey eventkey = null; try { // we figure out what logs are on the machine by looking in the registry. eventkey = GetEventLogRegKey(machineName, false); if (eventkey == null) // there's not even an event log service on the machine. // or, more likely, we don't have the access to read the registry. throw new InvalidOperationException(SR.Format(SR.RegKeyMissingShort, EventLogKey, machineName)); // Most machines will return only { "Application", "System", "Security" }, // but you can create your own if you want. logNames = eventkey.GetSubKeyNames(); } finally { eventkey?.Close(); } // now create EventLog objects that point to those logs EventLog[] logs = new EventLog[logNames.Length]; for (int i = 0; i < logNames.Length; i++) { EventLog log = new EventLog(logNames[i], machineName); logs[i] = log; } return logs; } internal static RegistryKey GetEventLogRegKey(string machine, bool writable) { RegistryKey lmkey = null; try { if (machine.Equals(".")) { lmkey = Registry.LocalMachine; } else { lmkey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, machine); } if (lmkey != null) return lmkey.OpenSubKey(EventLogKey, writable); } finally { lmkey?.Close(); } return null; } internal static string GetDllPath(string machineName) { return Path.Combine(NetFrameworkUtils.GetLatestBuildDllDirectory(machineName), DllName); } public static bool SourceExists(string source) { return SourceExists(source, "."); } public static bool SourceExists(string source, string machineName) { return SourceExists(source, machineName, false); } internal static bool SourceExists(string source, string machineName, bool wantToCreate) { if (!SyntaxCheck.CheckMachineName(machineName)) { throw new ArgumentException(SR.Format(SR.InvalidParameter, nameof(machineName), machineName)); } using (RegistryKey keyFound = FindSourceRegistration(source, machineName, true, wantToCreate)) { return (keyFound != null); } } public static string LogNameFromSourceName(string source, string machineName) { return _InternalLogNameFromSourceName(source, machineName); } internal static string _InternalLogNameFromSourceName(string source, string machineName) { using (RegistryKey key = FindSourceRegistration(source, machineName, true)) { if (key == null) return string.Empty; else { string name = key.Name; int whackPos = name.LastIndexOf('\\'); // this will work even if whackPos is -1 return name.Substring(whackPos + 1); } } } public void ModifyOverflowPolicy(OverflowAction action, int retentionDays) { _underlyingEventLog.ModifyOverflowPolicy(action, retentionDays); } public void RegisterDisplayName(string resourceFile, long resourceId) { _underlyingEventLog.RegisterDisplayName(resourceFile, resourceId); } private static void SetSpecialLogRegValues(RegistryKey logKey, string logName) { // Set all the default values for this log. AutoBackupLogfiles only makes sense in // Win2000 SP4, WinXP SP1, and Win2003, but it should alright elsewhere. // Since we use this method on the existing system logs as well as our own, // we need to make sure we don't overwrite any existing values. if (logKey.GetValue("MaxSize") == null) logKey.SetValue("MaxSize", DefaultMaxSize, RegistryValueKind.DWord); if (logKey.GetValue("AutoBackupLogFiles") == null) logKey.SetValue("AutoBackupLogFiles", 0, RegistryValueKind.DWord); } private static void SetSpecialSourceRegValues(RegistryKey sourceLogKey, EventSourceCreationData sourceData) { if (string.IsNullOrEmpty(sourceData.MessageResourceFile)) sourceLogKey.SetValue("EventMessageFile", GetDllPath(sourceData.MachineName), RegistryValueKind.ExpandString); else sourceLogKey.SetValue("EventMessageFile", FixupPath(sourceData.MessageResourceFile), RegistryValueKind.ExpandString); if (!string.IsNullOrEmpty(sourceData.ParameterResourceFile)) sourceLogKey.SetValue("ParameterMessageFile", FixupPath(sourceData.ParameterResourceFile), RegistryValueKind.ExpandString); if (!string.IsNullOrEmpty(sourceData.CategoryResourceFile)) { sourceLogKey.SetValue("CategoryMessageFile", FixupPath(sourceData.CategoryResourceFile), RegistryValueKind.ExpandString); sourceLogKey.SetValue("CategoryCount", sourceData.CategoryCount, RegistryValueKind.DWord); } } private static string FixupPath(string path) { if (path[0] == '%') return path; else return Path.GetFullPath(path); } internal static string TryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) { if (insertionStrings.Length == 0) { return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings); } // If you pass in an empty array UnsafeTryFormatMessage will just pull out the message. string formatString = UnsafeTryFormatMessage(hModule, messageNum, Array.Empty<string>()); if (formatString == null) { return null; } int largestNumber = 0; for (int i = 0; i < formatString.Length; i++) { if (formatString[i] == '%') { if (formatString.Length > i + 1) { StringBuilder sb = new StringBuilder(); while (i + 1 < formatString.Length && char.IsDigit(formatString[i + 1])) { sb.Append(formatString[i + 1]); i++; } // move over the non number character that broke us out of the loop i++; if (sb.Length > 0) { int num = -1; if (int.TryParse(sb.ToString(), NumberStyles.None, CultureInfo.InvariantCulture, out num)) { largestNumber = Math.Max(largestNumber, num); } } } } } // Replacement strings are 1 indexed. if (largestNumber > insertionStrings.Length) { string[] newStrings = new string[largestNumber]; Array.Copy(insertionStrings, newStrings, insertionStrings.Length); for (int i = insertionStrings.Length; i < newStrings.Length; i++) { newStrings[i] = "%" + (i + 1); } insertionStrings = newStrings; } return UnsafeTryFormatMessage(hModule, messageNum, insertionStrings); } // FormatMessageW will AV if you don't pass in enough format strings. If you call TryFormatMessage we ensure insertionStrings // is long enough. You don't want to call this directly unless you're sure insertionStrings is long enough! internal static string UnsafeTryFormatMessage(SafeLibraryHandle hModule, uint messageNum, string[] insertionStrings) { string msg = null; int msgLen = 0; var buf = new char[1024]; int flags = Interop.Kernel32.FORMAT_MESSAGE_FROM_HMODULE | Interop.Kernel32.FORMAT_MESSAGE_ARGUMENT_ARRAY; IntPtr[] addresses = new IntPtr[insertionStrings.Length]; GCHandle[] handles = new GCHandle[insertionStrings.Length]; GCHandle stringsRoot = GCHandle.Alloc(addresses, GCHandleType.Pinned); if (insertionStrings.Length == 0) { flags |= Interop.Kernel32.FORMAT_MESSAGE_IGNORE_INSERTS; } try { for (int i = 0; i < handles.Length; i++) { handles[i] = GCHandle.Alloc(insertionStrings[i], GCHandleType.Pinned); addresses[i] = handles[i].AddrOfPinnedObject(); } int lastError = Interop.Errors.ERROR_INSUFFICIENT_BUFFER; while (msgLen == 0 && lastError == Interop.Errors.ERROR_INSUFFICIENT_BUFFER) { msgLen = Interop.Kernel32.FormatMessage( flags, hModule, messageNum, 0, buf, buf.Length, addresses); if (msgLen == 0) { lastError = Marshal.GetLastWin32Error(); if (lastError == Interop.Errors.ERROR_INSUFFICIENT_BUFFER) buf = new char[buf.Length * 2]; } } } catch { msgLen = 0; // return empty on failure } finally { for (int i = 0; i < handles.Length; i++) { if (handles[i].IsAllocated) handles[i].Free(); } stringsRoot.Free(); } if (msgLen > 0) { msg = msgLen > 1 && buf[msgLen - 1] == '\n' ? new string(buf, 0, msgLen - 2) : // chop off a single CR/LF pair from the end if there is one. FormatMessage always appends one extra. new string(buf, 0, msgLen); } return msg; } // CharIsPrintable used to be Char.IsPrintable, but Jay removed it and // is forcing people to use the Unicode categories themselves. Copied // the code here. private static bool CharIsPrintable(char c) { UnicodeCategory uc = char.GetUnicodeCategory(c); return (!(uc == UnicodeCategory.Control) || (uc == UnicodeCategory.Format) || (uc == UnicodeCategory.LineSeparator) || (uc == UnicodeCategory.ParagraphSeparator) || (uc == UnicodeCategory.OtherNotAssigned)); } internal static bool ValidLogName(string logName, bool ignoreEmpty) { // No need to trim here since the next check will verify that there are no spaces. // We need to ignore the empty string as an invalid log name sometimes because it can // be passed in from our default constructor. if (logName.Length == 0 && !ignoreEmpty) return false; //any space, backslash, asterisk, or question mark is bad //any non-printable characters are also bad foreach (char c in logName) if (!CharIsPrintable(c) || (c == '\\') || (c == '*') || (c == '?')) return false; return true; } public void WriteEntry(string message) { WriteEntry(message, EventLogEntryType.Information, (short)0, 0, null); } public static void WriteEntry(string source, string message) { WriteEntry(source, message, EventLogEntryType.Information, (short)0, 0, null); } public void WriteEntry(string message, EventLogEntryType type) { WriteEntry(message, type, (short)0, 0, null); } public static void WriteEntry(string source, string message, EventLogEntryType type) { WriteEntry(source, message, type, (short)0, 0, null); } public void WriteEntry(string message, EventLogEntryType type, int eventID) { WriteEntry(message, type, eventID, 0, null); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID) { WriteEntry(source, message, type, eventID, 0, null); } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category) { WriteEntry(message, type, eventID, category, null); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category) { WriteEntry(source, message, type, eventID, category, null); } public static void WriteEntry(string source, string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { log.WriteEntry(message, type, eventID, category, rawData); } } public void WriteEntry(string message, EventLogEntryType type, int eventID, short category, byte[] rawData) { _underlyingEventLog.WriteEntry(message, type, eventID, category, rawData); } public void WriteEvent(EventInstance instance, params object[] values) { WriteEvent(instance, null, values); } public void WriteEvent(EventInstance instance, byte[] data, params object[] values) { _underlyingEventLog.WriteEvent(instance, data, values); } public static void WriteEvent(string source, EventInstance instance, params object[] values) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { log.WriteEvent(instance, null, values); } } public static void WriteEvent(string source, EventInstance instance, byte[] data, params object[] values) { using (EventLogInternal log = new EventLogInternal(string.Empty, ".", CheckAndNormalizeSourceName(source))) { log.WriteEvent(instance, data, values); } } // The EventLog.set_Source used to do some normalization and throw some exceptions. We mimic that behavior here. private static string CheckAndNormalizeSourceName(string source) { if (source == null) source = string.Empty; // this 254 limit is the max length of a registry key. if (source.Length + EventLogKey.Length > 254) throw new ArgumentException(SR.Format(SR.ParameterTooLong, nameof(source), 254 - EventLogKey.Length)); return source; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== namespace System.Globalization { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; /* SSS_DROP_BEGIN */ /* SSS_WARNINGS_OFF */ /*=================================TaiwanCalendar========================== ** ** Taiwan calendar is based on the Gregorian calendar. And the year is an offset to Gregorian calendar. ** That is, ** Taiwan year = Gregorian year - 1911. So 1912/01/01 A.D. is Taiwan 1/01/01 ** ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1912/01/01 9999/12/31 ** Taiwan 01/01/01 8088/12/31 ============================================================================*/ /* SSS_WARNINGS_ON */ /* SSS_DROP_END */ [System.Runtime.InteropServices.ComVisible(true)] [Serializable] public class TaiwanCalendar: Calendar { // // The era value for the current era. // // Since // Gregorian Year = Era Year + yearOffset // When Gregorian Year 1912 is year 1, so that // 1912 = 1 + yearOffset // So yearOffset = 1911 //m_EraInfo[0] = new EraInfo(1, new DateTime(1912, 1, 1).Ticks, 1911, 1, GregorianCalendar.MaxYear - 1911); // Initialize our era info. static internal EraInfo[] taiwanEraInfo = new EraInfo[] { new EraInfo( 1, 1912, 1, 1, 1911, 1, GregorianCalendar.MaxYear - 1911) // era #, start year/month/day, yearOffset, minEraYear }; internal static volatile Calendar s_defaultInstance; internal GregorianCalendarHelper helper; /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of TaiwanCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new TaiwanCalendar(); } return (s_defaultInstance); } internal static readonly DateTime calendarMinValue = new DateTime(1912, 1, 1); [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MinSupportedDateTime { get { return (calendarMinValue); } } [System.Runtime.InteropServices.ComVisible(false)] public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } // Return the type of the Taiwan calendar. // [System.Runtime.InteropServices.ComVisible(false)] public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } public TaiwanCalendar() { try { new CultureInfo("zh-TW"); } catch (ArgumentException e) { throw new TypeInitializationException(this.GetType().FullName, e); } helper = new GregorianCalendarHelper(this, taiwanEraInfo); } internal override int ID { get { return (CAL_TAIWAN); } } public override DateTime AddMonths(DateTime time, int months) { return (helper.AddMonths(time, months)); } public override DateTime AddYears(DateTime time, int years) { return (helper.AddYears(time, years)); } public override int GetDaysInMonth(int year, int month, int era) { return (helper.GetDaysInMonth(year, month, era)); } public override int GetDaysInYear(int year, int era) { return (helper.GetDaysInYear(year, era)); } public override int GetDayOfMonth(DateTime time) { return (helper.GetDayOfMonth(time)); } public override DayOfWeek GetDayOfWeek(DateTime time) { return (helper.GetDayOfWeek(time)); } public override int GetDayOfYear(DateTime time) { return (helper.GetDayOfYear(time)); } public override int GetMonthsInYear(int year, int era) { return (helper.GetMonthsInYear(year, era)); } [SuppressMessage("Microsoft.Contracts", "CC1055")] // Skip extra error checking to avoid *potential* AppCompat problems. [System.Runtime.InteropServices.ComVisible(false)] public override int GetWeekOfYear(DateTime time, CalendarWeekRule rule, DayOfWeek firstDayOfWeek) { return (helper.GetWeekOfYear(time, rule, firstDayOfWeek)); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } public override int GetMonth(DateTime time) { return (helper.GetMonth(time)); } public override int GetYear(DateTime time) { return (helper.GetYear(time)); } public override bool IsLeapDay(int year, int month, int day, int era) { return (helper.IsLeapDay(year, month, day, era)); } public override bool IsLeapYear(int year, int era) { return (helper.IsLeapYear(year, era)); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // [System.Runtime.InteropServices.ComVisible(false)] public override int GetLeapMonth(int year, int era) { return (helper.GetLeapMonth(year, era)); } public override bool IsLeapMonth(int year, int month, int era) { return (helper.IsLeapMonth(year, month, era)); } public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { return (helper.ToDateTime(year, month, day, hour, minute, second, millisecond, era)); } public override int[] Eras { get { return (helper.Eras); } } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 99; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 99, helper.MaxYear)); } twoDigitYearMax = value; } } // For Taiwan calendar, four digit year is not used. // Therefore, for any two digit number, we just return the original number. public override int ToFourDigitYear(int year) { if (year <= 0) { throw new ArgumentOutOfRangeException("year", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); } Contract.EndContractBlock(); if (year > helper.MaxYear) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), 1, helper.MaxYear)); } return (year); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using Lucene.Net.Documents; using Lucene.Net.Support; using NUnit.Framework; using SimpleAnalyzer = Lucene.Net.Analysis.SimpleAnalyzer; using FileDocument = Lucene.Net.Demo.FileDocument; using Document = Lucene.Net.Documents.Document; using Directory = Lucene.Net.Store.Directory; using FSDirectory = Lucene.Net.Store.FSDirectory; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; namespace Lucene.Net.Index { /// <summary>JUnit adaptation of an older test case DocTest.</summary> [TestFixture] public class TestDoc:LuceneTestCase { /// <summary>Main for running test case by itself. </summary> [STAThread] public static void Main(System.String[] args) { // TestRunner.run(new TestSuite(typeof(TestDoc))); // {{Aroush-2.9}} how is this done in NUnit? } private System.IO.DirectoryInfo workDir; private System.IO.DirectoryInfo indexDir; private System.Collections.ArrayList files; /// <summary>Set the test case. This test case needs /// a few text files created in the current working directory. /// </summary> [SetUp] public override void SetUp() { base.SetUp(); workDir = new System.IO.DirectoryInfo(System.IO.Path.Combine(Path.GetTempPath(), "TestDoc")); System.IO.Directory.CreateDirectory(workDir.FullName); indexDir = new System.IO.DirectoryInfo(System.IO.Path.Combine(workDir.FullName, "testIndex")); System.IO.Directory.CreateDirectory(indexDir.FullName); Directory directory = FSDirectory.Open(indexDir); directory.Close(); files = new System.Collections.ArrayList(); files.Add(CreateOutput("test.txt", "This is the first test file")); files.Add(CreateOutput("test2.txt", "This is the second test file")); } private System.IO.DirectoryInfo CreateOutput(System.String name, System.String text) { System.IO.StreamWriter fw = null; System.IO.StreamWriter pw = null; try { System.IO.DirectoryInfo f = new System.IO.DirectoryInfo(System.IO.Path.Combine(workDir.FullName, name)); bool tmpBool; if (System.IO.File.Exists(f.FullName)) tmpBool = true; else tmpBool = System.IO.Directory.Exists(f.FullName); if (tmpBool) { bool tmpBool2; if (System.IO.File.Exists(f.FullName)) { System.IO.File.Delete(f.FullName); tmpBool2 = true; } else if (System.IO.Directory.Exists(f.FullName)) { System.IO.Directory.Delete(f.FullName); tmpBool2 = true; } else tmpBool2 = false; bool generatedAux = tmpBool2; } fw = new System.IO.StreamWriter(f.FullName, false, System.Text.Encoding.Default); pw = new System.IO.StreamWriter(fw.BaseStream, fw.Encoding); pw.WriteLine(text); return f; } finally { if (pw != null) { pw.Close(); } } } /// <summary>This test executes a number of merges and compares the contents of /// the segments created when using compound file or not using one. /// /// TODO: the original test used to print the segment contents to System.out /// for visual validation. To have the same effect, a new method /// checkSegment(String name, ...) should be created that would /// assert various things about the segment. /// </summary> [Test] public virtual void TestIndexAndMerge() { System.IO.MemoryStream sw = new System.IO.MemoryStream(); System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(sw); Directory directory = FSDirectory.Open(indexDir); IndexWriter writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); SegmentInfo si1 = IndexDoc(writer, "test.txt"); PrintSegment(out_Renamed, si1); SegmentInfo si2 = IndexDoc(writer, "test2.txt"); PrintSegment(out_Renamed, si2); writer.Close(); SegmentInfo siMerge = Merge(si1, si2, "merge", false); PrintSegment(out_Renamed, siMerge); SegmentInfo siMerge2 = Merge(si1, si2, "merge2", false); PrintSegment(out_Renamed, siMerge2); SegmentInfo siMerge3 = Merge(siMerge, siMerge2, "merge3", false); PrintSegment(out_Renamed, siMerge3); directory.Close(); out_Renamed.Close(); sw.Close(); System.String multiFileOutput = System.Text.ASCIIEncoding.ASCII.GetString(sw.ToArray()); //System.out.println(multiFileOutput); sw = new System.IO.MemoryStream(); out_Renamed = new System.IO.StreamWriter(sw); directory = FSDirectory.Open(indexDir); writer = new IndexWriter(directory, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED); si1 = IndexDoc(writer, "test.txt"); PrintSegment(out_Renamed, si1); si2 = IndexDoc(writer, "test2.txt"); PrintSegment(out_Renamed, si2); writer.Close(); siMerge = Merge(si1, si2, "merge", true); PrintSegment(out_Renamed, siMerge); siMerge2 = Merge(si1, si2, "merge2", true); PrintSegment(out_Renamed, siMerge2); siMerge3 = Merge(siMerge, siMerge2, "merge3", true); PrintSegment(out_Renamed, siMerge3); directory.Close(); out_Renamed.Close(); sw.Close(); System.String singleFileOutput = System.Text.ASCIIEncoding.ASCII.GetString(sw.ToArray()); Assert.AreEqual(multiFileOutput, singleFileOutput); } private SegmentInfo IndexDoc(IndexWriter writer, System.String fileName) { System.IO.FileInfo file = new System.IO.FileInfo(System.IO.Path.Combine(workDir.FullName, fileName)); Document doc = FileDocument.Document(file); doc.Add(new Field("contents", new System.IO.StreamReader(file.FullName))); writer.AddDocument(doc); writer.Commit(); return writer.NewestSegment(); } private SegmentInfo Merge(SegmentInfo si1, SegmentInfo si2, System.String merged, bool useCompoundFile) { SegmentReader r1 = SegmentReader.Get(true, si1, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR); SegmentReader r2 = SegmentReader.Get(true, si2, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR); SegmentMerger merger = new SegmentMerger(si1.dir, merged); merger.Add(r1); merger.Add(r2); merger.Merge(); merger.CloseReaders(); if (useCompoundFile) { System.Collections.Generic.ICollection<string> filesToDelete = merger.CreateCompoundFile(merged + ".cfs"); for (System.Collections.IEnumerator iter = filesToDelete.GetEnumerator(); iter.MoveNext(); ) { si1.dir.DeleteFile((System.String) iter.Current); } } return new SegmentInfo(merged, si1.docCount + si2.docCount, si1.dir, useCompoundFile, true); } private void PrintSegment(System.IO.StreamWriter out_Renamed, SegmentInfo si) { SegmentReader reader = SegmentReader.Get(true, si, IndexReader.DEFAULT_TERMS_INDEX_DIVISOR); for (int i = 0; i < reader.NumDocs(); i++) { out_Renamed.WriteLine(reader.Document(i)); } TermEnum tis = reader.Terms(); while (tis.Next()) { out_Renamed.Write(tis.Term); out_Renamed.WriteLine(" DF=" + tis.DocFreq()); TermPositions positions = reader.TermPositions(tis.Term); try { while (positions.Next()) { out_Renamed.Write(" doc=" + positions.Doc); out_Renamed.Write(" TF=" + positions.Freq); out_Renamed.Write(" pos="); out_Renamed.Write(positions.NextPosition()); for (int j = 1; j < positions.Freq; j++) out_Renamed.Write("," + positions.NextPosition()); out_Renamed.WriteLine(""); } } finally { positions.Close(); } } tis.Close(); reader.Close(); } } }
using FluentAssertions; using Xunit; namespace Meziantou.Framework.Tests; public class StringSearchUtilitiesTests { [Theory] [InlineData("", "", 0)] [InlineData("aa", "", 2)] [InlineData("", "aa", 2)] [InlineData("test", "Test", 1)] [InlineData("chien", "chienne", 2)] [InlineData("Cat", "Cat", 0)] [InlineData("Car", "Kart", 2)] public void Levenshtein_Tests(string word1, string word2, int expected) { StringSearchUtilities.Levenshtein(word1, word2).Should().Be(expected); } [Theory] [InlineData(0b101010u, 0b101010u, 0u)] [InlineData(0b010101u, 0b101010u, 6u)] [InlineData(0b1111u, 0b0u, 4u)] [InlineData(0b11111111u, 0b11110111u, 1u)] public void Hamming_Uint32Tests(uint word1, uint word2, uint expected) { StringSearchUtilities.Hamming(word1, word2).Should().Be(expected); } [Theory] [InlineData("ramer", "cases", 3)] public void Hamming_StringTests(string word1, string word2, int expected) { StringSearchUtilities.Hamming(word1, word2).Should().Be(expected); } [Fact] public void Soundex_Test() { var soundex = StringSearchUtilities.Soundex("", new Dictionary<char, byte>()); soundex.Should().Be("0000"); } [Theory] [InlineData("R163", "Robert")] [InlineData("R163", "Rupert")] [InlineData("R150", "Rubin")] [InlineData("H400", "Hello")] [InlineData("E460", "Euler")] [InlineData("E460", "Ellery")] [InlineData("G200", "Gauss")] [InlineData("G200", "Ghosh")] [InlineData("H416", "Hilbert")] [InlineData("H416", "Heilbronn")] [InlineData("K530", "Knuth")] [InlineData("K530", "Kant")] [InlineData("L300", "Ladd")] [InlineData("L300", "Lloyd")] [InlineData("L222", "Lukasiewicz")] [InlineData("L222", "Lissajous")] [InlineData("L222", "Lishsajwjous")] [InlineData("A462", "Allricht")] [InlineData("E166", "Eberhard")] [InlineData("E521", "Engebrethson")] [InlineData("H512", "Heimbach")] [InlineData("H524", "Hanselmann")] [InlineData("H524", "Henzelmann")] [InlineData("H431", "Hildebrand")] [InlineData("K152", "Kavanagh")] [InlineData("L530", " Lind, Van")] [InlineData("L222", "Lukaschowsky")] [InlineData("M235", "McDonnell")] [InlineData("M200", "McGee")] [InlineData("O165", "O'Brien")] [InlineData("O155", "Opnian")] [InlineData("O155", "Oppenheimer")] [InlineData("S460", "Swhgler")] [InlineData("R355", "Riedemanas")] [InlineData("Z300", "Zita")] [InlineData("Z325", "Zitzmeinn")] public void SoundexEnglish_Test(string expected, string value) { StringSearchUtilities.SoundexEnglish(value).Should().Be(expected); } [Theory] [InlineData(" ", "")] [InlineData("MRTN", "MARTIN")] [InlineData("BRNR", "BERNARD")] [InlineData("FR ", "FAURE")] [InlineData("PRZ ", "PEREZ")] [InlineData("GR ", "GROS")] [InlineData("CHP ", "CHAPUIS ")] [InlineData("BYR ", "BOYER")] [InlineData("KTR ", "GAUTHIER")] [InlineData("RY ", "REY")] [InlineData("BRTL", "BARTHELEMY")] [InlineData("ANR ", "HENRY")] [InlineData("MLN ", "MOULIN")] [InlineData("RS ", "ROUSSEAU")] [InlineData("RS ", "YROUSSYEAU")] public void Soundex2_Test(string expected, string value) { StringSearchUtilities.Soundex2(value).Should().Be(expected); } [Theory] [InlineData("T830", "test")] [InlineData("H560", "Henry")] [InlineData("R000", "ray")] [InlineData("R000", "rey")] [InlineData("R000", "REY")] [InlineData("R000", "RAY")] public void SoundexFrench_Test(string expected, string value) { StringSearchUtilities.SoundexFrench(value).Should().Be(expected); } [Theory] [InlineData("TSTN", "testing")] [InlineData("0", "The")] [InlineData("KK", "quick")] [InlineData("BRN", "brown")] [InlineData("FKS", "fox")] [InlineData("JMPT", "jumped")] [InlineData("OFR", "over")] [InlineData("LS", "lazy")] [InlineData("TKS", "dogs")] [InlineData("TMP", "dump")] [InlineData("XFKS", "cheveux")] [InlineData("SKFK", "scheveux")] [InlineData("SFKS", "sciveux")] [InlineData("SKKF", "sccuveux")] [InlineData("KHLN", "khalens")] [InlineData("SFKS", "scyveux")] [InlineData("BSN", "buisson")] [InlineData("BB", "bebe")] [InlineData("LXS", "lacias")] [InlineData("TJKS", "dijkstra")] [InlineData("TJKS", "djikstra")] [InlineData("JKST", "dgikstra")] [InlineData("JKST", "dgekstra")] [InlineData("TKKS", "dgakstra")] [InlineData("KST", "ghost")] [InlineData("0R", "through")] [InlineData("NM", "gnome")] [InlineData("KSK", "chzkou")] [InlineData("BLKK", "blaggyguest")] [InlineData("AXXX", "atiatiotch")] public void Metaphone_Test(string expected, string value) { StringSearchUtilities.Metaphone(value).Should().Be(expected); } [Theory] [InlineData("Case", "case")] [InlineData("CASE", "Case")] [InlineData("caSe", "cAsE")] [InlineData("cookie", "quick")] [InlineData("T", "T")] [InlineData("Lorenza", "Lawrence")] [InlineData("Aero", "Eure")] [MemberData(nameof(MetaphoneList))] public void Metaphone_Test2(string value, string otherValue) { var v1 = StringSearchUtilities.Metaphone(value); var v2 = StringSearchUtilities.Metaphone(otherValue); v2.Should().Be(v1); } public static IEnumerable<object[]> MetaphoneList() { foreach (var item in new[] { "Wade", "Wait", "Waite", "Wat", "Whit", "Wiatt", "Wit", "Wittie", "Witty", "Wood", "Woodie", "Woody" }) yield return new object[] { "White", item }; foreach (var item in new[] { "Ailbert", "Alberik", "Albert", "Alberto", "Albrecht" }) yield return new object[] { "Albert", item }; foreach (var item in new[] { "Cahra", "Cara", "Carey", "Cari", "Caria", "Carie", "Caro", "Carree", "Carri", "Carrie", "Carry", "Cary", "Cora", "Corey", "Cori", "Corie", "Correy", "Corri", "Corrie", "Corry", "Cory", "Gray", "Kara", "Kare", "Karee", "Kari", "Karia", "Karie", "Karrah", "Karrie", "Karry", "Kary", "Keri", "Kerri", "Kerrie", "Kerry", "Kira", "Kiri", "Kora", "Kore", "Kori", "Korie", "Korrie", "Korry", }) { yield return new object[] { "Gary", item }; } foreach (var item in new[] { "Gena", "Gene", "Genia", "Genna", "Genni", "Gennie", "Genny", "Giana", "Gianna", "Gina", "Ginni", "Ginnie", "Ginny", "Jaine", "Jan", "Jana", "Jane", "Janey", "Jania", "Janie", "Janna", "Jany", "Jayne", "Jean", "Jeana", "Jeane", "Jeanie", "Jeanna", "Jeanne", "Jeannie", "Jen", "Jena", "Jeni", "Jenn", "Jenna", "Jennee", "Jenni", "Jennie", "Jenny", "Jinny", "Jo Ann", "Jo-Ann", "Jo-Anne", "Joan", "Joana", "Joane", "Joanie", "Joann", "Joanna", "Joanne", "Joeann", "Johna", "Johnna", "Joni", "Jonie", "Juana", "June", "Junia", "Junie", }) { yield return new object[] { "John", item }; } foreach (var item in new[] { "Mair", "Maire", "Mara", "Mareah", "Mari", "Maria", "Marie", "Mary", "Maura", "Maure", "Meara", "Merrie", "Merry", "Mira", "Moira", "Mora", "Moria", "Moyra", "Muire", "Myra", "Myrah", }) { yield return new object[] { "Mary", item }; } foreach (var item in new[] { "Pearcy", "Perris", "Piercy", "Pierz", "Pryse" }) yield return new object[] { "Paris", item }; foreach (var item in new[] { "Peadar", "Peder", "Pedro", "Peter", "Petr", "Peyter", "Pieter", "Pietro", "Piotr" }) yield return new object[] { "Peter", item }; foreach (var item in new[] { "Ray", "Rey", "Roi", "Roy", "Ruy" }) yield return new object[] { "Ray", item }; foreach (var item in new[] { "Siusan", "Sosanna", "Susan", "Susana", "Susann", "Susanna", "Susannah", "Susanne", "Suzann", "Suzanna", "Suzanne", "Zuzana" }) yield return new object[] { "Susan", item }; foreach (var item in new[] { "Rota", "Rudd", "Ryde" }) yield return new object[] { "Wright", item }; foreach (var item in new[] { "Celene", "Celina", "Celine", "Selena", "Selene", "Selina", "Seline", "Suellen", "Xylina" }) yield return new object[] { "Xalan", item }; } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; #if !__MonoCS__ using System.Deployment.Application; #endif using System.Diagnostics; using System.Drawing; using System.Drawing.Design; using System.IO; using System.Reflection; using System.Xml; using System.Xml.Serialization; using AgentInterface; namespace Agent { public enum EOptionsVersion { OriginalVersion = 3, NewBarColors = 4, CacheManagement = 5, NewStartupColor = 6, AdjustedProgressionColors = 7, TweaksToTheNumberOfThreads = 8, FixTheOptionsReset = 9, DeployNewFarmMachineNames = 10, BumpTheJobsToKeepCount = 11, MoveTheDefaultCacheFolder = 12, ChangeCoordinatorLocation = 13, AddPerformanceMonitoringDisable = 14, MakeLocalJobsProcessorsCountLimited = 15, Current = MakeLocalJobsProcessorsCountLimited }; public class EnumedCollectionPropertyDescriptor<E, T> : PropertyDescriptor { private EnumedCollection<E, T> Collection = null; private int Index = -1; public EnumedCollectionPropertyDescriptor( EnumedCollection<E, T> InCollection, int InIndex ) : base( "#" + InIndex.ToString(), null ) { Collection = InCollection; Index = InIndex; } public override AttributeCollection Attributes { get { return( new AttributeCollection( null ) ); } } public override bool CanResetValue( object component ) { return( true ); } public override Type ComponentType { get { return( Collection.GetType() ); } } public override string Description { get { return ( "The colour representing this state of the job." ); } } public override string DisplayName { get { return( Enum.GetName( typeof( E ), Index ) ); } } public override object GetValue( object component ) { return( Collection[Index] ); } public override bool IsReadOnly { get { return( false ); } } public override string Name { get { return( "#" + Index.ToString() ); } } public override Type PropertyType { get { return( typeof( T ) ); } } public override void ResetValue( object component ) { } public override bool ShouldSerializeValue( object component ) { return( true ); } public override void SetValue( object component, object value ) { Collection[Index] = ( T )value; } } public class EnumedCollection<E, T> : CollectionBase, ICustomTypeDescriptor { public void Add( T BarColour ) { List.Add( BarColour ); } public void Remove( T BarColour ) { List.Remove( BarColour ); } public T this[int Index] { get { return ( ( T )List[Index] ); } set { List[Index] = ( T )value; } } // Implementation of interface ICustomTypeDescriptor public String GetClassName() { return TypeDescriptor.GetClassName( this, true ); } public AttributeCollection GetAttributes() { return TypeDescriptor.GetAttributes( this, true ); } public String GetComponentName() { return TypeDescriptor.GetComponentName( this, true ); } public TypeConverter GetConverter() { return TypeDescriptor.GetConverter( this, true ); } public EventDescriptor GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent( this, true ); } public PropertyDescriptor GetDefaultProperty() { return TypeDescriptor.GetDefaultProperty( this, true ); } public object GetEditor( Type editorBaseType ) { return TypeDescriptor.GetEditor( this, editorBaseType, true ); } public EventDescriptorCollection GetEvents( Attribute[] attributes ) { return TypeDescriptor.GetEvents( this, attributes, true ); } public EventDescriptorCollection GetEvents() { return TypeDescriptor.GetEvents( this, true ); } public object GetPropertyOwner( PropertyDescriptor pd ) { return this; } public PropertyDescriptorCollection GetProperties( Attribute[] attributes ) { return GetProperties(); } public PropertyDescriptorCollection GetProperties() { PropertyDescriptorCollection PropertyDescriptions = new PropertyDescriptorCollection( null ); for( int i = 0; i < List.Count; i++ ) { EnumedCollectionPropertyDescriptor<E, T> PropertyDescriptor = new EnumedCollectionPropertyDescriptor<E, T>( this, i ); PropertyDescriptions.Add( PropertyDescriptor ); } return( PropertyDescriptions ); } } internal class EnumedCollectionConverter : ExpandableObjectConverter { public override object ConvertTo( ITypeDescriptorContext Context, System.Globalization.CultureInfo Culture, object Value, Type DestType ) { if( DestType == typeof( string ) && ( Value is EnumedCollection<EProgressionState, Color> ) ) { return( "Progress bar colors" ); } return base.ConvertTo( Context, Culture, Value, DestType ); } } public class SuppressCollectionEditor : UITypeEditor { public override UITypeEditorEditStyle GetEditStyle( ITypeDescriptorContext context ) { return( UITypeEditorEditStyle.None ); } } public class SerialisableColour { public SerialisableColour() { Colour = Color.Black; } public SerialisableColour( Color InColour ) { Colour = InColour; } [XmlIgnore] public Color Colour { get { return ( Color.FromArgb( LocalColour ) ); } set { LocalColour = value.ToArgb(); } } [XmlAttribute] public int LocalColour = 0; } public class SettableOptions { [CategoryAttribute( "Log Settings" )] [DescriptionAttribute( "The amount of text spewed to the window." )] [DefaultValueAttribute( EVerbosityLevel.Informative )] public EVerbosityLevel Verbosity { get { return ( LocalVerbosity ); } set { LocalVerbosity = value; } } [XmlEnumAttribute] private EVerbosityLevel LocalVerbosity = EVerbosityLevel.Informative; [CategoryAttribute( "Log Settings" )] [DescriptionAttribute( "The font used in all Swarm Agent dialogs." )] [DefaultValueAttribute( SwarmAgentWindow.DialogFont.Tahoma )] public SwarmAgentWindow.DialogFont TextFont { get { return ( LocalTextFont ); } set { LocalTextFont = value; } } [XmlAttribute] private SwarmAgentWindow.DialogFont LocalTextFont = SwarmAgentWindow.DialogFont.Tahoma; [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "Whether to allow only distribution of jobs and tasks from this agent (no local execution)." )] [DefaultValueAttribute( false )] public bool AvoidLocalExecution { get { return ( LocalAvoidLocalExecution ); } set { LocalAvoidLocalExecution = value; } } [XmlAttribute] private bool LocalAvoidLocalExecution = false; [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "Enables Standalone mode, which disables the distribution system for both outgoing and incoming tasks." )] [DefaultValueAttribute( false )] public bool EnableStandaloneMode { get { return ( LocalEnableStandaloneMode ); } set { LocalEnableStandaloneMode = value; } } [XmlAttribute] private bool LocalEnableStandaloneMode = false; [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "[Advanced] The remote machine filter string (' ', ',' or ';' delimited)." )] [DefaultValueAttribute( "RENDER*" )] public string AllowedRemoteAgentNames { get { return ( LocalAllowedRemoteAgentNames ); } set { LocalAllowedRemoteAgentNames = value; } } [XmlTextAttribute] private string LocalAllowedRemoteAgentNames = "RENDER*"; [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "[Advanced] The name of the agent group jobs can be distributed to." )] [DefaultValueAttribute( "DefaultDeployed" )] public string AllowedRemoteAgentGroup { get { return ( LocalAllowedRemoteAgentGroup ); } set { LocalAllowedRemoteAgentGroup = value; } } [XmlTextAttribute] private string LocalAllowedRemoteAgentGroup = "DefaultDeployed"; [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "[Advanced] The name of the agent group to which this machine belongs." )] [DefaultValueAttribute( "Default" )] public string AgentGroupName { get { return ( LocalAgentGroupName ); } set { LocalAgentGroupName = value; } } [XmlTextAttribute] #if !__MonoCS__ private string LocalAgentGroupName = ( ApplicationDeployment.IsNetworkDeployed ? "DefaultDeployed" : "Default" ); #else private string LocalAgentGroupName = "Default"; #endif [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "[Advanced] The name of the machine hosting the Coordinator." )] [DefaultValueAttribute( "RENDER-01" )] public string CoordinatorRemotingHost { get { return ( LocalCoordinatorRemotingHost ); } set { LocalCoordinatorRemotingHost = value; } } [XmlTextAttribute] private string LocalCoordinatorRemotingHost = "RENDER-01"; [CategoryAttribute( "Cache Settings" )] [DescriptionAttribute( "The location of the cache folder. This should be on a fast drive with plenty of free space." )] [DefaultValueAttribute( "C:\\SwarmCache" )] public string CacheFolder { get { return ( LocalCacheFolder ); } set { LocalCacheFolder = value; } } [XmlTextAttribute] private string LocalCacheFolder = "C:\\SwarmCache"; [CategoryAttribute( "Cache Settings" )] [DescriptionAttribute( "The number of previous jobs to keep the logs and output data for." )] [DefaultValueAttribute( 10 )] public Int32 MaximumJobsToKeep { get { return ( LocalMaximumJobsToKeep ); } set { LocalMaximumJobsToKeep = value; } } [XmlTextAttribute] private Int32 LocalMaximumJobsToKeep = 10; [CategoryAttribute( "Cache Settings" )] [DescriptionAttribute( "The approximate maximum size, in gigabytes, of the cache folder." )] [DefaultValueAttribute( 10 )] public Int32 MaximumCacheSize { get { return ( LocalMaximumCacheSize ); } set { LocalMaximumCacheSize = value; } } [XmlTextAttribute] private Int32 LocalMaximumCacheSize = 10; [CategoryAttribute( "General Settings" )] [DescriptionAttribute( "If enabled, brings the Agent window to the front when a Job is started." )] [DefaultValueAttribute( true )] public bool BringToFront { get { return ( LocalBringToFront ); } set { LocalBringToFront = value; } } [XmlEnumAttribute] private bool LocalBringToFront = false; [CategoryAttribute( "Visualizer Settings" )] [DescriptionAttribute( "The colors used to draw the progress bars." )] [Editor( typeof( SuppressCollectionEditor ), typeof( UITypeEditor ) )] [TypeConverter( typeof( EnumedCollectionConverter ) )] [XmlIgnore] public EnumedCollection<EProgressionState, Color> VisualizerColors { get { return LocalColours; } } private EnumedCollection<EProgressionState, Color> LocalColours = new EnumedCollection<EProgressionState, Color>(); [BrowsableAttribute( false )] public List<SerialisableColour> SerialisableColours = new List<SerialisableColour>(); [CategoryAttribute( "Developer Settings" )] [DescriptionAttribute( "[DEVELOPER AND QA USE ONLY] If enabled, shows the developer menu." )] [DefaultValueAttribute( false )] public bool ShowDeveloperMenu { get { return ( LocalShowDeveloperMenu ); } set { LocalShowDeveloperMenu = value; } } [XmlEnumAttribute] private bool LocalShowDeveloperMenu = false; /* * State variables that do not appear in the property grid, but are still serialized out */ [BrowsableAttribute( false )] public int OptionsVersion { get { return ( LocalOptionsVersion ); } set { LocalOptionsVersion = value; } } [XmlAttribute] private int LocalOptionsVersion = (int)EOptionsVersion.Current; [BrowsableAttribute( false )] public Point WindowLocation { get { return ( LocalWindowLocation ); } set { LocalWindowLocation = value; } } [XmlAttribute] private Point LocalWindowLocation = new Point( 0, 0 ); [BrowsableAttribute( false )] public Size WindowSize { get { return ( LocalWindowSize ); } set { LocalWindowSize = value; } } [XmlAttribute] private Size LocalWindowSize = new Size( 768, 768 ); [BrowsableAttribute( false )] public int AgentTabIndex { get { return ( LocalAgentTabIndex ); } set { LocalAgentTabIndex = value; } } [XmlAttribute] private int LocalAgentTabIndex = 0; [BrowsableAttribute( false )] public float VisualiserZoomLevel { get { return ( LocalVisualiserZoomLevel ); } set { LocalVisualiserZoomLevel = value; } } [XmlAttribute] private float LocalVisualiserZoomLevel = 4.0f; /* * Set up any required default states */ private void SetDefaults() { Verbosity = EVerbosityLevel.Informative; TextFont = SwarmAgentWindow.DialogFont.Tahoma; AvoidLocalExecution = false; EnableStandaloneMode = false; AllowedRemoteAgentNames = "RENDER*"; AllowedRemoteAgentGroup = "DefaultDeployed"; #if !__MonoCS__ AgentGroupName = ( ApplicationDeployment.IsNetworkDeployed ? "DefaultDeployed" : "Default" ); #else AgentGroupName = "Default"; #endif #if !__MonoCS__ // The cache folder location depends on how the Agent is deployed if( ApplicationDeployment.IsNetworkDeployed ) { // If we're network deployed, we can't make assumptions about the drives available, // so stick with a reasonable default string LocationRoot = Path.GetPathRoot( Assembly.GetExecutingAssembly().Location ); if( LocationRoot != null ) { // Base it at the root of the drive this executable is running from CacheFolder = Path.Combine( LocationRoot, "SwarmCache" ); } else { // The old stand-by... CacheFolder = "C:\\SwarmCache"; } } else #endif if ( AgentApplication.OptionsFolder.Length > 0 ) { // If an options folder was specified, set the default CacheFolder to be within it CacheFolder = Path.Combine(AgentApplication.OptionsFolder, "SwarmCache"); } else { // Otherwise, keep the cache close to the Agent using it so that it's easy to // locate, easy to end up on the faster drive in the system, and easier to // delete when removing the Agent CacheFolder = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location ) + "/SwarmCache"; } MaximumJobsToKeep = 5; MaximumCacheSize = 10; BringToFront = true; ShowDeveloperMenu = false; SerialisableColours.Clear(); SerialisableColours.Add( new SerialisableColour( Color.White ) ); // PROGSTATE_TaskTotal SerialisableColours.Add( new SerialisableColour( Color.White ) ); // PROGSTATE_TasksInProgress SerialisableColours.Add( new SerialisableColour( Color.White ) ); // PROGSTATE_TasksCompleted SerialisableColours.Add( new SerialisableColour( Color.White ) ); // PROGSTATE_Idle SerialisableColours.Add( new SerialisableColour( Color.DarkGray ) ); // PROGSTATE_InstigatorConnected, SerialisableColours.Add( new SerialisableColour( Color.DarkGray ) ); // PROGSTATE_RemoteConnected, SerialisableColours.Add( new SerialisableColour( Color.DarkGray ) ); // PROGSTATE_Exporting, SerialisableColours.Add( new SerialisableColour( Color.LightGray ) ); // PROGSTATE_BeginJob, SerialisableColours.Add( new SerialisableColour( Color.White ) ); // PROGSTATE_Blocked, SerialisableColours.Add( new SerialisableColour( Color.DarkRed ) ); // PROGSTATE_Preparing0, SerialisableColours.Add( new SerialisableColour( Color.DarkRed ) ); // PROGSTATE_Preparing1, SerialisableColours.Add( new SerialisableColour( Color.Chocolate ) ); // PROGSTATE_Preparing2, SerialisableColours.Add( new SerialisableColour( Color.Chocolate ) ); // PROGSTATE_Preparing3, SerialisableColours.Add( new SerialisableColour( Color.DarkBlue ) ); // PROGSTATE_Processing0, SerialisableColours.Add( new SerialisableColour( Color.DarkBlue ) ); // PROGSTATE_Processing1, SerialisableColours.Add( new SerialisableColour( Color.DarkBlue ) ); // PROGSTATE_Processing2, SerialisableColours.Add( new SerialisableColour( Color.DarkBlue ) ); // PROGSTATE_Processing3, SerialisableColours.Add( new SerialisableColour( Color.DarkBlue ) ); // PROGSTATE_FinishedProcessing0, SerialisableColours.Add( new SerialisableColour( Color.DarkBlue ) ); // PROGSTATE_FinishedProcessing1, SerialisableColours.Add( new SerialisableColour( Color.LightGreen ) ); // PROGSTATE_FinishedProcessing2, SerialisableColours.Add( new SerialisableColour( Color.Green ) ); // PROGSTATE_FinishedProcessing3, SerialisableColours.Add( new SerialisableColour( Color.Cyan ) ); // PROGSTATE_ExportingResults, SerialisableColours.Add( new SerialisableColour( Color.Purple ) ); // PROGSTATE_ImportingResults, SerialisableColours.Add( new SerialisableColour( Color.Green ) ); // PROGSTATE_Finished, SerialisableColours.Add( new SerialisableColour( Color.Black ) ); // PROGSTATE_RemoteDisconnected SerialisableColours.Add( new SerialisableColour( Color.Black ) ); // PROGSTATE_InstigatorDisconnected OptionsVersion = (int)EOptionsVersion.Current; } /* * Validate the collections */ private void Validate() { if( OptionsVersion < (int)EOptionsVersion.Current || SerialisableColours.Count == 0 ) { SetDefaults(); } // Ensure we have enough colours for the enum for( int Index = SerialisableColours.Count; Index <= ( int )EProgressionState.InstigatorDisconnected; Index++ ) { SerialisableColours.Add( new SerialisableColour( Color.Black ) ); } } /* * Copy the property grid values to a serializable version */ public void PreSave() { // Copy the property grid friendly data to the xml friendly data // (should not be required) SerialisableColours.Clear(); foreach( Color Colour in VisualizerColors ) { SerialisableColours.Add( new SerialisableColour( Colour ) ); } } /* * Fix up anything that can't the automatically serialized */ public void PostLoad() { // Make sure the loaded data is valid Validate(); // Copy the xml friendly data to the property grid friendly data // (should not be required) VisualizerColors.Clear(); foreach( SerialisableColour Colour in SerialisableColours ) { VisualizerColors.Add( Colour.Colour ); } } } // A limited range of values for the process priority enum public enum AgentProcessPriorityClass { Normal = ProcessPriorityClass.Normal, Idle = ProcessPriorityClass.Idle, BelowNormal = ProcessPriorityClass.BelowNormal, AboveNormal = ProcessPriorityClass.AboveNormal } public class SettableDeveloperOptions { [CategoryAttribute( "Developer Settings" )] [DescriptionAttribute( "[DEVELOPER AND QA USE ONLY] Enables a distribution mode which attempts to reproduce the distribution behavior of the last Job." )] [DefaultValueAttribute( false )] public bool ReplayLastDistribution { get { return ( LocalReplayLastDistribution ); } set { LocalReplayLastDistribution = value; } } [XmlAttribute] private bool LocalReplayLastDistribution = false; [CategoryAttribute("Local Performance Settings")] [DescriptionAttribute("Whether to enable local performance monitoring")] public bool LocalEnableLocalPerformanceMonitoring { get { return (PrivateLocalEnableLocalPerformanceMonitoring); } set { PrivateLocalEnableLocalPerformanceMonitoring = value; } } [XmlAttribute] private bool PrivateLocalEnableLocalPerformanceMonitoring = true; [CategoryAttribute("Local Performance Settings")] [DescriptionAttribute( "The number of processors to make available to locally initiated jobs" )] public int LocalJobsDefaultProcessorCount { get { return ( PrivateLocalJobsDefaultProcessorCount ); } set { PrivateLocalJobsDefaultProcessorCount = value; } } [XmlAttribute] private int PrivateLocalJobsDefaultProcessorCount = GetDefaultLocalJobsDefaultProcessorCount(); [CategoryAttribute( "Local Performance Settings" )] [DescriptionAttribute( "The default priority for locally initiated jobs" )] public AgentProcessPriorityClass LocalJobsDefaultProcessPriority { get { return ( PrivateLocalJobsDefaultProcessPriority ); } set { PrivateLocalJobsDefaultProcessPriority = value; } } [XmlAttribute] private AgentProcessPriorityClass PrivateLocalJobsDefaultProcessPriority = AgentProcessPriorityClass.BelowNormal; [CategoryAttribute( "Local Performance Settings" )] [DescriptionAttribute( "The number of processors to make available to remotely initiated jobs" )] public int RemoteJobsDefaultProcessorCount { get { return ( PrivateRemoteJobsDefaultProcessorCount ); } set { PrivateRemoteJobsDefaultProcessorCount = value; } } [XmlAttribute] private int PrivateRemoteJobsDefaultProcessorCount = GetDefaultRemoteJobsDefaultProcessorCount(); [CategoryAttribute( "Local Performance Settings" )] [DescriptionAttribute( "The default priority for remotely initiated jobs" )] public AgentProcessPriorityClass RemoteJobsDefaultProcessPriority { get { return ( PrivateRemoteJobsDefaultProcessPriority ); } set { PrivateRemoteJobsDefaultProcessPriority = value; } } [XmlAttribute] private AgentProcessPriorityClass PrivateRemoteJobsDefaultProcessPriority = AgentProcessPriorityClass.Idle; [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "The amount of time to wait before forefully killing a Job executable after the Job is closed (in seconds). Set to anything < 0 for an infinite timeout." )] [DefaultValueAttribute( 5 )] public int JobExecutableTimeout { get { return ( LocalJobExecutableTimeout ); } set { LocalJobExecutableTimeout = value; } } [XmlAttribute] private int LocalJobExecutableTimeout = 5; [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "The amount of time to wait before considering a remote Agent dropped (in seconds). Set to anything < 0 for an infinite timeout." )] [DefaultValueAttribute( 30 )] public int RemoteAgentTimeout { get { return ( LocalRemoteAgentTimeout ); } set { LocalRemoteAgentTimeout = value; } } [XmlAttribute] private int LocalRemoteAgentTimeout = 30; [CategoryAttribute( "Distribution Settings" )] [DescriptionAttribute( "[Advanced] Enables auto updating for deployed agents." )] [DefaultValueAttribute( true )] public bool UpdateAutomatically { get { return ( LocalUpdateAutomatically ); } set { LocalUpdateAutomatically = value; } } [XmlTextAttribute] #if !__MonoCS__ private bool LocalUpdateAutomatically = ( ApplicationDeployment.IsNetworkDeployed ? true : false ); #else private bool LocalUpdateAutomatically = false; #endif [CategoryAttribute( "Log Settings" )] [DescriptionAttribute( "The maximum number of lines of output from a job application before it truncates what goes to the window. All of the output is written to the log on disk." )] [DefaultValueAttribute( 1000 )] public Int32 MaximumJobApplicationLogLines { get { return ( LocalMaximumJobApplicationLogLines ); } set { LocalMaximumJobApplicationLogLines = value; } } [XmlAttribute] private Int32 LocalMaximumJobApplicationLogLines = 1000; /* * State variables that do not appear in the property grid, but are still serialized out */ [BrowsableAttribute( false )] public int OptionsVersion { get { return ( LocalOptionsVersion ); } set { LocalOptionsVersion = value; } } [XmlAttribute] private int LocalOptionsVersion = ( int )EOptionsVersion.Current; /** * Gets allowed processors count on this machine for local tasks. * * This value can be lass than logical processors count as we don't * want to block the editor on user's machine. * * @returns Allowed processors count. */ private static Int32 GetAllowedProcessorCount() { const Int32 NumUnusedSwarmThreads = 2; Int32 NumVirtualCores = Environment.ProcessorCount; Int32 NumThreads = NumVirtualCores - NumUnusedSwarmThreads; // On machines with few cores, each core will have a massive impact on build times, so we prioritize build latency over editor performance during the build if (NumVirtualCores <= 4) { NumThreads = NumVirtualCores - 1; } return Math.Max(1, NumThreads); } private static Int32 GetDefaultLocalJobsDefaultProcessorCount() { return #if !__MonoCS__ ApplicationDeployment.IsNetworkDeployed ? Environment.ProcessorCount : GetAllowedProcessorCount(); #else GetAllowedProcessorCount(); #endif } private static Int32 GetDefaultRemoteJobsDefaultProcessorCount() { return Environment.ProcessorCount; } /* * Set up any required default states */ private void SetDefaults() { ReplayLastDistribution = false; LocalEnableLocalPerformanceMonitoring = true; LocalJobsDefaultProcessorCount = GetDefaultLocalJobsDefaultProcessorCount(); LocalJobsDefaultProcessPriority = AgentProcessPriorityClass.BelowNormal; RemoteJobsDefaultProcessorCount = GetDefaultRemoteJobsDefaultProcessorCount(); RemoteJobsDefaultProcessPriority = AgentProcessPriorityClass.Idle; JobExecutableTimeout = 5; RemoteAgentTimeout = 30; #if !__MonoCS__ UpdateAutomatically = ( ApplicationDeployment.IsNetworkDeployed ? true : false ); #else UpdateAutomatically = false; #endif MaximumJobApplicationLogLines = 1000; OptionsVersion = ( int )EOptionsVersion.Current; } /* * Validate the collections */ private void Validate() { if( OptionsVersion < ( int )EOptionsVersion.Current ) { SetDefaults(); } } /* * Copy the property grid values to a serializable version */ public void PreSave() { } /* * Fix up anything that can't the automatically serialized */ public void PostLoad() { // Make sure the loaded data is valid Validate(); } } }
using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; namespace SelfLoadSoftDelete.Business.ERCLevel { /// <summary> /// H07Level1111ReChild (editable child object).<br/> /// This is a generated base class of <see cref="H07Level1111ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="H06Level111"/> collection. /// </remarks> [Serializable] public partial class H07Level1111ReChild : BusinessBase<H07Level1111ReChild> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Level_1_1_1_1_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Level_1_1_1_1_Child_NameProperty = RegisterProperty<string>(p => p.Level_1_1_1_1_Child_Name, "Level_1_1_1_1 Child Name"); /// <summary> /// Gets or sets the Level_1_1_1_1 Child Name. /// </summary> /// <value>The Level_1_1_1_1 Child Name.</value> public string Level_1_1_1_1_Child_Name { get { return GetProperty(Level_1_1_1_1_Child_NameProperty); } set { SetProperty(Level_1_1_1_1_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="H07Level1111ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="H07Level1111ReChild"/> object.</returns> internal static H07Level1111ReChild NewH07Level1111ReChild() { return DataPortal.CreateChild<H07Level1111ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="H07Level1111ReChild"/> object, based on given parameters. /// </summary> /// <param name="cLarentID2">The CLarentID2 parameter of the H07Level1111ReChild to fetch.</param> /// <returns>A reference to the fetched <see cref="H07Level1111ReChild"/> object.</returns> internal static H07Level1111ReChild GetH07Level1111ReChild(int cLarentID2) { return DataPortal.FetchChild<H07Level1111ReChild>(cLarentID2); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="H07Level1111ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> private H07Level1111ReChild() { // Prevent direct creation // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="H07Level1111ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="H07Level1111ReChild"/> object from the database, based on given criteria. /// </summary> /// <param name="cLarentID2">The CLarent ID2.</param> protected void Child_Fetch(int cLarentID2) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("GetH07Level1111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@CLarentID2", cLarentID2).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, cLarentID2); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } BusinessRules.CheckRules(); } } /// <summary> /// Loads a <see cref="H07Level1111ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Level_1_1_1_1_Child_NameProperty, dr.GetString("Level_1_1_1_1_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="H07Level1111ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(H06Level111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("AddH07Level1111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); } } } /// <summary> /// Updates in the database all changes made to the <see cref="H07Level1111ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(H06Level111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("UpdateH07Level1111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@Level_1_1_1_1_Child_Name", ReadProperty(Level_1_1_1_1_Child_NameProperty)).DbType = DbType.String; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); } } } /// <summary> /// Self deletes the <see cref="H07Level1111ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(H06Level111 parent) { using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad")) { using (var cmd = new SqlCommand("DeleteH07Level1111ReChild", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@Level_1_1_1_ID", parent.Level_1_1_1_ID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } } } #endregion #region Pseudo Events /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using UnityEngine; using UnityEditor; using System; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; namespace PixelCrushers.DialogueSystem { /// <summary> /// This is an example converter that demonstrates how to make a subclass of /// AbstractConverterWindow to make your own converter for the Dialogue System. /// It converts CSV (comma-separated value) files in a specific format into a /// dialogue database. /// /// In the CSV file, each section is optional. The sections are: /// /// - Database /// - Actors /// - Items (also used for quests) /// - Locations /// - Variables /// - Conversations (high level information about each conversation) /// - DialogueEntries (individual dialogue entries in the conversations) /// - OutgoingLinks (links between dialogue entries) /// /// The Database section must contain: /// <pre> /// Database /// Name,Version,Author,Description,Emphasis1,Emphasis2,Emphasis3,Emphasis4 /// (name),(version),(author),(description),(emphasis setting 1 in format #rrggbbaa biu),(emphasis2),(emphasis3),(emphasis4) /// Global User Script /// (luacode) /// </pre> /// /// The Actors section must contain: /// <pre> /// Actors /// ID,Portrait,AltPortraits,Name,Pictures,Description,IsPlayer /// Number,Special,Special,Text,Files,Text,Boolean /// (id),(texturename),[(texturenames)],(name),[(picturenames)],(description),(isplayer) /// ... /// </pre> /// /// The Items, Locations, Variables, and Conversations section must contain: /// <pre> /// (Heading) -- where this is Items, Locations, Variables, or Conversations /// ID,(field),(field),(field)... /// Number,(fieldtype),(fieldtype),(fieldtype)... /// (id),(fieldvalue),(fieldvalue),(fieldvalue)... /// </pre> /// The Variables section may have a final column InitialValueType that specifies the type (Text, Number, or Boolean). /// /// The DialogueEntries section must contain: /// <pre> /// DialogueEntries /// entrytag,ConvID,ID,Actor,Conversant,MenuText,DialogueText,IsGroup,FalseConditionAction,ConditionPriority,Conditions,Script,Sequence,(field),(field)...,canvasRect /// Text,Number,Number,Number,Number,Text,Text,Boolean,Special,Special,Text,Text,Text,(fieldtype),(fieldtype),...,Text /// (entrytag),(ConvID),(ID),(ActorID),(ConversantID),(MenuText),(DialogueText),(IsGroup),(FalseConditionAction),(ConditionPriority),(Conditions),(Script),(Sequence),(fieldvalue),(fieldvalue)...,#;# /// </pre> /// However canvasRect (the last column) is optional. /// /// The OutgoingLinks section must contain: /// <pre> /// OutgoingLinks /// OriginConvID,OriginID,DestConvID,DestID,ConditionPriority /// Number,Number,Number,Number,Special /// #,#,#,#,(priority) /// </pre> /// /// Omitted values in any particular asset should be tagged with "{{omit}}". /// </summary> public class CSVConverterWindow : AbstractConverterWindow { /// <summary> /// Gets the source file extension (CSV). /// </summary> /// <value>The source file extension (e.g., 'xml' for XML files).</value> public override string SourceFileExtension { get { return "csv"; } } /// <summary> /// Gets the EditorPrefs key to save the converter window's settings under. /// </summary> /// <value>The EditorPrefs key.</value> public override string PrefsKey { get { return "PixelCrushers.DialogueSystem.CSVConverterSettings"; } } /// <summary> /// Menu item code to create a CSVConverterWindow. /// </summary> [MenuItem("Window/Dialogue System/Converters/CSV Converter", false, 1)] public static void Init() { EditorWindow.GetWindow(typeof(CSVConverterWindow), false, "CSV Converter"); } /// <summary> /// A list of all asset type headings. /// </summary> private static List<string> AssetTypeHeadings = new List<string>() { "Database", "Actors", "Items", "Locations", "Variables", "Conversations", "DialogueEntries", "OutgoingLinks" }; /// <summary> /// Special values aren't actually fields in an asset's Field array, but they're still /// columns in the CSV that must be read and assigned to the asset's variables. /// </summary> private static List<string> DefaultSpecialValues = new List<string>() { "ID", "InitialValueType" }; /// <summary> /// Portrait and AltPortraits are variables in the Actor class, not fields. /// </summary> private static List<string> ActorSpecialValues = new List<string>() { "ID", "Portrait", "AltPortraits" }; /// <summary> /// The exporter manually places these columns at the front of dialogue entry rows, and the /// importer reads them in the order that they were exported. Some of them are special /// variables of the DialogueEntry class and not actually fields. MenuText and DialogueText /// are fields, but the exporter puts them with this front section to make them more accessible /// to people editing the CSV file. /// </summary> private static List<string> DialogueEntrySpecialValues = new List<string>() { "entrytag", "ConvID", "ID", "Actor", "Conversant", "Title", "MenuText", "DialogueText", "IsGroup", "FalseConditionAction", "ConditionPriority", "Conditions", "Script" }; private static bool sortByID = true; /// <summary> /// Draws the destination section. You can override this if you want to draw /// more than the default controls. /// </summary> protected override void DrawDestinationSection() { base.DrawDestinationSection(); EditorWindowTools.StartIndentedSection(); sortByID = EditorGUILayout.Toggle("Sort By ID", sortByID); EditorWindowTools.EndIndentedSection(); } private const int MaxIterations = 999999; /// <summary> /// Copies the source CSV file to a dialogue database. This method demonstrates /// the helper methods LoadSourceFile(), IsSourceAtEnd(), PeekNextSourceLine(), /// and GetNextSourceLine(). /// </summary> /// <param name="database">Dialogue database to copy into.</param> protected override void CopySourceToDialogueDatabase(DialogueDatabase database) { Debug.Log("Copying source to dialogue database"); var hadError = false; var readConversations = false; var readDialogueEntries = false; try { try { LoadSourceFile(); int numLines = sourceLines.Count; int safeguard = 0; bool cancel = false; while (!IsSourceAtEnd() && (safeguard < MaxIterations) && !cancel) { safeguard++; cancel = EditorUtility.DisplayCancelableProgressBar("Converting CSV", "Please wait...", (float)sourceLines.Count / (float)numLines); string line = GetNextSourceLine(); if (string.Equals(GetFirstField(line), "Database")) { ReadDatabaseProperties(database); } else if (string.Equals(GetFirstField(line), "Actors")) { ReadAssets<Actor>(database.actors, true); } else if (string.Equals(GetFirstField(line), "Items")) { ReadAssets<Item>(database.items, true); } else if (string.Equals(GetFirstField(line), "Locations")) { ReadAssets<Location>(database.locations, true); } else if (string.Equals(GetFirstField(line), "Variables")) { ReadAssets<Variable>(database.variables, true); } else if (string.Equals(GetFirstField(line), "Conversations")) { readConversations = true; ReadAssets<Conversation>(database.conversations, true); } else if (string.Equals(GetFirstField(line), "DialogueEntries")) { ReadDialogueEntries(database, readConversations); readDialogueEntries = readConversations; } else if (string.Equals(GetFirstField(line), "OutgoingLinks")) { ReadOutgoingLinks(database, readConversations && readDialogueEntries); } else { throw new InvalidDataException("Line not recognized: " + line); } } // If we skipped dialogue entries, we need to re-read them now: if (!readDialogueEntries) { Debug.Log("Conversations section was after DialogueEntries section. Going back to read DialogueEntries now..."); LoadSourceFile(); safeguard = 0; while (!IsSourceAtEnd() && (safeguard < MaxIterations) && !cancel) { safeguard++; cancel = EditorUtility.DisplayCancelableProgressBar("Converting CSV", "Convering dialogue entries...", (float)sourceLines.Count / (float)numLines); string line = GetNextSourceLine(); if (string.Equals(GetFirstField(line), "Database")) { ReadDatabaseProperties(database); } else if (string.Equals(GetFirstField(line), "Actors")) { ReadAssets<Actor>(database.actors, false); } else if (string.Equals(GetFirstField(line), "Items")) { ReadAssets<Item>(database.items, false); } else if (string.Equals(GetFirstField(line), "Locations")) { ReadAssets<Location>(database.locations, false); } else if (string.Equals(GetFirstField(line), "Variables")) { ReadAssets<Variable>(database.variables, false); } else if (string.Equals(GetFirstField(line), "Conversations")) { ReadAssets<Conversation>(database.conversations, false); } else if (string.Equals(GetFirstField(line), "DialogueEntries")) { ReadDialogueEntries(database, true); } else if (string.Equals(GetFirstField(line), "OutgoingLinks")) { ReadOutgoingLinks(database, true); } else { throw new InvalidDataException("Line not recognized: " + line); } } } if (sortByID) SortAssetsByID(database); } catch (Exception e) { Debug.LogError(string.Format("{0}: CSV conversion failed: {1}\nLine {2}: {3}", DialogueDebug.Prefix, e.Message, currentLineNumber, currentSourceLine)); hadError = true; } } finally { EditorUtility.ClearProgressBar(); if (hadError) Debug.LogWarning("Dialogue System: There were errors during conversion of " + prefs.sourceFilename + "."); } } /// <summary> /// Reads the database properties section. /// </summary> /// <param name="database">Dialogue database.</param> private void ReadDatabaseProperties(DialogueDatabase database) { Debug.Log("Reading database properties"); GetNextSourceLine(); // Field headings string[] values = GetValues(GetNextSourceLine()); if (values.Length < 8) throw new IndexOutOfRangeException("Incorrect number of values in database properties line"); database.name = values[0]; database.version = values[1]; database.author = values[2]; database.description = values[3]; database.emphasisSettings[0] = UnwrapEmField(values[4]); database.emphasisSettings[1] = UnwrapEmField(values[5]); database.emphasisSettings[2] = UnwrapEmField(values[6]); database.emphasisSettings[3] = UnwrapEmField(values[7]); GetNextSourceLine(); // Global User Script heading database.globalUserScript = UnwrapValue(GetNextSourceLine()); } /// <summary> /// Reads a section of assets such as Actors, Items, etc. /// </summary> /// <param name="assets">List of assets to populate.</param> /// <typeparam name="T">The type of asset.</typeparam> private void ReadAssets<T>(List<T> assets, bool add) where T : Asset, new() { string typeName = typeof(T).Name; bool isActorSection = (typeof(T) == typeof(Actor)); Debug.Log(string.Format("{0} {1} section", (add ? "Reading" : "Skipping"), typeName)); // Read field names and types: string[] fieldNames = GetValues(GetNextSourceLine()); string[] fieldTypes = GetValues(GetNextSourceLine()); // Set up ignore list for values that aren't actual fields: List<string> ignore = isActorSection ? ActorSpecialValues : DefaultSpecialValues; // Keep reading until we reach another asset type heading or end of file: int safeguard = 0; while (!(IsSourceAtEnd() || AssetTypeHeadings.Contains(GetFirstField(PeekNextSourceLine())))) { safeguard++; if (safeguard > MaxIterations) break; string[] values = GetValues(GetNextSourceLine()); if (add) { // Create the asset: T asset = new T(); asset.id = Tools.StringToInt(values[0]); asset.fields = new List<Field>(); // Preprocess a couple extra values for actors: if (isActorSection) FindActorPortraits(asset as Actor, values[1], values[2]); // Read the remaining values and assign them to the asset's fields: ReadAssetFields(fieldNames, fieldTypes, ignore, values, asset.fields); // If the database already has an old asset with the same ID, delete it first: assets.RemoveAll(a => a.id == asset.id); // Finally, add the asset: assets.Add(asset); } } } /// <summary> /// Reads the asset fields. /// </summary> /// <param name="fieldNames">Field names.</param> /// <param name="fieldTypes">Field types.</param> /// <param name="ignore">List of field names to not add.</param> /// <param name="values">CSV values.</param> /// <param name="fields">Fields list of populate.</param> private void ReadAssetFields(string[] fieldNames, string[] fieldTypes, List<string> ignore, string[] values, List<Field> fields) { // Look for a special field named "InitialValueType" used in Variables section: var isInitialValueTypeKnown = false; var initialValueType = FieldType.Text; for (int i = 0; i < fieldNames.Length; i++) { if (string.Equals(fieldNames[i], "InitialValueType")) { initialValueType = Field.StringToFieldType(values[i]); isInitialValueTypeKnown = true; break; } } // Convert all fields: for (int i = 0; i < fieldNames.Length; i++) { if ((ignore != null) && ignore.Contains(fieldNames[i])) continue; if (string.Equals(values[i], "{{omit}}")) continue; if (string.IsNullOrEmpty(fieldNames[i])) continue; string title = fieldNames[i]; string value = values[i]; // Special handling required for Initial Value of Variables section: FieldType type = (string.Equals(title, "Initial Value") && isInitialValueTypeKnown) ? initialValueType : GuessFieldType(value, fieldTypes[i]); fields.Add(new Field(title, value, type)); } } private void FindActorPortraits(Actor actor, string portraitName, string alternatePortraitNames) { if (!string.IsNullOrEmpty(portraitName)) { actor.portrait = AssetDatabase.LoadAssetAtPath(portraitName, typeof(Texture2D)) as Texture2D; } if (!(string.IsNullOrEmpty(alternatePortraitNames) || string.Equals(alternatePortraitNames, "[]"))) { var inner = alternatePortraitNames.Substring(1, alternatePortraitNames.Length - 2); var names = inner.Split(new char[] { ';' }); if (actor.alternatePortraits == null) actor.alternatePortraits = new List<Texture2D>(); foreach (var altPortraitName in names) { var texture = AssetDatabase.LoadAssetAtPath(altPortraitName, typeof(Texture2D)) as Texture2D; if (texture != null) { actor.alternatePortraits.Add(texture); } } } } /// <summary> /// Reads the DialogueEntries section. DialogueEntry is not a subclass of Asset, /// so we can't reuse the ReadAssets() code above. /// </summary> /// <param name="database">Dialogue database.</param> private void ReadDialogueEntries(DialogueDatabase database, bool add) { Debug.Log((add ? "Reading" : "Skipping") + " DialogueEntries section"); // Read field names and types: string[] fieldNames = GetValues(GetNextSourceLine()); string[] fieldTypes = GetValues(GetNextSourceLine()); // Keep reading until we reach another asset type heading or end of file: int safeguard = 0; while (!(IsSourceAtEnd() || AssetTypeHeadings.Contains(GetFirstField(PeekNextSourceLine())))) { safeguard++; if (safeguard > MaxIterations) break; string[] values = GetValues(GetNextSourceLine()); if (add) { // Create the dialogue entry: DialogueEntry entry = new DialogueEntry(); entry.fields = new List<Field>(); // We can ignore value[0] (entrytag). entry.conversationID = Tools.StringToInt(values[1]); entry.id = Tools.StringToInt(values[2]); entry.ActorID = Tools.StringToInt(values[3]); entry.ConversantID = Tools.StringToInt(values[4]); entry.Title = values[5]; entry.DefaultMenuText = values[6]; entry.DefaultDialogueText = values[7]; entry.isGroup = Tools.StringToBool(values[8]); entry.falseConditionAction = values[9]; entry.conditionPriority = ConditionPriorityTools.StringToConditionPriority(values[10]); entry.conditionsString = values[11]; entry.userScript = values[12]; // Read the remaining values and assign them to the asset's fields: ReadAssetFields(fieldNames, fieldTypes, DialogueEntrySpecialValues, values, entry.fields); // Convert canvasRect field to entry position on node editor canvas: entry.UseCanvasRectField(); // Finally, add the asset: var conversation = database.GetConversation(entry.conversationID); if (conversation == null) throw new InvalidDataException(string.Format("Conversation {0} referenced in entry {1} not found", entry.conversationID, entry.id)); conversation.dialogueEntries.Add(entry); } } } /// <summary> /// Reads the OutgoingLinks section. Again, Link is not a subclass of Asset, /// so we can't reuse the ReadAssets() method. /// </summary> /// <param name="database">Dialogue database.</param> private void ReadOutgoingLinks(DialogueDatabase database, bool add) { Debug.Log((add ? "Reading" : "Skipping") + " OutgoingLinks section"); GetNextSourceLine(); // Headings GetNextSourceLine(); // Types // Keep reading until we reach another asset type heading or end of file: int safeguard = 0; while (!(IsSourceAtEnd() || AssetTypeHeadings.Contains(GetFirstField(PeekNextSourceLine())))) { safeguard++; if (safeguard > MaxIterations) break; string[] values = GetValues(GetNextSourceLine()); if (add) { var link = new Link(Tools.StringToInt(values[0]), Tools.StringToInt(values[1]), Tools.StringToInt(values[2]), Tools.StringToInt(values[3])); link.priority = ConditionPriorityTools.StringToConditionPriority(values[4]); var entry = database.GetDialogueEntry(link.originConversationID, link.originDialogueID); if (entry == null) throw new InvalidDataException(string.Format("Dialogue entry {0}.{1} referenced in link not found", link.originConversationID, link.originDialogueID)); entry.outgoingLinks.Add(link); } } } protected override void LoadSourceFile() { base.LoadSourceFile(); CombineMultilineSourceLines(); } /// <summary> /// Combines lines that are actually a multiline CSV row. This also helps prevent the /// CSV-splitting regex from hanging due to catastrophic backtracking on unterminated quotes. /// </summary> private void CombineMultilineSourceLines() { int lineNum = 0; int safeguard = 0; while ((lineNum < sourceLines.Count) && (safeguard < MaxIterations)) { safeguard++; string line = sourceLines[lineNum]; if (line == null) { sourceLines.RemoveAt(lineNum); } else { bool terminated = true; char previousChar = (char)0; for (int i = 0; i < line.Length; i++) { char currentChar = line[i]; bool isQuote = (currentChar == '"') && (previousChar != '\\'); if (isQuote) terminated = !terminated; previousChar = currentChar; } if (terminated || (lineNum + 1) >= sourceLines.Count) { if (!terminated) sourceLines[lineNum] = line + '"'; lineNum++; } else { sourceLines[lineNum] = line + "\\n" + sourceLines[lineNum + 1]; sourceLines.RemoveAt(lineNum + 1); } } } } /// <summary> /// Returns the individual comma-separated values in a line. /// </summary> /// <returns>The values.</returns> /// <param name="line">Line.</param> private string[] GetValues(string line) { Regex csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled); List<string> values = new List<string>(); foreach (Match match in csvSplit.Matches(line)) { values.Add(UnwrapValue(match.Value.TrimStart(','))); } return values.ToArray(); } private string GetFirstField(string line) { if (line.Contains(",")) { var values = line.Split(new char[] { ',' }); return values[0]; } else { return line; } } /// <summary> /// Returns a "fixed" version of a comma-separated value where escaped newlines /// have been converted back into real newlines, and optional surrounding quotes /// have been removed. /// </summary> /// <returns>The value.</returns> /// <param name="value">Value.</param> private string UnwrapValue(string value) { string s = value.Replace("\\n", "\n").Replace("\\r", "\r"); if (s.StartsWith("\"") && s.EndsWith("\"")) { s = s.Substring(1, s.Length - 2).Replace("\"\"", "\""); } return s; } /// <summary> /// Converts an emphasis field in the format "#rrggbbaa biu" into an EmphasisSetting object. /// </summary> /// <returns>An EmphasisSetting object.</returns> /// <param name="emField">Em field.</param> private EmphasisSetting UnwrapEmField(string emField) { return new EmphasisSetting(emField.Substring(0, 9), emField.Substring(10, 3)); } /// <summary> /// The CSV format isn't robust enough to describe if different assets define different /// types for the same field name. This method checks if a "Text" field has a Boolean /// or Number value and returns that type instead of Text. /// </summary> /// <returns>The field type.</returns> /// <param name="value">Value.</param> /// <param name="typeSpecifier">Type specifier.</param> private FieldType GuessFieldType(string value, string typeSpecifier) { if (string.Equals(typeSpecifier, "Text") && !string.IsNullOrEmpty(value)) { if (IsBoolean(value)) { return FieldType.Boolean; } else if (IsNumber(value)) { return FieldType.Number; } } return Field.StringToFieldType(typeSpecifier); } /// <summary> /// Determines whether a string represents a Boolean value. /// </summary> /// <returns><c>true</c> if this is a Boolean value; otherwise, <c>false</c>.</returns> /// <param name="value">String value.</param> private bool IsBoolean(string value) { return ((string.Compare(value, "True", System.StringComparison.OrdinalIgnoreCase) == 0) || (string.Compare(value, "False", System.StringComparison.OrdinalIgnoreCase) == 0)); } /// <summary> /// Determines whether a string represents a Number value. /// </summary> /// <returns><c>true</c> if this is a number; otherwise, <c>false</c>.</returns> /// <param name="value">String value.</param> private bool IsNumber(string value) { float n; return float.TryParse(value, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out n); } private void SortAssetsByID(DialogueDatabase database) { if (database == null) return; database.actors.Sort((x, y) => x.id.CompareTo(y.id)); database.items.Sort((x, y) => x.id.CompareTo(y.id)); database.locations.Sort((x, y) => x.id.CompareTo(y.id)); database.variables.Sort((x, y) => x.id.CompareTo(y.id)); database.conversations.Sort((x, y) => x.id.CompareTo(y.id)); foreach (var conversation in database.conversations) { conversation.dialogueEntries.Sort((x, y) => x.id.CompareTo(y.id)); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TestMenus.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // The test menus. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleMinesweeper.Test { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using ConsoleMinesweeper.Interfaces; using ConsoleMinesweeper.Models; using ConsoleMinesweeper.View; using Microsoft.VisualStudio.TestTools.UnitTesting; using Minesweeper.Models; using Minesweeper.Models.Interfaces; using Moq; /// <summary> /// The test menus. /// </summary> [TestClass] [ExcludeFromCodeCoverage] public class TestMenus { /// <summary> /// The test keys. /// </summary> private readonly ConsoleKeyInfo[] testKeys = new ConsoleKeyInfo[30]; /// <summary> /// The keys cnt. /// </summary> private int keysCnt; /// <summary> /// The test str. /// </summary> private string testStr; /// <summary> /// The console mock. /// </summary> /// <returns> /// The <see cref="IConsoleWrapper"/>. /// </returns> private IConsoleWrapper<ConsoleColor, ConsoleKeyInfo> ConsoleMock() { var mockedConsole = new Mock<IConsoleWrapper<ConsoleColor, ConsoleKeyInfo>>(); mockedConsole.Setup(r => r.Write(It.IsAny<string>())).Callback<string>(r => { this.testStr = r; }); mockedConsole.Setup(r => r.ReadKey(It.IsAny<bool>())) .Returns(() => { return this.testKeys[this.keysCnt++]; }); mockedConsole.Setup(r => r.ResetColor()).Verifiable(); mockedConsole.Setup(r => r.SetCursorPosition(It.IsAny<int>(), It.IsAny<int>())).Verifiable(); return mockedConsole.Object; } /// <summary> /// The view mock. /// </summary> /// <returns> /// The <see cref="IConsoleView"/>. /// </returns> private IConsoleView ViewMock() { var mockedView = new Mock<IConsoleView>(); mockedView.Setup(r => r.DisplayGameOver(It.IsAny<bool>())).Verifiable(); mockedView.Setup(r => r.DisplayGrid(It.IsAny<IMinesweeperGrid>())).Verifiable(); mockedView.Setup(r => r.DisplayMoves(It.IsAny<int>())).Verifiable(); mockedView.Setup(r => r.DisplayTime(It.IsAny<int>())).Verifiable(); mockedView.Setup(r => r.DisplayScoreBoard(It.IsAny<List<MinesweeperPlayer>>())).Verifiable(); return mockedView.Object; } /// <summary> /// The test start menus should display. /// </summary> [TestMethod] public void TestStartMenusShouldDisplay() { var i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.UpArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.UpArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.UpArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.UpArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.UpArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartGameMenu( this.ConsoleMock(), new ConsoleView(false, this.ConsoleMock()), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); this.testStr = string.Empty; ConsoleMenus.StartMainMenu(this.ConsoleMock()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); this.testStr = string.Empty; } /// <summary> /// The test game start menu items should display. /// </summary> [TestMethod] public void TestGameStartMenuItemsShouldDisplay() { var i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.Enter, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartGameMenu(this.ConsoleMock(), this.ViewMock(), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.Enter, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartGameMenu(this.ConsoleMock(), this.ViewMock(), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.Enter, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartGameMenu(this.ConsoleMock(), this.ViewMock(), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.Enter, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartGameMenu(this.ConsoleMock(), this.ViewMock(), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); } /// <summary> /// The test score start menu items should display. /// </summary> [TestMethod] public void TestScoreStartMenuItemsShouldDisplay() { var i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.Enter, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartScoresMenu(this.ConsoleMock(), this.ViewMock(), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.Enter, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartScoresMenu(this.ConsoleMock(), this.ViewMock(), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.Enter, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartScoresMenu(this.ConsoleMock(), this.ViewMock(), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); i = 0; this.keysCnt = 0; this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.DownArrow, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.Enter, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testKeys[i++] = new ConsoleKeyInfo(' ', ConsoleKey.E, false, false, false); this.testStr = string.Empty; ConsoleMenus.StartScoresMenu(this.ConsoleMock(), this.ViewMock(), new ConsoleTimer()); Assert.AreEqual(this.testStr != string.Empty, true, "No output for menu!"); } } }
// // typemanager.cs: C# type manager // // Author: Miguel de Icaza ([email protected]) // Ravi Pratap ([email protected]) // Marek Safar ([email protected]) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com) // Copyright 2003-2008 Novell, Inc. // using System; using System.Globalization; using System.Collections.Generic; using System.Text; namespace Mono.CSharp { // // All compiler build-in types (they have to exist otherwise the compile will not work) // public class BuildinTypes { public readonly BuildinTypeSpec Object; public readonly BuildinTypeSpec ValueType; public readonly BuildinTypeSpec Attribute; public readonly BuildinTypeSpec Int; public readonly BuildinTypeSpec UInt; public readonly BuildinTypeSpec Long; public readonly BuildinTypeSpec ULong; public readonly BuildinTypeSpec Float; public readonly BuildinTypeSpec Double; public readonly BuildinTypeSpec Char; public readonly BuildinTypeSpec Short; public readonly BuildinTypeSpec Decimal; public readonly BuildinTypeSpec Bool; public readonly BuildinTypeSpec SByte; public readonly BuildinTypeSpec Byte; public readonly BuildinTypeSpec UShort; public readonly BuildinTypeSpec String; public readonly BuildinTypeSpec Enum; public readonly BuildinTypeSpec Delegate; public readonly BuildinTypeSpec MulticastDelegate; public readonly BuildinTypeSpec Void; public readonly BuildinTypeSpec Array; public readonly BuildinTypeSpec Type; public readonly BuildinTypeSpec IEnumerator; public readonly BuildinTypeSpec IEnumerable; public readonly BuildinTypeSpec IDisposable; public readonly BuildinTypeSpec IntPtr; public readonly BuildinTypeSpec UIntPtr; public readonly BuildinTypeSpec RuntimeFieldHandle; public readonly BuildinTypeSpec RuntimeTypeHandle; public readonly BuildinTypeSpec Exception; // // These are internal buil-in types which depend on other // build-in type (mostly object) // public readonly BuildinTypeSpec Dynamic; public readonly BuildinTypeSpec Null; readonly BuildinTypeSpec[] types; public BuildinTypes () { Object = new BuildinTypeSpec (MemberKind.Class, "System", "Object", BuildinTypeSpec.Type.Object); ValueType = new BuildinTypeSpec (MemberKind.Class, "System", "ValueType", BuildinTypeSpec.Type.ValueType); Attribute = new BuildinTypeSpec (MemberKind.Class, "System", "Attribute", BuildinTypeSpec.Type.Attribute); Int = new BuildinTypeSpec (MemberKind.Struct, "System", "Int32", BuildinTypeSpec.Type.Int); Long = new BuildinTypeSpec (MemberKind.Struct, "System", "Int64", BuildinTypeSpec.Type.Long); UInt = new BuildinTypeSpec (MemberKind.Struct, "System", "UInt32", BuildinTypeSpec.Type.UInt); ULong = new BuildinTypeSpec (MemberKind.Struct, "System", "UInt64", BuildinTypeSpec.Type.ULong); Byte = new BuildinTypeSpec (MemberKind.Struct, "System", "Byte", BuildinTypeSpec.Type.Byte); SByte = new BuildinTypeSpec (MemberKind.Struct, "System", "SByte", BuildinTypeSpec.Type.SByte); Short = new BuildinTypeSpec (MemberKind.Struct, "System", "Int16", BuildinTypeSpec.Type.Short); UShort = new BuildinTypeSpec (MemberKind.Struct, "System", "UInt16", BuildinTypeSpec.Type.UShort); IEnumerator = new BuildinTypeSpec (MemberKind.Interface, "System.Collections", "IEnumerator", BuildinTypeSpec.Type.IEnumerator); IEnumerable = new BuildinTypeSpec (MemberKind.Interface, "System.Collections", "IEnumerable", BuildinTypeSpec.Type.IEnumerable); IDisposable = new BuildinTypeSpec (MemberKind.Interface, "System", "IDisposable", BuildinTypeSpec.Type.IDisposable); Char = new BuildinTypeSpec (MemberKind.Struct, "System", "Char", BuildinTypeSpec.Type.Char); String = new BuildinTypeSpec (MemberKind.Class, "System", "String", BuildinTypeSpec.Type.String); Float = new BuildinTypeSpec (MemberKind.Struct, "System", "Single", BuildinTypeSpec.Type.Float); Double = new BuildinTypeSpec (MemberKind.Struct, "System", "Double", BuildinTypeSpec.Type.Double); Decimal = new BuildinTypeSpec (MemberKind.Struct, "System", "Decimal", BuildinTypeSpec.Type.Decimal); Bool = new BuildinTypeSpec (MemberKind.Struct, "System", "Boolean", BuildinTypeSpec.Type.Bool); IntPtr = new BuildinTypeSpec (MemberKind.Struct, "System", "IntPtr", BuildinTypeSpec.Type.IntPtr); UIntPtr = new BuildinTypeSpec (MemberKind.Struct, "System", "UIntPtr", BuildinTypeSpec.Type.UIntPtr); MulticastDelegate = new BuildinTypeSpec (MemberKind.Class, "System", "MulticastDelegate", BuildinTypeSpec.Type.MulticastDelegate); Delegate = new BuildinTypeSpec (MemberKind.Class, "System", "Delegate", BuildinTypeSpec.Type.Delegate); Enum = new BuildinTypeSpec (MemberKind.Class, "System", "Enum", BuildinTypeSpec.Type.Enum); Array = new BuildinTypeSpec (MemberKind.Class, "System", "Array", BuildinTypeSpec.Type.Array); Void = new BuildinTypeSpec (MemberKind.Struct, "System", "Void", BuildinTypeSpec.Type.Void); Type = new BuildinTypeSpec (MemberKind.Class, "System", "Type", BuildinTypeSpec.Type.Type); Exception = new BuildinTypeSpec (MemberKind.Class, "System", "Exception", BuildinTypeSpec.Type.Exception); RuntimeFieldHandle = new BuildinTypeSpec (MemberKind.Struct, "System", "RuntimeFieldHandle", BuildinTypeSpec.Type.RuntimeFieldHandle); RuntimeTypeHandle = new BuildinTypeSpec (MemberKind.Struct, "System", "RuntimeTypeHandle", BuildinTypeSpec.Type.RuntimeTypeHandle); Dynamic = new BuildinTypeSpec ("dynamic", BuildinTypeSpec.Type.Dynamic); Null = new BuildinTypeSpec ("null", BuildinTypeSpec.Type.Null); Null.MemberCache = MemberCache.Empty; types = new BuildinTypeSpec[] { Object, ValueType, Attribute, Int, UInt, Long, ULong, Float, Double, Char, Short, Decimal, Bool, SByte, Byte, UShort, String, Enum, Delegate, MulticastDelegate, Void, Array, Type, IEnumerator, IEnumerable, IDisposable, IntPtr, UIntPtr, RuntimeFieldHandle, RuntimeTypeHandle, Exception }; // Deal with obsolete static types // TODO: remove TypeManager.object_type = Object; TypeManager.value_type = ValueType; TypeManager.string_type = String; TypeManager.int32_type = Int; TypeManager.uint32_type = UInt; TypeManager.int64_type = Long; TypeManager.uint64_type = ULong; TypeManager.float_type = Float; TypeManager.double_type = Double; TypeManager.char_type = Char; TypeManager.short_type = Short; TypeManager.decimal_type = Decimal; TypeManager.bool_type = Bool; TypeManager.sbyte_type = SByte; TypeManager.byte_type = Byte; TypeManager.ushort_type = UShort; TypeManager.enum_type = Enum; TypeManager.delegate_type = Delegate; TypeManager.multicast_delegate_type = MulticastDelegate; ; TypeManager.void_type = Void; TypeManager.array_type = Array; ; TypeManager.runtime_handle_type = RuntimeTypeHandle; TypeManager.type_type = Type; TypeManager.ienumerator_type = IEnumerator; TypeManager.ienumerable_type = IEnumerable; TypeManager.idisposable_type = IDisposable; TypeManager.intptr_type = IntPtr; TypeManager.uintptr_type = UIntPtr; TypeManager.runtime_field_handle_type = RuntimeFieldHandle; TypeManager.attribute_type = Attribute; TypeManager.exception_type = Exception; InternalType.Dynamic = Dynamic; InternalType.Null = Null; } public BuildinTypeSpec[] AllTypes { get { return types; } } public bool CheckDefinitions (ModuleContainer module) { var ctx = module.Compiler; foreach (var p in types) { var found = PredefinedType.Resolve (module, p.Kind, p.Namespace, p.Name, p.Arity, Location.Null); if (found == null || found == p) continue; var tc = found.MemberDefinition as TypeContainer; if (tc != null) { var ns = module.GlobalRootNamespace.GetNamespace (p.Namespace, false); ns.ReplaceTypeWithPredefined (found, p); tc.SetPredefinedSpec (p); p.SetDefinition (found); } } if (ctx.Report.Errors != 0) return false; // Set internal build-in types Dynamic.SetDefinition (Object); Null.SetDefinition (Object); return true; } } // // Compiler predefined types. Usually used for compiler generated // code or for comparison against well known framework type // class PredefinedTypes { // TODO: These two exist only to reject type comparison public readonly PredefinedType TypedReference; public readonly PredefinedType ArgIterator; public readonly PredefinedType MarshalByRefObject; public readonly PredefinedType RuntimeHelpers; public readonly PredefinedType IAsyncResult; public readonly PredefinedType AsyncCallback; public readonly PredefinedType RuntimeArgumentHandle; public readonly PredefinedType CharSet; public readonly PredefinedType IsVolatile; public readonly PredefinedType IEnumeratorGeneric; public readonly PredefinedType IListGeneric; public readonly PredefinedType ICollectionGeneric; public readonly PredefinedType IEnumerableGeneric; public readonly PredefinedType Nullable; public readonly PredefinedType Activator; public readonly PredefinedType Interlocked; public readonly PredefinedType Monitor; public readonly PredefinedType NotSupportedException; public readonly PredefinedType RuntimeFieldHandle; public readonly PredefinedType RuntimeMethodHandle; public readonly PredefinedType SecurityAction; // // C# 3.0 // public readonly PredefinedType Expression; public readonly PredefinedType ExpressionGeneric; public readonly PredefinedType ParameterExpression; public readonly PredefinedType FieldInfo; public readonly PredefinedType MethodBase; public readonly PredefinedType MethodInfo; public readonly PredefinedType ConstructorInfo; // // C# 4.0 // public readonly PredefinedType Binder; public readonly PredefinedType CallSite; public readonly PredefinedType CallSiteGeneric; public readonly PredefinedType BinderFlags; public PredefinedTypes (ModuleContainer module) { TypedReference = new PredefinedType (module, MemberKind.Struct, "System", "TypedReference"); ArgIterator = new PredefinedType (module, MemberKind.Struct, "System", "ArgIterator"); MarshalByRefObject = new PredefinedType (module, MemberKind.Class, "System", "MarshalByRefObject"); RuntimeHelpers = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "RuntimeHelpers"); IAsyncResult = new PredefinedType (module, MemberKind.Interface, "System", "IAsyncResult"); AsyncCallback = new PredefinedType (module, MemberKind.Delegate, "System", "AsyncCallback"); RuntimeArgumentHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeArgumentHandle"); CharSet = new PredefinedType (module, MemberKind.Enum, "System.Runtime.InteropServices", "CharSet"); IsVolatile = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "IsVolatile"); IEnumeratorGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IEnumerator", 1); IListGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IList", 1); ICollectionGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "ICollection", 1); IEnumerableGeneric = new PredefinedType (module, MemberKind.Interface, "System.Collections.Generic", "IEnumerable", 1); Nullable = new PredefinedType (module, MemberKind.Struct, "System", "Nullable", 1); Activator = new PredefinedType (module, MemberKind.Class, "System", "Activator"); Interlocked = new PredefinedType (module, MemberKind.Class, "System.Threading", "Interlocked"); Monitor = new PredefinedType (module, MemberKind.Class, "System.Threading", "Monitor"); NotSupportedException = new PredefinedType (module, MemberKind.Class, "System", "NotSupportedException"); RuntimeFieldHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeFieldHandle"); RuntimeMethodHandle = new PredefinedType (module, MemberKind.Struct, "System", "RuntimeMethodHandle"); SecurityAction = new PredefinedType (module, MemberKind.Enum, "System.Security.Permissions", "SecurityAction"); Expression = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "Expression"); ExpressionGeneric = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "Expression", 1); ParameterExpression = new PredefinedType (module, MemberKind.Class, "System.Linq.Expressions", "ParameterExpression"); FieldInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "FieldInfo"); MethodBase = new PredefinedType (module, MemberKind.Class, "System.Reflection", "MethodBase"); MethodInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "MethodInfo"); ConstructorInfo = new PredefinedType (module, MemberKind.Class, "System.Reflection", "ConstructorInfo"); CallSite = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "CallSite"); CallSiteGeneric = new PredefinedType (module, MemberKind.Class, "System.Runtime.CompilerServices", "CallSite", 1); Binder = new PredefinedType (module, MemberKind.Class, "Microsoft.CSharp.RuntimeBinder", "Binder"); BinderFlags = new PredefinedType (module, MemberKind.Enum, "Microsoft.CSharp.RuntimeBinder", "CSharpBinderFlags"); // // Define types which are used for comparison. It does not matter // if they don't exist as no error report is needed // TypedReference.Define (); ArgIterator.Define (); MarshalByRefObject.Define (); CharSet.Define (); IEnumerableGeneric.Define (); IListGeneric.Define (); ICollectionGeneric.Define (); IEnumerableGeneric.Define (); IEnumeratorGeneric.Define (); Nullable.Define (); ExpressionGeneric.Define (); // Deal with obsolete static types // TODO: remove TypeManager.typed_reference_type = TypedReference.TypeSpec; TypeManager.arg_iterator_type = ArgIterator.TypeSpec; TypeManager.mbr_type = MarshalByRefObject.TypeSpec; TypeManager.generic_ilist_type = IListGeneric.TypeSpec; TypeManager.generic_icollection_type = ICollectionGeneric.TypeSpec; TypeManager.generic_ienumerator_type = IEnumeratorGeneric.TypeSpec; TypeManager.generic_ienumerable_type = IEnumerableGeneric.TypeSpec; TypeManager.generic_nullable_type = Nullable.TypeSpec; TypeManager.expression_type = ExpressionGeneric.TypeSpec; } } public class PredefinedType { string name; string ns; int arity; MemberKind kind; protected readonly ModuleContainer module; protected TypeSpec type; public PredefinedType (ModuleContainer module, MemberKind kind, string ns, string name, int arity) : this (module, kind, ns, name) { this.arity = arity; } public PredefinedType (ModuleContainer module, MemberKind kind, string ns, string name) { this.module = module; this.kind = kind; this.name = name; this.ns = ns; } #region Properties public int Arity { get { return arity; } } public bool IsDefined { get { return type != null; } } public string Name { get { return name; } } public string Namespace { get { return ns; } } public TypeSpec TypeSpec { get { return type; } } #endregion public bool Define () { if (type != null) return true; Namespace type_ns = module.GlobalRootNamespace.GetNamespace (ns, true); var te = type_ns.LookupType (module, name, arity, true, Location.Null); if (te == null) return false; if (te.Type.Kind != kind) return false; type = te.Type; return true; } public FieldSpec GetField (string name, TypeSpec memberType, Location loc) { return TypeManager.GetPredefinedField (type, name, loc, memberType); } public string GetSignatureForError () { return ns + "." + name; } public static TypeSpec Resolve (ModuleContainer module, MemberKind kind, string ns, string name, int arity, Location loc) { Namespace type_ns = module.GlobalRootNamespace.GetNamespace (ns, true); var te = type_ns.LookupType (module, name, arity, false, Location.Null); if (te == null) { module.Compiler.Report.Error (518, loc, "The predefined type `{0}.{1}' is not defined or imported", ns, name); return null; } var type = te.Type; if (type.Kind != kind) { module.Compiler.Report.Error (520, loc, "The predefined type `{0}.{1}' is not declared correctly", ns, name); return null; } return type; } public TypeSpec Resolve (Location loc) { if (type == null) type = Resolve (module, kind, ns, name, arity, loc); return type; } } partial class TypeManager { // // A list of core types that the compiler requires or uses // static public BuildinTypeSpec object_type; static public BuildinTypeSpec value_type; static public BuildinTypeSpec string_type; static public BuildinTypeSpec int32_type; static public BuildinTypeSpec uint32_type; static public BuildinTypeSpec int64_type; static public BuildinTypeSpec uint64_type; static public BuildinTypeSpec float_type; static public BuildinTypeSpec double_type; static public BuildinTypeSpec char_type; static public BuildinTypeSpec short_type; static public BuildinTypeSpec decimal_type; static public BuildinTypeSpec bool_type; static public BuildinTypeSpec sbyte_type; static public BuildinTypeSpec byte_type; static public BuildinTypeSpec ushort_type; static public BuildinTypeSpec enum_type; static public BuildinTypeSpec delegate_type; static public BuildinTypeSpec multicast_delegate_type; static public BuildinTypeSpec void_type; static public BuildinTypeSpec array_type; static public BuildinTypeSpec runtime_handle_type; static public BuildinTypeSpec type_type; static public BuildinTypeSpec ienumerator_type; static public BuildinTypeSpec ienumerable_type; static public BuildinTypeSpec idisposable_type; static public BuildinTypeSpec intptr_type; static public BuildinTypeSpec uintptr_type; static public BuildinTypeSpec runtime_field_handle_type; static public BuildinTypeSpec attribute_type; static public BuildinTypeSpec exception_type; static public TypeSpec typed_reference_type; static public TypeSpec arg_iterator_type; static public TypeSpec mbr_type; static public TypeSpec generic_ilist_type; static public TypeSpec generic_icollection_type; static public TypeSpec generic_ienumerator_type; static public TypeSpec generic_ienumerable_type; static public TypeSpec generic_nullable_type; static internal TypeSpec expression_type; // // These methods are called by code generated by the compiler // static public FieldSpec string_empty; static public MethodSpec system_type_get_type_from_handle; static public MethodSpec bool_movenext_void; static public MethodSpec void_dispose_void; static public MethodSpec void_monitor_enter_object; static public MethodSpec void_monitor_exit_object; static public MethodSpec void_initializearray_array_fieldhandle; static public MethodSpec delegate_combine_delegate_delegate; static public MethodSpec delegate_remove_delegate_delegate; static public PropertySpec int_get_offset_to_string_data; static public MethodSpec int_interlocked_compare_exchange; public static MethodSpec gen_interlocked_compare_exchange; static public PropertySpec ienumerator_getcurrent; public static MethodSpec methodbase_get_type_from_handle; public static MethodSpec methodbase_get_type_from_handle_generic; public static MethodSpec fieldinfo_get_field_from_handle; public static MethodSpec fieldinfo_get_field_from_handle_generic; public static MethodSpec activator_create_instance; // // The constructors. // static public MethodSpec void_decimal_ctor_five_args; static public MethodSpec void_decimal_ctor_int_arg; public static MethodSpec void_decimal_ctor_long_arg; static TypeManager () { Reset (); } static public void Reset () { // object_type = null; // TODO: I am really bored by all this static stuff system_type_get_type_from_handle = bool_movenext_void = void_dispose_void = void_monitor_enter_object = void_monitor_exit_object = void_initializearray_array_fieldhandle = int_interlocked_compare_exchange = gen_interlocked_compare_exchange = methodbase_get_type_from_handle = methodbase_get_type_from_handle_generic = fieldinfo_get_field_from_handle = fieldinfo_get_field_from_handle_generic = activator_create_instance = delegate_combine_delegate_delegate = delegate_remove_delegate_delegate = null; int_get_offset_to_string_data = ienumerator_getcurrent = null; void_decimal_ctor_five_args = void_decimal_ctor_int_arg = void_decimal_ctor_long_arg = null; string_empty = null; typed_reference_type = arg_iterator_type = mbr_type = generic_ilist_type = generic_icollection_type = generic_ienumerator_type = generic_ienumerable_type = generic_nullable_type = expression_type = null; } /// <summary> /// Returns the C# name of a type if possible, or the full type name otherwise /// </summary> static public string CSharpName (TypeSpec t) { return t.GetSignatureForError (); } static public string CSharpName (IList<TypeSpec> types) { if (types.Count == 0) return string.Empty; StringBuilder sb = new StringBuilder (); for (int i = 0; i < types.Count; ++i) { if (i > 0) sb.Append (","); sb.Append (CSharpName (types [i])); } return sb.ToString (); } static public string GetFullNameSignature (MemberSpec mi) { return mi.GetSignatureForError (); } static public string CSharpSignature (MemberSpec mb) { return mb.GetSignatureForError (); } static MemberSpec GetPredefinedMember (TypeSpec t, MemberFilter filter, bool optional, Location loc) { var member = MemberCache.FindMember (t, filter, BindingRestriction.DeclaredOnly); if (member != null && member.IsAccessible (InternalType.FakeInternalType)) return member; if (optional) return member; string method_args = null; if (filter.Parameters != null) method_args = filter.Parameters.GetSignatureForError (); RootContext.ToplevelTypes.Compiler.Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible", TypeManager.CSharpName (t), filter.Name, method_args); return null; } // // Returns the ConstructorInfo for "args" // public static MethodSpec GetPredefinedConstructor (TypeSpec t, Location loc, params TypeSpec [] args) { var pc = ParametersCompiled.CreateFullyResolved (args); return GetPredefinedMember (t, MemberFilter.Constructor (pc), false, loc) as MethodSpec; } // // Returns the method specification for a method named `name' defined // in type `t' which takes arguments of types `args' // public static MethodSpec GetPredefinedMethod (TypeSpec t, string name, Location loc, params TypeSpec [] args) { var pc = ParametersCompiled.CreateFullyResolved (args); return GetPredefinedMethod (t, MemberFilter.Method (name, 0, pc, null), false, loc); } public static MethodSpec GetPredefinedMethod (TypeSpec t, MemberFilter filter, Location loc) { return GetPredefinedMethod (t, filter, false, loc); } public static MethodSpec GetPredefinedMethod (TypeSpec t, MemberFilter filter, bool optional, Location loc) { return GetPredefinedMember (t, filter, optional, loc) as MethodSpec; } public static FieldSpec GetPredefinedField (TypeSpec t, string name, Location loc, TypeSpec type) { return GetPredefinedMember (t, MemberFilter.Field (name, type), false, loc) as FieldSpec; } public static PropertySpec GetPredefinedProperty (TypeSpec t, string name, Location loc, TypeSpec type) { return GetPredefinedMember (t, MemberFilter.Property (name, type), false, loc) as PropertySpec; } public static bool IsBuiltinType (TypeSpec t) { if (t == object_type || t == string_type || t == int32_type || t == uint32_type || t == int64_type || t == uint64_type || t == float_type || t == double_type || t == char_type || t == short_type || t == decimal_type || t == bool_type || t == sbyte_type || t == byte_type || t == ushort_type || t == void_type) return true; else return false; } // // This is like IsBuiltinType, but lacks decimal_type, we should also clean up // the pieces in the code where we use IsBuiltinType and special case decimal_type. // public static bool IsPrimitiveType (TypeSpec t) { return (t == int32_type || t == uint32_type || t == int64_type || t == uint64_type || t == float_type || t == double_type || t == char_type || t == short_type || t == bool_type || t == sbyte_type || t == byte_type || t == ushort_type); } // Obsolete public static bool IsDelegateType (TypeSpec t) { return t.IsDelegate; } // Obsolete public static bool IsEnumType (TypeSpec t) { return t.IsEnum; } public static bool IsBuiltinOrEnum (TypeSpec t) { if (IsBuiltinType (t)) return true; if (IsEnumType (t)) return true; return false; } // // Whether a type is unmanaged. This is used by the unsafe code (25.2) // public static bool IsUnmanagedType (TypeSpec t) { var ds = t.MemberDefinition as DeclSpace; if (ds != null) return ds.IsUnmanagedType (); // some builtins that are not unmanaged types if (t == TypeManager.object_type || t == TypeManager.string_type) return false; if (IsBuiltinOrEnum (t)) return true; // Someone did the work of checking if the ElementType of t is unmanaged. Let's not repeat it. if (t.IsPointer) return IsUnmanagedType (GetElementType (t)); if (!IsValueType (t)) return false; if (t.IsNested && t.DeclaringType.IsGenericOrParentIsGeneric) return false; return true; } // // Null is considered to be a reference type // public static bool IsReferenceType (TypeSpec t) { if (t.IsGenericParameter) return ((TypeParameterSpec) t).IsReferenceType; return !t.IsStruct && !IsEnumType (t); } public static bool IsValueType (TypeSpec t) { if (t.IsGenericParameter) return ((TypeParameterSpec) t).IsValueType; return t.IsStruct || IsEnumType (t); } public static bool IsStruct (TypeSpec t) { return t.IsStruct; } public static bool IsFamilyAccessible (TypeSpec type, TypeSpec parent) { // TypeParameter tparam = LookupTypeParameter (type); // TypeParameter pparam = LookupTypeParameter (parent); if (type.Kind == MemberKind.TypeParameter && parent.Kind == MemberKind.TypeParameter) { // (tparam != null) && (pparam != null)) { if (type == parent) return true; throw new NotImplementedException ("net"); // return tparam.IsSubclassOf (parent); } do { if (IsInstantiationOfSameGenericType (type, parent)) return true; type = type.BaseType; } while (type != null); return false; } // // Checks whether `type' is a subclass or nested child of `base_type'. // public static bool IsNestedFamilyAccessible (TypeSpec type, TypeSpec base_type) { do { if (IsFamilyAccessible (type, base_type)) return true; // Handle nested types. type = type.DeclaringType; } while (type != null); return false; } // // Checks whether `type' is a nested child of `parent'. // public static bool IsNestedChildOf (TypeSpec type, ITypeDefinition parent) { if (type == null) return false; if (type.MemberDefinition == parent) return false; type = type.DeclaringType; while (type != null) { if (type.MemberDefinition == parent) return true; type = type.DeclaringType; } return false; } public static bool IsSpecialType (TypeSpec t) { return t == arg_iterator_type || t == typed_reference_type; } public static TypeSpec GetElementType (TypeSpec t) { return ((ElementTypeSpec)t).Element; } /// <summary> /// This method is not implemented by MS runtime for dynamic types /// </summary> public static bool HasElementType (TypeSpec t) { return t is ElementTypeSpec; } static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat; // This is a custom version of Convert.ChangeType() which works // with the TypeBuilder defined types when compiling corlib. public static object ChangeType (object value, TypeSpec targetType, out bool error) { IConvertible convert_value = value as IConvertible; if (convert_value == null){ error = true; return null; } // // We cannot rely on build-in type conversions as they are // more limited than what C# supports. // See char -> float/decimal/double conversion // error = false; try { if (targetType == TypeManager.bool_type) return convert_value.ToBoolean (nf_provider); if (targetType == TypeManager.byte_type) return convert_value.ToByte (nf_provider); if (targetType == TypeManager.char_type) return convert_value.ToChar (nf_provider); if (targetType == TypeManager.short_type) return convert_value.ToInt16 (nf_provider); if (targetType == TypeManager.int32_type) return convert_value.ToInt32 (nf_provider); if (targetType == TypeManager.int64_type) return convert_value.ToInt64 (nf_provider); if (targetType == TypeManager.sbyte_type) return convert_value.ToSByte (nf_provider); if (targetType == TypeManager.decimal_type) { if (convert_value.GetType () == typeof (char)) return (decimal) convert_value.ToInt32 (nf_provider); return convert_value.ToDecimal (nf_provider); } if (targetType == TypeManager.double_type) { if (convert_value.GetType () == typeof (char)) return (double) convert_value.ToInt32 (nf_provider); return convert_value.ToDouble (nf_provider); } if (targetType == TypeManager.float_type) { if (convert_value.GetType () == typeof (char)) return (float)convert_value.ToInt32 (nf_provider); return convert_value.ToSingle (nf_provider); } if (targetType == TypeManager.string_type) return convert_value.ToString (nf_provider); if (targetType == TypeManager.ushort_type) return convert_value.ToUInt16 (nf_provider); if (targetType == TypeManager.uint32_type) return convert_value.ToUInt32 (nf_provider); if (targetType == TypeManager.uint64_type) return convert_value.ToUInt64 (nf_provider); if (targetType == TypeManager.object_type) return value; error = true; } catch { error = true; } return null; } /// <summary> /// Utility function that can be used to probe whether a type /// is managed or not. /// </summary> public static bool VerifyUnmanaged (ModuleContainer rc, TypeSpec t, Location loc) { while (t.IsPointer) t = GetElementType (t); if (IsUnmanagedType (t)) return true; rc.Compiler.Report.SymbolRelatedToPreviousError (t); rc.Compiler.Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'", CSharpName (t)); return false; } #region Generics // This method always return false for non-generic compiler, // while Type.IsGenericParameter is returned if it is supported. public static bool IsGenericParameter (TypeSpec type) { return type.IsGenericParameter; } public static bool IsGenericType (TypeSpec type) { return type.IsGeneric; } public static TypeSpec[] GetTypeArguments (TypeSpec t) { // TODO: return empty array !! return t.TypeArguments; } /// <summary> /// Check whether `type' and `parent' are both instantiations of the same /// generic type. Note that we do not check the type parameters here. /// </summary> public static bool IsInstantiationOfSameGenericType (TypeSpec type, TypeSpec parent) { return type == parent || type.MemberDefinition == parent.MemberDefinition; } public static bool IsNullableType (TypeSpec t) { return generic_nullable_type == t.GetDefinition (); } #endregion } }
using Jint.Collections; using Jint.Native.ArrayBuffer; using Jint.Native.Object; using Jint.Native.Symbol; using Jint.Native.TypedArray; using Jint.Runtime; using Jint.Runtime.Descriptors; using Jint.Runtime.Interop; namespace Jint.Native.DataView { /// <summary> /// https://tc39.es/ecma262/#sec-properties-of-the-dataview-prototype-object /// </summary> public sealed class DataViewPrototype : ObjectInstance { private readonly Realm _realm; private readonly DataViewConstructor _constructor; internal DataViewPrototype( Engine engine, Realm realm, DataViewConstructor constructor, ObjectPrototype objectPrototype) : base(engine) { _prototype = objectPrototype; _realm = realm; _constructor = constructor; } protected override void Initialize() { const PropertyFlag lengthFlags = PropertyFlag.Configurable; const PropertyFlag propertyFlags = PropertyFlag.Configurable | PropertyFlag.Writable; var properties = new PropertyDictionary(24, checkExistingKeys: false) { ["buffer"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(_engine, "get buffer", Buffer, 0, lengthFlags), Undefined, PropertyFlag.Configurable), ["byteLength"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(_engine, "get byteLength", ByteLength, 0, lengthFlags), Undefined, PropertyFlag.Configurable), ["byteOffset"] = new GetSetPropertyDescriptor(new ClrFunctionInstance(Engine, "get byteOffset", ByteOffset, 0, lengthFlags), Undefined, PropertyFlag.Configurable), ["constructor"] = new PropertyDescriptor(_constructor, PropertyFlag.NonEnumerable), ["getBigInt64"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getBigInt64", GetBigInt64, length: 1, lengthFlags), propertyFlags), ["getBigUint64"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getBigUint64", GetBigUint64, length: 1, lengthFlags), propertyFlags), ["getFloat32"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getFloat32", GetFloat32, length: 1, lengthFlags), propertyFlags), ["getFloat64"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getFloat64", GetFloat64, length: 1, lengthFlags), propertyFlags), ["getInt8"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getInt8", GetInt8, length: 1, lengthFlags), propertyFlags), ["getInt16"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getInt16", GetInt16, length: 1, lengthFlags), propertyFlags), ["getInt32"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getInt32", GetInt32, length: 1, lengthFlags), propertyFlags), ["getUint8"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getUint8", GetUint8, length: 1, lengthFlags), propertyFlags), ["getUint16"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getUint16", GetUint16, length: 1, lengthFlags), propertyFlags), ["getUint32"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "getUint32", GetUint32, length: 1, lengthFlags), propertyFlags), ["setBigInt64"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setBigInt64", SetBigInt64, length: 2, lengthFlags), propertyFlags), ["setBigUint64"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setBigUint64", SetBigUint64, length: 2, lengthFlags), propertyFlags), ["setFloat32"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setFloat32", SetFloat32, length: 2, lengthFlags), propertyFlags), ["setFloat64"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setFloat64", SetFloat64, length: 2, lengthFlags), propertyFlags), ["setInt8"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setInt8", SetInt8, length: 2, lengthFlags), propertyFlags), ["setInt16"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setInt16", SetInt16, length: 2, lengthFlags), propertyFlags), ["setInt32"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setInt32", SetInt32, length: 2, lengthFlags), propertyFlags), ["setUint8"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setUint8", SetUint8, length: 2, lengthFlags), propertyFlags), ["setUint16"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setUint16", SetUint16, length: 2, lengthFlags), propertyFlags), ["setUint32"] = new PropertyDescriptor(new ClrFunctionInstance(Engine, "setUint32", SetUint32, length: 2, lengthFlags), propertyFlags) }; SetProperties(properties); var symbols = new SymbolDictionary(1) { [GlobalSymbolRegistry.ToStringTag] = new PropertyDescriptor("DataView", PropertyFlag.Configurable) }; SetSymbols(symbols); } /// <summary> /// https://tc39.es/ecma262/#sec-get-dataview.prototype.buffer /// </summary> private JsValue Buffer(JsValue thisObj, JsValue[] arguments) { var o = thisObj as DataViewInstance; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.buffer called on incompatible receiver " + thisObj); } return o._viewedArrayBuffer; } /// <summary> /// https://tc39.es/ecma262/#sec-get-dataview.prototype.bytelength /// </summary> private JsValue ByteLength(JsValue thisObj, JsValue[] arguments) { var o = thisObj as DataViewInstance; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteLength called on incompatible receiver " + thisObj); } var buffer = o._viewedArrayBuffer; buffer.AssertNotDetached(); return JsNumber.Create(o._byteLength); } /// <summary> /// https://tc39.es/ecma262/#sec-get-dataview.prototype.byteoffset /// </summary> private JsValue ByteOffset(JsValue thisObj, JsValue[] arguments) { var o = thisObj as DataViewInstance; if (o is null) { ExceptionHelper.ThrowTypeError(_realm, "Method get DataView.prototype.byteOffset called on incompatible receiver " + thisObj); } var buffer = o._viewedArrayBuffer; buffer.AssertNotDetached(); return JsNumber.Create(o._byteOffset); } private JsValue GetBigInt64(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), arguments.At(1), TypedArrayElementType.BigInt64); } private JsValue GetBigUint64(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), arguments.At(1), TypedArrayElementType.BigUint64); } private JsValue GetFloat32(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Float32); } private JsValue GetFloat64(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Float64); } private JsValue GetInt8(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), JsBoolean.True, TypedArrayElementType.Int8); } private JsValue GetInt16(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Int16); } private JsValue GetInt32(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Int32); } private JsValue GetUint8(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), JsBoolean.True, TypedArrayElementType.Uint8); } private JsValue GetUint16(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Uint16); } private JsValue GetUint32(JsValue thisObj, JsValue[] arguments) { return GetViewValue(thisObj, arguments.At(0), arguments.At(1, JsBoolean.False), TypedArrayElementType.Uint32); } private JsValue SetBigInt64(JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), arguments.At(2), TypedArrayElementType.BigInt64, arguments.At(1)); } private JsValue SetBigUint64(JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), arguments.At(2), TypedArrayElementType.BigUint64, arguments.At(1)); } private JsValue SetFloat32 (JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Float32, arguments.At(1)); } private JsValue SetFloat64(JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Float64, arguments.At(1)); } private JsValue SetInt8 (JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), JsBoolean.True, TypedArrayElementType.Int8, arguments.At(1)); } private JsValue SetInt16(JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Int16, arguments.At(1)); } private JsValue SetInt32(JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Int32, arguments.At(1)); } private JsValue SetUint8(JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), JsBoolean.True, TypedArrayElementType.Uint8, arguments.At(1)); } private JsValue SetUint16(JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Uint16, arguments.At(1)); } private JsValue SetUint32(JsValue thisObj, JsValue[] arguments) { return SetViewValue(thisObj, arguments.At(0), arguments.At(2, JsBoolean.False), TypedArrayElementType.Uint32, arguments.At(1)); } /// <summary> /// https://tc39.es/ecma262/#sec-getviewvalue /// </summary> private JsValue GetViewValue( JsValue view, JsValue requestIndex, JsValue isLittleEndian, TypedArrayElementType type) { var dataView = view as DataViewInstance; if (dataView is null) { ExceptionHelper.ThrowTypeError(_realm, "Method called on incompatible receiver " + view); } var getIndex = (int) TypeConverter.ToIndex(_realm, requestIndex); var isLittleEndianBoolean = TypeConverter.ToBoolean(isLittleEndian); var buffer = dataView._viewedArrayBuffer; buffer.AssertNotDetached(); var viewOffset = dataView._byteOffset; var viewSize = dataView._byteLength; var elementSize = type.GetElementSize(); if (getIndex + elementSize > viewSize) { ExceptionHelper.ThrowRangeError(_realm, "Offset is outside the bounds of the DataView"); } var bufferIndex = (int) (getIndex + viewOffset); return buffer.GetValueFromBuffer(bufferIndex, type, false, ArrayBufferOrder.Unordered, isLittleEndianBoolean).ToJsValue(); } /// <summary> /// https://tc39.es/ecma262/#sec-setviewvalue /// </summary> private JsValue SetViewValue( JsValue view, JsValue requestIndex, JsValue isLittleEndian, TypedArrayElementType type, JsValue value) { var dataView = view as DataViewInstance; if (dataView is null) { ExceptionHelper.ThrowTypeError(_realm, "Method called on incompatible receiver " + view); } var getIndex = TypeConverter.ToIndex(_realm, requestIndex); TypedArrayValue numberValue; if (type.IsBigIntElementType()) { numberValue = TypeConverter.ToBigInt(value); } else { numberValue = TypeConverter.ToNumber(value); } var isLittleEndianBoolean = TypeConverter.ToBoolean(isLittleEndian); var buffer = dataView._viewedArrayBuffer; buffer.AssertNotDetached(); var viewOffset = dataView._byteOffset; var viewSize = dataView._byteLength; var elementSize = type.GetElementSize(); if (getIndex + elementSize > viewSize) { ExceptionHelper.ThrowRangeError(_realm, "Offset is outside the bounds of the DataView"); } var bufferIndex = (int) (getIndex + viewOffset); buffer.SetValueInBuffer(bufferIndex, type, numberValue, false, ArrayBufferOrder.Unordered, isLittleEndianBoolean); return Undefined; } } }
using Godot; using GodotTools.Core; using GodotTools.Export; using GodotTools.Utils; using System; using System.Collections.Generic; using System.IO; using System.Linq; using GodotTools.Build; using GodotTools.Ides; using GodotTools.Ides.Rider; using GodotTools.Internals; using GodotTools.ProjectEditor; using JetBrains.Annotations; using static GodotTools.Internals.Globals; using File = GodotTools.Utils.File; using OS = GodotTools.Utils.OS; using Path = System.IO.Path; namespace GodotTools { public class GodotSharpEditor : EditorPlugin, ISerializationListener { private EditorSettings _editorSettings; private PopupMenu _menuPopup; private AcceptDialog _errorDialog; private Button _bottomPanelBtn; private Button _toolBarBuildButton; // TODO Use WeakReference once we have proper serialization. private WeakRef _exportPluginWeak; public GodotIdeManager GodotIdeManager { get; private set; } public MSBuildPanel MSBuildPanel { get; private set; } public bool SkipBuildBeforePlaying { get; set; } = false; public static string ProjectAssemblyName { get { string projectAssemblyName = (string)ProjectSettings.GetSetting("application/config/name"); projectAssemblyName = projectAssemblyName.ToSafeDirName(); if (string.IsNullOrEmpty(projectAssemblyName)) projectAssemblyName = "UnnamedProject"; return projectAssemblyName; } } private bool CreateProjectSolution() { using (var pr = new EditorProgress("create_csharp_solution", "Generating solution...".TTR(), 3)) { pr.Step("Generating C# project...".TTR()); string resourceDir = ProjectSettings.GlobalizePath("res://"); string path = resourceDir; string name = ProjectAssemblyName; string guid = CsProjOperations.GenerateGameProject(path, name); if (guid.Length > 0) { var solution = new DotNetSolution(name) { DirectoryPath = path }; var projectInfo = new DotNetSolution.ProjectInfo { Guid = guid, PathRelativeToSolution = name + ".csproj", Configs = new List<string> {"Debug", "ExportDebug", "ExportRelease"} }; solution.AddNewProject(name, projectInfo); try { solution.Save(); } catch (IOException e) { ShowErrorDialog("Failed to save solution. Exception message: ".TTR() + e.Message); return false; } pr.Step("Updating Godot API assemblies...".TTR()); string debugApiAssembliesError = Internal.UpdateApiAssembliesFromPrebuilt("Debug"); if (!string.IsNullOrEmpty(debugApiAssembliesError)) { ShowErrorDialog("Failed to update the Godot API assemblies: " + debugApiAssembliesError); return false; } string releaseApiAssembliesError = Internal.UpdateApiAssembliesFromPrebuilt("Release"); if (!string.IsNullOrEmpty(releaseApiAssembliesError)) { ShowErrorDialog("Failed to update the Godot API assemblies: " + releaseApiAssembliesError); return false; } pr.Step("Done".TTR()); // Here, after all calls to progress_task_step CallDeferred(nameof(_RemoveCreateSlnMenuOption)); } else { ShowErrorDialog("Failed to create C# project.".TTR()); } return true; } } private void _RemoveCreateSlnMenuOption() { _menuPopup.RemoveItem(_menuPopup.GetItemIndex((int)MenuOptions.CreateSln)); _bottomPanelBtn.Show(); _toolBarBuildButton.Show(); } private void _MenuOptionPressed(int id) { switch ((MenuOptions)id) { case MenuOptions.CreateSln: CreateProjectSolution(); break; case MenuOptions.SetupGodotNugetFallbackFolder: { try { string fallbackFolder = NuGetUtils.GodotFallbackFolderPath; NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, fallbackFolder); NuGetUtils.AddBundledPackagesToFallbackFolder(fallbackFolder); } catch (Exception e) { ShowErrorDialog("Failed to setup Godot NuGet Offline Packages: " + e.Message); } break; } default: throw new ArgumentOutOfRangeException(nameof(id), id, "Invalid menu option"); } } private void BuildSolutionPressed() { if (!File.Exists(GodotSharpDirs.ProjectSlnPath)) { if (!CreateProjectSolution()) return; // Failed to create solution } Instance.MSBuildPanel.BuildSolution(); } public override void _Ready() { base._Ready(); MSBuildPanel.BuildOutputView.BuildStateChanged += BuildStateChanged; } private enum MenuOptions { CreateSln, SetupGodotNugetFallbackFolder, } public void ShowErrorDialog(string message, string title = "Error") { _errorDialog.Title = title; _errorDialog.DialogText = message; _errorDialog.PopupCentered(); } private static string _vsCodePath = string.Empty; private static readonly string[] VsCodeNames = { "code", "code-oss", "vscode", "vscode-oss", "visual-studio-code", "visual-studio-code-oss" }; [UsedImplicitly] public Error OpenInExternalEditor(Script script, int line, int col) { var editorId = (ExternalEditorId)_editorSettings.GetSetting("mono/editor/external_editor"); switch (editorId) { case ExternalEditorId.None: // Not an error. Tells the caller to fallback to the global external editor settings or the built-in editor. return Error.Unavailable; case ExternalEditorId.VisualStudio: { string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath); var args = new List<string> { GodotSharpDirs.ProjectSlnPath, line >= 0 ? $"{scriptPath};{line + 1};{col + 1}" : scriptPath }; string command = Path.Combine(GodotSharpDirs.DataEditorToolsDir, "GodotTools.OpenVisualStudio.exe"); try { if (Godot.OS.IsStdoutVerbose()) Console.WriteLine($"Running: \"{command}\" {string.Join(" ", args.Select(a => $"\"{a}\""))}"); OS.RunProcess(command, args); } catch (Exception e) { GD.PushError($"Error when trying to run code editor: VisualStudio. Exception message: '{e.Message}'"); } break; } case ExternalEditorId.VisualStudioForMac: goto case ExternalEditorId.MonoDevelop; case ExternalEditorId.Rider: { string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath); RiderPathManager.OpenFile(GodotSharpDirs.ProjectSlnPath, scriptPath, line); return Error.Ok; } case ExternalEditorId.MonoDevelop: { string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath); GodotIdeManager.LaunchIdeAsync().ContinueWith(launchTask => { var editorPick = launchTask.Result; if (line >= 0) editorPick?.SendOpenFile(scriptPath, line + 1, col); else editorPick?.SendOpenFile(scriptPath); }); break; } case ExternalEditorId.VsCode: { if (string.IsNullOrEmpty(_vsCodePath) || !File.Exists(_vsCodePath)) { // Try to search it again if it wasn't found last time or if it was removed from its location _vsCodePath = VsCodeNames.SelectFirstNotNull(OS.PathWhich, orElse: string.Empty); } var args = new List<string>(); bool osxAppBundleInstalled = false; if (OS.IsMacOS) { // The package path is '/Applications/Visual Studio Code.app' const string vscodeBundleId = "com.microsoft.VSCode"; osxAppBundleInstalled = Internal.IsOsxAppBundleInstalled(vscodeBundleId); if (osxAppBundleInstalled) { args.Add("-b"); args.Add(vscodeBundleId); // The reusing of existing windows made by the 'open' command might not choose a wubdiw that is // editing our folder. It's better to ask for a new window and let VSCode do the window management. args.Add("-n"); // The open process must wait until the application finishes (which is instant in VSCode's case) args.Add("--wait-apps"); args.Add("--args"); } } string resourcePath = ProjectSettings.GlobalizePath("res://"); args.Add(resourcePath); string scriptPath = ProjectSettings.GlobalizePath(script.ResourcePath); if (line >= 0) { args.Add("-g"); args.Add($"{scriptPath}:{line}:{col}"); } else { args.Add(scriptPath); } string command; if (OS.IsMacOS) { if (!osxAppBundleInstalled && string.IsNullOrEmpty(_vsCodePath)) { GD.PushError("Cannot find code editor: VSCode"); return Error.FileNotFound; } command = osxAppBundleInstalled ? "/usr/bin/open" : _vsCodePath; } else { if (string.IsNullOrEmpty(_vsCodePath)) { GD.PushError("Cannot find code editor: VSCode"); return Error.FileNotFound; } command = _vsCodePath; } try { OS.RunProcess(command, args); } catch (Exception e) { GD.PushError($"Error when trying to run code editor: VSCode. Exception message: '{e.Message}'"); } break; } default: throw new ArgumentOutOfRangeException(); } return Error.Ok; } [UsedImplicitly] public bool OverridesExternalEditor() { return (ExternalEditorId)_editorSettings.GetSetting("mono/editor/external_editor") != ExternalEditorId.None; } public override bool _Build() { return BuildManager.EditorBuildCallback(); } private void ApplyNecessaryChangesToSolution() { try { // Migrate solution from old configuration names to: Debug, ExportDebug and ExportRelease DotNetSolution.MigrateFromOldConfigNames(GodotSharpDirs.ProjectSlnPath); var msbuildProject = ProjectUtils.Open(GodotSharpDirs.ProjectCsProjPath) ?? throw new Exception("Cannot open C# project"); // NOTE: The order in which changes are made to the project is important // Migrate to MSBuild project Sdks style if using the old style ProjectUtils.MigrateToProjectSdksStyle(msbuildProject, ProjectAssemblyName); ProjectUtils.EnsureGodotSdkIsUpToDate(msbuildProject); if (msbuildProject.HasUnsavedChanges) { // Save a copy of the project before replacing it FileUtils.SaveBackupCopy(GodotSharpDirs.ProjectCsProjPath); msbuildProject.Save(); } } catch (Exception e) { GD.PushError(e.ToString()); } } private void BuildStateChanged() { if (_bottomPanelBtn != null) _bottomPanelBtn.Icon = MSBuildPanel.BuildOutputView.BuildStateIcon; } public override void _EnablePlugin() { base._EnablePlugin(); if (Instance != null) throw new InvalidOperationException(); Instance = this; var editorInterface = GetEditorInterface(); var editorBaseControl = editorInterface.GetBaseControl(); _editorSettings = editorInterface.GetEditorSettings(); _errorDialog = new AcceptDialog(); editorBaseControl.AddChild(_errorDialog); MSBuildPanel = new MSBuildPanel(); _bottomPanelBtn = AddControlToBottomPanel(MSBuildPanel, "MSBuild".TTR()); AddChild(new HotReloadAssemblyWatcher {Name = "HotReloadAssemblyWatcher"}); _menuPopup = new PopupMenu(); _menuPopup.Hide(); AddToolSubmenuItem("C#", _menuPopup); var buildSolutionShortcut = (Shortcut)EditorShortcut("mono/build_solution"); _toolBarBuildButton = new Button { Text = "Build", HintTooltip = "Build Solution".TTR(), FocusMode = Control.FocusModeEnum.None, Shortcut = buildSolutionShortcut, ShortcutInTooltip = true }; _toolBarBuildButton.PressedSignal += BuildSolutionPressed; AddControlToContainer(CustomControlContainer.Toolbar, _toolBarBuildButton); if (File.Exists(GodotSharpDirs.ProjectSlnPath) && File.Exists(GodotSharpDirs.ProjectCsProjPath)) { ApplyNecessaryChangesToSolution(); } else { _bottomPanelBtn.Hide(); _toolBarBuildButton.Hide(); _menuPopup.AddItem("Create C# solution".TTR(), (int)MenuOptions.CreateSln); } _menuPopup.IdPressed += _MenuOptionPressed; // External editor settings EditorDef("mono/editor/external_editor", ExternalEditorId.None); string settingsHintStr = "Disabled"; if (OS.IsWindows) { settingsHintStr += $",Visual Studio:{(int)ExternalEditorId.VisualStudio}" + $",MonoDevelop:{(int)ExternalEditorId.MonoDevelop}" + $",Visual Studio Code:{(int)ExternalEditorId.VsCode}" + $",JetBrains Rider:{(int)ExternalEditorId.Rider}"; } else if (OS.IsMacOS) { settingsHintStr += $",Visual Studio:{(int)ExternalEditorId.VisualStudioForMac}" + $",MonoDevelop:{(int)ExternalEditorId.MonoDevelop}" + $",Visual Studio Code:{(int)ExternalEditorId.VsCode}" + $",JetBrains Rider:{(int)ExternalEditorId.Rider}"; } else if (OS.IsUnixLike) { settingsHintStr += $",MonoDevelop:{(int)ExternalEditorId.MonoDevelop}" + $",Visual Studio Code:{(int)ExternalEditorId.VsCode}" + $",JetBrains Rider:{(int)ExternalEditorId.Rider}"; } _editorSettings.AddPropertyInfo(new Godot.Collections.Dictionary { ["type"] = Variant.Type.Int, ["name"] = "mono/editor/external_editor", ["hint"] = PropertyHint.Enum, ["hint_string"] = settingsHintStr }); // Export plugin var exportPlugin = new ExportPlugin(); AddExportPlugin(exportPlugin); exportPlugin.RegisterExportSettings(); _exportPluginWeak = WeakRef(exportPlugin); try { // At startup we make sure NuGet.Config files have our Godot NuGet fallback folder included NuGetUtils.AddFallbackFolderToUserNuGetConfigs(NuGetUtils.GodotFallbackFolderName, NuGetUtils.GodotFallbackFolderPath); } catch (Exception e) { GD.PushError("Failed to add Godot NuGet Offline Packages to NuGet.Config: " + e.Message); } BuildManager.Initialize(); RiderPathManager.Initialize(); GodotIdeManager = new GodotIdeManager(); AddChild(GodotIdeManager); } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (_exportPluginWeak != null) { // We need to dispose our export plugin before the editor destroys EditorSettings. // Otherwise, if the GC disposes it at a later time, EditorExportPlatformAndroid // will be freed after EditorSettings already was, and its device polling thread // will try to access the EditorSettings singleton, resulting in null dereferencing. (_exportPluginWeak.GetRef() as ExportPlugin)?.Dispose(); _exportPluginWeak.Dispose(); } GodotIdeManager?.Dispose(); } public void OnBeforeSerialize() { } public void OnAfterDeserialize() { Instance = this; } // Singleton public static GodotSharpEditor Instance { get; private set; } [UsedImplicitly] private GodotSharpEditor() { } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using AngularMaterialDotNet.API.Areas.HelpPage.ModelDescriptions; using AngularMaterialDotNet.API.Areas.HelpPage.Models; namespace AngularMaterialDotNet.API.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// BasicOperations operations. /// </summary> internal partial class BasicOperations : Microsoft.Rest.IServiceOperations<AzureCompositeModel>, IBasicOperations { /// <summary> /// Initializes a new instance of the BasicOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal BasicOperations(AzureCompositeModel client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex type {id: 2, name: 'abc', color: 'YELLOW'} /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </summary> /// <param name='complexBody'> /// Please put {id: 2, name: 'abc', color: 'Magenta'} /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PutValidWithHttpMessagesAsync(Basic complexBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (complexBody == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "complexBody"); } string apiVersion = "2016-02-29"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/valid").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is invalid for the local strong type /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetInvalidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/invalid").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type that is empty /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetEmptyWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/empty").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type whose properties are null /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/null").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get a basic complex type while the server doesn't provide a response /// payload /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Basic>> GetNotProvidedWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNotProvided", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/basic/notprovided").ToString(); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Basic>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Basic>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
//----------------------------------------------------------------------- // <copyright file="PersonPOCOTests.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Tests of serialization behaviour on the AutoSerializable class PersonPOCO</summary> //----------------------------------------------------------------------- using Csla.Serialization.Mobile; using Csla.Serialization; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using Csla.Generators.CSharp.TestObjects; using Csla.Generators.CSharp.Tests.Helpers; using Microsoft.Extensions.DependencyInjection; using Csla.Configuration; using Csla.TestHelpers; namespace Csla.Generators.CSharp.Tests { /// <summary> /// Tests of serialization on the PersonPOCO class and its children /// </summary> [TestClass] public class PersonPOCOTests { private static TestDIContext _testDIContext; [ClassInitialize] public static void ClassInitialize(TestContext testContext) { _testDIContext = TestDIContextFactory.CreateDefaultContext(); } #region GetState [TestMethod] public void GetState_WithPersonId5_ReturnsInfoContaining5() { // Arrange SerializationInfo serializationInfo = new SerializationInfo(); int actual; int expected = 5; IMobileObject mobileObject; PersonPOCO person = new PersonPOCO(); person.PersonId = 5; // Act mobileObject = (IMobileObject)person; mobileObject.GetState(serializationInfo); actual = serializationInfo.GetValue<int>("PersonId"); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void GetState_WithFirstNameJoe_ReturnsInfoContainingJoe() { // Arrange SerializationInfo serializationInfo = new SerializationInfo(); string actual; string expected = "Joe"; IMobileObject mobileObject; PersonPOCO person = new PersonPOCO(); person.FirstName = "Joe"; // Act mobileObject = (IMobileObject)person; mobileObject.GetState(serializationInfo); actual = serializationInfo.GetValue<string>("FirstName"); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void GetState_WithLastNameSmith_ReturnsInfoContainingSmith() { // Arrange SerializationInfo serializationInfo = new SerializationInfo(); string actual; string expected = "Smith"; IMobileObject mobileObject; PersonPOCO person = new PersonPOCO(); person.LastName = "Smith"; // Act mobileObject = (IMobileObject)person; mobileObject.GetState(serializationInfo); actual = serializationInfo.GetValue<string>("LastName"); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void GetState_WithInternalDateOfBirth210412_ReturnsInfoWithoutDateOfBirth() { // Arrange SerializationInfo serializationInfo = new SerializationInfo(); bool actual; bool expected = false; IMobileObject mobileObject; PersonPOCO person = new PersonPOCO(); person.SetDateOfBirth(new DateTime(2021, 04, 12, 16, 57, 53)); // Act mobileObject = (IMobileObject)person; mobileObject.GetState(serializationInfo); actual = serializationInfo.Values.ContainsKey("DateOfBirth"); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void GetState_WithMiddleNameMid_ReturnsInfoWithoutMiddleName() { // Arrange SerializationInfo serializationInfo = new SerializationInfo(); bool actual; bool expected = false; IMobileObject mobileObject; PersonPOCO person = new PersonPOCO(); person.SetMiddleName("Mid"); // Act mobileObject = (IMobileObject)person; mobileObject.GetState(serializationInfo); actual = serializationInfo.Values.ContainsKey("MiddleName"); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void GetState_WithFieldMiddleNameMid_ReturnsInfoContainingMid() { // Arrange SerializationInfo serializationInfo = new SerializationInfo(); string actual; string expected = "Mid"; IMobileObject mobileObject; PersonPOCO person = new PersonPOCO(); person.SetMiddleName("Mid"); // Act mobileObject = (IMobileObject)person; mobileObject.GetState(serializationInfo); actual = serializationInfo.GetValue<string>("_middleName"); // Assert Assert.AreEqual(expected, actual); } #endregion #region SetState [TestMethod] public void SetState_WithPersonId5_ReturnsPersonWithId5() { // Arrange SerializationInfo serializationInfo = PersonSerializationInfoFactory.GetDefaultSerializationInfo(); int actual; int expected = 5; PersonPOCO person = new PersonPOCO(); IMobileObject mobileObject; // Act serializationInfo.Values["PersonId"].Value = 5; mobileObject = (IMobileObject)person; mobileObject.SetState(serializationInfo); actual = person.PersonId; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SetState_WithFirstNameJoe_ReturnsPersonWithFirstNameJoe() { // Arrange SerializationInfo serializationInfo = PersonSerializationInfoFactory.GetDefaultSerializationInfo(); string actual; string expected = "Joe"; PersonPOCO person = new PersonPOCO(); IMobileObject mobileObject; // Act serializationInfo.Values["FirstName"].Value = "Joe"; mobileObject = (IMobileObject)person; mobileObject.SetState(serializationInfo); actual = person.FirstName; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SetState_WithLastNameSmith_ReturnsPersonWithLastNameSmith() { // Arrange SerializationInfo serializationInfo = PersonSerializationInfoFactory.GetDefaultSerializationInfo(); string actual; string expected = "Smith"; PersonPOCO person = new PersonPOCO(); IMobileObject mobileObject; // Act serializationInfo.Values["LastName"].Value = "Smith"; mobileObject = (IMobileObject)person; mobileObject.SetState(serializationInfo); actual = person.LastName; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SetState_WithInternalDateOfBirth210412_ReturnsPersonWithNoDateOfBirth() { // Arrange SerializationInfo serializationInfo = PersonSerializationInfoFactory.GetDefaultSerializationInfo(); DateTime actual; DateTime expected = DateTime.MinValue; PersonPOCO person = new PersonPOCO(); IMobileObject mobileObject; // Act serializationInfo.Values["DateOfBirth"].Value = new DateTime(2021, 04, 12, 18, 27, 43); mobileObject = (IMobileObject)person; mobileObject.SetState(serializationInfo); actual = person.GetDateOfBirth(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SetState_WithNonSerializedTextFred_ReturnsEmptyString() { // Arrange SerializationInfo serializationInfo = PersonSerializationInfoFactory.GetDefaultSerializationInfo(); string actual; string expected = string.Empty; PersonPOCO person = new PersonPOCO(); IMobileObject mobileObject; // Act serializationInfo.Values["NonSerializedText"].Value = "Fred"; mobileObject = (IMobileObject)person; mobileObject.SetState(serializationInfo); actual = person.NonSerializedText; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SetState_WithPrivateTextFred_ReturnsEmptyString() { // Arrange SerializationInfo serializationInfo = PersonSerializationInfoFactory.GetDefaultSerializationInfo(); string actual; string expected = string.Empty; PersonPOCO person = new PersonPOCO(); IMobileObject mobileObject; // Act serializationInfo.Values["PrivateText"].Value = "Fred"; mobileObject = (IMobileObject)person; mobileObject.SetState(serializationInfo); actual = person.GetUnderlyingPrivateText(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SetState_WithPrivateSerializedTextFred_ReturnsFred() { // Arrange SerializationInfo serializationInfo = PersonSerializationInfoFactory.GetDefaultSerializationInfo(); string actual; string expected = "Fred"; PersonPOCO person = new PersonPOCO(); IMobileObject mobileObject; // Act serializationInfo.Values["PrivateSerializedText"].Value = "Fred"; mobileObject = (IMobileObject)person; mobileObject.SetState(serializationInfo); actual = person.GetPrivateSerializedText(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SetState_WithIncludedMiddleNameFieldMid_ReturnsMiddleNamePropertyMid() { // Arrange SerializationInfo serializationInfo = PersonSerializationInfoFactory.GetDefaultSerializationInfo(); string actual; string expected = "Mid"; PersonPOCO person = new PersonPOCO(); IMobileObject mobileObject; // Act serializationInfo.Values["_middleName"].Value = "Mid"; mobileObject = (IMobileObject)person; mobileObject.SetState(serializationInfo); actual = person.MiddleName; // Assert Assert.AreEqual(expected, actual); } #endregion #region GetChildren [TestMethod] public void GetChildren_WithAddress1HighStreet_IncludesAddressKey() { var applicationContext = _testDIContext.CreateTestApplicationContext(); // Arrange SerializationInfo serializationInfo = new SerializationInfo(); bool expected = true; bool actual; IMobileObject mobileObject; PersonPOCO person = new PersonPOCO(); person.Address = new AddressPOCO() { AddressLine1 = "1 High Street" }; MobileFormatter formatter = new MobileFormatter(applicationContext); // Act mobileObject = (IMobileObject)person; mobileObject.GetChildren(serializationInfo, formatter); actual = serializationInfo.Children.ContainsKey("Address"); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void GetChildren_WithEmailAddress_IncludesEmailAddressKey() { var applicationContext = _testDIContext.CreateTestApplicationContext(); // Arrange SerializationInfo serializationInfo = new SerializationInfo(); bool expected = true; bool actual; IMobileObject mobileObject; PersonPOCO person = new PersonPOCO(); person.EmailAddress = new EmailAddress() { Email = "[email protected]" }; MobileFormatter formatter = new MobileFormatter(applicationContext); // Act mobileObject = (IMobileObject)person; mobileObject.GetChildren(serializationInfo, formatter); actual = serializationInfo.Children.ContainsKey("EmailAddress"); // Assert Assert.AreEqual(expected, actual); } #endregion #region SetChildren #endregion #region Serialize Then Deserialize [TestMethod] public void SerializeThenDeserialize_WithPublicAutoImpPropertyPersonId5_HasPersonId5() { // Arrange int actual; int expected = 5; PersonPOCO person = new PersonPOCO(); person.PersonId = 5; PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.PersonId; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithPublicAutoImpPropertyFirstNameJoe_HasFirstNameJoe() { // Arrange string actual; string expected = "Joe"; PersonPOCO person = new PersonPOCO(); person.FirstName = "Joe"; PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.FirstName; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithPublicPropertyLastNameSmith_HasLastNameSmith() { // Arrange string actual; string expected = "Smith"; PersonPOCO person = new PersonPOCO(); person.LastName = "Smith"; PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.LastName; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithIncludedPrivateFieldMiddleNameMid_HasMiddleNameMid() { // Arrange string actual; string expected = "Mid"; PersonPOCO person = new PersonPOCO(); person.SetMiddleName("Mid"); PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.MiddleName; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithExcludedPublicAutoImpPropertyNonSerializedTextNon_HasEmptyNonSerializedText() { // Arrange string actual; string expected = ""; PersonPOCO person = new PersonPOCO(); person.NonSerializedText = "Non"; PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.NonSerializedText; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithIncludedPrivateAutoImpPropertyPrivateSerializedTextPri_HasPrivateSerializedTextPri() { // Arrange string actual; string expected = "Pri"; PersonPOCO person = new PersonPOCO(); person.SetPrivateSerializedText("Pri"); PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.GetPrivateSerializedText(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithPrivateAutoImpPropertyPrivateTextPriv_HasEmptyPrivateText() { // Arrange string actual; string expected = ""; PersonPOCO person = new PersonPOCO(); person.SetUnderlyingPrivateText("Priv"); PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.GetUnderlyingPrivateText(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithInternalAutoImpPropertyDateOfBirth20210412165753_HasMinDateOfBirth() { // Arrange DateTime actual; DateTime expected = DateTime.MinValue; PersonPOCO person = new PersonPOCO(); person.SetDateOfBirth(new DateTime(2021, 04, 12, 16, 57, 53)); PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.GetDateOfBirth(); // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithAutoSerializableAddress1HighStreet_HasAddressOf1HighStreet() { // Arrange string actual; string expected = "1 High Street"; PersonPOCO person = new PersonPOCO(); person.Address = new AddressPOCO() { AddressLine1 = "1 High Street" }; PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson?.Address?.AddressLine1; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithAutoSerializableAddressNull_HasNullAddress() { // Arrange AddressPOCO actual; PersonPOCO person = new PersonPOCO(); PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.Address; // Assert Assert.IsNull(actual); } [TestMethod] public void SerializeThenDeserialize_WithAutoSerializableAddressTownsville_HasAddressOfTownsville() { // Arrange string actual; string expected = "Townsville"; PersonPOCO person = new PersonPOCO(); person.Address = new AddressPOCO() { Town = "Townsville" }; PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson?.Address?.Town; // Assert Assert.AreEqual(expected, actual); } [TestMethod] public void SerializeThenDeserialize_WithIMobileObjectEmailAddressNull_HasEmailAddressNull() { // Arrange EmailAddress actual; PersonPOCO person = new PersonPOCO(); PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson.EmailAddress; // Assert Assert.IsNull(actual); } [TestMethod] public void SerializeThenDeserialize_WithIMobileObjectEmailAddressAatBdotCom_HasEmailAddressAatBdotCom() { // Arrange string actual; string expected = "[email protected]"; PersonPOCO person = new PersonPOCO(); person.EmailAddress = new EmailAddress() { Email = "[email protected]" }; PersonPOCO deserializedPerson; // Act deserializedPerson = SerializeThenDeserialisePersonPOCO(person); actual = deserializedPerson?.EmailAddress?.Email; // Assert Assert.AreEqual(expected, actual); } #endregion #region Private Helper Methods /// <summary> /// Serialize and then deserialize a PersonPOCO object, exercising the generated code /// associated with these two operations on the PersonPOCO test object /// </summary> /// <param name="valueToSerialize">The object to be serialized</param> /// <returns>The PersonPOCO that results from serialization then deserialization</returns> private PersonPOCO SerializeThenDeserialisePersonPOCO(PersonPOCO valueToSerialize) { var applicationContext = _testDIContext.CreateTestApplicationContext(); System.IO.MemoryStream serializationStream; PersonPOCO deserializedValue; MobileFormatter formatter = new MobileFormatter(applicationContext); // Act using (serializationStream = new System.IO.MemoryStream()) { formatter.Serialize(serializationStream, valueToSerialize); serializationStream.Seek(0, System.IO.SeekOrigin.Begin); deserializedValue = formatter.Deserialize(serializationStream) as PersonPOCO; } return deserializedValue; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.IO; using System.Linq; using System.Xml.Linq; using Microsoft.Build.Framework; using Microsoft.Build.UnitTests; using Microsoft.Build.Utilities; using Shouldly; using Xunit; using Xunit.Abstractions; namespace Microsoft.Build.Tasks.Unittest { public class GenerateBindingRedirectsTests : IDisposable { private readonly ITestOutputHelper _output; private readonly TestEnvironment _env; public GenerateBindingRedirectsTests(ITestOutputHelper output) { _output = output; _env = TestEnvironment.Create(output); } public void Dispose() { _env.Dispose(); } /// <summary> /// In this case, /// - A valid redirect information is provided for <see cref="GenerateBindingRedirects"/> task. /// Expected: /// - Task should create a target app.config with specified redirect information. /// Rationale: /// - The only goal for <see cref="GenerateBindingRedirects"/> task is to add specified redirects to the output app.config. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TargetAppConfigShouldContainsBindingRedirects() { // Arrange // Current appConfig is empty string appConfigFile = WriteAppConfigRuntimeSection(string.Empty); TaskItemMock redirect = new TaskItemMock("System, Version=10.0.0.0, Culture=Neutral, PublicKeyToken='b77a5c561934e089'", "40.0.0.0"); // Act var redirectResults = GenerateBindingRedirects(appConfigFile, null, redirect); // Assert redirectResults.ExecuteResult.ShouldBeTrue(); redirectResults.TargetAppConfigContent.ShouldContain("<assemblyIdentity name=\"System\" publicKeyToken=\"b77a5c561934e089\" culture=\"neutral\" />"); redirectResults.TargetAppConfigContent.ShouldContain("newVersion=\"40.0.0.0\""); } /// <summary> /// In this case, /// - A valid redirect information is provided for <see cref="GenerateBindingRedirects"/> task and app.config is not empty. /// Expected: /// - Task should create a target app.config with specified redirect information. /// Rationale: /// - The only goal for <see cref="GenerateBindingRedirects"/> task is to add specified redirects to the output app.config. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void TargetAppConfigShouldContainsBindingRedirectsFromAppConfig() { // Arrange string appConfigFile = WriteAppConfigRuntimeSection( @"<assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <dependentAssembly> <assemblyIdentity name=""MyAssembly"" publicKeyToken = ""14a739be0244c389"" culture = ""Neutral""/> <bindingRedirect oldVersion= ""1.0.0.0"" newVersion = ""5.0.0.0"" /> </dependentAssembly> </assemblyBinding>"); TaskItemMock redirect = new TaskItemMock("MyAssembly, Version=10.0.0.0, Culture=Neutral, PublicKeyToken='14a739be0244c389'", "40.0.0.0"); // Act var redirectResults = GenerateBindingRedirects(appConfigFile, null, redirect); // Assert redirectResults.TargetAppConfigContent.ShouldContain("MyAssembly"); redirectResults.TargetAppConfigContent.ShouldContain("<bindingRedirect oldVersion=\"0.0.0.0-40.0.0.0\" newVersion=\"40.0.0.0\""); } /// <summary> /// In this case, /// - An app.config is passed in with two dependentAssembly elements /// Expected: /// - Both redirects appears in the output app.config /// Rationale: /// - assemblyBinding could have more than one dependentAssembly elements and <see cref="GenerateBindingRedirects"/> /// should respect that. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void GenerateBindingRedirectsFromTwoDependentAssemblySections() { // Arrange string appConfigFile = WriteAppConfigRuntimeSection( @"<loadFromRemoteSources enabled=""true""/> <assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"" > <dependentAssembly> <assemblyIdentity name=""Microsoft.ServiceBus"" publicKeyToken =""31bf3856ad364e35"" culture =""neutral"" /> <bindingRedirect oldVersion=""2.0.0.0-3.0.0.0"" newVersion =""2.2.0.0"" /> </dependentAssembly> <probing privatePath=""VSO14"" /> <dependentAssembly> <assemblyIdentity name=""System.Web.Http"" publicKeyToken =""31bf3856ad364e35"" culture =""neutral"" /> <bindingRedirect oldVersion=""4.0.0.0-6.0.0.0"" newVersion =""4.0.0.0"" /> </dependentAssembly> <dependentAssembly> <assemblyIdentity name=""Microsoft.TeamFoundation.Common"" publicKeyToken =""b03f5f7f11d50a3a"" culture =""neutral"" /> <codeBase version=""11.0.0.0"" href =""Microsoft.TeamFoundation.Common.dll"" /> <codeBase version=""14.0.0.0"" href =""VSO14\Microsoft.TeamFoundation.Common.dll"" /> </dependentAssembly> </assemblyBinding>"); TaskItemMock serviceBusRedirect = new TaskItemMock("Microsoft.ServiceBus, Version=2.0.0.0, Culture=Neutral, PublicKeyToken='31bf3856ad364e35'", "41.0.0.0"); TaskItemMock webHttpRedirect = new TaskItemMock("System.Web.Http, Version=4.0.0.0, Culture=Neutral, PublicKeyToken='31bf3856ad364e35'", "40.0.0.0"); // Act var redirectResults = GenerateBindingRedirects(appConfigFile, null, serviceBusRedirect, webHttpRedirect); // Assert redirectResults.ExecuteResult.ShouldBeTrue(); // Naive check that target app.config contains custom redirects. // Output config should have max versions for both serviceBus and webhttp assemblies. redirectResults.TargetAppConfigContent.ShouldContain($"oldVersion=\"0.0.0.0-{serviceBusRedirect.MaxVersion}\""); redirectResults.TargetAppConfigContent.ShouldContain($"newVersion=\"{serviceBusRedirect.MaxVersion}\""); redirectResults.TargetAppConfigContent.ShouldContain($"oldVersion=\"0.0.0.0-{webHttpRedirect.MaxVersion}\""); redirectResults.TargetAppConfigContent.ShouldContain($"newVersion=\"{webHttpRedirect.MaxVersion}\""); XElement targetAppConfig = XElement.Parse(redirectResults.TargetAppConfigContent); targetAppConfig.Descendants() .Count(e => e.Name.LocalName.Equals("assemblyBinding", StringComparison.OrdinalIgnoreCase)) .ShouldBe(1); // "Binding redirects should not add additional assemblyBinding sections into the target app.config: " + targetAppConfig // Log file should contains a warning when GenerateBindingRedirects updates existing app.config entries redirectResults.Engine.AssertLogContains("MSB3836"); } /// <summary> /// In this case, /// - An app.config is passed in that has dependentAssembly section with probing element but without /// assemblyIdentity or bindingRedirect elements. /// Expected: /// - No warning /// Rationale: /// - In initial implementation such app.config was considered invalid and MSB3835 was issued. /// But due to MSDN documentation, dependentAssembly could have only probing element without any other elements inside. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void AppConfigWithProbingPathAndWithoutDependentAssemblyShouldNotProduceWarningsBug1161241() { // Arrange string appConfigFile = WriteAppConfigRuntimeSection( @"<assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <probing privatePath = 'bin;bin2\subbin;bin3'/> </assemblyBinding>"); TaskItemMock redirect = new TaskItemMock("System, Version=10.0.0.0, Culture=Neutral, PublicKeyToken='b77a5c561934e089'", "40.0.0.0"); // Act var redirectResults = GenerateBindingRedirects(appConfigFile, null, redirect); // Assert redirectResults.Engine.Errors.ShouldBe(0); // "Unexpected errors. Engine log: " + redirectResults.Engine.Log redirectResults.Engine.Warnings.ShouldBe(0); // "Unexpected errors. Engine log: " + redirectResults.Engine.Log } /// <summary> /// In this case, /// - An app.config is passed in that has empty assemblyBinding section. /// Expected: /// - No warning /// Rationale: /// - In initial implementation such app.config was considered invalid and MSB3835 was issued. /// But due to MSDN documentation, dependentAssembly could have only probing element without any other elements inside. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void AppConfigWithEmptyAssemblyBindingShouldNotProduceWarnings() { // Arrange string appConfigFile = WriteAppConfigRuntimeSection( @"<assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"" appliesTo=""v1.0.3705""> </assemblyBinding>"); TaskItemMock redirect = new TaskItemMock("System, Version=10.0.0.0, Culture=Neutral, PublicKeyToken='b77a5c561934e089'", "40.0.0.0"); // Act var redirectResults = GenerateBindingRedirects(appConfigFile, null, redirect); // Assert redirectResults.Engine.Errors.ShouldBe(0); redirectResults.Engine.Warnings.ShouldBe(0); } /// <summary> /// In this case, /// - An app.config is passed in that has dependentAssembly section with assemblyIdentity but without bindingRedirect /// Expected: /// - No warning /// Rationale: /// - Due to app.config xsd schema this is a valid configuration. /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void DependentAssemblySectionWithoutBindingRedirectShouldNotProduceWarnings() { // Arrange string appConfigFile = WriteAppConfigRuntimeSection( @"<assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1"" appliesTo=""v1.0.3705""> <dependentAssembly> <assemblyIdentity name=""Microsoft.TeamFoundation.Common"" publicKeyToken =""b03f5f7f11d50a3a"" culture =""neutral"" /> <codeBase version=""11.0.0.0"" href =""Microsoft.TeamFoundation.Common.dll"" /> <codeBase version=""14.0.0.0"" href =""VSO14\Microsoft.TeamFoundation.Common.dll"" /> </dependentAssembly> </assemblyBinding>"); TaskItemMock redirect = new TaskItemMock("System, Version=10.0.0.0, Culture=Neutral, PublicKeyToken='b77a5c561934e089'", "40.0.0.0"); // Act var redirectResults = GenerateBindingRedirects(appConfigFile, null, redirect); // Assert redirectResults.Engine.Errors.ShouldBe(0); redirectResults.Engine.Warnings.ShouldBe(0); } /// <summary> /// In this case, /// - An app.config is passed in but dependentAssembly element is empty. /// Expected: /// - MSB3835 /// Rationale: /// - Due to MSDN documentation, assemblyBinding element should always have a dependentAssembly subsection. /// </summary> [Fact] public void AppConfigInvalidIfDependentAssemblyNodeIsEmpty() { // Construct the app.config. string appConfigFile = WriteAppConfigRuntimeSection( @"<assemblyBinding xmlns=""urn:schemas-microsoft-com:asm.v1""> <dependentAssembly> </dependentAssembly> </assemblyBinding>"); TaskItemMock redirect = new TaskItemMock("System, Version=10.0.0.0, Culture=Neutral, PublicKeyToken='b77a5c561934e089'", "40.0.0.0"); // Act var redirectResults = GenerateBindingRedirects(appConfigFile, null, redirect); // Assert redirectResults.Engine.AssertLogContains("MSB3835"); } [Fact] public void AppConfigFileNotSavedWhenIdentical() { string appConfigFile = WriteAppConfigRuntimeSection(string.Empty); string outputAppConfigFile = _env.ExpectFile(".config").Path; TaskItemMock redirect = new TaskItemMock("System, Version=10.0.0.0, Culture=Neutral, PublicKeyToken='b77a5c561934e089'", "40.0.0.0"); var redirectResults = GenerateBindingRedirects(appConfigFile, outputAppConfigFile, redirect); // Verify it ran correctly redirectResults.ExecuteResult.ShouldBeTrue(); redirectResults.TargetAppConfigContent.ShouldContain("<assemblyIdentity name=\"System\" publicKeyToken=\"b77a5c561934e089\" culture=\"neutral\" />"); redirectResults.TargetAppConfigContent.ShouldContain("newVersion=\"40.0.0.0\""); var oldTimestamp = DateTime.Now.Subtract(TimeSpan.FromDays(30)); File.SetCreationTime(outputAppConfigFile, oldTimestamp); File.SetLastWriteTime(outputAppConfigFile, oldTimestamp); // Make sure it's old File.GetCreationTime(outputAppConfigFile).ShouldBe(oldTimestamp, TimeSpan.FromSeconds(5)); File.GetLastWriteTime(outputAppConfigFile).ShouldBe(oldTimestamp, TimeSpan.FromSeconds(5)); // Re-run the task var redirectResults2 = GenerateBindingRedirects(appConfigFile, outputAppConfigFile, redirect); // Verify it ran correctly and that it's still old redirectResults2.ExecuteResult.ShouldBeTrue(); redirectResults2.TargetAppConfigContent.ShouldContain("<assemblyIdentity name=\"System\" publicKeyToken=\"b77a5c561934e089\" culture=\"neutral\" />"); redirectResults.TargetAppConfigContent.ShouldContain("newVersion=\"40.0.0.0\""); File.GetCreationTime(outputAppConfigFile).ShouldBe(oldTimestamp, TimeSpan.FromSeconds(5)); File.GetLastWriteTime(outputAppConfigFile).ShouldBe(oldTimestamp, TimeSpan.FromSeconds(5)); } private BindingRedirectsExecutionResult GenerateBindingRedirects(string appConfigFile, string targetAppConfigFile, params ITaskItem[] suggestedRedirects) { // Create the engine. MockEngine engine = new MockEngine(_output); string outputAppConfig = string.IsNullOrEmpty(targetAppConfigFile) ? _env.ExpectFile(".config").Path : targetAppConfigFile; GenerateBindingRedirects bindingRedirects = new GenerateBindingRedirects { BuildEngine = engine, SuggestedRedirects = suggestedRedirects ?? new ITaskItem[] { }, AppConfigFile = new TaskItem(appConfigFile), OutputAppConfigFile = new TaskItem(outputAppConfig) }; bool executionResult = bindingRedirects.Execute(); return new BindingRedirectsExecutionResult { ExecuteResult = executionResult, Engine = engine, SourceAppConfigContent = File.ReadAllText(appConfigFile), TargetAppConfigContent = File.ReadAllText(outputAppConfig), TargetAppConfigFilePath = outputAppConfig }; } private string WriteAppConfigRuntimeSection(string runtimeSection) { string formatString = @"<configuration> <runtime> {0} </runtime> </configuration>"; string appConfigContents = string.Format(formatString, runtimeSection); string appConfigFile = _env.CreateFile(".config").Path; File.WriteAllText(appConfigFile, appConfigContents); return appConfigFile; } /// <summary> /// Helper class that contains execution results for <see cref="GenerateBindingRedirects"/>. /// </summary> private class BindingRedirectsExecutionResult { public MockEngine Engine { get; set; } public string SourceAppConfigContent { get; set; } public string TargetAppConfigContent { get; set; } public bool ExecuteResult { get; set; } public string TargetAppConfigFilePath { get; set; } } /// <summary> /// Mock implementation of the <see cref="ITaskItem"/>. /// </summary> private class TaskItemMock : ITaskItem { public TaskItemMock(string assemblyName, string maxVersion) { ((ITaskItem)this).ItemSpec = assemblyName; MaxVersion = maxVersion; } public string MaxVersion { get; } string ITaskItem.ItemSpec { get; set; } ICollection ITaskItem.MetadataNames { get; } int ITaskItem.MetadataCount { get; } string ITaskItem.GetMetadata(string metadataName) { return MaxVersion; } void ITaskItem.SetMetadata(string metadataName, string metadataValue) { throw new NotImplementedException(); } void ITaskItem.RemoveMetadata(string metadataName) { throw new NotImplementedException(); } void ITaskItem.CopyMetadataTo(ITaskItem destinationItem) { throw new NotImplementedException(); } IDictionary ITaskItem.CloneCustomMetadata() { throw new NotImplementedException(); } } } }
// // https://github.com/ServiceStack/ServiceStack.Text // ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers. // // Authors: // Demis Bellot ([email protected]) // // Copyright 2012 Service Stack LLC. All Rights Reserved. // // Licensed under the same terms of ServiceStack. // using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using ServiceStack.Text.Json; namespace ServiceStack.Text.Common { public static class DeserializeType<TSerializer> where TSerializer : ITypeSerializer { private static readonly ITypeSerializer Serializer = JsWriter.GetTypeSerializer<TSerializer>(); internal static ParseStringDelegate GetParseMethod(TypeConfig typeConfig) { var type = typeConfig.Type; if (!type.IsStandardClass()) return null; var map = DeserializeTypeRef.GetTypeAccessorMap(typeConfig, Serializer); var ctorFn = JsConfig.ModelFactory(type); if (map == null) return value => ctorFn(); return typeof(TSerializer) == typeof(Json.JsonTypeSerializer) ? (ParseStringDelegate)(value => DeserializeTypeRefJson.StringToType(typeConfig, value, ctorFn, map)) : value => DeserializeTypeRefJsv.StringToType(typeConfig, value, ctorFn, map); } public static object ObjectStringToType(string strType) { var type = ExtractType(strType); if (type != null) { var parseFn = Serializer.GetParseFn(type); var propertyValue = parseFn(strType); return propertyValue; } if (JsConfig.ConvertObjectTypesIntoStringDictionary && !string.IsNullOrEmpty(strType)) { if (strType[0] == JsWriter.MapStartChar) { var dynamicMatch = DeserializeDictionary<TSerializer>.ParseDictionary<string, object>(strType, null, Serializer.UnescapeString, Serializer.UnescapeString); if (dynamicMatch != null && dynamicMatch.Count > 0) { return dynamicMatch; } } if (strType[0] == JsWriter.ListStartChar) { return DeserializeList<List<object>, TSerializer>.Parse(strType); } } return Serializer.UnescapeString(strType); } public static Type ExtractType(string strType) { if (strType == null || strType.Length <= 1) return null; var hasWhitespace = JsonUtils.WhiteSpaceChars.Contains(strType[1]); if (hasWhitespace) { var pos = strType.IndexOf('"'); if (pos >= 0) strType = "{" + strType.Substring(pos); } var typeAttrInObject = Serializer.TypeAttrInObject; if (strType.Length > typeAttrInObject.Length && strType.Substring(0, typeAttrInObject.Length) == typeAttrInObject) { var propIndex = typeAttrInObject.Length; var typeName = Serializer.UnescapeSafeString(Serializer.EatValue(strType, ref propIndex)); var type = JsConfig.TypeFinder(typeName); if (type == null) { Tracer.Instance.WriteWarning("Could not find type: " + typeName); return null; } return PclExport.Instance.UseType(type); } return null; } public static object ParseAbstractType<T>(string value) { if (typeof(T).IsAbstract()) { if (string.IsNullOrEmpty(value)) return null; var concreteType = ExtractType(value); if (concreteType != null) { return Serializer.GetParseFn(concreteType)(value); } Tracer.Instance.WriteWarning( "Could not deserialize Abstract Type with unknown concrete type: " + typeof(T).FullName); } return null; } public static object ParseQuotedPrimitive(string value) { if (string.IsNullOrEmpty(value)) return null; Guid guidValue; if (Guid.TryParse(value, out guidValue)) return guidValue; if (value.StartsWith(DateTimeSerializer.EscapedWcfJsonPrefix, StringComparison.Ordinal) || value.StartsWith(DateTimeSerializer.WcfJsonPrefix, StringComparison.Ordinal)) { return DateTimeSerializer.ParseWcfJsonDate(value); } if (JsConfig.DateHandler == DateHandler.ISO8601) { // check that we have UTC ISO8601 date: // YYYY-MM-DDThh:mm:ssZ // YYYY-MM-DDThh:mm:ss+02:00 // YYYY-MM-DDThh:mm:ss-02:00 if (value.Length > 14 && value[10] == 'T' && (value.EndsWithInvariant("Z") || value[value.Length - 6] == '+' || value[value.Length - 6] == '-')) { return DateTimeSerializer.ParseShortestXsdDateTime(value); } } if (JsConfig.DateHandler == DateHandler.RFC1123) { // check that we have RFC1123 date: // ddd, dd MMM yyyy HH:mm:ss GMT if (value.Length == 29 && (value.EndsWithInvariant("GMT"))) { return DateTimeSerializer.ParseRFC1123DateTime(value); } } return Serializer.UnescapeString(value); } public static object ParsePrimitive(string value) { if (string.IsNullOrEmpty(value)) return null; bool boolValue; if (bool.TryParse(value, out boolValue)) return boolValue; // Parse as decimal decimal decimalValue; var acceptDecimal = JsConfig.ParsePrimitiveFloatingPointTypes.HasFlag(ParseAsType.Decimal); var isDecimal = decimal.TryParse(value, NumberStyles.Number, CultureInfo.InvariantCulture, out decimalValue); // Check if the number is an Primitive Integer type given that we have a decimal if (isDecimal && decimalValue == decimal.Truncate(decimalValue)) { // Value is a whole number var parseAs = JsConfig.ParsePrimitiveIntegerTypes; if (parseAs.HasFlag(ParseAsType.Byte) && decimalValue <= byte.MaxValue && decimalValue >= byte.MinValue) return (byte)decimalValue; if (parseAs.HasFlag(ParseAsType.SByte) && decimalValue <= sbyte.MaxValue && decimalValue >= sbyte.MinValue) return (sbyte)decimalValue; if (parseAs.HasFlag(ParseAsType.Int16) && decimalValue <= Int16.MaxValue && decimalValue >= Int16.MinValue) return (Int16)decimalValue; if (parseAs.HasFlag(ParseAsType.UInt16) && decimalValue <= UInt16.MaxValue && decimalValue >= UInt16.MinValue) return (UInt16)decimalValue; if (parseAs.HasFlag(ParseAsType.Int32) && decimalValue <= Int32.MaxValue && decimalValue >= Int32.MinValue) return (Int32)decimalValue; if (parseAs.HasFlag(ParseAsType.UInt32) && decimalValue <= UInt32.MaxValue && decimalValue >= UInt32.MinValue) return (UInt32)decimalValue; if (parseAs.HasFlag(ParseAsType.Int64) && decimalValue <= Int64.MaxValue && decimalValue >= Int64.MinValue) return (Int64)decimalValue; if (parseAs.HasFlag(ParseAsType.UInt64) && decimalValue <= UInt64.MaxValue && decimalValue >= UInt64.MinValue) return (UInt64)decimalValue; return decimalValue; } // Value is a floating point number // Return a decimal if the user accepts a decimal if (isDecimal && acceptDecimal) return decimalValue; float floatValue; var acceptFloat = JsConfig.ParsePrimitiveFloatingPointTypes.HasFlag(ParseAsType.Single); var isFloat = float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out floatValue); if (acceptFloat && isFloat) return floatValue; double doubleValue; var acceptDouble = JsConfig.ParsePrimitiveFloatingPointTypes.HasFlag(ParseAsType.Double); var isDouble = double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out doubleValue); if (acceptDouble && isDouble) return doubleValue; if (isDecimal) return decimalValue; if (isFloat) return floatValue; if (isDouble) return doubleValue; return null; } internal static object ParsePrimitive(string value, char firstChar) { if (typeof(TSerializer) == typeof(JsonTypeSerializer)) { return firstChar == JsWriter.QuoteChar ? ParseQuotedPrimitive(value) : ParsePrimitive(value); } return (ParsePrimitive(value) ?? ParseQuotedPrimitive(value)); } } internal class TypeAccessor { internal ParseStringDelegate GetProperty; internal SetPropertyDelegate SetProperty; internal Type PropertyType; public static Type ExtractType(ITypeSerializer Serializer, string strType) { if (strType == null || strType.Length <= 1) return null; var hasWhitespace = JsonUtils.WhiteSpaceChars.Contains(strType[1]); if (hasWhitespace) { var pos = strType.IndexOf('"'); if (pos >= 0) strType = "{" + strType.Substring(pos); } var typeAttrInObject = Serializer.TypeAttrInObject; if (strType.Length > typeAttrInObject.Length && strType.Substring(0, typeAttrInObject.Length) == typeAttrInObject) { var propIndex = typeAttrInObject.Length; var typeName = Serializer.EatValue(strType, ref propIndex); var type = JsConfig.TypeFinder(typeName); if (type == null) Tracer.Instance.WriteWarning("Could not find type: " + typeName); return type; } return null; } public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, PropertyInfo propertyInfo) { return new TypeAccessor { PropertyType = propertyInfo.PropertyType, GetProperty = serializer.GetParseFn(propertyInfo.PropertyType), SetProperty = GetSetPropertyMethod(typeConfig, propertyInfo), }; } private static SetPropertyDelegate GetSetPropertyMethod(TypeConfig typeConfig, PropertyInfo propertyInfo) { if (propertyInfo.ReflectedType() != propertyInfo.DeclaringType) propertyInfo = propertyInfo.DeclaringType.GetPropertyInfo(propertyInfo.Name); if (!propertyInfo.CanWrite && !typeConfig.EnableAnonymousFieldSetterses) return null; FieldInfo fieldInfo = null; if (!propertyInfo.CanWrite) { //TODO: What string comparison is used in SST? string fieldNameFormat = Env.IsMono ? "<{0}>" : "<{0}>i__Field"; var fieldName = string.Format(fieldNameFormat, propertyInfo.Name); var fieldInfos = typeConfig.Type.GetWritableFields(); foreach (var f in fieldInfos) { if (f.IsInitOnly && f.FieldType == propertyInfo.PropertyType && f.Name == fieldName) { fieldInfo = f; break; } } if (fieldInfo == null) return null; } return PclExport.Instance.GetSetMethod(propertyInfo, fieldInfo); } internal static SetPropertyDelegate GetSetPropertyMethod(Type type, PropertyInfo propertyInfo) { if (!propertyInfo.CanWrite || propertyInfo.GetIndexParameters().Any()) return null; return PclExport.Instance.GetSetPropertyMethod(propertyInfo); } internal static SetPropertyDelegate GetSetFieldMethod(Type type, FieldInfo fieldInfo) { return PclExport.Instance.GetSetFieldMethod(fieldInfo); } public static TypeAccessor Create(ITypeSerializer serializer, TypeConfig typeConfig, FieldInfo fieldInfo) { return new TypeAccessor { PropertyType = fieldInfo.FieldType, GetProperty = serializer.GetParseFn(fieldInfo.FieldType), SetProperty = GetSetFieldMethod(typeConfig, fieldInfo), }; } private static SetPropertyDelegate GetSetFieldMethod(TypeConfig typeConfig, FieldInfo fieldInfo) { if (fieldInfo.ReflectedType() != fieldInfo.DeclaringType) fieldInfo = fieldInfo.DeclaringType.GetFieldInfo(fieldInfo.Name); return PclExport.Instance.GetSetFieldMethod(fieldInfo); } } }
using J2N.Collections.Generic.Extensions; using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Search; using Lucene.Net.Store; using Lucene.Net.Support; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Codec = Lucene.Net.Codecs.Codec; // NOTE: this test will fail w/ PreFlexRW codec! (Because // this test uses full binary term space, but PreFlex cannot // handle this since it requires the terms are UTF8 bytes). // // Also, SimpleText codec will consume very large amounts of // disk (but, should run successfully). Best to run w/ // -Dtests.codec=Standard, and w/ plenty of RAM, eg: // // ant test -Dtest.slow=true -Dtests.heapsize=8g // // java -server -Xmx8g -d64 -cp .:lib/junit-4.10.jar:./build/classes/test:./build/classes/test-framework:./build/classes/java -Dlucene.version=4.0-dev -Dtests.directory=MMapDirectory -DtempDir=build -ea org.junit.runner.JUnitCore Lucene.Net.Index.Test2BTerms // [SuppressCodecs("SimpleText", "Memory", "Direct")] [Ignore("SimpleText codec will consume very large amounts of memory.")] [TestFixture] public class Test2BTerms : LuceneTestCase { private const int TOKEN_LEN = 5; private static readonly BytesRef bytes = new BytesRef(TOKEN_LEN); private sealed class MyTokenStream : TokenStream { internal readonly int tokensPerDoc; internal int tokenCount; public readonly IList<BytesRef> savedTerms = new List<BytesRef>(); internal int nextSave; internal long termCounter; internal readonly Random random; public MyTokenStream(Random random, int tokensPerDoc) : base(new MyAttributeFactory(AttributeFactory.DEFAULT_ATTRIBUTE_FACTORY)) { this.tokensPerDoc = tokensPerDoc; AddAttribute<ITermToBytesRefAttribute>(); bytes.Length = TOKEN_LEN; this.random = random; nextSave = TestUtil.NextInt32(random, 500000, 1000000); } public override bool IncrementToken() { ClearAttributes(); if (tokenCount >= tokensPerDoc) { return false; } int shift = 32; for (int i = 0; i < 5; i++) { bytes.Bytes[i] = unchecked((byte)((termCounter >> shift) & 0xFF)); shift -= 8; } termCounter++; tokenCount++; if (--nextSave == 0) { savedTerms.Add(BytesRef.DeepCopyOf(bytes)); Console.WriteLine("TEST: save term=" + bytes); nextSave = TestUtil.NextInt32(random, 500000, 1000000); } return true; } public override void Reset() { tokenCount = 0; } private sealed class MyTermAttributeImpl : Util.Attribute, ITermToBytesRefAttribute { public void FillBytesRef() { // no-op: the bytes was already filled by our owner's incrementToken } public BytesRef BytesRef => bytes; public override void Clear() { } public override bool Equals(object other) { return other == this; } public override int GetHashCode() { return RuntimeHelpers.GetHashCode(this); } public override void CopyTo(IAttribute target) { } public override object Clone() { throw new NotSupportedException(); } } private sealed class MyAttributeFactory : AttributeFactory { internal readonly AttributeFactory @delegate; public MyAttributeFactory(AttributeFactory @delegate) { this.@delegate = @delegate; } public override Util.Attribute CreateAttributeInstance<T>() { var attClass = typeof(T); if (attClass == typeof(ITermToBytesRefAttribute)) { return new MyTermAttributeImpl(); } if (attClass.IsSubclassOf(typeof(CharTermAttribute))) { throw new ArgumentException("no"); } return @delegate.CreateAttributeInstance<T>(); } } } [Ignore("Very slow. Enable manually by removing Ignore.")] [Test] public virtual void Test2BTerms_Mem([ValueSource(typeof(ConcurrentMergeSchedulerFactories), "Values")]Func<IConcurrentMergeScheduler> newScheduler) { if ("Lucene3x".Equals(Codec.Default.Name, StringComparison.Ordinal)) { throw new Exception("this test cannot run with PreFlex codec"); } Console.WriteLine("Starting Test2B"); long TERM_COUNT = ((long)int.MaxValue) + 100000000; int TERMS_PER_DOC = TestUtil.NextInt32(Random, 100000, 1000000); IList<BytesRef> savedTerms = null; BaseDirectoryWrapper dir = NewFSDirectory(CreateTempDir("2BTerms")); //MockDirectoryWrapper dir = NewFSDirectory(new File("/p/lucene/indices/2bindex")); if (dir is MockDirectoryWrapper) { ((MockDirectoryWrapper)dir).Throttling = Throttling.NEVER; } dir.CheckIndexOnDispose = false; // don't double-checkindex if (true) { IndexWriter w = new IndexWriter(dir, new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)) .SetMaxBufferedDocs(IndexWriterConfig.DISABLE_AUTO_FLUSH) .SetRAMBufferSizeMB(256.0) .SetMergeScheduler(newScheduler()) .SetMergePolicy(NewLogMergePolicy(false, 10)) .SetOpenMode(OpenMode.CREATE)); MergePolicy mp = w.Config.MergePolicy; if (mp is LogByteSizeMergePolicy) { // 1 petabyte: ((LogByteSizeMergePolicy)mp).MaxMergeMB = 1024 * 1024 * 1024; } Documents.Document doc = new Documents.Document(); MyTokenStream ts = new MyTokenStream(Random, TERMS_PER_DOC); FieldType customType = new FieldType(TextField.TYPE_NOT_STORED); customType.IndexOptions = IndexOptions.DOCS_ONLY; customType.OmitNorms = true; Field field = new Field("field", ts, customType); doc.Add(field); //w.setInfoStream(System.out); int numDocs = (int)(TERM_COUNT / TERMS_PER_DOC); Console.WriteLine("TERMS_PER_DOC=" + TERMS_PER_DOC); Console.WriteLine("numDocs=" + numDocs); for (int i = 0; i < numDocs; i++) { long t0 = Environment.TickCount; w.AddDocument(doc); Console.WriteLine(i + " of " + numDocs + " " + (Environment.TickCount - t0) + " msec"); } savedTerms = ts.savedTerms; Console.WriteLine("TEST: full merge"); w.ForceMerge(1); Console.WriteLine("TEST: close writer"); w.Dispose(); } Console.WriteLine("TEST: open reader"); IndexReader r = DirectoryReader.Open(dir); if (savedTerms == null) { savedTerms = FindTerms(r); } int numSavedTerms = savedTerms.Count; IList<BytesRef> bigOrdTerms = new List<BytesRef>(savedTerms.SubList(numSavedTerms - 10, numSavedTerms)); Console.WriteLine("TEST: test big ord terms..."); TestSavedTerms(r, bigOrdTerms); Console.WriteLine("TEST: test all saved terms..."); TestSavedTerms(r, savedTerms); r.Dispose(); Console.WriteLine("TEST: now CheckIndex..."); CheckIndex.Status status = TestUtil.CheckIndex(dir); long tc = status.SegmentInfos[0].TermIndexStatus.TermCount; Assert.IsTrue(tc > int.MaxValue, "count " + tc + " is not > " + int.MaxValue); dir.Dispose(); Console.WriteLine("TEST: done!"); } private IList<BytesRef> FindTerms(IndexReader r) { Console.WriteLine("TEST: findTerms"); TermsEnum termsEnum = MultiFields.GetTerms(r, "field").GetEnumerator(); IList<BytesRef> savedTerms = new List<BytesRef>(); int nextSave = TestUtil.NextInt32(Random, 500000, 1000000); BytesRef term; while (termsEnum.MoveNext()) { term = termsEnum.Term; if (--nextSave == 0) { savedTerms.Add(BytesRef.DeepCopyOf(term)); Console.WriteLine("TEST: add " + term); nextSave = TestUtil.NextInt32(Random, 500000, 1000000); } } return savedTerms; } private void TestSavedTerms(IndexReader r, IList<BytesRef> terms) { Console.WriteLine("TEST: run " + terms.Count + " terms on reader=" + r); IndexSearcher s = NewSearcher(r); terms.Shuffle(Random); TermsEnum termsEnum = MultiFields.GetTerms(r, "field").GetEnumerator(); bool failed = false; for (int iter = 0; iter < 10 * terms.Count; iter++) { BytesRef term = terms[Random.Next(terms.Count)]; Console.WriteLine("TEST: search " + term); long t0 = Environment.TickCount; int count = s.Search(new TermQuery(new Term("field", term)), 1).TotalHits; if (count <= 0) { Console.WriteLine(" FAILED: count=" + count); failed = true; } long t1 = Environment.TickCount; Console.WriteLine(" took " + (t1 - t0) + " millis"); TermsEnum.SeekStatus result = termsEnum.SeekCeil(term); if (result != TermsEnum.SeekStatus.FOUND) { if (result == TermsEnum.SeekStatus.END) { Console.WriteLine(" FAILED: got END"); } else { Console.WriteLine(" FAILED: wrong term: got " + termsEnum.Term); } failed = true; } } Assert.IsFalse(failed); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Drawing; using System.Threading; namespace System.ComponentModel { /// <summary> /// This type description provider provides type information through /// reflection. Unless someone has provided a custom type description /// provider for a type or instance, or unless an instance implements /// ICustomTypeDescriptor, any query for type information will go through /// this class. There should be a single instance of this class associated /// with "object", as it can provide all type information for any type. /// </summary> internal sealed partial class ReflectTypeDescriptionProvider : TypeDescriptionProvider { // Hastable of Type -> ReflectedTypeData. ReflectedTypeData contains all // of the type information we have gathered for a given type. // private Hashtable _typeData; // This is the signature we look for when creating types that are generic, but // want to know what type they are dealing with. Enums are a good example of this; // there is one enum converter that can work with all enums, but it needs to know // the type of enum it is dealing with. // private static Type[] s_typeConstructor = new Type[] { typeof(Type) }; // This is where we store the various converters, etc for the intrinsic types. // private static Hashtable s_editorTables; private static Hashtable s_intrinsicTypeConverters; // For converters, etc that are bound to class attribute data, rather than a class // type, we have special key sentinel values that we put into the hash table. // private static object s_intrinsicReferenceKey = new object(); private static object s_intrinsicNullableKey = new object(); // The key we put into IDictionaryService to store our cache dictionary. // private static object s_dictionaryKey = new object(); // This is a cache on top of core reflection. The cache // builds itself recursively, so if you ask for the properties // on Control, Component and object are also automatically filled // in. The keys to the property and event caches are types. // The keys to the attribute cache are either MemberInfos or types. // private static Hashtable s_propertyCache; private static Hashtable s_eventCache; private static Hashtable s_attributeCache; private static Hashtable s_extendedPropertyCache; // These are keys we stuff into our object cache. We use this // cache data to store extender provider info for an object. // private static readonly Guid s_extenderPropertiesKey = Guid.NewGuid(); private static readonly Guid s_extenderProviderPropertiesKey = Guid.NewGuid(); // These are attributes that, when we discover them on interfaces, we do // not merge them into the attribute set for a class. private static readonly Type[] s_skipInterfaceAttributeList = new Type[] { #if FEATURE_SKIP_INTERFACE typeof(System.Runtime.InteropServices.GuidAttribute), typeof(System.Runtime.InteropServices.InterfaceTypeAttribute) #endif typeof(System.Runtime.InteropServices.ComVisibleAttribute), }; internal static Guid ExtenderProviderKey { get; } = Guid.NewGuid(); private static readonly object s_internalSyncObject = new object(); /// <summary> /// Creates a new ReflectTypeDescriptionProvider. The type is the /// type we will obtain type information for. /// </summary> internal ReflectTypeDescriptionProvider() { } private static Hashtable EditorTables => LazyInitializer.EnsureInitialized(ref s_editorTables, () => new Hashtable(4)); /// <summary> /// This is a table we create for intrinsic types. /// There should be entries here ONLY for intrinsic /// types, as all other types we should be able to /// add attributes directly as metadata. /// </summary> private static Hashtable IntrinsicTypeConverters => LazyInitializer.EnsureInitialized(ref s_intrinsicTypeConverters, () => new Hashtable { // Add the intrinsics // [typeof(bool)] = typeof(BooleanConverter), [typeof(byte)] = typeof(ByteConverter), [typeof(SByte)] = typeof(SByteConverter), [typeof(char)] = typeof(CharConverter), [typeof(double)] = typeof(DoubleConverter), [typeof(string)] = typeof(StringConverter), [typeof(int)] = typeof(Int32Converter), [typeof(short)] = typeof(Int16Converter), [typeof(long)] = typeof(Int64Converter), [typeof(float)] = typeof(SingleConverter), [typeof(UInt16)] = typeof(UInt16Converter), [typeof(UInt32)] = typeof(UInt32Converter), [typeof(UInt64)] = typeof(UInt64Converter), [typeof(object)] = typeof(TypeConverter), [typeof(void)] = typeof(TypeConverter), [typeof(DateTime)] = typeof(DateTimeConverter), [typeof(DateTimeOffset)] = typeof(DateTimeOffsetConverter), [typeof(Decimal)] = typeof(DecimalConverter), [typeof(TimeSpan)] = typeof(TimeSpanConverter), [typeof(Guid)] = typeof(GuidConverter), [typeof(Uri)] = typeof(UriTypeConverter), [typeof(Color)] = typeof(ColorConverter), [typeof(Point)] = typeof(PointConverter), [typeof(Rectangle)] = typeof(RectangleConverter), [typeof(Size)] = typeof(SizeConverter), [typeof(SizeF)] = typeof(SizeFConverter), // Special cases for things that are not bound to a specific type // [typeof(Array)] = typeof(ArrayConverter), [typeof(ICollection)] = typeof(CollectionConverter), [typeof(Enum)] = typeof(EnumConverter), [s_intrinsicNullableKey] = typeof(NullableConverter), }); private static Hashtable PropertyCache => LazyInitializer.EnsureInitialized(ref s_propertyCache, () => new Hashtable()); private static Hashtable EventCache => LazyInitializer.EnsureInitialized(ref s_eventCache, () => new Hashtable()); private static Hashtable AttributeCache => LazyInitializer.EnsureInitialized(ref s_attributeCache, () => new Hashtable()); private static Hashtable ExtendedPropertyCache => LazyInitializer.EnsureInitialized(ref s_extendedPropertyCache, () => new Hashtable()); /// <summary> /// Adds an editor table for the given editor base type. /// Typically, editors are specified as metadata on an object. If no metadata for a /// requested editor base type can be found on an object, however, the /// TypeDescriptor will search an editor /// table for the editor type, if one can be found. /// </summary> internal static void AddEditorTable(Type editorBaseType, Hashtable table) { if (editorBaseType == null) { throw new ArgumentNullException(nameof(editorBaseType)); } if (table == null) { Debug.Fail("COMPAT: Editor table should not be null"); // don't throw; RTM didn't so we can't do it either. } lock (s_internalSyncObject) { Hashtable editorTables = EditorTables; if (!editorTables.ContainsKey(editorBaseType)) { editorTables[editorBaseType] = table; } } } /// <summary> /// CreateInstance implementation. We delegate to Activator. /// </summary> public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args) { Debug.Assert(objectType != null, "Should have arg-checked before coming in here"); object obj = null; if (argTypes != null) { obj = objectType.GetConstructor(argTypes)?.Invoke(args); } else { if (args != null) { argTypes = new Type[args.Length]; for (int idx = 0; idx < args.Length; idx++) { if (args[idx] != null) { argTypes[idx] = args[idx].GetType(); } else { argTypes[idx] = typeof(object); } } } else { argTypes = Array.Empty<Type>(); } obj = objectType.GetConstructor(argTypes)?.Invoke(args); } return obj ?? Activator.CreateInstance(objectType, args); } /// <summary> /// Helper method to create editors and type converters. This checks to see if the /// type implements a Type constructor, and if it does it invokes that ctor. /// Otherwise, it just tries to create the type. /// </summary> private static object CreateInstance(Type objectType, Type callingType) { return objectType.GetConstructor(s_typeConstructor)?.Invoke(new object[] { callingType }) ?? Activator.CreateInstance(objectType); } /// <summary> /// Retrieves custom attributes. /// </summary> internal AttributeCollection GetAttributes(Type type) { ReflectedTypeData td = GetTypeData(type, true); return td.GetAttributes(); } /// <summary> /// Our implementation of GetCache sits on top of IDictionaryService. /// </summary> public override IDictionary GetCache(object instance) { IComponent comp = instance as IComponent; if (comp != null && comp.Site != null) { IDictionaryService ds = comp.Site.GetService(typeof(IDictionaryService)) as IDictionaryService; if (ds != null) { IDictionary dict = ds.GetValue(s_dictionaryKey) as IDictionary; if (dict == null) { dict = new Hashtable(); ds.SetValue(s_dictionaryKey, dict); } return dict; } } return null; } /// <summary> /// Retrieves the class name for our type. /// </summary> internal string GetClassName(Type type) { ReflectedTypeData td = GetTypeData(type, true); return td.GetClassName(null); } /// <summary> /// Retrieves the component name from the site. /// </summary> internal string GetComponentName(Type type, object instance) { ReflectedTypeData td = GetTypeData(type, true); return td.GetComponentName(instance); } /// <summary> /// Retrieves the type converter. If instance is non-null, /// it will be used to retrieve attributes. Otherwise, _type /// will be used. /// </summary> internal TypeConverter GetConverter(Type type, object instance) { ReflectedTypeData td = GetTypeData(type, true); return td.GetConverter(instance); } /// <summary> /// Return the default event. The default event is determined by the /// presence of a DefaultEventAttribute on the class. /// </summary> internal EventDescriptor GetDefaultEvent(Type type, object instance) { ReflectedTypeData td = GetTypeData(type, true); return td.GetDefaultEvent(instance); } /// <summary> /// Return the default property. /// </summary> internal PropertyDescriptor GetDefaultProperty(Type type, object instance) { ReflectedTypeData td = GetTypeData(type, true); return td.GetDefaultProperty(instance); } /// <summary> /// Retrieves the editor for the given base type. /// </summary> internal object GetEditor(Type type, object instance, Type editorBaseType) { ReflectedTypeData td = GetTypeData(type, true); return td.GetEditor(instance, editorBaseType); } /// <summary> /// Retrieves a default editor table for the given editor base type. /// </summary> private static Hashtable GetEditorTable(Type editorBaseType) { Hashtable editorTables = EditorTables; object table = editorTables[editorBaseType]; if (table == null) { // Before we give up, it is possible that the // class initializer for editorBaseType hasn't // actually run. // System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(editorBaseType.TypeHandle); table = editorTables[editorBaseType]; // If the table is still null, then throw a // sentinel in there so we don't // go through this again. // if (table == null) { lock (s_internalSyncObject) { table = editorTables[editorBaseType]; if (table == null) { editorTables[editorBaseType] = editorTables; } } } } // Look for our sentinel value that indicates // we have already tried and failed to get // a table. // if (table == editorTables) { table = null; } return (Hashtable)table; } /// <summary> /// Retrieves the events for this type. /// </summary> internal EventDescriptorCollection GetEvents(Type type) { ReflectedTypeData td = GetTypeData(type, true); return td.GetEvents(); } /// <summary> /// Retrieves custom extender attributes. We don't support /// extender attributes, so we always return an empty collection. /// </summary> internal AttributeCollection GetExtendedAttributes(object instance) { return AttributeCollection.Empty; } /// <summary> /// Retrieves the class name for our type. /// </summary> internal string GetExtendedClassName(object instance) { return GetClassName(instance.GetType()); } /// <summary> /// Retrieves the component name from the site. /// </summary> internal string GetExtendedComponentName(object instance) { return GetComponentName(instance.GetType(), instance); } /// <summary> /// Retrieves the type converter. If instance is non-null, /// it will be used to retrieve attributes. Otherwise, _type /// will be used. /// </summary> internal TypeConverter GetExtendedConverter(object instance) { return GetConverter(instance.GetType(), instance); } /// <summary> /// Return the default event. The default event is determined by the /// presence of a DefaultEventAttribute on the class. /// </summary> internal EventDescriptor GetExtendedDefaultEvent(object instance) { return null; // we don't support extended events. } /// <summary> /// Return the default property. /// </summary> internal PropertyDescriptor GetExtendedDefaultProperty(object instance) { return null; // extender properties are never the default. } /// <summary> /// Retrieves the editor for the given base type. /// </summary> internal object GetExtendedEditor(object instance, Type editorBaseType) { return GetEditor(instance.GetType(), instance, editorBaseType); } /// <summary> /// Retrieves the events for this type. /// </summary> internal EventDescriptorCollection GetExtendedEvents(object instance) { return EventDescriptorCollection.Empty; } /// <summary> /// Retrieves the properties for this type. /// </summary> internal PropertyDescriptorCollection GetExtendedProperties(object instance) { // Is this object a sited component? If not, then it // doesn't have any extender properties. // Type componentType = instance.GetType(); // Check the component for extender providers. We prefer // IExtenderListService, but will use the container if that's // all we have. In either case, we check the list of extenders // against previously stored data in the object cache. If // the cache is up to date, we just return the extenders in the // cache. // IExtenderProvider[] extenders = GetExtenderProviders(instance); IDictionary cache = TypeDescriptor.GetCache(instance); if (extenders.Length == 0) { return PropertyDescriptorCollection.Empty; } // Ok, we have a set of extenders. Now, check to see if there // are properties already in our object cache. If there aren't, // then we will need to create them. // PropertyDescriptorCollection properties = null; if (cache != null) { properties = cache[s_extenderPropertiesKey] as PropertyDescriptorCollection; } if (properties != null) { return properties; } // Unlike normal properties, it is fine for there to be properties with // duplicate names here. // List<PropertyDescriptor> propertyList = null; for (int idx = 0; idx < extenders.Length; idx++) { PropertyDescriptor[] propertyArray = ReflectGetExtendedProperties(extenders[idx]); if (propertyList == null) { propertyList = new List<PropertyDescriptor>(propertyArray.Length * extenders.Length); } for (int propIdx = 0; propIdx < propertyArray.Length; propIdx++) { PropertyDescriptor prop = propertyArray[propIdx]; ExtenderProvidedPropertyAttribute eppa = prop.Attributes[typeof(ExtenderProvidedPropertyAttribute)] as ExtenderProvidedPropertyAttribute; Debug.Assert(eppa != null, $"Extender property {prop.Name} has no provider attribute. We will skip it."); if (eppa != null) { Type receiverType = eppa.ReceiverType; if (receiverType != null) { if (receiverType.IsAssignableFrom(componentType)) { propertyList.Add(prop); } } } } } // propertyHash now contains ExtendedPropertyDescriptor objects // for each extended property. // if (propertyList != null) { PropertyDescriptor[] fullArray = new PropertyDescriptor[propertyList.Count]; propertyList.CopyTo(fullArray, 0); properties = new PropertyDescriptorCollection(fullArray, true); } else { properties = PropertyDescriptorCollection.Empty; } if (cache != null) { cache[s_extenderPropertiesKey] = properties; } return properties; } protected internal override IExtenderProvider[] GetExtenderProviders(object instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } IComponent component = instance as IComponent; if (component != null && component.Site != null) { IExtenderListService extenderList = component.Site.GetService(typeof(IExtenderListService)) as IExtenderListService; IDictionary cache = TypeDescriptor.GetCache(instance); if (extenderList != null) { return GetExtenders(extenderList.GetExtenderProviders(), instance, cache); } #if FEATURE_COMPONENT_COLLECTION else { IContainer cont = component.Site.Container; if (cont != null) { return GetExtenders(cont.Components, instance, cache); } } #endif } return Array.Empty<IExtenderProvider>(); } /// <summary> /// GetExtenders builds a list of extender providers from /// a collection of components. It validates the extenders /// against any cached collection of extenders in the /// cache. If there is a discrepancy, this will erase /// any cached extender properties from the cache and /// save the updated extender list. If there is no /// discrepancy this will simply return the cached list. /// </summary> private static IExtenderProvider[] GetExtenders(ICollection components, object instance, IDictionary cache) { bool newExtenders = false; int extenderCount = 0; IExtenderProvider[] existingExtenders = null; //CanExtend is expensive. We will remember results of CanExtend for the first 64 extenders and using "long canExtend" as a bit vector. // we want to avoid memory allocation as well so we don't use some more sophisticated data structure like an array of booleans UInt64 canExtend = 0; int maxCanExtendResults = 64; // currentExtenders is what we intend to return. If the caller passed us // the return value from IExtenderListService, components will already be // an IExtenderProvider[]. If not, then we must treat components as an // opaque collection. We spend a great deal of energy here to avoid // copying or allocating memory because this method is called every // time a component is asked for its properties. IExtenderProvider[] currentExtenders = components as IExtenderProvider[]; if (cache != null) { existingExtenders = cache[ExtenderProviderKey] as IExtenderProvider[]; } if (existingExtenders == null) { newExtenders = true; } int curIdx = 0; int idx = 0; if (currentExtenders != null) { for (curIdx = 0; curIdx < currentExtenders.Length; curIdx++) { if (currentExtenders[curIdx].CanExtend(instance)) { extenderCount++; // Performance:We would like to call CanExtend as little as possible therefore we remember its result if (curIdx < maxCanExtendResults) canExtend |= (UInt64)1 << curIdx; if (!newExtenders && (idx >= existingExtenders.Length || currentExtenders[curIdx] != existingExtenders[idx++])) { newExtenders = true; } } } } else if (components != null) { foreach (object obj in components) { IExtenderProvider prov = obj as IExtenderProvider; if (prov != null && prov.CanExtend(instance)) { extenderCount++; if (curIdx < maxCanExtendResults) canExtend |= (UInt64)1 << curIdx; if (!newExtenders && (idx >= existingExtenders.Length || prov != existingExtenders[idx++])) { newExtenders = true; } } curIdx++; } } if (existingExtenders != null && extenderCount != existingExtenders.Length) { newExtenders = true; } if (newExtenders) { if (currentExtenders == null || extenderCount != currentExtenders.Length) { IExtenderProvider[] newExtenderArray = new IExtenderProvider[extenderCount]; curIdx = 0; idx = 0; if (currentExtenders != null && extenderCount > 0) { while (curIdx < currentExtenders.Length) { if ((curIdx < maxCanExtendResults && (canExtend & ((UInt64)1 << curIdx)) != 0) || (curIdx >= maxCanExtendResults && currentExtenders[curIdx].CanExtend(instance))) { Debug.Assert(idx < extenderCount, "There are more extenders than we expect"); newExtenderArray[idx++] = currentExtenders[curIdx]; } curIdx++; } Debug.Assert(idx == extenderCount, "Wrong number of extenders"); } else if (extenderCount > 0) { foreach (var component in components) { IExtenderProvider p = component as IExtenderProvider; if (p != null && ((curIdx < maxCanExtendResults && (canExtend & ((UInt64)1 << curIdx)) != 0) || (curIdx >= maxCanExtendResults && p.CanExtend(instance)))) { Debug.Assert(idx < extenderCount, "There are more extenders than we expect"); newExtenderArray[idx++] = p; } curIdx++; } Debug.Assert(idx == extenderCount, "Wrong number of extenders"); } currentExtenders = newExtenderArray; } if (cache != null) { cache[ExtenderProviderKey] = currentExtenders; cache.Remove(s_extenderPropertiesKey); } } else { currentExtenders = existingExtenders; } return currentExtenders; } /// <summary> /// Retrieves the owner for a property. /// </summary> internal object GetExtendedPropertyOwner(object instance, PropertyDescriptor pd) { return GetPropertyOwner(instance.GetType(), instance, pd); } ////////////////////////////////////////////////////////// /// <summary> /// Provides a type descriptor for the given object. We only support this /// if the object is a component that /// </summary> public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance) { Debug.Fail("This should never be invoked. TypeDescriptionNode should wrap for us."); return null; } /// <summary> /// The name of the specified component, or null if the component has no name. /// In many cases this will return the same value as GetComponentName. If the /// component resides in a nested container or has other nested semantics, it may /// return a different fully qualified name. /// /// If not overridden, the default implementation of this method will call /// GetComponentName. /// </summary> public override string GetFullComponentName(object component) { IComponent comp = component as IComponent; INestedSite ns = comp?.Site as INestedSite; if (ns != null) { return ns.FullName; } return TypeDescriptor.GetComponentName(component); } /// <summary> /// Returns an array of types we have populated metadata for that live /// in the current module. /// </summary> internal Type[] GetPopulatedTypes(Module module) { List<Type> typeList = new List<Type>(); // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = _typeData.GetEnumerator(); while (e.MoveNext()) { DictionaryEntry de = e.Entry; Type type = (Type)de.Key; ReflectedTypeData typeData = (ReflectedTypeData)de.Value; if (type.Module == module && typeData.IsPopulated) { typeList.Add(type); } } return typeList.ToArray(); } /// <summary> /// Retrieves the properties for this type. /// </summary> internal PropertyDescriptorCollection GetProperties(Type type) { ReflectedTypeData td = GetTypeData(type, true); return td.GetProperties(); } /// <summary> /// Retrieves the owner for a property. /// </summary> internal object GetPropertyOwner(Type type, object instance, PropertyDescriptor pd) { return TypeDescriptor.GetAssociation(type, instance); } /// <summary> /// Returns an Type for the given type. Since type implements IReflect, /// we just return objectType. /// </summary> public override Type GetReflectionType(Type objectType, object instance) { Debug.Assert(objectType != null, "Should have arg-checked before coming in here"); return objectType; } /// <summary> /// Returns the type data for the given type, or /// null if there is no type data for the type yet and /// createIfNeeded is false. /// </summary> private ReflectedTypeData GetTypeData(Type type, bool createIfNeeded) { ReflectedTypeData td = null; if (_typeData != null) { td = (ReflectedTypeData)_typeData[type]; if (td != null) { return td; } } lock (s_internalSyncObject) { if (_typeData != null) { td = (ReflectedTypeData)_typeData[type]; } if (td == null && createIfNeeded) { td = new ReflectedTypeData(type); if (_typeData == null) { _typeData = new Hashtable(); } _typeData[type] = td; } } return td; } /// <summary> /// This method returns a custom type descriptor for the given type / object. /// The objectType parameter is always valid, but the instance parameter may /// be null if no instance was passed to TypeDescriptor. The method should /// return a custom type descriptor for the object. If the method is not /// interested in providing type information for the object it should /// return null. /// </summary> public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance) { Debug.Fail("This should never be invoked. TypeDescriptionNode should wrap for us."); return null; } /// <summary> /// Retrieves a type from a name. /// </summary> private static Type GetTypeFromName(string typeName) { Type t = Type.GetType(typeName); if (t == null) { int commaIndex = typeName.IndexOf(','); if (commaIndex != -1) { // At design time, it's possible for us to reuse // an assembly but add new types. The app domain // will cache the assembly based on identity, however, // so it could be looking in the previous version // of the assembly and not finding the type. We work // around this by looking for the non-assembly qualified // name, which causes the domain to raise a type // resolve event. // t = Type.GetType(typeName.Substring(0, commaIndex)); } } return t; } /// <summary> /// This method returns true if the data cache in this reflection /// type descriptor has data in it. /// </summary> internal bool IsPopulated(Type type) { ReflectedTypeData td = GetTypeData(type, false); if (td != null) { return td.IsPopulated; } return false; } /// <summary> /// Static helper API around reflection to get and cache /// custom attributes. This does not recurse, but it will /// walk interfaces on the type. Interfaces are added /// to the end, so merging should be done from length - 1 /// to 0. /// </summary> internal static Attribute[] ReflectGetAttributes(Type type) { Hashtable attributeCache = AttributeCache; Attribute[] attrs = (Attribute[])attributeCache[type]; if (attrs != null) { return attrs; } lock (s_internalSyncObject) { attrs = (Attribute[])attributeCache[type]; if (attrs == null) { // Get the type's attributes. // attrs = type.GetCustomAttributes(typeof(Attribute), false).OfType<Attribute>().ToArray(); attributeCache[type] = attrs; } } return attrs; } /// <summary> /// Static helper API around reflection to get and cache /// custom attributes. This does not recurse to the base class. /// </summary> internal static Attribute[] ReflectGetAttributes(MemberInfo member) { Hashtable attributeCache = AttributeCache; Attribute[] attrs = (Attribute[])attributeCache[member]; if (attrs != null) { return attrs; } lock (s_internalSyncObject) { attrs = (Attribute[])attributeCache[member]; if (attrs == null) { // Get the member's attributes. // attrs = member.GetCustomAttributes(typeof(Attribute), false).OfType<Attribute>().ToArray(); attributeCache[member] = attrs; } } return attrs; } /// <summary> /// Static helper API around reflection to get and cache /// events. This does not recurse to the base class. /// </summary> private static EventDescriptor[] ReflectGetEvents(Type type) { Hashtable eventCache = EventCache; EventDescriptor[] events = (EventDescriptor[])eventCache[type]; if (events != null) { return events; } lock (s_internalSyncObject) { events = (EventDescriptor[])eventCache[type]; if (events == null) { BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance; // Get the type's events. Events may have their add and // remove methods individually overridden in a derived // class, but at some point in the base class chain both // methods must exist. If we find an event that doesn't // have both add and remove, we skip it here, because it // will be picked up in our base class scan. // EventInfo[] eventInfos = type.GetEvents(bindingFlags); events = new EventDescriptor[eventInfos.Length]; int eventCount = 0; for (int idx = 0; idx < eventInfos.Length; idx++) { EventInfo eventInfo = eventInfos[idx]; // GetEvents returns events that are on nonpublic types // if those types are from our assembly. Screen these. // if ((!(eventInfo.DeclaringType.IsPublic || eventInfo.DeclaringType.IsNestedPublic)) && (eventInfo.DeclaringType.Assembly == typeof(ReflectTypeDescriptionProvider).Assembly)) { Debug.Fail("Hey, assumption holds true. Rip this assert."); continue; } if (eventInfo.AddMethod != null && eventInfo.RemoveMethod != null) { events[eventCount++] = new ReflectEventDescriptor(type, eventInfo); } } if (eventCount != events.Length) { EventDescriptor[] newEvents = new EventDescriptor[eventCount]; Array.Copy(events, 0, newEvents, 0, eventCount); events = newEvents; } #if DEBUG foreach (EventDescriptor dbgEvent in events) { Debug.Assert(dbgEvent != null, "Holes in event array for type " + type); } #endif eventCache[type] = events; } } return events; } /// <summary> /// This performs the actual reflection needed to discover /// extender properties. If object caching is supported this /// will maintain a cache of property descriptors on the /// extender provider. Extender properties are actually two /// property descriptors in one. There is a chunk of per-class /// data in a ReflectPropertyDescriptor that defines the /// parameter types and get and set methods of the extended property, /// and there is an ExtendedPropertyDescriptor that combines this /// with an extender provider object to create what looks like a /// normal property. ReflectGetExtendedProperties maintains two /// separate caches for these two sets: a static one for the /// ReflectPropertyDescriptor values that don't change for each /// provider instance, and a per-provider cache that contains /// the ExtendedPropertyDescriptors. /// </summary> private static PropertyDescriptor[] ReflectGetExtendedProperties(IExtenderProvider provider) { IDictionary cache = TypeDescriptor.GetCache(provider); PropertyDescriptor[] properties; if (cache != null) { properties = cache[s_extenderProviderPropertiesKey] as PropertyDescriptor[]; if (properties != null) { return properties; } } // Our per-instance cache missed. We have never seen this instance of the // extender provider before. See if we can find our class-based // property store. // Type providerType = provider.GetType(); Hashtable extendedPropertyCache = ExtendedPropertyCache; ReflectPropertyDescriptor[] extendedProperties = (ReflectPropertyDescriptor[])extendedPropertyCache[providerType]; if (extendedProperties == null) { lock (s_internalSyncObject) { extendedProperties = (ReflectPropertyDescriptor[])extendedPropertyCache[providerType]; // Our class-based property store failed as well, so we need to build up the set of // extended properties here. // if (extendedProperties == null) { AttributeCollection attributes = TypeDescriptor.GetAttributes(providerType); List<ReflectPropertyDescriptor> extendedList = new List<ReflectPropertyDescriptor>(attributes.Count); foreach (Attribute attr in attributes) { ProvidePropertyAttribute provideAttr = attr as ProvidePropertyAttribute; if (provideAttr != null) { Type receiverType = GetTypeFromName(provideAttr.ReceiverTypeName); if (receiverType != null) { MethodInfo getMethod = providerType.GetMethod("Get" + provideAttr.PropertyName, new Type[] { receiverType }); if (getMethod != null && !getMethod.IsStatic && getMethod.IsPublic) { MethodInfo setMethod = providerType.GetMethod("Set" + provideAttr.PropertyName, new Type[] { receiverType, getMethod.ReturnType }); if (setMethod != null && (setMethod.IsStatic || !setMethod.IsPublic)) { setMethod = null; } extendedList.Add(new ReflectPropertyDescriptor(providerType, provideAttr.PropertyName, getMethod.ReturnType, receiverType, getMethod, setMethod, null)); } } } } extendedProperties = new ReflectPropertyDescriptor[extendedList.Count]; extendedList.CopyTo(extendedProperties, 0); extendedPropertyCache[providerType] = extendedProperties; } } } // Now that we have our extended properties we can build up a list of callable properties. These can be // returned to the user. // properties = new PropertyDescriptor[extendedProperties.Length]; for (int idx = 0; idx < extendedProperties.Length; idx++) { ReflectPropertyDescriptor rpd = extendedProperties[idx]; properties[idx] = new ExtendedPropertyDescriptor(rpd, rpd.ExtenderGetReceiverType(), provider, null); } if (cache != null) { cache[s_extenderProviderPropertiesKey] = properties; } return properties; } /// <summary> /// Static helper API around reflection to get and cache /// properties. This does not recurse to the base class. /// </summary> private static PropertyDescriptor[] ReflectGetProperties(Type type) { Hashtable propertyCache = PropertyCache; PropertyDescriptor[] properties = (PropertyDescriptor[])propertyCache[type]; if (properties != null) { return properties; } lock (s_internalSyncObject) { properties = (PropertyDescriptor[])propertyCache[type]; if (properties == null) { BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance; // Get the type's properties. Properties may have their // get and set methods individually overridden in a derived // class, so if we find a missing method we need to walk // down the base class chain to find it. We actually merge // "new" properties of the same name, so we must preserve // the member info for each method individually. // PropertyInfo[] propertyInfos = type.GetProperties(bindingFlags); properties = new PropertyDescriptor[propertyInfos.Length]; int propertyCount = 0; for (int idx = 0; idx < propertyInfos.Length; idx++) { PropertyInfo propertyInfo = propertyInfos[idx]; // Today we do not support parameterized properties. // if (propertyInfo.GetIndexParameters().Length > 0) { continue; } MethodInfo getMethod = propertyInfo.GetMethod; MethodInfo setMethod = propertyInfo.SetMethod; string name = propertyInfo.Name; // If the property only overrode "set", then we don't // pick it up here. Rather, we just merge it in from // the base class list. // If a property had at least a get method, we consider it. We don't // consider write-only properties. // if (getMethod != null) { properties[propertyCount++] = new ReflectPropertyDescriptor(type, name, propertyInfo.PropertyType, propertyInfo, getMethod, setMethod, null); } } if (propertyCount != properties.Length) { PropertyDescriptor[] newProperties = new PropertyDescriptor[propertyCount]; Array.Copy(properties, 0, newProperties, 0, propertyCount); properties = newProperties; } Debug.Assert(!properties.Any(dbgProp => dbgProp == null), $"Holes in property array for type {type}"); propertyCache[type] = properties; } } return properties; } /// <summary> /// Refreshes the contents of this type descriptor. This does not /// actually requery, but it will clear our state so the next /// query re-populates. /// </summary> internal void Refresh(Type type) { ReflectedTypeData td = GetTypeData(type, false); td?.Refresh(); } /// <summary> /// Searches the provided intrinsic hashtable for a match with the object type. /// At the beginning, the hashtable contains types for the various converters. /// As this table is searched, the types for these objects /// are replaced with instances, so we only create as needed. This method /// does the search up the base class hierarchy and will create instances /// for types as needed. These instances are stored back into the table /// for the base type, and for the original component type, for fast access. /// </summary> private static object SearchIntrinsicTable(Hashtable table, Type callingType) { object hashEntry = null; // We take a lock on this table. Nothing in this code calls out to // other methods that lock, so it should be fairly safe to grab this // lock. Also, this allows multiple intrinsic tables to be searched // at once. // lock (table) { Type baseType = callingType; while (baseType != null && baseType != typeof(object)) { hashEntry = table[baseType]; // If the entry is a late-bound type, then try to // resolve it. // string typeString = hashEntry as string; if (typeString != null) { hashEntry = Type.GetType(typeString); if (hashEntry != null) { table[baseType] = hashEntry; } } if (hashEntry != null) { break; } baseType = baseType.BaseType; } // Now make a scan through each value in the table, looking for interfaces. // If we find one, see if the object implements the interface. // if (hashEntry == null) { // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = table.GetEnumerator(); while (e.MoveNext()) { DictionaryEntry de = e.Entry; Type keyType = de.Key as Type; if (keyType != null && keyType.IsInterface && keyType.IsAssignableFrom(callingType)) { hashEntry = de.Value; string typeString = hashEntry as string; if (typeString != null) { hashEntry = Type.GetType(typeString); if (hashEntry != null) { table[callingType] = hashEntry; } } if (hashEntry != null) { break; } } } } // Special case converters // if (hashEntry == null) { if (callingType.IsGenericType && callingType.GetGenericTypeDefinition() == typeof(Nullable<>)) { // Check if it is a nullable value hashEntry = table[s_intrinsicNullableKey]; } else if (callingType.IsInterface) { // Finally, check to see if the component type is some unknown interface. // We have a custom converter for that. hashEntry = table[s_intrinsicReferenceKey]; } } // Interfaces do not derive from object, so we // must handle the case of no hash entry here. // if (hashEntry == null) { hashEntry = table[typeof(object)]; } // If the entry is a type, create an instance of it and then // replace the entry. This way we only need to create once. // We can only do this if the object doesn't want a type // in its constructor. // Type type = hashEntry as Type; if (type != null) { hashEntry = CreateInstance(type, callingType); if (type.GetConstructor(s_typeConstructor) == null) { table[callingType] = hashEntry; } } } return hashEntry; } } }
#define DEBUG using System; using System.Collections; using System.Collections.Generic; namespace ICSimulator { class AveragingWindow { protected int len, ptr; protected double[] window; protected double sum; public AveragingWindow(int N) { len = N; window = new double[N]; ptr = 0; sum = 0.0; } public virtual void accumulate(double t) { sum -= window[ptr]; window[ptr] = t; sum += window[ptr]; ptr = (ptr + 1) % len; } public double average() { return sum / (double)len; } } class AveragingWindow_Binary : AveragingWindow { public AveragingWindow_Binary(int N) : base(N) { } public void accumulate(bool t) { base.accumulate(t ? 1 : 0); } } public class myReverseSort : IComparer { int IComparer.Compare( Object x, Object y ) { double v1 = (double) x; double v2 = (double) y; if (v1 < v2) return 1; if (v1 > v2) return -1; else return 0; } } public enum APP_TYPE {LATENCY_SEN, THROUGHPUT_SEN, STC, NSTC}; // latency sensitive = non-memory intensive; throughput_sensitive = memory intensive, Stall Time Critical, Non-Stall Time Critical public class Controller_QoSThrottle : Controller { private double [] throttle_rate = new double[Config.N]; private double [] m_est_sd = new double[Config.N]; private double [] m_est_sd_unsort = new double[Config.N]; private double [] m_stc = new double[Config.N]; private double [] m_stc_unsort = new double[Config.N]; private ulong[] m_index_stc = new ulong[Config.N]; private ulong[] m_index_sd = new ulong[Config.N]; private double m_l1miss_avg; private double m_sd_avg; private double m_uf_target; public static ulong [] app_rank = new ulong[Config.N]; public static APP_TYPE [] app_type = new APP_TYPE[Config.N]; public static APP_TYPE [] fast_app_type = new APP_TYPE[Config.N]; public static bool [] most_mem_inten = new bool[Config.N]; public static bool enable_qos, enable_qos_mem, enable_qos_non_mem; public static ulong max_rank, max_rank_mem, max_rank_non_mem; public static int [] mshr_quota = new int[Config.N]; public int [] mshr_best_sol = new int[Config.N]; public int [] bad_decision_counter = new int[Config.N]; private int m_slowest_core; private int m_fastest_core; private int m_epoch_counter; private int m_opt_counter; private int m_perf_opt_counter, m_fair_opt_counter, m_idle_counter, m_succ_meet_counter; private double m_currunfairness, m_oldunfairness; private double m_currperf, m_oldperf; private string [] throttle_node = new string[Config.N]; // to enable/disable the throttling mechanism private double m_init_unfairness, m_init_perf; private bool m_throttle_enable; private int unthrottable_count; private THROTTLE_ACTION m_action; private double m_stc_max, m_stc_avg; private double m_fast_throttle_stc_threshold; private THROTTLE_ACTION [] m_actionQ = new THROTTLE_ACTION[Config.N]; enum OPT_STATE { IDLE, PERFORMANCE_OPT, FAIR_OPT }; enum THROTTLE_ACTION { NO_OP, UP, DOWN, RESET }; OPT_STATE m_opt_state; double unfairness_old = 0; private bool[] pre_throt = new bool[Config.N]; IPrioPktPool[] m_injPools = new IPrioPktPool[Config.N]; public Controller_QoSThrottle() { Console.WriteLine("init Controller_QoSThrottle"); for (int i = 0; i < Config.N; i++) { throttle_rate [i] = 0; throttle_node [i] = "1"; m_est_sd [i] = 1; m_stc [i] = 0; m_stc_unsort[i] = 0; m_est_sd_unsort [i] = 0; // assign initial mshr quota mshr_quota [i] = Config.mshrs; mshr_best_sol [i] = Config.mshrs; app_rank [i] = 0; app_type [i] = APP_TYPE.LATENCY_SEN; fast_app_type [i] = APP_TYPE.STC; most_mem_inten [i] = false; pre_throt [i] = false; bad_decision_counter [i] = 0; m_actionQ [i] = THROTTLE_ACTION.NO_OP; m_uf_target = 0; } m_opt_state = OPT_STATE.PERFORMANCE_OPT; max_rank = 0; m_slowest_core = 0; m_fastest_core = 0; m_perf_opt_counter = 0; m_fair_opt_counter = 0; m_succ_meet_counter = 0; m_init_unfairness = 0; m_init_perf = 0; m_epoch_counter = 0; m_idle_counter = 0; m_oldperf = 0; m_oldunfairness = 0; m_opt_counter = 0; m_throttle_enable = Config.throttle_enable; m_l1miss_avg = 0; m_sd_avg = 0; unthrottable_count = 0; m_action = THROTTLE_ACTION.NO_OP; } public override void doStep() { if (Simulator.CurrentRound > (ulong)Config.warmup_cyc && Simulator.CurrentRound % Config.slowdown_epoch == 0 ) { Console.WriteLine ("\n---- A new epoch starts from here. -----\n"); Console.WriteLine ("@TIME = {0}", Simulator.CurrentRound); ComputeSD (); ComputePerformance (); ComputeUnfairness (); ComputeMPKI (); ComputeSTC (); RankBySTC (); // use to mark unthrottled core RankBySD (); // use to select the throttled core if (Config.throttle_enable) { throttleFAST (); } doStat(); } // end if } public void ComputeSD () { double max_sd = double.MinValue; double min_sd = double.MaxValue; double sum_sd = 0; for (int i = 0; i < Config.N; i++) { // compute slowdown m_est_sd[i] = (double)((int)Simulator.CurrentRound-Config.warmup_cyc)/((int)Simulator.CurrentRound-Config.warmup_cyc-Simulator.stats.non_overlap_penalty [i].Count); // find the slowest and fastest core // slowest core will determine the unfairness of the system if (m_est_sd[i] > max_sd) { m_slowest_core = i; max_sd = m_est_sd[i]; } if (m_est_sd[i] < min_sd) { m_fastest_core = i; min_sd = m_est_sd[i]; } sum_sd += m_est_sd [i]; m_est_sd_unsort [i] = m_est_sd [i]; } // end for m_sd_avg = sum_sd / Config.N; } public void ComputeMPKI () { double mpki_max = 0; double mpki_sum=0; double l1miss_sum = 0; for (int i = 0; i < Config.N; i++) { // compute MPKI prev_MPKI[i]=MPKI[i]; if(num_ins_last_epoch[i]==0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count); else { if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]); else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0) MPKI[i]=0; else throw new Exception("MPKI error!"); } mpki_sum+=MPKI[i]; most_mem_inten[i] = false; if (MPKI[i] > mpki_max) mpki_max = MPKI[i]; l1miss_sum += curr_L1misses [i]; } m_l1miss_avg = l1miss_sum / Config.N; Simulator.stats.total_sum_mpki.Add(mpki_sum); } public void ComputeSTC () { // NoC stall-time criticality = Slowdown / #_of_L1misses // Approach 1: Reason to use the absolute number of L1misses: // L1miss will be affected by the throttling mechanism, however, MPKI won't // Approach 2: Use MPKI since it is more statble double stc_sum = 0; double count = 0; for (int i = 0; i < Config.N; i++) { curr_L1misses[i] = L1misses[i]-prev_L1misses[i]; prev_L1misses[i]=L1misses[i]; if (curr_L1misses [i] > 0) { m_stc [i] = m_est_sd [i] / curr_L1misses [i]; //m_stc [i] = m_est_sd[i] / MPKI[i]; stc_sum += m_stc[i]; count++; } else m_stc [i] = double.MaxValue; m_stc_unsort [i] = m_stc [i]; } m_stc_avg = stc_sum / count; } public void ComputePerformance () { m_currperf = 0; // performance is the sum of slowdown of each core for (int i = 0; i < Config.N; i++) m_currperf = m_currperf + m_est_sd[i]; Console.WriteLine("Current Perf is {0:0.000}", m_currperf); } public void ComputeUnfairness () { m_currunfairness = m_est_sd[m_slowest_core]; Console.WriteLine("Current Unfairness is {0:0.000}", m_currunfairness); } // sort from low stc to high stc public void RankBySTC () { for (int i = 0; i < Config.N; i++) m_index_stc [i] = (ulong)i; Array.Sort (m_stc, m_index_stc); for (int i = 0; i < Config.N; i++) app_rank [m_index_stc [i]] = (ulong) i; m_stc_max = m_stc [Config.N-1]; } // sort from low to high slowdown public void RankBySD () { for (int i = 0; i < Config.N; i++) m_index_sd [i] = (ulong)i; IComparer revSort = new myReverseSort (); Array.Sort (m_est_sd, m_index_sd, revSort); } public bool badDecision () { // return true for bad, otherwise good double sd_delta, uf_delta; sd_delta = m_currperf - m_oldperf; uf_delta = m_currunfairness - m_oldunfairness; Console.WriteLine ("sd_delta = {0:0.000}", sd_delta); Console.WriteLine ("uf_delta = {0:0.000}", uf_delta); // the average slowdown decrease of each node exceed the increased unfairness. // or // the unfairness reduction outweight the average increased slowdown at each node. if (Config.favor_performance == true) { if (sd_delta < 0) { Console.WriteLine ("Good deal!"); return false; // the average of slowdown reduction of each core outweight the degradation of unfairness; Or simply both of them are improved. } else { Console.WriteLine ("Bad Idea! Rollback is needed."); return true; } } else { if (sd_delta / Config.N + uf_delta <= 0) { Console.WriteLine ("Good deal!"); return false; // the average of slowdown reduction of each core outweight the degradation of unfairness; Or simply both of them are improved. } else { Console.WriteLine ("Bad Idea! Rollback is needed."); return true; } } } public void throttleFAST() { m_opt_counter++; if (Config.throttle_at_NI) { classifyApp (); Adjust_opt_target (); throttleAction (); } if (Config.throttle_at_mshr) { if (badDecision()) { // previous iteration made a bad decision SetBestSol (); MarkBadDecision (); } else AddBestSol (); // previous iteration made a wise decision ThrottleUpBySDRank (); PickNewThrtDwn (); ThrottleFlagReset (); if (m_opt_counter % Config.th_bad_rst_counter == 0) ThrottleCounterReset(); } } public void SetBestSol () { Console.Write ("Use the best solution so far, as :"); for (int i = 0; i < Config.N; i++) { mshr_quota [i] = mshr_best_sol [i]; Console.Write (" {0}", mshr_quota[i]); } Console.WriteLine(); } public void MarkBadDecision () { Console.WriteLine ("Previous decision sucks. Increase the bad_decision_counter as :"); for (int i = 0; i < Config.N; i++) { if (pre_throt [i] == true) { bad_decision_counter [i]++; } Console.Write (" {0}", bad_decision_counter[i]); } } public void AddBestSol () { Console.WriteLine ("This is the best solution so far, as"); for (int i = 0; i < Config.N; i++) { mshr_best_sol [i] = mshr_quota [i]; Console.Write (" {0}", mshr_quota[i]); Console.WriteLine(); } } public void ThrottleUpBySDRank (){ int unthrottled = -1; int pick = -1; Console.Write ("\n Cores too SLOW:"); for (int i = 0; i < Config.N && unthrottled < Config.thrt_up_slow_app - 1; i++) { pick = (int)m_index_sd [i]; throttle_node [pick] = "0"; Console.Write (" {0}", pick); unthrottled++; unthrottable_count++; ThrottleUpMSHR (pick); } Console.Write ("\n"); Console.Write (" Cores too LIGHT:"); for (int i = 0; i < Config.N; i++) { double miss_rate = curr_L1misses [i] / Config.slowdown_epoch; if (miss_rate < Config.curr_L1miss_threshold) { throttle_node [i] = "0"; unthrottable_count++; ThrottleUpMSHR (i); Console.Write (" {0}", i); } } Console.Write ("\n"); } public void PickNewThrtDwn (){ int throttled = 0; int throttled_old = 0; // when throttled_old = throttled, no more node can be throttled down bool no_more_throt = false; MarkUnthrottled_v2 (); for (int i = 0; i < Config.N; i++) pre_throt [i] = false; while (throttled < Config.thrt_down_stc_app && m_throttle_enable == true && no_more_throt == false) { for (int i = 0; i < Config.N && throttled < Config.thrt_down_stc_app; i++) { int pick = (int)m_index_stc [i]; // check pre_throt to make sure no application is throttled twice if (String.Compare(throttle_node[pick],"0")==0) continue; if (CoidToss (i) == false) continue; if (ThrottleDownMSHR (pick)) { pre_throt [pick] = true; throttle_node [pick] = "0"; throttled++; unthrottable_count++; //Console.WriteLine ("Throttle Down Core {0} to {1}", pick, mshr_quota [pick]); Simulator.stats.throttle_down_profile [pick].Add (); } //Console.WriteLine ("Throttled down counts {0}", throttled); } if (throttled_old == throttled) { no_more_throt = true; // exit the while loop when no more node can be throttled //Console.WriteLine ("No more throttling attempt!"); } else throttled_old = throttled; } } public void ThrottleFlagReset () { Console.WriteLine ("Reset throttle flag"); for (int i = 0; i < Config.N; i++) throttle_node [i] = "1"; } public void ThrottleCounterReset () { Console.WriteLine("Reset bad decision counter"); for (int i = 0; i < Config.N; i++) bad_decision_counter[i] = 0; } public void MarkUnthrottled_v2 () { //Console.WriteLine("CANNOT THROTTLE: Maintain the current MSHR Quota"); Console.Write (" Cores NOOP:"); // mark the slowest core and the all core with MPI < MPI_threshold (light apps) for (int i = 0; i < Config.N; i++) { if (bad_decision_counter[i] >= Config.th_bad_dec_counter || (mshr_quota[i] - 1 ) < Config.throt_min*Config.mshrs){ //Console.WriteLine(" Core {0} bad decision counter reach threshold.", i); throttle_node [i] = "0"; Console.Write(" {0}", i); unthrottable_count++; } } Console.Write (" \n"); } public void classifyApp() { // applications cannot have exact the same STC. // FAST will converge if the STC of each application stays within Config.fast_throttle_threshold % of avg stc. // Smaller (i.e. < 1) Config.fast_throttle_threshold is likely to prevent more application being throttling down and therefore improve system performance. // And vice versa. m_fast_throttle_stc_threshold = Config.fast_throttle_threshold * m_stc_avg; for (int i = 0; i < Config.N; i++) { // stall-time critical applications // a * m_fact_throttle_stc_threshold if (m_stc_unsort [i] >= m_fast_throttle_stc_threshold) fast_app_type [i] = APP_TYPE.STC; // non-stall-time critical applications else { fast_app_type [i] = APP_TYPE.NSTC; } } } public void throttleAction() { double unfairness_delta = m_est_sd [0] - m_est_sd [Config.N-1] ; m_throttle_enable = (unfairness_delta > Config.th_unfairness) ? true : false; switch (m_action) { case THROTTLE_ACTION.RESET: for (int i = 0; i < Config.N; i++) { m_actionQ [i] = THROTTLE_ACTION.RESET; throttle_rate [i] = 0; } break; case THROTTLE_ACTION.DOWN: for (int i = 0; i < Config.N; i++) { m_actionQ [i] = THROTTLE_ACTION.NO_OP; // the slowest thrt_down_stc_app applications are not throttled if (fast_app_type [i] == APP_TYPE.NSTC && m_est_sd_unsort[i] <= m_est_sd[Config.thrt_down_stc_app]) { if (ThrottleDownNI (i)) m_actionQ [i] = THROTTLE_ACTION.DOWN; } } break; case THROTTLE_ACTION.UP: for (int i = 0; i < Config.N; i++) { m_actionQ [i] = THROTTLE_ACTION.NO_OP; if (ThrottleUpNI(i)) m_actionQ [i] = THROTTLE_ACTION.UP; } break; default: for (int i = 0; i < Config.N; i++) m_actionQ [i] = THROTTLE_ACTION.NO_OP; break; } } public void Adjust_opt_target () { // First epoch only set the initial UF target if (m_opt_counter == 1) { m_uf_target = m_currunfairness; m_opt_state = OPT_STATE.FAIR_OPT; return; } // if uf target meets if (m_currunfairness - m_uf_target < 0) { Console.WriteLine ("Meet unfairness target."); if (++m_succ_meet_counter > Config.succ_meet_fair) { m_uf_target = m_currunfairness - Config.uf_adjust; m_opt_state = OPT_STATE.PERFORMANCE_OPT; m_fair_opt_counter = 0; m_action = THROTTLE_ACTION.UP; } else { m_opt_state = OPT_STATE.FAIR_OPT; m_fair_opt_counter++; m_action = THROTTLE_ACTION.NO_OP; } } else { // uf target miss Console.WriteLine ("Miss unfairness target."); if (m_fair_opt_counter > Config.fair_keep_trying) { m_uf_target = m_currunfairness - Config.uf_adjust; m_opt_state = OPT_STATE.PERFORMANCE_OPT; m_action = THROTTLE_ACTION.RESET; m_fair_opt_counter = 0; Console.WriteLine ("FAIR_OPT_COUNT reaches max value."); } else { m_fair_opt_counter++; m_action = THROTTLE_ACTION.DOWN; m_opt_state = OPT_STATE.FAIR_OPT; } m_succ_meet_counter = 0; } Console.WriteLine ("Next state is {0}", m_opt_state.ToString()); Console.WriteLine ("New UF target is {0:0.00}", m_uf_target); } public override bool tryInject(int node) { double prob = Simulator.rand.NextDouble (); if (prob >= throttle_rate [node]) return true; else return false; } public bool CoidToss (int i) { int can_throttle = Config.N - unthrottable_count; int toss_val = Simulator.rand.Next (can_throttle); if (i < (Config.throt_prob_lv1 * Config.N) && toss_val < ((1-Config.throt_prob_lv1) * Config.N)) return true; else if (i < Config.throt_prob_lv2 * Config.N && toss_val < (1-Config.throt_prob_lv2) * Config.N) return true; //else if (toss_val < (1-Config.throt_prob_lv3) * Config.N) return true; else return false; } public bool ThrottleDownMSHR (int node) { bool throttled = false; if (mshr_quota [node] > Config.mshrs * Config.throt_down_stage1) { mshr_quota [node] = (int)(Config.mshrs * Config.throt_down_stage1); throttled = true; } else if (mshr_quota[node] > Config.throt_min*Config.mshrs) { mshr_quota [node] = mshr_quota [node] - 1; throttled = true; } return throttled; } public bool ThrottleDownNI (int node) { if (throttle_rate [node] < 0.6) throttle_rate [node] = throttle_rate [node] + 0.3; else if (throttle_rate [node] < 0.8) throttle_rate [node] = throttle_rate [node] + 0.05; else if (throttle_rate [node] < 0.85) throttle_rate [node] = throttle_rate [node] + 0.01; else return false; return true; } public void ThrottleUpMSHR (int pick) { if (mshr_quota [pick] < Config.mshrs) { //mshr_quota [pick] = mshr_quota [pick] + 1; mshr_quota [pick] = Config.mshrs; mshr_best_sol [pick] = mshr_quota [pick]; //Console.WriteLine ("Throttle UP: Core {0} to {1}.", pick, mshr_quota [pick]); } } public bool ThrottleUpNI (int node) { if (throttle_rate [node] < 0.6 && throttle_rate [node] > 0) throttle_rate [node] = Math.Max(throttle_rate [node] - 0.3, 0); else if (throttle_rate [node] < 0.8 && throttle_rate [node] > 0) throttle_rate [node] = Math.Max(throttle_rate [node] - 0.05, 0); else if (throttle_rate [node] < 0.85 && throttle_rate [node] > 0) throttle_rate [node] = Math.Max(throttle_rate [node] - 0.01, 0); else return false; return true; } public void doStat() { unthrottable_count = 0; Console.WriteLine ("STC Threshold = {0,-8:0.00000}", m_fast_throttle_stc_threshold); Console.WriteLine ("SD AVG = {0,-8:0.00000}", m_sd_avg); Console.WriteLine ("ACTION Core TH MSHR SD STC L1MPC LI_miss"); for (int i = 0; i < Config.N; i++) { double miss_rate = curr_L1misses[i]/Config.slowdown_epoch; #if DEBUG Console.WriteLine ("{0,-10}{1,-8}{2, -8:0.00}{3, -8}{4, -8:0.00}{5, -10:0.00000}{6,-8:0.000}{7, -8}", m_actionQ[i].ToString(), i, throttle_rate[i], mshr_quota[i], m_est_sd_unsort[i], m_stc_unsort[i], miss_rate, curr_L1misses[i]); #endif Simulator.stats.app_stall_per_epoch.Add(Simulator.stats.non_overlap_penalty_period[i].Count); Simulator.stats.L1miss_persrc_period [i].Add(curr_L1misses[i]); Simulator.stats.mpki_bysrc[i].Add(MPKI[i]); Simulator.stats.estimated_slowdown [i].Add (m_est_sd_unsort[i]); Simulator.stats.noc_stc[i].Add(m_stc_unsort[i]); Simulator.stats.app_rank [i].Add(app_rank [i]); Simulator.stats.L1miss_persrc_period [i].EndPeriod(); Simulator.stats.estimated_slowdown [i].EndPeriod (); Simulator.stats.insns_persrc_period [i].EndPeriod (); Simulator.stats.non_overlap_penalty_period [i].EndPeriod (); Simulator.stats.causeIntf [i].EndPeriod (); Simulator.stats.noc_stc[i].EndPeriod(); Simulator.stats.app_rank [i].EndPeriod (); Simulator.stats.mshrs_credit [i].Add (Controller_QoSThrottle.mshr_quota [i]); } m_oldperf = m_currperf; m_oldunfairness = m_currunfairness; m_l1miss_avg = 0; m_sd_avg = 0; } public override void setInjPool(int node, IPrioPktPool pool) { m_injPools[node] = pool; pool.setNodeId(node); } public override IPrioPktPool newPrioPktPool(int node) { return MultiQThrottlePktPool.construct(); } public void throttle_stc () { m_currunfairness = m_est_sd [m_slowest_core]; ComputePerformance (); RankBySD (); // use to mark unthrottled core RankBySTC (); if (m_epoch_counter == 0) m_init_perf = m_currperf; if (m_opt_state == OPT_STATE.PERFORMANCE_OPT) { //if (m_perf_opt_counter == Config.opt_perf_bound || m_currunfairness >= m_budget_unfairness) { if (m_perf_opt_counter == Config.opt_perf_bound) { //m_init_unfairness = m_currunfairness; //m_budget_perf = m_currperf + (m_init_perf - m_currperf) * Config.perf_budget_factor; //m_budget_perf = m_currperf * 1.05; //throttle_reset (); //if (m_budget_perf < m_currperf) // m_opt_state = OPT_STATE.IDLE; //else m_opt_state = OPT_STATE.FAIR_OPT; m_perf_opt_counter = 0; } else { Optimize (); Simulator.stats.opt_perf.Add(1); Console.WriteLine ("Optimize Performance epoch: {0}", Simulator.stats.opt_perf.Count); m_perf_opt_counter++; } } else if (m_opt_state == OPT_STATE.FAIR_OPT) { //if (m_fair_opt_counter == Config.opt_fair_bound || m_currperf >= m_budget_perf) { if (m_fair_opt_counter == Config.opt_fair_bound) { //m_init_perf = m_currperf; //m_budget_unfairness = m_currunfairness + (m_init_unfairness - m_currunfairness) * Config.fair_budget_factor; //throttle_reset (); //if (m_budget_unfairness < m_currunfairness) // m_opt_state = OPT_STATE.IDLE; //else m_opt_state = OPT_STATE.PERFORMANCE_OPT; m_fair_opt_counter = 0; } else { Optimize (); Simulator.stats.opt_fair.Add(1); Console.WriteLine ("Optimize Fairness epoch: {0}", Simulator.stats.opt_fair.Count); m_fair_opt_counter++; } } else if (m_opt_state == OPT_STATE.IDLE) { if (m_currperf - m_init_perf > Config.th_init_perf_loss) { m_opt_state = OPT_STATE.PERFORMANCE_OPT; m_init_perf = m_currperf; } else if (m_currunfairness - m_init_unfairness > Config.th_init_fair_loss) { m_opt_state = OPT_STATE.FAIR_OPT; m_init_unfairness = m_currunfairness; } m_idle_counter++; Console.WriteLine("Stay idle epoch: {0}", m_idle_counter); } m_epoch_counter++; unfairness_old = m_currunfairness; m_oldperf = m_currperf; // just log the mshr quota for (int i = 0; i < Config.N; i++) Simulator.stats.mshrs_credit [i].Add (Controller_QoSThrottle.mshr_quota [i]); } public void throttle_reset () { Console.WriteLine("MSHR is reset"); for (int i = 0; i < Config.N; i++) { mshr_quota [i] = Config.mshrs; throttle_node[i] = "1"; } } public void ClassifyAPP () { for (int i = 0; i < Config.N; i++) // Classify applications if (MPKI[i] >= Config.mpki_threshold) app_type[i] = APP_TYPE.THROUGHPUT_SEN; else app_type[i] = APP_TYPE.LATENCY_SEN; } public void Optimize () { MarkNoThrottle(); int throttled=0; for (int i = 0; i < Config.N && throttled < Config.throt_app_count; i++) { if (CoidToss (i) == false) continue; int pick = (int)m_index_stc [i]; if (ThrottleDownMSHR (pick)) { pre_throt[pick] = true; throttled++; Console.WriteLine ("Throttle Down Core {0} to {1}", pick, mshr_quota[pick]); } } } public void MarkNoThrottle () { if (m_opt_state == OPT_STATE.PERFORMANCE_OPT) { for (int i = 0; i < Config.N; i++) { if (mshr_quota [i] - 1 <= Config.throt_min * Config.mshrs) { Console.WriteLine ("Reach minimum MSHR, mark core {0} UNTHROTTLE", i); throttle_node [i] = "0"; } else if (m_currperf - m_oldperf > 0 && pre_throt[i] == true && mshr_quota[i] < Config.mshrs) { mshr_quota [i] = mshr_quota[i] + 1; // rollback Console.WriteLine ("Previous decision is wrong, throttle up core {0} to {1}", i, mshr_quota[i]); } pre_throt [i] = false; // reset pre_throt here } } else if (m_opt_state == OPT_STATE.FAIR_OPT) { int unthrottled=0; int pick = -1; for (int i = 0; i < Config.N && unthrottled < Config.unthrot_app_count; i++) { pick = (int)m_index_sd[i]; throttle_node[pick] = "0"; unthrottled ++; if (mshr_quota[pick] < Config.mshrs) mshr_quota [pick] = mshr_quota[pick] + 1; Console.WriteLine("Core {0} is protected and throttled up to {1} because it is too slow.", pick, mshr_quota[pick]); } for (int i = 0; i < Config.N; i++) { if (mshr_quota [i] - 1 <= Config.throt_min * Config.mshrs) { Console.WriteLine ("Reach minimum MSHR, mark core {0} UNTHROTTLE", i); throttle_node [i] = "0"; } else if (m_currunfairness - unfairness_old > 0 && pre_throt [i] == true && mshr_quota[i] < Config.mshrs) { // previous decision is wrong mshr_quota [i] = mshr_quota[i] + 1; // rollback Console.WriteLine ("Previous decision is wrong, throttle up core {0} to {1}", i, mshr_quota[i]); } pre_throt [i] = false; // reset pre_throt here } } } } public class Controller_Throttle : Controller_ClassicBLESS { double[] m_throttleRates = new double[Config.N]; IPrioPktPool[] m_injPools = new IPrioPktPool[Config.N]; bool[] m_starved = new bool[Config.N]; AveragingWindow_Binary[] avg_starve = new AveragingWindow_Binary[Config.N]; AveragingWindow[] avg_qlen = new AveragingWindow[Config.N]; public Controller_Throttle() { Console.WriteLine("init"); for (int i = 0; i < Config.N; i++) { avg_starve[i] = new AveragingWindow_Binary(Config.throttle_averaging_window); avg_qlen[i] = new AveragingWindow(Config.throttle_averaging_window); } } void setThrottleRate(int node, double rate) { m_throttleRates[node] = rate; } public override IPrioPktPool newPrioPktPool(int node) { return MultiQThrottlePktPool.construct(); } // true to allow injection, false to block (throttle) public override bool tryInject(int node) { if (m_throttleRates[node] > 0.0) return Simulator.rand.NextDouble() > m_throttleRates[node]; else return true; } public override void setInjPool(int node, IPrioPktPool pool) { m_injPools[node] = pool; pool.setNodeId(node); } public override void reportStarve(int node) { m_starved[node] = true; } public override void doStep() { for (int i = 0; i < Config.N; i++) { int qlen = Simulator.network.nodes[i].RequestQueueLen; avg_starve[i].accumulate(m_starved[i]); avg_qlen[i].accumulate(qlen); m_starved[i] = false; } if (Simulator.CurrentRound > 0 && (Simulator.CurrentRound % (ulong)Config.throttle_epoch) == 0) setThrottling(); } void setThrottling() { // find the average IPF double avg = 0.0; for (int i = 0; i < Config.N; i++) avg += avg_qlen[i].average(); avg /= Config.N; // determine whether any node is congested bool congested = false; for (int i = 0; i < Config.N; i++) if (avg_starve[i].average() > Config.srate_thresh) { congested = true; break; } #if DEBUG Console.WriteLine("throttle: cycle {0} congested {1}\n---", Simulator.CurrentRound, congested ? 1 : 0); Console.WriteLine("avg qlen is {0}", avg); #endif for (int i = 0; i < Config.N; i++) if (congested && avg_qlen[i].average() > avg) { setThrottleRate(i, Math.Min(Config.throt_max, Config.throt_min+Config.throt_scale * avg_qlen[i].average())); #if DEBUG Console.WriteLine("node {0} qlen {1} rate {2}", i, avg_qlen[i].average(), Math.Min(Config.throt_max, Config.throt_min+Config.throt_scale * avg_qlen[i].average())); #endif } else { setThrottleRate(i, 0.0); #if DEBUG Console.WriteLine("node {0} qlen {1} rate 0.0", i, avg_qlen[i].average()); #endif } #if DEBUG Console.WriteLine("---\n"); #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; using System.Threading; using Microsoft.Internal; namespace System.ComponentModel.Composition.Hosting { /// <summary> /// An immutable ComposablePartCatalog created from a managed code assembly. /// </summary> /// <remarks> /// This type is thread safe. /// </remarks> [DebuggerTypeProxy(typeof(AssemblyCatalogDebuggerProxy))] public class AssemblyCatalog : ComposablePartCatalog, ICompositionElement { private readonly object _thisLock = new object(); private readonly ICompositionElement _definitionOrigin; private volatile Assembly _assembly = null; private volatile ComposablePartCatalog _innerCatalog = null; private int _isDisposed = 0; private ReflectionContext _reflectionContext = default(ReflectionContext); /// <summary> /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class /// with the specified code base. /// </summary> /// <param name="codeBase"> /// A <see cref="String"/> containing the code base of the assembly containing the /// attributed <see cref="Type"/> objects to add to the <see cref="AssemblyCatalog"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="codeBase"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="codeBase"/> is a zero-length string, contains only white space, /// or contains one or more invalid characters. />. /// </exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. /// </exception> /// <exception cref="System.Security.SecurityException"> /// The caller does not have path discovery permission. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="codeBase"/> is not found. /// </exception> /// <exception cref="FileLoadException "> /// <paramref name="codeBase"/> could not be loaded. /// <para> /// -or- /// </para> /// <paramref name="codeBase"/> specified a directory. /// </exception> /// <exception cref="BadImageFormatException"> /// <paramref name="codeBase"/> is not a valid assembly /// -or- /// Version 2.0 or later of the common language runtime is currently loaded /// and <paramref name="codeBase"/> was compiled with a later version. /// </exception> /// <remarks> /// The assembly referenced by <paramref langword="codeBase"/> is loaded into the Load context. /// </remarks> public AssemblyCatalog(string codeBase) { Requires.NotNullOrEmpty(codeBase, nameof(codeBase)); InitializeAssemblyCatalog(LoadAssembly(codeBase)); _definitionOrigin = this; } /// <summary> /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class /// with the specified code base. /// </summary> /// <param name="codeBase"> /// A <see cref="String"/> containing the code base of the assembly containing the /// attributed <see cref="Type"/> objects to add to the <see cref="AssemblyCatalog"/>. /// </param> /// <param name="reflectionContext"> /// The <see cref="ReflectionContext"/> a context used by the catalog when /// interpreting the types to inject attributes into the type definition<see cref="AssemblyCatalog"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="codeBase"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="reflectionContext"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="codeBase"/> is a zero-length string, contains only white space, /// or contains one or more invalid characters. />. /// </exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. /// </exception> /// <exception cref="System.Security.SecurityException"> /// The caller does not have path discovery permission. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="codeBase"/> is not found. /// </exception> /// <exception cref="FileLoadException "> /// <paramref name="codeBase"/> could not be loaded. /// <para> /// -or- /// </para> /// <paramref name="codeBase"/> specified a directory. /// </exception> /// <exception cref="BadImageFormatException"> /// <paramref name="codeBase"/> is not a valid assembly /// -or- /// Version 2.0 or later of the common language runtime is currently loaded /// and <paramref name="codeBase"/> was compiled with a later version. /// </exception> /// <remarks> /// The assembly referenced by <paramref langword="codeBase"/> is loaded into the Load context. /// </remarks> public AssemblyCatalog(string codeBase, ReflectionContext reflectionContext) { Requires.NotNullOrEmpty(codeBase, nameof(codeBase)); Requires.NotNull(reflectionContext, nameof(reflectionContext)); InitializeAssemblyCatalog(LoadAssembly(codeBase)); _reflectionContext = reflectionContext; _definitionOrigin = this; } /// <summary> /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class /// with the specified code base. /// </summary> /// <param name="codeBase"> /// A <see cref="String"/> containing the code base of the assembly containing the /// attributed <see cref="Type"/> objects to add to the <see cref="AssemblyCatalog"/>. /// </param> /// <param name="definitionOrigin"> /// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="codeBase"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="definitionOrigin"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="codeBase"/> is a zero-length string, contains only white space, /// or contains one or more invalid characters. />. /// </exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. /// </exception> /// <exception cref="System.Security.SecurityException"> /// The caller does not have path discovery permission. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="codeBase"/> is not found. /// </exception> /// <exception cref="FileLoadException "> /// <paramref name="codeBase"/> could not be loaded. /// <para> /// -or- /// </para> /// <paramref name="codeBase"/> specified a directory. /// </exception> /// <exception cref="BadImageFormatException"> /// <paramref name="codeBase"/> is not a valid assembly /// -or- /// Version 2.0 or later of the common language runtime is currently loaded /// and <paramref name="codeBase"/> was compiled with a later version. /// </exception> /// <remarks> /// The assembly referenced by <paramref langword="codeBase"/> is loaded into the Load context. /// </remarks> public AssemblyCatalog(string codeBase, ICompositionElement definitionOrigin) { Requires.NotNullOrEmpty(codeBase, nameof(codeBase)); Requires.NotNull(definitionOrigin, nameof(definitionOrigin)); InitializeAssemblyCatalog(LoadAssembly(codeBase)); _definitionOrigin = definitionOrigin; } /// <summary> /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class /// with the specified code base. /// </summary> /// <param name="codeBase"> /// A <see cref="String"/> containing the code base of the assembly containing the /// attributed <see cref="Type"/> objects to add to the <see cref="AssemblyCatalog"/>. /// </param> /// <param name="reflectionContext"> /// The <see cref="ReflectionContext"/> a context used by the catalog when /// interpreting the types to inject attributes into the type definition<see cref="AssemblyCatalog"/>. /// </param> /// <param name="definitionOrigin"> /// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="codeBase"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="reflectionContext"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="definitionOrigin"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="codeBase"/> is a zero-length string, contains only white space, /// or contains one or more invalid characters. />. /// </exception> /// <exception cref="PathTooLongException"> /// The specified path, file name, or both exceed the system-defined maximum length. /// </exception> /// <exception cref="System.Security.SecurityException"> /// The caller does not have path discovery permission. /// </exception> /// <exception cref="FileNotFoundException"> /// <paramref name="codeBase"/> is not found. /// </exception> /// <exception cref="FileLoadException "> /// <paramref name="codeBase"/> could not be loaded. /// <para> /// -or- /// </para> /// <paramref name="codeBase"/> specified a directory. /// </exception> /// <exception cref="BadImageFormatException"> /// <paramref name="codeBase"/> is not a valid assembly /// -or- /// Version 2.0 or later of the common language runtime is currently loaded /// and <paramref name="codeBase"/> was compiled with a later version. /// </exception> /// <remarks> /// The assembly referenced by <paramref langword="codeBase"/> is loaded into the Load context. /// </remarks> public AssemblyCatalog(string codeBase, ReflectionContext reflectionContext, ICompositionElement definitionOrigin) { Requires.NotNullOrEmpty(codeBase, nameof(codeBase)); Requires.NotNull(reflectionContext, nameof(reflectionContext)); Requires.NotNull(definitionOrigin, nameof(definitionOrigin)); InitializeAssemblyCatalog(LoadAssembly(codeBase)); _reflectionContext = reflectionContext; _definitionOrigin = definitionOrigin; } /// <summary> /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class /// with the specified assembly and reflection context. /// </summary> /// <param name="assembly"> /// The <see cref="Assembly"/> containing the attributed <see cref="Type"/> objects to /// add to the <see cref="AssemblyCatalog"/>. /// </param> /// <param name="reflectionContext"> /// The <see cref="ReflectionContext"/> a context used by the catalog when /// interpreting the types to inject attributes into the type definition. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="assembly"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="assembly"/> was loaded in the reflection-only context. /// <para> /// -or- /// </para> /// <paramref name="reflectionContext"/> is <see langword="null"/>. /// </exception> public AssemblyCatalog(Assembly assembly, ReflectionContext reflectionContext) { Requires.NotNull(assembly, nameof(assembly)); Requires.NotNull(reflectionContext, nameof(reflectionContext)); InitializeAssemblyCatalog(assembly); _reflectionContext = reflectionContext; _definitionOrigin = this; } /// <summary> /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class /// with the specified assembly, reflectionContext and definitionOrigin. /// </summary> /// <param name="assembly"> /// The <see cref="Assembly"/> containing the attributed <see cref="Type"/> objects to /// add to the <see cref="AssemblyCatalog"/>. /// </param> /// <param name="reflectionContext"> /// The <see cref="ReflectionContext"/> a context used by the catalog when /// interpreting the types to inject attributes into the type definition. /// </param> /// <param name="definitionOrigin"> /// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="assembly"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="assembly"/> was loaded in the reflection-only context. /// <para> /// -or- /// </para> /// <paramref name="reflectionContext"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="definitionOrigin"/> is <see langword="null"/>. /// </exception> public AssemblyCatalog(Assembly assembly, ReflectionContext reflectionContext, ICompositionElement definitionOrigin) { Requires.NotNull(assembly, nameof(assembly)); Requires.NotNull(reflectionContext, nameof(reflectionContext)); Requires.NotNull(definitionOrigin, nameof(definitionOrigin)); InitializeAssemblyCatalog(assembly); _reflectionContext = reflectionContext; _definitionOrigin = definitionOrigin; } /// <summary> /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class /// with the specified assembly. /// </summary> /// <param name="assembly"> /// The <see cref="Assembly"/> containing the attributed <see cref="Type"/> objects to /// add to the <see cref="AssemblyCatalog"/>. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="assembly"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="assembly"/> was loaded in the reflection-only context. /// </exception> public AssemblyCatalog(Assembly assembly) { Requires.NotNull(assembly, nameof(assembly)); InitializeAssemblyCatalog(assembly); _definitionOrigin = this; } /// <summary> /// Initializes a new instance of the <see cref="AssemblyCatalog"/> class /// with the specified assembly. /// </summary> /// <param name="assembly"> /// The <see cref="Assembly"/> containing the attributed <see cref="Type"/> objects to /// add to the <see cref="AssemblyCatalog"/>. /// </param> /// <param name="definitionOrigin"> /// The <see cref="ICompositionElement"/> CompositionElement used by Diagnostics to identify the source for parts. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="assembly"/> is <see langword="null"/>. /// <para> /// -or- /// </para> /// <paramref name="assembly"/> was loaded in the reflection-only context. /// <para> /// -or- /// </para> /// <paramref name="definitionOrigin"/> is <see langword="null"/>. /// </exception> public AssemblyCatalog(Assembly assembly, ICompositionElement definitionOrigin) { Requires.NotNull(assembly, nameof(assembly)); Requires.NotNull(definitionOrigin, nameof(definitionOrigin)); InitializeAssemblyCatalog(assembly); _definitionOrigin = definitionOrigin; } private void InitializeAssemblyCatalog(Assembly assembly) { if (assembly.ReflectionOnly) { throw new ArgumentException(SR.Format(SR.Argument_AssemblyReflectionOnly, nameof(assembly)), nameof(assembly)); } _assembly = assembly; } /// <summary> /// Returns the export definitions that match the constraint defined by the specified definition. /// </summary> /// <param name="definition"> /// The <see cref="ImportDefinition"/> that defines the conditions of the /// <see cref="ExportDefinition"/> objects to return. /// </param> /// <returns> /// An <see cref="IEnumerable{T}"/> of <see cref="Tuple{T1, T2}"/> containing the /// <see cref="ExportDefinition"/> objects and their associated /// <see cref="ComposablePartDefinition"/> for objects that match the constraint defined /// by <paramref name="definition"/>. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="definition"/> is <see langword="null"/>. /// </exception> /// <exception cref="ObjectDisposedException"> /// The <see cref="ComposablePartCatalog"/> has been disposed of. /// </exception> /// <remarks> /// <note type="inheritinfo"> /// Overriders of this property should never return <see langword="null"/>, if no /// <see cref="ExportDefinition"/> match the conditions defined by /// <paramref name="definition"/>, return an empty <see cref="IEnumerable{T}"/>. /// </note> /// </remarks> public override IEnumerable<Tuple<ComposablePartDefinition, ExportDefinition>> GetExports(ImportDefinition definition) { return InnerCatalog.GetExports(definition); } private ComposablePartCatalog InnerCatalog { get { ThrowIfDisposed(); if (_innerCatalog == null) { var catalogReflectionContextAttribute = _assembly.GetFirstAttribute<CatalogReflectionContextAttribute>(); var assembly = (catalogReflectionContextAttribute != null) ? catalogReflectionContextAttribute.CreateReflectionContext().MapAssembly(_assembly) : _assembly; lock (_thisLock) { if (_innerCatalog == null) { var catalog = (_reflectionContext != null) ? new TypeCatalog(assembly.GetTypes(), _reflectionContext, _definitionOrigin) : new TypeCatalog(assembly.GetTypes(), _definitionOrigin); Thread.MemoryBarrier(); _innerCatalog = catalog; } } } return _innerCatalog; } } /// <summary> /// Gets the assembly containing the attributed types contained within the assembly /// catalog. /// </summary> /// <value> /// The <see cref="Assembly"/> containing the attributed <see cref="Type"/> objects /// contained within the <see cref="AssemblyCatalog"/>. /// </value> public Assembly Assembly { get { Debug.Assert(_assembly != null); return _assembly; } } /// <summary> /// Gets the display name of the assembly catalog. /// </summary> /// <value> /// A <see cref="String"/> containing a human-readable display name of the <see cref="AssemblyCatalog"/>. /// </value> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] string ICompositionElement.DisplayName { get { return GetDisplayName(); } } /// <summary> /// Gets the composition element from which the assembly catalog originated. /// </summary> /// <value> /// This property always returns <see langword="null"/>. /// </value> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")] ICompositionElement ICompositionElement.Origin { get { return null; } } /// <summary> /// Returns a string representation of the assembly catalog. /// </summary> /// <returns> /// A <see cref="String"/> containing the string representation of the <see cref="AssemblyCatalog"/>. /// </returns> public override string ToString() { return GetDisplayName(); } protected override void Dispose(bool disposing) { try { if (Interlocked.CompareExchange(ref _isDisposed, 1, 0) == 0) { if (disposing) { if (_innerCatalog != null) { _innerCatalog.Dispose(); } } } } finally { base.Dispose(disposing); } } public override IEnumerator<ComposablePartDefinition> GetEnumerator() { return InnerCatalog.GetEnumerator(); } private void ThrowIfDisposed() { if (_isDisposed == 1) { throw ExceptionBuilder.CreateObjectDisposed(this); } } private string GetDisplayName() { return string.Format(CultureInfo.CurrentCulture, "{0} (Assembly=\"{1}\")", // NOLOC GetType().Name, Assembly.FullName); } private static Assembly LoadAssembly(string codeBase) { Requires.NotNullOrEmpty(codeBase, nameof(codeBase)); AssemblyName assemblyName; try { assemblyName = AssemblyName.GetAssemblyName(codeBase); } catch (ArgumentException) { assemblyName = new AssemblyName(); assemblyName.CodeBase = codeBase; } try { return Assembly.Load(assemblyName); } //fallback attempt issue https://github.com/dotnet/corefx/issues/27433 catch (FileNotFoundException) { return Assembly.LoadFrom(codeBase); } } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Gl { /// <summary> /// [GL] glVertexAttribL1i64NV: Binding for glVertexAttribL1i64NV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:long"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL1NV(uint index, long x) { Debug.Assert(Delegates.pglVertexAttribL1i64NV != null, "pglVertexAttribL1i64NV not implemented"); Delegates.pglVertexAttribL1i64NV(index, x); LogCommand("glVertexAttribL1i64NV", null, index, x ); DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL2i64NV: Binding for glVertexAttribL2i64NV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:long"/>. /// </param> /// <param name="y"> /// A <see cref="T:long"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL2NV(uint index, long x, long y) { Debug.Assert(Delegates.pglVertexAttribL2i64NV != null, "pglVertexAttribL2i64NV not implemented"); Delegates.pglVertexAttribL2i64NV(index, x, y); LogCommand("glVertexAttribL2i64NV", null, index, x, y ); DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL3i64NV: Binding for glVertexAttribL3i64NV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:long"/>. /// </param> /// <param name="y"> /// A <see cref="T:long"/>. /// </param> /// <param name="z"> /// A <see cref="T:long"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL3NV(uint index, long x, long y, long z) { Debug.Assert(Delegates.pglVertexAttribL3i64NV != null, "pglVertexAttribL3i64NV not implemented"); Delegates.pglVertexAttribL3i64NV(index, x, y, z); LogCommand("glVertexAttribL3i64NV", null, index, x, y, z ); DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL4i64NV: Binding for glVertexAttribL4i64NV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:long"/>. /// </param> /// <param name="y"> /// A <see cref="T:long"/>. /// </param> /// <param name="z"> /// A <see cref="T:long"/>. /// </param> /// <param name="w"> /// A <see cref="T:long"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL4NV(uint index, long x, long y, long z, long w) { Debug.Assert(Delegates.pglVertexAttribL4i64NV != null, "pglVertexAttribL4i64NV not implemented"); Delegates.pglVertexAttribL4i64NV(index, x, y, z, w); LogCommand("glVertexAttribL4i64NV", null, index, x, y, z, w ); DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL1i64vNV: Binding for glVertexAttribL1i64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="v"> /// A <see cref="T:long[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL1NV(uint index, long[] v) { Debug.Assert(v.Length >= 1); unsafe { fixed (long* p_v = v) { Debug.Assert(Delegates.pglVertexAttribL1i64vNV != null, "pglVertexAttribL1i64vNV not implemented"); Delegates.pglVertexAttribL1i64vNV(index, p_v); LogCommand("glVertexAttribL1i64vNV", null, index, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL2i64vNV: Binding for glVertexAttribL2i64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="v"> /// A <see cref="T:long[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL2NV(uint index, long[] v) { Debug.Assert(v.Length >= 2); unsafe { fixed (long* p_v = v) { Debug.Assert(Delegates.pglVertexAttribL2i64vNV != null, "pglVertexAttribL2i64vNV not implemented"); Delegates.pglVertexAttribL2i64vNV(index, p_v); LogCommand("glVertexAttribL2i64vNV", null, index, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL3i64vNV: Binding for glVertexAttribL3i64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="v"> /// A <see cref="T:long[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL3NV(uint index, long[] v) { Debug.Assert(v.Length >= 3); unsafe { fixed (long* p_v = v) { Debug.Assert(Delegates.pglVertexAttribL3i64vNV != null, "pglVertexAttribL3i64vNV not implemented"); Delegates.pglVertexAttribL3i64vNV(index, p_v); LogCommand("glVertexAttribL3i64vNV", null, index, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL4i64vNV: Binding for glVertexAttribL4i64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="v"> /// A <see cref="T:long[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL4NV(uint index, long[] v) { Debug.Assert(v.Length >= 4); unsafe { fixed (long* p_v = v) { Debug.Assert(Delegates.pglVertexAttribL4i64vNV != null, "pglVertexAttribL4i64vNV not implemented"); Delegates.pglVertexAttribL4i64vNV(index, p_v); LogCommand("glVertexAttribL4i64vNV", null, index, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL1ui64NV: Binding for glVertexAttribL1ui64NV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:ulong"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL1NV(uint index, ulong x) { Debug.Assert(Delegates.pglVertexAttribL1ui64NV != null, "pglVertexAttribL1ui64NV not implemented"); Delegates.pglVertexAttribL1ui64NV(index, x); LogCommand("glVertexAttribL1ui64NV", null, index, x ); DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL2ui64NV: Binding for glVertexAttribL2ui64NV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:ulong"/>. /// </param> /// <param name="y"> /// A <see cref="T:ulong"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL2NV(uint index, ulong x, ulong y) { Debug.Assert(Delegates.pglVertexAttribL2ui64NV != null, "pglVertexAttribL2ui64NV not implemented"); Delegates.pglVertexAttribL2ui64NV(index, x, y); LogCommand("glVertexAttribL2ui64NV", null, index, x, y ); DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL3ui64NV: Binding for glVertexAttribL3ui64NV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:ulong"/>. /// </param> /// <param name="y"> /// A <see cref="T:ulong"/>. /// </param> /// <param name="z"> /// A <see cref="T:ulong"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL3NV(uint index, ulong x, ulong y, ulong z) { Debug.Assert(Delegates.pglVertexAttribL3ui64NV != null, "pglVertexAttribL3ui64NV not implemented"); Delegates.pglVertexAttribL3ui64NV(index, x, y, z); LogCommand("glVertexAttribL3ui64NV", null, index, x, y, z ); DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL4ui64NV: Binding for glVertexAttribL4ui64NV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="x"> /// A <see cref="T:ulong"/>. /// </param> /// <param name="y"> /// A <see cref="T:ulong"/>. /// </param> /// <param name="z"> /// A <see cref="T:ulong"/>. /// </param> /// <param name="w"> /// A <see cref="T:ulong"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL4NV(uint index, ulong x, ulong y, ulong z, ulong w) { Debug.Assert(Delegates.pglVertexAttribL4ui64NV != null, "pglVertexAttribL4ui64NV not implemented"); Delegates.pglVertexAttribL4ui64NV(index, x, y, z, w); LogCommand("glVertexAttribL4ui64NV", null, index, x, y, z, w ); DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL1ui64vNV: Binding for glVertexAttribL1ui64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="v"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL1NV(uint index, ulong[] v) { Debug.Assert(v.Length >= 1); unsafe { fixed (ulong* p_v = v) { Debug.Assert(Delegates.pglVertexAttribL1ui64vNV != null, "pglVertexAttribL1ui64vNV not implemented"); Delegates.pglVertexAttribL1ui64vNV(index, p_v); LogCommand("glVertexAttribL1ui64vNV", null, index, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL2ui64vNV: Binding for glVertexAttribL2ui64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="v"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL2NV(uint index, ulong[] v) { Debug.Assert(v.Length >= 2); unsafe { fixed (ulong* p_v = v) { Debug.Assert(Delegates.pglVertexAttribL2ui64vNV != null, "pglVertexAttribL2ui64vNV not implemented"); Delegates.pglVertexAttribL2ui64vNV(index, p_v); LogCommand("glVertexAttribL2ui64vNV", null, index, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL3ui64vNV: Binding for glVertexAttribL3ui64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="v"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL3NV(uint index, ulong[] v) { Debug.Assert(v.Length >= 3); unsafe { fixed (ulong* p_v = v) { Debug.Assert(Delegates.pglVertexAttribL3ui64vNV != null, "pglVertexAttribL3ui64vNV not implemented"); Delegates.pglVertexAttribL3ui64vNV(index, p_v); LogCommand("glVertexAttribL3ui64vNV", null, index, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribL4ui64vNV: Binding for glVertexAttribL4ui64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="v"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribL4NV(uint index, ulong[] v) { Debug.Assert(v.Length >= 4); unsafe { fixed (ulong* p_v = v) { Debug.Assert(Delegates.pglVertexAttribL4ui64vNV != null, "pglVertexAttribL4ui64vNV not implemented"); Delegates.pglVertexAttribL4ui64vNV(index, p_v); LogCommand("glVertexAttribL4ui64vNV", null, index, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetVertexAttribLi64vNV: Binding for glGetVertexAttribLi64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:VertexAttribEnum"/>. /// </param> /// <param name="params"> /// A <see cref="T:long[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void GetVertexAttribLNV(uint index, VertexAttribEnum pname, [Out] long[] @params) { unsafe { fixed (long* p_params = @params) { Debug.Assert(Delegates.pglGetVertexAttribLi64vNV != null, "pglGetVertexAttribLi64vNV not implemented"); Delegates.pglGetVertexAttribLi64vNV(index, (int)pname, p_params); LogCommand("glGetVertexAttribLi64vNV", null, index, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetVertexAttribLui64vNV: Binding for glGetVertexAttribLui64vNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="pname"> /// A <see cref="T:VertexAttribEnum"/>. /// </param> /// <param name="params"> /// A <see cref="T:ulong[]"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void GetVertexAttribLNV(uint index, VertexAttribEnum pname, [Out] ulong[] @params) { unsafe { fixed (ulong* p_params = @params) { Debug.Assert(Delegates.pglGetVertexAttribLui64vNV != null, "pglGetVertexAttribLui64vNV not implemented"); Delegates.pglGetVertexAttribLui64vNV(index, (int)pname, p_params); LogCommand("glGetVertexAttribLui64vNV", null, index, pname, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glVertexAttribLFormatNV: Binding for glVertexAttribLFormatNV. /// </summary> /// <param name="index"> /// A <see cref="T:uint"/>. /// </param> /// <param name="size"> /// A <see cref="T:int"/>. /// </param> /// <param name="type"> /// A <see cref="T:VertexAttribType"/>. /// </param> /// <param name="stride"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] public static void VertexAttribLFormatNV(uint index, int size, VertexAttribType type, int stride) { Debug.Assert(Delegates.pglVertexAttribLFormatNV != null, "pglVertexAttribLFormatNV not implemented"); Delegates.pglVertexAttribLFormatNV(index, size, (int)type, stride); LogCommand("glVertexAttribLFormatNV", null, index, size, type, stride ); DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL1i64NV(uint index, long x); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL1i64NV pglVertexAttribL1i64NV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL2i64NV(uint index, long x, long y); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL2i64NV pglVertexAttribL2i64NV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL3i64NV(uint index, long x, long y, long z); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL3i64NV pglVertexAttribL3i64NV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL4i64NV(uint index, long x, long y, long z, long w); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL4i64NV pglVertexAttribL4i64NV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL1i64vNV(uint index, long* v); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL1i64vNV pglVertexAttribL1i64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL2i64vNV(uint index, long* v); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL2i64vNV pglVertexAttribL2i64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL3i64vNV(uint index, long* v); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL3i64vNV pglVertexAttribL3i64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL4i64vNV(uint index, long* v); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL4i64vNV pglVertexAttribL4i64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL1ui64NV(uint index, ulong x); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL1ui64NV pglVertexAttribL1ui64NV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL2ui64NV(uint index, ulong x, ulong y); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL2ui64NV pglVertexAttribL2ui64NV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL3ui64NV(uint index, ulong x, ulong y, ulong z); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL3ui64NV pglVertexAttribL3ui64NV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL4ui64NV(uint index, ulong x, ulong y, ulong z, ulong w); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL4ui64NV pglVertexAttribL4ui64NV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL1ui64vNV(uint index, ulong* v); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL1ui64vNV pglVertexAttribL1ui64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL2ui64vNV(uint index, ulong* v); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL2ui64vNV pglVertexAttribL2ui64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL3ui64vNV(uint index, ulong* v); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL3ui64vNV pglVertexAttribL3ui64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribL4ui64vNV(uint index, ulong* v); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribL4ui64vNV pglVertexAttribL4ui64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetVertexAttribLi64vNV(uint index, int pname, long* @params); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glGetVertexAttribLi64vNV pglGetVertexAttribLi64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetVertexAttribLui64vNV(uint index, int pname, ulong* @params); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glGetVertexAttribLui64vNV pglGetVertexAttribLui64vNV; [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glVertexAttribLFormatNV(uint index, int size, int type, int stride); [RequiredByFeature("GL_NV_vertex_attrib_integer_64bit", Api = "gl|glcore")] [ThreadStatic] internal static glVertexAttribLFormatNV pglVertexAttribLFormatNV; } } }
///////////////////////////////////////////////////////////////////////////////// // Paint.NET // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See license-pdn.txt for full licensing and attribution details. // // // // Ported to Pinta by: Jonathan Pobst <[email protected]> // ///////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using Gdk; using Pinta.Core; namespace Pinta.Gui.Widgets { class CanvasRenderer { private static Cairo.Pattern tranparent_pattern; private Size source_size; private Size destination_size; private Layer offset_layer; private bool enable_pixel_grid; private ScaleFactor scale_factor; private bool generated; private int[] d2sLookupX; private int[] d2sLookupY; private int[] s2dLookupX; private int[] s2dLookupY; public CanvasRenderer (bool enable_pixel_grid) { this.enable_pixel_grid = enable_pixel_grid; } static CanvasRenderer () { using (var grid = GdkExtensions.CreateTransparentColorSwatch (false)) using (var surf = grid.ToSurface ()) tranparent_pattern = surf.ToTiledPattern (); } public void Initialize (Size sourceSize, Size destinationSize) { if (sourceSize == source_size && destinationSize == destination_size) return; source_size = sourceSize; destination_size = destinationSize; scale_factor = new ScaleFactor (source_size.Width, destination_size.Width); generated = false; } public void Render (List<Layer> layers, Cairo.ImageSurface dst, Gdk.Point offset) { dst.Flush (); // Our rectangle of interest var r = new Gdk.Rectangle (offset, dst.GetBounds ().Size).ToCairoRectangle (); using (var g = new Cairo.Context (dst)) { // Create the transparent checkerboard background g.Translate (-offset.X, -offset.Y); g.FillRectangle (r, tranparent_pattern, new Cairo.PointD (offset.X, offset.Y)); for (var i = 0; i < layers.Count; i++) { var layer = layers[i]; // If we're in LivePreview, substitute current layer with the preview layer if (layer == PintaCore.Layers.CurrentLayer && PintaCore.LivePreview.IsEnabled) layer = CreateLivePreviewLayer (layer); // If the layer is offset, handle it here if (!layer.Transform.IsIdentity ()) layer = CreateOffsetLayer (layer); // No need to resize the surface if we're at 100% zoom if (scale_factor.Ratio == 1) layer.Draw (g, layer.Surface, layer.Opacity, false); else { using (var scaled = new Cairo.ImageSurface (Cairo.Format.Argb32, dst.Width, dst.Height)) { g.Save (); // Have to undo the translate set above g.Translate (offset.X, offset.Y); CopyScaled (layer.Surface, scaled, r.ToGdkRectangle ()); layer.Draw (g, scaled, layer.Opacity, false); g.Restore (); } } } } // If we are at least 200% and grid is requested, draw it if (enable_pixel_grid && PintaCore.Actions.View.PixelGrid.Active && scale_factor.Ratio <= 0.5d) RenderPixelGrid (dst, offset); dst.MarkDirty (); } private Layer OffsetLayer { get { // Create one if we don't have one if (offset_layer == null) offset_layer = new Layer (new Cairo.ImageSurface (Cairo.Format.ARGB32, source_size.Width, source_size.Height)); // If we have the wrong size one, dispose it and create the correct size if (offset_layer.Surface.Width != source_size.Width || offset_layer.Surface.Height != source_size.Height) { (offset_layer.Surface as IDisposable).Dispose (); offset_layer = new Layer (new Cairo.ImageSurface (Cairo.Format.ARGB32, source_size.Width, source_size.Height)); } return offset_layer; } } private Layer CreateLivePreviewLayer (Layer original) { var preview_layer = new Layer (PintaCore.LivePreview.LivePreviewSurface); preview_layer.BlendMode = original.BlendMode; preview_layer.Transform.InitMatrix (original.Transform); preview_layer.Opacity = original.Opacity; preview_layer.Hidden = original.Hidden; return preview_layer; } private Layer CreateOffsetLayer (Layer original) { var offset = OffsetLayer; offset.Surface.Clear (); using (var g = new Cairo.Context (offset.Surface)) original.Draw (g, original.Surface, 1); offset.BlendMode = original.BlendMode; offset.Transform.InitMatrix (original.Transform); offset.Opacity = original.Opacity; return offset; } #region Algorithms ported from PDN private void CopyScaled (Cairo.ImageSurface src, Cairo.ImageSurface dst, Rectangle roi) { if (scale_factor.Ratio < 1) CopyScaledZoomIn (src, dst, roi); else CopyScaledZoomOut (src, dst, roi); } private unsafe void CopyScaledZoomIn (Cairo.ImageSurface src, Cairo.ImageSurface dst, Rectangle roi) { // Tell Cairo we need the latest raw data dst.Flush (); EnsureLookupTablesCreated (); // Cache pointers to surface raw data var src_ptr = (ColorBgra*)src.DataPtr; var dst_ptr = (ColorBgra*)dst.DataPtr; // Cache surface sizes var src_width = src.Width; var dst_width = dst.Width; var dst_height = dst.Height; for (var dst_row = 0; dst_row < dst_height; ++dst_row) { // For each dest row, look up the src row to copy from var nnY = dst_row + roi.Y; var srcY = d2sLookupY[nnY]; // Get pointers to src and dest rows var dst_row_ptr = dst.GetRowAddressUnchecked (dst_ptr, dst_width, dst_row); var src_row_ptr = src.GetRowAddressUnchecked (src_ptr, src_width, srcY); for (var dstCol = 0; dstCol < dst_width; ++dstCol) { // Look up the src column to copy from var nnX = dstCol + roi.X; var srcX = d2sLookupX[nnX]; // Copy source to destination *dst_row_ptr++ = *(src_row_ptr + srcX); } } // Tell Cairo we changed the raw data dst.MarkDirty (); } private unsafe void CopyScaledZoomOut (Cairo.ImageSurface src, Cairo.ImageSurface dst, Rectangle roi) { // Tell Cairo we need the latest raw data dst.Flush (); const int fpShift = 12; const int fpFactor = (1 << fpShift); var source_size = src.GetBounds ().Size; // Find destination bounds var dst_left = (int)(((long)roi.X * fpFactor * (long)source_size.Width) / (long)destination_size.Width); var dst_top = (int)(((long)roi.Y * fpFactor * (long)source_size.Height) / (long)destination_size.Height); var dst_right = (int)(((long)(roi.X + dst.Width) * fpFactor * (long)source_size.Width) / (long)destination_size.Width); var dst_bottom = (int)(((long)(roi.Y + dst.Height) * fpFactor * (long)source_size.Height) / (long)destination_size.Height); var dx = (dst_right - dst_left) / dst.Width; var dy = (dst_bottom - dst_top) / dst.Height; // Cache pointers to surface raw data and sizes var src_ptr = (ColorBgra*)src.DataPtr; var dst_ptr = (ColorBgra*)dst.DataPtr; var src_width = src.Width; var dst_width = dst.Width; var dst_height = dst.Height; for (int dstRow = 0, fDstY = dst_top; dstRow < dst_height && fDstY < dst_bottom; ++dstRow, fDstY += dy) { var srcY1 = fDstY >> fpShift; // y var srcY2 = (fDstY + (dy >> 2)) >> fpShift; // y + 0.25 var srcY3 = (fDstY + (dy >> 1)) >> fpShift; // y + 0.50 var srcY4 = (fDstY + (dy >> 1) + (dy >> 2)) >> fpShift; // y + 0.75 var src1 = src.GetRowAddressUnchecked (src_ptr, src_width, srcY1); var src2 = src.GetRowAddressUnchecked (src_ptr, src_width, srcY2); var src3 = src.GetRowAddressUnchecked (src_ptr, src_width, srcY3); var src4 = src.GetRowAddressUnchecked (src_ptr, src_width, srcY4); var dstPtr = dst.GetRowAddressUnchecked (dst_ptr, dst_width, dstRow); var checkerY = dstRow + roi.Y; var checkerX = roi.X; var maxCheckerX = checkerX + dst.Width; for (var fDstX = dst_left; checkerX < maxCheckerX && fDstX < dst_right; ++checkerX, fDstX += dx) { var srcX1 = (fDstX + (dx >> 2)) >> fpShift; // x + 0.25 var srcX2 = (fDstX + (dx >> 1) + (dx >> 2)) >> fpShift; // x + 0.75 var srcX3 = fDstX >> fpShift; // x var srcX4 = (fDstX + (dx >> 1)) >> fpShift; // x + 0.50 var p1 = src1 + srcX1; var p2 = src2 + srcX2; var p3 = src3 + srcX3; var p4 = src4 + srcX4; var r = (2 + p1->R + p2->R + p3->R + p4->R) >> 2; var g = (2 + p1->G + p2->G + p3->G + p4->G) >> 2; var b = (2 + p1->B + p2->B + p3->B + p4->B) >> 2; var a = (2 + p1->A + p2->A + p3->A + p4->A) >> 2; // Copy color to destination *dstPtr++ = ColorBgra.FromUInt32 ((uint)b + ((uint)g << 8) + ((uint)r << 16) + ((uint)a << 24)); } } // Tell Cairo we changed the raw data dst.MarkDirty (); } private unsafe void RenderPixelGrid (Cairo.ImageSurface dst, Gdk.Point offset) { EnsureLookupTablesCreated (); // Draw horizontal lines var dst_ptr = (ColorBgra*)dst.DataPtr; int dstHeight = dst.Height; int dstWidth = dst.Width; int dstStride = dst.Stride; int sTop = d2sLookupY[offset.Y]; int sBottom = d2sLookupY[offset.Y + dstHeight]; for (int srcY = sTop; srcY <= sBottom; ++srcY) { int dstY = s2dLookupY[srcY]; int dstRow = dstY - offset.Y; if (dstRow >= 0 && dstRow < dstHeight) { ColorBgra* dstRowPtr = dst.GetRowAddressUnchecked (dst_ptr, dstWidth, dstRow); ColorBgra* dstRowEndPtr = dstRowPtr + dstWidth; dstRowPtr += offset.X & 1; while (dstRowPtr < dstRowEndPtr) { *dstRowPtr = ColorBgra.Black; dstRowPtr += 2; } } } // Draw vertical lines int sLeft = d2sLookupX[offset.X]; int sRight = d2sLookupX[offset.X + dstWidth]; for (int srcX = sLeft; srcX <= sRight; ++srcX) { int dstX = s2dLookupX[srcX]; int dstCol = dstX - offset.X; if (dstCol >= 0 && dstCol < dstWidth) { byte* dstColPtr = (byte*)dst.GetPointAddress (dstCol, 0); byte* dstColEndPtr = dstColPtr + dstStride * dstHeight; dstColPtr += (offset.Y & 1) * dstStride; while (dstColPtr < dstColEndPtr) { *((ColorBgra*)dstColPtr) = ColorBgra.Black; dstColPtr += 2 * dstStride; } } } } private void EnsureLookupTablesCreated () { if (!generated) { d2sLookupX = CreateLookupX (source_size.Width, destination_size.Width, scale_factor); d2sLookupY = CreateLookupY (source_size.Height, destination_size.Height, scale_factor); s2dLookupX = CreateS2DLookupX (source_size.Width, destination_size.Width, scale_factor); s2dLookupY = CreateS2DLookupY (source_size.Height, destination_size.Height, scale_factor); generated = true; } } private int[] CreateLookupX (int srcWidth, int dstWidth, ScaleFactor scaleFactor) { var lookup = new int[dstWidth + 1]; for (int x = 0; x < lookup.Length; ++x) { Gdk.Point pt = new Gdk.Point (x, 0); Gdk.Point clientPt = scaleFactor.ScalePoint (pt); // Sometimes the scale factor is slightly different on one axis than // on another, simply due to accuracy. So we have to clamp this value to // be within bounds. lookup[x] = Utility.Clamp (clientPt.X, 0, srcWidth - 1); } return lookup; } private int[] CreateLookupY (int srcHeight, int dstHeight, ScaleFactor scaleFactor) { var lookup = new int[dstHeight + 1]; for (int y = 0; y < lookup.Length; ++y) { Gdk.Point pt = new Gdk.Point (0, y); Gdk.Point clientPt = scaleFactor.ScalePoint (pt); // Sometimes the scale factor is slightly different on one axis than // on another, simply due to accuracy. So we have to clamp this value to // be within bounds. lookup[y] = Utility.Clamp (clientPt.Y, 0, srcHeight - 1); } return lookup; } private int[] CreateS2DLookupX(int srcWidth, int dstWidth, ScaleFactor scaleFactor) { var lookup = new int[srcWidth + 1]; for (int x = 0; x < lookup.Length; ++x) { Gdk.Point pt = new Gdk.Point (x, 0); Gdk.Point clientPt = scaleFactor.UnscalePoint (pt); // Sometimes the scale factor is slightly different on one axis than // on another, simply due to accuracy. So we have to clamp this value to // be within bounds. lookup[x] = Utility.Clamp (clientPt.X, 0, dstWidth - 1); } return lookup; } private int[] CreateS2DLookupY (int srcHeight, int dstHeight, ScaleFactor scaleFactor) { var lookup = new int[srcHeight + 1]; for (int y = 0; y < lookup.Length; ++y) { Gdk.Point pt = new Gdk.Point (0, y); Gdk.Point clientPt = scaleFactor.UnscalePoint (pt); // Sometimes the scale factor is slightly different on one axis than // on another, simply due to accuracy. So we have to clamp this value to // be within bounds. lookup[y] = Utility.Clamp (clientPt.Y, 0, dstHeight - 1); } return lookup; } #endregion } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.UnitTests.LayoutRenderers { using System; using System.Reflection; using System.Threading; using System.IO; using System.Threading.Tasks; using Xunit; public class CallSiteTests : NLogTestBase { #if !SILVERLIGHT [Fact] public void HiddenAssemblyTest() { const string code = @" namespace Foo { public class HiddenAssemblyLogger { public void LogDebug(NLog.Logger logger) { logger.Debug(""msg""); } } } "; var provider = new Microsoft.CSharp.CSharpCodeProvider(); var parameters = new System.CodeDom.Compiler.CompilerParameters(); // reference the NLog dll parameters.ReferencedAssemblies.Add("NLog.dll"); // the assembly should be generated in memory parameters.GenerateInMemory = true; // generate a dll instead of an executable parameters.GenerateExecutable = false; // compile code and generate assembly System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); Assert.False(results.Errors.HasErrors); // create nlog configuration LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); // create logger Logger logger = LogManager.GetLogger("A"); // load HiddenAssemblyLogger type Assembly compiledAssembly = results.CompiledAssembly; Type hiddenAssemblyLoggerType = compiledAssembly.GetType("Foo.HiddenAssemblyLogger"); Assert.NotNull(hiddenAssemblyLoggerType); // load methodinfo MethodInfo logDebugMethod = hiddenAssemblyLoggerType.GetMethod("LogDebug"); Assert.NotNull(logDebugMethod); // instantiate the HiddenAssemblyLogger from previously generated assembly object instance = Activator.CreateInstance(hiddenAssemblyLoggerType); // Add the previously generated assembly to the "blacklist" LogManager.AddHiddenAssembly(compiledAssembly); // call the log method logDebugMethod.Invoke(instance, new object[] { logger }); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } #endif #if !SILVERLIGHT #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void LineNumberTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:filename=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); #if !NET4_5 && !MONO #line 100000 #endif logger.Debug("msg"); var linenumber = GetPrevLineNumber(); string lastMessage = GetDebugLastMessage("debug"); // There's a difference in handling line numbers between .NET and Mono // We're just interested in checking if it's above 100000 Assert.True(lastMessage.IndexOf("callsitetests.cs:" + linenumber, StringComparison.OrdinalIgnoreCase) >= 0, "Invalid line number. Expected prefix of 10000, got: " + lastMessage); #if !NET4_5 && !MONO #line default #endif } #endif [Fact] public void MethodNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + "." + currentMethod.Name + " msg"); } [Fact] public void ClassNameTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName + " msg"); } [Fact] public void ClassNameWithPaddingTestPadLeftAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadLeftAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); var typeName = currentMethod.DeclaringType.FullName; AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadRightAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); AssertDebugLastMessage("debug", currentMethod.DeclaringType.FullName.Substring(0, 3) + " msg"); } [Fact] public void ClassNameWithPaddingTestPadRightAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=false:padding=-3:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); MethodBase currentMethod = MethodBase.GetCurrentMethod(); var typeName = currentMethod.DeclaringType.FullName; AssertDebugLastMessage("debug", typeName.Substring(typeName.Length - 3) + " msg"); } [Fact] public void MethodNameWithPaddingTestPadLeftAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void MethodNameWithPaddingTestPadLeftAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "ftAlignRightTest msg"); } [Fact] public void MethodNameWithPaddingTestPadRightAlignLeftTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=left} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "MethodNameWithPa msg"); } [Fact] public void MethodNameWithPaddingTestPadRightAlignRightTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=false:methodname=true:padding=-16:fixedlength=true:alignmentOnTruncation=right} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "htAlignRightTest msg"); } [Fact] public void GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenSkipFrameNotDefined_WhenLogging_ThenLogFirstUserStackFrame msg"); } [Fact] public void GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:skipframes=1} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); Action action = () => logger.Debug("msg"); action.Invoke(); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.GivenOneSkipFrameDefined_WhenLogging_ShouldSkipOneUserStackFrame msg"); } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void CleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "CleanMethodNamesOfAnonymousDelegatesTest"); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void DontCleanMethodNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.True(lastMessage.StartsWith("<DontCleanMethodNamesOfAnonymousDelegatesTest>")); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void CleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=true}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests"); } } #if MONO [Fact(Skip="Not working under MONO - not sure if unit test is wrong, or the code")] #else [Fact] #endif public void DontCleanClassNamesOfAnonymousDelegatesTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:ClassName=true:MethodName=false:CleanNamesOfAnonymousDelegates=false}' /></targets> <rules> <logger name='*' levels='Fatal' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); bool done = false; ThreadPool.QueueUserWorkItem( state => { logger.Fatal("message"); done = true; }, null); while (done == false) { Thread.Sleep(10); } if (done == true) { string lastMessage = GetDebugLastMessage("debug"); Assert.True(lastMessage.Contains("+<>")); } } [Fact] public void When_Wrapped_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_Wrapped_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); LoggerTests.BaseWrapper wrappedLogger = new LoggerTests.MyWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName)); } #region Compositio unit test [Fact] public void When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.When_WrappedInCompsition_Ignore_Wrapper_Methods_In_Callstack"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); var logger = LogManager.GetLogger("A"); logger.Warn("direct"); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); CompositeWrapper wrappedLogger = new CompositeWrapper(); wrappedLogger.Log("wrapped"); AssertDebugLastMessage("debug", string.Format("{0}|wrapped", currentMethodFullName)); } #if ASYNC_SUPPORTED [Fact] public void Show_correct_method_with_async() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } [Fact] public void Show_correct_method_with_async2() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod2b"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod2a().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod2a() { await AsyncMethod2b(); } private async Task AsyncMethod2b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); } [Fact] public void Show_correct_method_with_async3() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.AsyncMethod3b"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); AsyncMethod3a().Wait(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private async Task AsyncMethod3a() { var reader = new StreamReader(new MemoryStream(new byte[0])); await reader.ReadLineAsync(); AsyncMethod3b(); } private void AsyncMethod3b() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } #endif [Fact] public void Show_correct_method_for_moveNext() { //namespace en name of current method const string currentMethodFullName = "NLog.UnitTests.LayoutRenderers.CallSiteTests.MoveNext"; LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite}|${message}' /></targets> <rules> <logger name='*' levels='Warn' writeTo='debug' /> </rules> </nlog>"); MoveNext(); AssertDebugLastMessage("debug", string.Format("{0}|direct", currentMethodFullName)); } private void MoveNext() { var logger = LogManager.GetCurrentClassLogger(); logger.Warn("direct"); } public class CompositeWrapper { private readonly MyWrapper wrappedLogger; public CompositeWrapper() { wrappedLogger = new MyWrapper(); } public void Log(string what) { wrappedLogger.Log(typeof(CompositeWrapper), what); } } public abstract class BaseWrapper { public void Log(string what) { InternalLog(typeof(BaseWrapper), what); } public void Log(Type type, string what) //overloaded with type for composition { InternalLog(type, what); } protected abstract void InternalLog(Type type, string what); } public class MyWrapper : BaseWrapper { private readonly ILogger wrapperLogger; public MyWrapper() { wrapperLogger = LogManager.GetLogger("WrappedLogger"); } protected override void InternalLog(Type type, string what) //added type for composition { LogEventInfo info = new LogEventInfo(LogLevel.Warn, wrapperLogger.Name, what); // Provide BaseWrapper as wrapper type. // Expected: UserStackFrame should point to the method that calls a // method of BaseWrapper. wrapperLogger.Log(type, info); } } #endregion private class MyLogger : Logger { } [Fact] public void CallsiteBySubclass_interface() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)); Assert.True(logger is MyLogger, "logger isn't MyLogger"); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_interface msg"); } [Fact] public void CallsiteBySubclass_mylogger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); MyLogger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as MyLogger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_mylogger msg"); } [Fact] public void CallsiteBySubclass_logger() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${callsite:classname=true:methodname=true} ${message}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("mylogger", typeof(MyLogger)) as Logger; Assert.NotNull(logger); logger.Debug("msg"); AssertDebugLastMessage("debug", "NLog.UnitTests.LayoutRenderers.CallSiteTests.CallsiteBySubclass_logger msg"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using Microsoft.Test.ModuleCore; using System.IO; namespace CoreXml.Test.XLinq { public partial class FunctionalTests : TestModule { public partial class XNodeBuilderTests : XLinqTestCase { public partial class NamespacehandlingWriterSanity : XLinqTestCase { #region helpers private string SaveXElementUsingXmlWriter(XElement elem, NamespaceHandling nsHandling) { StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = nsHandling, OmitXmlDeclaration = true })) { elem.WriteTo(w); } sw.Dispose(); return sw.ToString(); } #endregion //[Variation(Desc = "1 level down", Priority = 0, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></p:A>" })] //[Variation(Desc = "1 level down II.", Priority = 0, Params = new object[] { "<A><p:B xmlns:p='nsp'><p:C xmlns:p='nsp'/></p:B></A>" })] // start at not root node //[Variation(Desc = "2 levels down", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></p:A>" })] //[Variation(Desc = "2 levels down II.", Priority = 1, Params = new object[] { "<p:A xmlns:p='nsp'><B><C xmlns:p='nsp'/></B></p:A>" })] //[Variation(Desc = "2 levels down III.", Priority = 1, Params = new object[] { "<A xmlns:p='nsp'><B><p:C xmlns:p='nsp'/></B></A>" })] //[Variation(Desc = "Siblings", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'/><C xmlns:p='nsp'/><p:C xmlns:p='nsp'/></A>" })] //[Variation(Desc = "Children", Priority = 2, Params = new object[] { "<A xmlns:p='nsp'><p:B xmlns:p='nsp'><C xmlns:p='nsp'><p:C xmlns:p='nsp'/></C></p:B></A>" })] //[Variation(Desc = "Xml namespace I.", Priority = 3, Params = new object[] { "<A xmlns:xml='http://www.w3.org/XML/1998/namespace'/>" })] //[Variation(Desc = "Xml namespace II.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })] //[Variation(Desc = "Xml namespace III.", Priority = 3, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:xml='http://www.w3.org/XML/1998/namespace' xmlns:p='nsp'><p:C xmlns:p='nsp' xmlns:xml='http://www.w3.org/XML/1998/namespace'/></p:B></p:A>" })] //[Variation(Desc = "Default namespaces", Priority = 1, Params = new object[] { "<A xmlns='nsp'><p:B xmlns:p='nsp'><C xmlns='nsp' /></p:B></A>" })] //[Variation(Desc = "Not used NS declarations", Priority = 2, Params = new object[] { "<A xmlns='nsp' xmlns:u='not-used'><p:B xmlns:p='nsp'><C xmlns:u='not-used' xmlns='nsp' /></p:B></A>" })] //[Variation(Desc = "SameNS, different prefix", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><B xmlns:q='nsp'><p:C xmlns:p='nsp'/></B></p:A>" })] public void testFromTheRootNodeSimple() { string xml = CurrentChild.Params[0] as string; XElement elem = XElement.Parse(xml); // Write using XmlWriter in duplicate namespace decl. removal mode string removedByWriter = SaveXElementUsingXmlWriter(elem, NamespaceHandling.OmitDuplicates); // Remove the namespace decl. duplicates from the Xlinq tree (from a in elem.DescendantsAndSelf().Attributes() where a.IsNamespaceDeclaration && ((a.Name.LocalName == "xml" && (string)a == XNamespace.Xml.NamespaceName) || (from parentDecls in a.Parent.Ancestors().Attributes(a.Name) where parentDecls.IsNamespaceDeclaration && (string)parentDecls == (string)a select parentDecls).Any() ) select a).ToList().Remove(); // Write XElement using XmlWriter without omitting string removedByManual = SaveXElementUsingXmlWriter(elem, NamespaceHandling.Default); ReaderDiff.Compare(removedByWriter, removedByManual); } //[Variation(Desc = "Default ns parent autogenerated", Priority = 1)] public void testFromTheRootNodeTricky() { XElement e = new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute("xmlns", "nsp"))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e, NamespaceHandling.OmitDuplicates), "<A xmlns='nsp'><B/></A>"); } //[Variation(Desc = "Conflicts: NS redefinition", Priority = 2, Params = new object[] { "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D xmlns:p='nsp'/></p:C></p:B></p:A>", // "<p:A xmlns:p='nsp'><p:B xmlns:p='ns-other'><p:C xmlns:p='nsp'><D/></p:C></p:B></p:A>" })] //[Variation(Desc = "Conflicts: NS redefinition, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>", // "<A xmlns='nsp'><B xmlns='ns-other'><C xmlns='nsp'><D/></C></B></A>" })] //[Variation(Desc = "Conflicts: NS redefinition, default NS II.", Priority = 2, Params = new object[] { "<A xmlns=''><B xmlns='ns-other'><C xmlns=''><D xmlns=''/></C></B></A>", // "<A><B xmlns='ns-other'><C xmlns=''><D/></C></B></A>" })] //[Variation(Desc = "Conflicts: NS undeclaration, default NS", Priority = 2, Params = new object[] { "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D xmlns='nsp'/></C></B></A>", // "<A xmlns='nsp'><B xmlns=''><C xmlns='nsp'><D/></C></B></A>" })] public void testConflicts() { XElement e1 = XElement.Parse(CurrentChild.Params[0] as string); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e1, NamespaceHandling.OmitDuplicates), CurrentChild.Params[1] as string); } //[Variation(Desc = "Not from root", Priority = 1)] public void testFromChildNode1() { XElement e = new XElement("root", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute("xmlns", "nsp")))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Element("{nsp}A"), NamespaceHandling.OmitDuplicates), "<p1:A xmlns:p1='nsp'><B xmlns='nsp'/></p1:A>"); } //[Variation(Desc = "Not from root II.", Priority = 1)] public void testFromChildNode2() { XElement e = new XElement("root", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute(XNamespace.Xmlns + "p1", "nsp")))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Element("{nsp}A"), NamespaceHandling.OmitDuplicates), "<p1:A xmlns:p1='nsp'><p1:B/></p1:A>"); } //[Variation(Desc = "Not from root III.", Priority = 2)] public void testFromChildNode3() { XElement e = new XElement("root", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}A", new XElement("{nsp}B", new XAttribute(XNamespace.Xmlns + "p1", "nsp")))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Descendants("{nsp}B").FirstOrDefault(), NamespaceHandling.OmitDuplicates), "<p1:B xmlns:p1='nsp'/>"); } //[Variation(Desc = "Not from root IV.", Priority = 2)] public void testFromChildNode4() { XElement e = new XElement("root", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}A", new XElement("{nsp}B"))); ReaderDiff.Compare(SaveXElementUsingXmlWriter(e.Descendants("{nsp}B").FirstOrDefault(), NamespaceHandling.OmitDuplicates), "<p1:B xmlns:p1='nsp'/>"); } //[Variation(Desc = "Write into used reader I.", Priority = 0, Params = new object[] { "<A xmlns:p1='nsp'/>", "<p1:root xmlns:p1='nsp'><A/></p1:root>" })] //[Variation(Desc = "Write into used reader II.", Priority = 2, Params = new object[] { "<p1:A xmlns:p1='nsp'/>", "<p1:root xmlns:p1='nsp'><p1:A/></p1:root>" })] //[Variation(Desc = "Write into used reader III.", Priority = 2, Params = new object[] { "<p1:A xmlns:p1='nsp'><B xmlns:p1='nsp'/></p1:A>", "<p1:root xmlns:p1='nsp'><p1:A><B/></p1:A></p1:root>" })] public void testIntoOpenedWriter() { XElement e = XElement.Parse(CurrentChild.Params[0] as string); StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true })) { // prepare writer w.WriteStartDocument(); w.WriteStartElement("p1", "root", "nsp"); // write xelement e.WriteTo(w); // close the prep. lines w.WriteEndElement(); w.WriteEndDocument(); } sw.Dispose(); ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[1] as string); } //[Variation(Desc = "Write into used reader I. (def. ns.)", Priority = 0, Params = new object[] { "<A xmlns='nsp'/>", "<root xmlns='nsp'><A/></root>" })] //[Variation(Desc = "Write into used reader II. (def. ns.)", Priority = 2, Params = new object[] { "<A xmlns='ns-other'><B xmlns='nsp'><C xmlns='nsp'/></B></A>", // "<root xmlns='nsp'><A xmlns='ns-other'><B xmlns='nsp'><C/></B></A></root>" })] public void testIntoOpenedWriterDefaultNS() { XElement e = XElement.Parse(CurrentChild.Params[0] as string); StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true })) { // prepare writer w.WriteStartDocument(); w.WriteStartElement("", "root", "nsp"); // write xelement e.WriteTo(w); // close the prep. lines w.WriteEndElement(); w.WriteEndDocument(); } sw.Dispose(); ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[1] as string); } //[Variation(Desc = "Write into used reader (Xlinq lookup + existing hint in the Writer; different prefix)", // Priority = 2, // Params = new object[] { "<p1:root xmlns:p1='nsp'><p2:B xmlns:p2='nsp'/></p1:root>" })] public void testIntoOpenedWriterXlinqLookup1() { XElement e = new XElement("A", new XAttribute(XNamespace.Xmlns + "p2", "nsp"), new XElement("{nsp}B")); StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true })) { // prepare writer w.WriteStartDocument(); w.WriteStartElement("p1", "root", "nsp"); // write xelement e.Element("{nsp}B").WriteTo(w); // close the prep. lines w.WriteEndElement(); w.WriteEndDocument(); } sw.Dispose(); ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[0] as string); } //[Variation(Desc = "Write into used reader (Xlinq lookup + existing hint in the Writer; same prefix)", // Priority = 2, // Params = new object[] { "<p1:root xmlns:p1='nsp'><p1:B /></p1:root>" })] public void testIntoOpenedWriterXlinqLookup2() { XElement e = new XElement("A", new XAttribute(XNamespace.Xmlns + "p1", "nsp"), new XElement("{nsp}B")); StringWriter sw = new StringWriter(); using (XmlWriter w = XmlWriter.Create(sw, new XmlWriterSettings() { NamespaceHandling = NamespaceHandling.OmitDuplicates, OmitXmlDeclaration = true })) { // prepare writer w.WriteStartDocument(); w.WriteStartElement("p1", "root", "nsp"); // write xelement e.Element("{nsp}B").WriteTo(w); // close the prep. lines w.WriteEndElement(); w.WriteEndDocument(); } sw.Dispose(); ReaderDiff.Compare(sw.ToString(), CurrentChild.Params[0] as string); } } } } }
// Knockout.cs // Script#/Libraries/Knockout // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections; using System.Collections.Generic; using System.Html; using System.Runtime.CompilerServices; namespace KnockoutApi { /// <summary> /// Provides Knockout functionality. /// </summary> [Imported] [IgnoreNamespace] [ScriptName("ko")] public static class Knockout { /// <summary> /// Provides access to the currently registered binding handlers. /// </summary> [IntrinsicProperty] public static JsDictionary<string, BindingHandler> BindingHandlers { get { return null; } } /// <summary> /// Gets the mapping plugin which allows converting models to plain /// objects and JSON and vice-versa. /// </summary> [IntrinsicProperty] public static KnockoutMapping Mapping { get { return null; } } /// <summary> /// Gets the current model. /// </summary> /// <returns>The object represented by 'this' within a handler.</returns> [ScriptAlias("this")] [IntrinsicProperty] public static object Model { get { return null; } } /// <summary> /// Sets up bindings using the specified model. /// </summary> /// <param name="model">The model.</param> public static void ApplyBindings(object model) { } /// <summary> /// Sets up bindings within the specified root element using the specified the model. /// </summary> /// <param name="model">The model.</param> /// <param name="rootElement">The element to bind to.</param> public static void ApplyBindings(object model, Element rootElement) { } /// <summary> /// Set up bindings on a single node without binding any of its descendents. /// </summary> /// <param name="node">The node to bind to.</param> /// <param name="bindings">An optional dictionary of bindings, pass null to let Knockout gather them from the element.</param> /// <param name="viewModel">The view model instance.</param> public static void ApplyBindingsToNode(Element node, JsDictionary bindings, object viewModel) { } /// <summary> /// Set up bindings on a single node without binding any of its descendents. /// </summary> /// <param name="rootNode">The root node to bind to.</param> /// <param name="viewModel">The view model instance.</param> public static void ApplyBindingsToDescendants(object viewModel, Element rootNode) { } /// <summary> /// Returns the entire binding context associated with the DOM element /// </summary> /// <param name="node"></param> public static BindingContext<TRoot, TParent, T> ContextFor<TRoot, TParent, T>(Element node) { return null; } /// <summary> /// Returns the data item associated with a particular DOM element /// </summary> /// <param name="node"></param> public static T DataFor<T>(Element node) { return default(T); } /// <summary> /// Creates an observable with a value computed from one or more other values. /// </summary> /// <typeparam name="T">The type of the observable value.</typeparam> /// <param name="function">A function to compute the value.</param> /// <returns>A new dependent observable instance.</returns> [Obsolete("Use Computed instead.")] public static ComputedObservable<T> DependentObservable<T>(Func<T> function) { return null; } /// <summary> /// Creates an observable with a value computed from one or more other values. /// </summary> /// <typeparam name="T">The type of the observable value.</typeparam> /// <param name="options">Options for the dependent observable.</param> [Obsolete("Use Computed instead.")] public static ComputedObservable<T> DependentObservable<T>(ComputedOptions<T> options) { return null; } /// <summary> /// Creates an observable with a value computed from one or more other values. /// </summary> /// <param name="options">Options for the dependent observable.</param> public static void Computed(Action options) { } /// <summary> /// Creates an observable with a value computed from one or more other values. /// </summary> /// <typeparam name="T">The type of the observable value.</typeparam> /// <param name="function">A function to compute the value.</param> /// <returns>A new dependent observable instance.</returns> public static ComputedObservable<T> Computed<T>(Func<T> function) { return null; } /// <summary> /// Creates an observable with a value computed from one or more other values. /// </summary> /// <typeparam name="T">The type of the observable value.</typeparam> /// <param name="options">Options for the dependent observable.</param> public static ComputedObservable<T> Computed<T>(ComputedOptions<T> options) { return null; } /// <summary> /// Returns true if the value is subscribable, false otherwise. /// </summary> /// <param name="value">The value to check.</param> public static bool IsSubscribable(object value) { return false; } /// <summary> /// Returns true if the value is an observable, false otherwise. /// </summary> /// <param name="value">The value to check.</param> public static bool IsObservable(object value) { return false; } /// <summary> /// Returns true if the value is an writable observable, false otherwise. /// </summary> /// <param name="value">The value to check.</param> public static bool IsWriteableObservable(object value) { return false; } /// <summary> /// Creates an subscribable value. /// </summary> /// <typeparam name="T">The type of the subscribable.</typeparam> /// <returns>A new subscribable value instance.</returns> public static Subscribable<T> Subscribable<T>() { return null; } /// <summary> /// Creates an observable value. /// </summary> /// <typeparam name="T">The type of the observable.</typeparam> /// <returns>A new observable value instance.</returns> public static Observable<T> Observable<T>() { return null; } /// <summary> /// Creates an observable with an initial value. /// </summary> /// <typeparam name="T">The type of the observable.</typeparam> /// <param name="initialValue">The initial value.</param> /// <returns>A new observable value instance.</returns> public static Observable<T> Observable<T>(T initialValue) { return null; } /// <summary> /// Creates an empty observable array. /// </summary> /// <returns>A new observable array.</returns> /// <typeparam name="T">The type of items in the array.</typeparam> public static ObservableArray<T> ObservableArray<T>() { return null; } /// <summary> /// Creates an observable array with some initial items. /// </summary> /// <param name="initialItems">A sequence of initial items.</param> /// <returns>A new observable array.</returns> /// <typeparam name="T">The type of items in the array.</typeparam> public static ObservableArray<T> ObservableArray<T>(T[] initialItems) { return null; } /// <summary> /// Creates an observable array with some initial items. /// </summary> /// <param name="initialItems">A sequence of initial items.</param> /// <returns>A new observable array.</returns> /// <typeparam name="T">The type of items in the array.</typeparam> public static ObservableArray<T> ObservableArray<T>(List<T> initialItems) { return null; } /// <summary> /// Creates an observable array with some initial items. /// </summary> /// <param name="initialItems">A sequence of initial items.</param> /// <returns>A new observable array.</returns> /// <typeparam name="T">The type of items in the array.</typeparam> [InlineCode("ko.observableArray({$System.Script}.arrayFromEnumerable({initialItems}))")] public static ObservableArray<T> ObservableArray<T>(IEnumerable<T> initialItems) { return null; } /// <summary> /// Converts a model into the equivalent JSON representation. /// </summary> /// <param name="model">The model object to convert.</param> /// <returns>The JSON string representing the model data.</returns> [ScriptName("toJSON")] public static string ToJson(object model) { return null; } /// <summary> /// Converts a model into the equivalent vanilla script object. /// </summary> /// <param name="model">The model object to convert.</param> /// <returns>The vanilla script object representing the model data.</returns> [ScriptName("toJS")] public static object ToObject(object model) { return null; } /// <summary> /// Converts a model into the equivalent vanilla script object. /// </summary> /// <param name="model">The model object to convert.</param> /// <returns>The vanilla script object representing the model data.</returns> [ScriptName("toJS")] public static T ToObject<T>(object model) { return default(T); } /// <summary> /// If the provided value is an observable, return its value, otherwise just pass it through. /// </summary> /// <param name="value">The value to unwrap.</param> [ScriptAlias("ko.utils.unwrapObservable")] public static T UnwrapObservable<T>(object value) { return default(T); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Cdn { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Use these APIs to manage Azure CDN resources through the Azure Resource /// Manager. You must make sure that requests made to these resources are /// secure. /// </summary> public partial class CdnManagementClient : ServiceClient<CdnManagementClient>, ICdnManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Azure Subscription ID. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Version of the API to be used with the client request. Current version is /// 2017-04-02. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IProfilesOperations. /// </summary> public virtual IProfilesOperations Profiles { get; private set; } /// <summary> /// Gets the IEndpointsOperations. /// </summary> public virtual IEndpointsOperations Endpoints { get; private set; } /// <summary> /// Gets the IOriginsOperations. /// </summary> public virtual IOriginsOperations Origins { get; private set; } /// <summary> /// Gets the ICustomDomainsOperations. /// </summary> public virtual ICustomDomainsOperations CustomDomains { get; private set; } /// <summary> /// Gets the IResourceUsageOperations. /// </summary> public virtual IResourceUsageOperations ResourceUsage { get; private set; } /// <summary> /// Gets the IOperations. /// </summary> public virtual IOperations Operations { get; private set; } /// <summary> /// Gets the IEdgeNodesOperations. /// </summary> public virtual IEdgeNodesOperations EdgeNodes { get; private set; } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected CdnManagementClient(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected CdnManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected CdnManagementClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected CdnManagementClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CdnManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CdnManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CdnManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the CdnManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public CdnManagementClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { Profiles = new ProfilesOperations(this); Endpoints = new EndpointsOperations(this); Origins = new OriginsOperations(this); CustomDomains = new CustomDomainsOperations(this); ResourceUsage = new ResourceUsageOperations(this); Operations = new Operations(this); EdgeNodes = new EdgeNodesOperations(this); BaseUri = new System.Uri("https://management.azure.com"); ApiVersion = "2017-04-02"; AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } /// <summary> /// Check the availability of a resource name. This is needed for resources /// where name is globally unique, such as a CDN endpoint. /// </summary> /// <param name='name'> /// The resource name to validate. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<CheckNameAvailabilityOutput>> CheckNameAvailabilityWithHttpMessagesAsync(string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } if (name == null) { throw new ValidationException(ValidationRules.CannotBeNull, "name"); } CheckNameAvailabilityInput checkNameAvailabilityInput = new CheckNameAvailabilityInput(); if (name != null) { checkNameAvailabilityInput.Name = name; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("checkNameAvailabilityInput", checkNameAvailabilityInput); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckNameAvailability", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Cdn/checkNameAvailability").ToString(); List<string> _queryParameters = new List<string>(); if (ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(checkNameAvailabilityInput != null) { _requestContent = SafeJsonConvert.SerializeObject(checkNameAvailabilityInput, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<CheckNameAvailabilityOutput>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<CheckNameAvailabilityOutput>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Check if the probe path is a valid path and the file can be accessed. Probe /// path is the path to a file hosted on the origin server to help accelerate /// the delivery of dynamic content via the CDN endpoint. This path is relative /// to the origin path specified in the endpoint configuration. /// </summary> /// <param name='probeURL'> /// The probe URL to validate. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ValidateProbeOutput>> ValidateProbeWithHttpMessagesAsync(string probeURL, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId"); } if (ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } if (probeURL == null) { throw new ValidationException(ValidationRules.CannotBeNull, "probeURL"); } ValidateProbeInput validateProbeInput = new ValidateProbeInput(); if (probeURL != null) { validateProbeInput.ProbeURL = probeURL; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("validateProbeInput", validateProbeInput); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ValidateProbe", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateProbe").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId)); List<string> _queryParameters = new List<string>(); if (ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(validateProbeInput != null) { _requestContent = SafeJsonConvert.SerializeObject(validateProbeInput, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ValidateProbeOutput>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ValidateProbeOutput>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class ArgumentValidation { // This type is used to test Socket.Select's argument validation. private sealed class LargeList : IList { private const int MaxSelect = 65536; public int Count { get { return MaxSelect + 1; } } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return true; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return null; } } public object this[int index] { get { return null; } set { } } public int Add(object value) { return -1; } public void Clear() { } public bool Contains(object value) { return false; } public void CopyTo(Array array, int index) { } public IEnumerator GetEnumerator() { return null; } public int IndexOf(object value) { return -1; } public void Insert(int index, object value) { } public void Remove(object value) { } public void RemoveAt(int index) { } } private static readonly byte[] s_buffer = new byte[1]; private static readonly IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private static readonly SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs(); private static readonly Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private static readonly Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); private static void TheAsyncCallback(IAsyncResult ar) { } private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6); return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket; } [Fact] public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => { socket.ExclusiveAddressUse = true; }); } } [Fact] public void SetReceiveBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveBufferSize = -1; }); } [Fact] public void SetSendBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendBufferSize = -1; }); } [Fact] public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveTimeout = int.MinValue; }); } [Fact] public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendTimeout = int.MinValue; }); } [Fact] public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = -1; }); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = 256; }); } [Fact] public void DontFragment_IPv6_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment); } [Fact] public void SetDontFragment_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetworkV6).DontFragment = true; }); } [Fact] public void Bind_Throws_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null)); } [Fact] public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null)); } [Fact] public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1))); } } [Fact] public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1)); } [Fact] public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536)); } [Fact] public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1)); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1)); } [Fact] public void Connect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1)); } [Fact] public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536)); } [Fact] public void Connect_IPAddresses_NullArray_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1)); } [Fact] public void Connect_IPAddresses_EmptyArray_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().Connect(new IPAddress[0], 1)); } [Fact] public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536)); } [Fact] public void Accept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().Accept()); } [Fact] public void Accept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.Accept()); } } [Fact] public void Send_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send((IList<ArraySegment<byte>>)null, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void SendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null)); } [Fact] public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint)); } [Fact] public void SendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint)); } [Fact] public void Receive_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive((IList<ArraySegment<byte>>)null, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void ReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null)); } [Fact] public void SetSocketOption_Linger_NotLingerOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object())); } [Fact] public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); AssertExtensions.Throws<ArgumentException>("optionValue.LingerTime", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); } [Fact] public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object())); AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object())); AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_Object_InvalidOptionName_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("optionValue", () => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object())); } [Fact] public void Select_NullOrEmptyLists_Throws_ArgumentNull() { var emptyList = new List<Socket>(); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1)); } [Fact] public void Select_LargeList_Throws_ArgumentOutOfRange() { var largeList = new LargeList(); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in AcceptAsync that dereferences null SAEA argument")] [Fact] public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null)); } [Fact] public void AcceptAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().AcceptAsync(eventArgs)); } [Fact] public void AcceptAsync_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs)); } [Fact] public void AcceptAsync_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs)); } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveAsync that dereferences null SAEA argument")] [Fact] public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null)); } [Fact] public void ConnectAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => GetSocket().ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs)); } [Fact] public void ConnectAsync_ListeningSocket_Throws_InvalidOperation() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1) }; using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs)); } } [Fact] public void ConnectAsync_AddressFamily_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6) }; Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ConnectAsync that dereferences null SAEA argument")] [Fact] public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null)); } [Fact] public void ConnectAsync_Static_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; AssertExtensions.Throws<ArgumentException>("BufferList", () => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); } [Fact] public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveAsync that dereferences null SAEA argument")] [Fact] public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveFromAsync that dereferences null SAEA argument")] [Fact] public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null)); } [Fact] public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] public void ReceiveFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveMessageFromAsync that dereferences null SAEA argument")] [Fact] public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null)); } [Fact] public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; AssertExtensions.Throws<ArgumentException>("RemoteEndPoint", () => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendAsync that dereferences null SAEA argument")] [Fact] public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")] [Fact] public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA.SendPacketsElements")] [Fact] public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs)); } [Fact] public void SendPacketsAsync_NotConnected_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] }; Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendToAsync that dereferences null SAEA argument")] [Fact] public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null)); } [Fact] public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_DnsEndPoint_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new DnsEndPoint("localhost", 12345))); } } [Fact] public async Task Socket_Connect_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } await accept; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_StringHost_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect("localhost", 12345)); } } [Fact] public async Task Socket_Connect_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] public async Task Socket_Connect_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_MultipleAddresses_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new[] { IPAddress.Loopback }, 12345)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_DnsEndPoint_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new DnsEndPoint("localhost", 12345)); }); } } [Fact] public async Task Socket_ConnectAsync_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port))); } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_StringHost_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync("localhost", 12345); }); } } [Fact] public async Task Socket_ConnectAsync_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Fact] public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void Connect_ConnectTwice_NotSupported(int invalidatingAction) { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // EndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1234); Assert.ThrowsAny<SocketException>(() => client.Connect(ep)); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.Connect(ep)); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void ConnectAsync_ConnectTwice_NotSupported(int invalidatingAction) { AutoResetEvent completed = new AutoResetEvent(false); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 1234); args.Completed += delegate { completed.Set(); }; if (client.ConnectAsync(args)) { Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); } Assert.NotEqual(SocketError.Success, args.SocketError); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.ConnectAsync(args)); } } [Fact] public void BeginAccept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().AcceptAsync(); }); } [Fact] public void BeginAccept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.AcceptAsync(); }); } } [Fact] public void EndAccept_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null)); } [Fact] public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((EndPoint)null); }); } [Fact] public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 1)); }); } } [Fact] public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null)); Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)); }); } [Fact] public void BeginConnect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((string)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync("localhost", port); }); } [Fact] public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync("localhost", 1); }); } } [Fact] public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(IPAddress.Loopback, 65536); }); } [Fact] public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null)); Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync(IPAddress.IPv6Loopback, 1); }); } [Fact] public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress[])null, 1); }); } [Fact] public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("addresses", () => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("addresses", () => { GetSocket().ConnectAsync(new IPAddress[0], 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(new[] { IPAddress.Loopback }, port); }); } [Fact] public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new[] { IPAddress.Loopback }, 1); }); } } [Fact] public void EndConnect_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null)); } [Fact] public void EndConnect_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndConnect(Task.CompletedTask)); } [Fact] public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_EmptyBuffers_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().SendAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndSend_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null)); } [Fact] public void EndSend_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSend(Task.CompletedTask)); } [Fact] public void BeginSendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)); }); } [Fact] public void BeginSendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, null); }); } [Fact] public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void EndSendTo_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null)); } [Fact] public void EndSendto_UnrelatedAsyncResult_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("asyncResult", () => GetSocket().EndSendTo(Task.CompletedTask)); } [Fact] public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync((IList<ArraySegment<byte>>)null, SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument() { AssertExtensions.Throws<ArgumentException>("buffers", () => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("buffers", () => { GetSocket().ReceiveAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndReceive_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint)); } [Fact] public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint remote = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument() { EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); AssertExtensions.Throws<ArgumentException>("remoteEP", () => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); AssertExtensions.Throws<ArgumentException>("remoteEP", () => { GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; AssertExtensions.Throws<ArgumentException>("endPoint", () => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void CancelConnectAsync_NullEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.CancelConnectAsync(null)); } } }
// dnlib: See LICENSE.txt for more info using dnlib.DotNet.MD; namespace dnlib.DotNet.Writer { /// <summary> /// Writes <see cref="MDTable{T}"/>s /// </summary> public static class MDTableWriter { /// <summary> /// Writes a <c>Module</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawModuleRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; var columns3 = columns[3]; var columns4 = columns[4]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.Generation); columns1.Write24(writer, stringsHeap.GetOffset(row.Name)); columns2.Write24(writer, row.Mvid); columns3.Write24(writer, row.EncId); columns4.Write24(writer, row.EncBaseId); } } /// <summary> /// Writes a <c>TypeRef</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawTypeRefRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; var columns2 = columns[2]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.ResolutionScope); columns1.Write24(writer, stringsHeap.GetOffset(row.Name)); columns2.Write24(writer, stringsHeap.GetOffset(row.Namespace)); } } /// <summary> /// Writes a <c>TypeDef</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawTypeDefRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; var columns3 = columns[3]; var columns4 = columns[4]; var columns5 = columns[5]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.Flags); columns1.Write24(writer, stringsHeap.GetOffset(row.Name)); columns2.Write24(writer, stringsHeap.GetOffset(row.Namespace)); columns3.Write24(writer, row.Extends); columns4.Write24(writer, row.FieldList); columns5.Write24(writer, row.MethodList); } } /// <summary> /// Writes a <c>FieldPtr</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawFieldPtrRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Field); } } /// <summary> /// Writes a <c>Field</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawFieldRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.Flags); columns1.Write24(writer, stringsHeap.GetOffset(row.Name)); columns2.Write24(writer, row.Signature); } } /// <summary> /// Writes a <c>MethodPtr</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawMethodPtrRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Method); } } /// <summary> /// Writes a <c>Method</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawMethodRow> table) { var columns = table.TableInfo.Columns; var columns3 = columns[3]; var columns4 = columns[4]; var columns5 = columns[5]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.RVA); writer.WriteUInt16(row.ImplFlags); writer.WriteUInt16(row.Flags); columns3.Write24(writer, stringsHeap.GetOffset(row.Name)); columns4.Write24(writer, row.Signature); columns5.Write24(writer, row.ParamList); } } /// <summary> /// Writes a <c>ParamPtr</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawParamPtrRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Param); } } /// <summary> /// Writes a <c>Param</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawParamRow> table) { var columns = table.TableInfo.Columns; var columns2 = columns[2]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.Flags); writer.WriteUInt16(row.Sequence); columns2.Write24(writer, stringsHeap.GetOffset(row.Name)); } } /// <summary> /// Writes a <c>InterfaceImpl</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawInterfaceImplRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Class); columns1.Write24(writer, row.Interface); } } /// <summary> /// Writes a <c>MemberRef</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawMemberRefRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; var columns2 = columns[2]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Class); columns1.Write24(writer, stringsHeap.GetOffset(row.Name)); columns2.Write24(writer, row.Signature); } } /// <summary> /// Writes a <c>Constant</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawConstantRow> table) { var columns = table.TableInfo.Columns; var columns2 = columns[2]; var columns3 = columns[3]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteByte(row.Type); writer.WriteByte(row.Padding); columns2.Write24(writer, row.Parent); columns3.Write24(writer, row.Value); } } /// <summary> /// Writes a <c>CustomAttribute</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawCustomAttributeRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; var columns2 = columns[2]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Parent); columns1.Write24(writer, row.Type); columns2.Write24(writer, row.Value); } } /// <summary> /// Writes a <c>FieldMarshal</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawFieldMarshalRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Parent); columns1.Write24(writer, row.NativeType); } } /// <summary> /// Writes a <c>DeclSecurity</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawDeclSecurityRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteInt16(row.Action); columns1.Write24(writer, row.Parent); columns2.Write24(writer, row.PermissionSet); } } /// <summary> /// Writes a <c>ClassLayout</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawClassLayoutRow> table) { var columns = table.TableInfo.Columns; var columns2 = columns[2]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.PackingSize); writer.WriteUInt32(row.ClassSize); columns2.Write24(writer, row.Parent); } } /// <summary> /// Writes a <c>FieldLayout</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawFieldLayoutRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.OffSet); columns1.Write24(writer, row.Field); } } /// <summary> /// Writes a <c>StandAloneSig</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawStandAloneSigRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Signature); } } /// <summary> /// Writes a <c>EventMap</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawEventMapRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Parent); columns1.Write24(writer, row.EventList); } } /// <summary> /// Writes a <c>EventPtr</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawEventPtrRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Event); } } /// <summary> /// Writes a <c>Event</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawEventRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.EventFlags); columns1.Write24(writer, stringsHeap.GetOffset(row.Name)); columns2.Write24(writer, row.EventType); } } /// <summary> /// Writes a <c>PropertyMap</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawPropertyMapRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Parent); columns1.Write24(writer, row.PropertyList); } } /// <summary> /// Writes a <c>PropertyPtr</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawPropertyPtrRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Property); } } /// <summary> /// Writes a <c>Property</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawPropertyRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.PropFlags); columns1.Write24(writer, stringsHeap.GetOffset(row.Name)); columns2.Write24(writer, row.Type); } } /// <summary> /// Writes a <c>MethodSemantics</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawMethodSemanticsRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.Semantic); columns1.Write24(writer, row.Method); columns2.Write24(writer, row.Association); } } /// <summary> /// Writes a <c>MethodImpl</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawMethodImplRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; var columns2 = columns[2]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Class); columns1.Write24(writer, row.MethodBody); columns2.Write24(writer, row.MethodDeclaration); } } /// <summary> /// Writes a <c>ModuleRef</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawModuleRefRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, stringsHeap.GetOffset(row.Name)); } } /// <summary> /// Writes a <c>TypeSpec</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawTypeSpecRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Signature); } } /// <summary> /// Writes a <c>ImplMap</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawImplMapRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; var columns3 = columns[3]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.MappingFlags); columns1.Write24(writer, row.MemberForwarded); columns2.Write24(writer, stringsHeap.GetOffset(row.ImportName)); columns3.Write24(writer, row.ImportScope); } } /// <summary> /// Writes a <c>FieldRVA</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawFieldRVARow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.RVA); columns1.Write24(writer, row.Field); } } /// <summary> /// Writes a <c>ENCLog</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawENCLogRow> table) { for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.Token); writer.WriteUInt32(row.FuncCode); } } /// <summary> /// Writes a <c>ENCMap</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawENCMapRow> table) { for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.Token); } } /// <summary> /// Writes a <c>Assembly</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawAssemblyRow> table) { var columns = table.TableInfo.Columns; var columns6 = columns[6]; var columns7 = columns[7]; var columns8 = columns[8]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.HashAlgId); writer.WriteUInt16(row.MajorVersion); writer.WriteUInt16(row.MinorVersion); writer.WriteUInt16(row.BuildNumber); writer.WriteUInt16(row.RevisionNumber); writer.WriteUInt32(row.Flags); columns6.Write24(writer, row.PublicKey); columns7.Write24(writer, stringsHeap.GetOffset(row.Name)); columns8.Write24(writer, stringsHeap.GetOffset(row.Locale)); } } /// <summary> /// Writes a <c>AssemblyProcessor</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawAssemblyProcessorRow> table) { for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.Processor); } } /// <summary> /// Writes a <c>AssemblyOS</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawAssemblyOSRow> table) { for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.OSPlatformId); writer.WriteUInt32(row.OSMajorVersion); writer.WriteUInt32(row.OSMinorVersion); } } /// <summary> /// Writes a <c>AssemblyRef</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawAssemblyRefRow> table) { var columns = table.TableInfo.Columns; var columns5 = columns[5]; var columns6 = columns[6]; var columns7 = columns[7]; var columns8 = columns[8]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.MajorVersion); writer.WriteUInt16(row.MinorVersion); writer.WriteUInt16(row.BuildNumber); writer.WriteUInt16(row.RevisionNumber); writer.WriteUInt32(row.Flags); columns5.Write24(writer, row.PublicKeyOrToken); columns6.Write24(writer, stringsHeap.GetOffset(row.Name)); columns7.Write24(writer, stringsHeap.GetOffset(row.Locale)); columns8.Write24(writer, row.HashValue); } } /// <summary> /// Writes a <c>AssemblyRefProcessor</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawAssemblyRefProcessorRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.Processor); columns1.Write24(writer, row.AssemblyRef); } } /// <summary> /// Writes a <c>AssemblyRefOS</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawAssemblyRefOSRow> table) { var columns = table.TableInfo.Columns; var columns3 = columns[3]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.OSPlatformId); writer.WriteUInt32(row.OSMajorVersion); writer.WriteUInt32(row.OSMinorVersion); columns3.Write24(writer, row.AssemblyRef); } } /// <summary> /// Writes a <c>File</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawFileRow> table) { var columns = table.TableInfo.Columns; var columns1 = columns[1]; var columns2 = columns[2]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.Flags); columns1.Write24(writer, stringsHeap.GetOffset(row.Name)); columns2.Write24(writer, row.HashValue); } } /// <summary> /// Writes a <c>ExportedType</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawExportedTypeRow> table) { var columns = table.TableInfo.Columns; var columns2 = columns[2]; var columns3 = columns[3]; var columns4 = columns[4]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.Flags); writer.WriteUInt32(row.TypeDefId); columns2.Write24(writer, stringsHeap.GetOffset(row.TypeName)); columns3.Write24(writer, stringsHeap.GetOffset(row.TypeNamespace)); columns4.Write24(writer, row.Implementation); } } /// <summary> /// Writes a <c>ManifestResource</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawManifestResourceRow> table) { var columns = table.TableInfo.Columns; var columns2 = columns[2]; var columns3 = columns[3]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt32(row.Offset); writer.WriteUInt32(row.Flags); columns2.Write24(writer, stringsHeap.GetOffset(row.Name)); columns3.Write24(writer, row.Implementation); } } /// <summary> /// Writes a <c>NestedClass</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawNestedClassRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.NestedClass); columns1.Write24(writer, row.EnclosingClass); } } /// <summary> /// Writes a <c>GenericParam</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawGenericParamRow> table) { var columns = table.TableInfo.Columns; var columns2 = columns[2]; var columns3 = columns[3]; var stringsHeap = metadata.StringsHeap; if (columns.Length >= 5) { var columns4 = columns[4]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.Number); writer.WriteUInt16(row.Flags); columns2.Write24(writer, row.Owner); columns3.Write24(writer, stringsHeap.GetOffset(row.Name)); columns4.Write24(writer, row.Kind); } } else { for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.Number); writer.WriteUInt16(row.Flags); columns2.Write24(writer, row.Owner); columns3.Write24(writer, stringsHeap.GetOffset(row.Name)); } } } /// <summary> /// Writes a <c>MethodSpec</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawMethodSpecRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Method); columns1.Write24(writer, row.Instantiation); } } /// <summary> /// Writes a <c>GenericParamConstraint</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawGenericParamConstraintRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Owner); columns1.Write24(writer, row.Constraint); } } /// <summary> /// Writes a <c>Document</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawDocumentRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; var columns2 = columns[2]; var columns3 = columns[3]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Name); columns1.Write24(writer, row.HashAlgorithm); columns2.Write24(writer, row.Hash); columns3.Write24(writer, row.Language); } } /// <summary> /// Writes a <c>MethodDebugInformation</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawMethodDebugInformationRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Document); columns1.Write24(writer, row.SequencePoints); } } /// <summary> /// Writes a <c>LocalScope</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawLocalScopeRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; var columns2 = columns[2]; var columns3 = columns[3]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Method); columns1.Write24(writer, row.ImportScope); columns2.Write24(writer, row.VariableList); columns3.Write24(writer, row.ConstantList); writer.WriteUInt32(row.StartOffset); writer.WriteUInt32(row.Length); } } /// <summary> /// Writes a <c>LocalVariable</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawLocalVariableRow> table) { var columns = table.TableInfo.Columns; var columns2 = columns[2]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; writer.WriteUInt16(row.Attributes); writer.WriteUInt16(row.Index); columns2.Write24(writer, stringsHeap.GetOffset(row.Name)); } } /// <summary> /// Writes a <c>LocalConstant</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawLocalConstantRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; var stringsHeap = metadata.StringsHeap; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, stringsHeap.GetOffset(row.Name)); columns1.Write24(writer, row.Signature); } } /// <summary> /// Writes a <c>ImportScope</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawImportScopeRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Parent); columns1.Write24(writer, row.Imports); } } /// <summary> /// Writes a <c>StateMachineMethod</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawStateMachineMethodRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.MoveNextMethod); columns1.Write24(writer, row.KickoffMethod); } } /// <summary> /// Writes a <c>CustomDebugInformation</c> table /// </summary> /// <param name="writer">Writer</param> /// <param name="metadata">Metadata</param> /// <param name="table">Table</param> public static void Write(this DataWriter writer, Metadata metadata, MDTable<RawCustomDebugInformationRow> table) { var columns = table.TableInfo.Columns; var columns0 = columns[0]; var columns1 = columns[1]; var columns2 = columns[2]; for (int i = 0; i < table.Rows; i++) { var row = table[(uint)i + 1]; columns0.Write24(writer, row.Parent); columns1.Write24(writer, row.Kind); columns2.Write24(writer, row.Value); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.Data; using System.Diagnostics.Contracts; namespace System.Data.Common { // Summary: // Automatically generates single-table commands used to reconcile changes made // to a System.Data.DataSet with the associated database. This is an abstract // class that can only be inherited. public abstract class DbCommandBuilder // : Component { // Summary: // Sets or gets the System.Data.Common.CatalogLocation for an instance of the // System.Data.Common.DbCommandBuilder class. // // Returns: // A System.Data.Common.CatalogLocation object. //[ResCategory("DataCategory_Schema")] //[ResDescription("DbCommandBuilder_CatalogLocation")] //public virtual CatalogLocation CatalogLocation { get; set; } // // Summary: // Sets or gets a string used as the catalog separator for an instance of the // System.Data.Common.DbCommandBuilder class. // // Returns: // A string indicating the catalog separator for use with an instance of the // System.Data.Common.DbCommandBuilder class. //[ResDescription("DbCommandBuilder_CatalogSeparator")] //[ResCategory("DataCategory_Schema")] //[DefaultValue(".")] //public virtual string CatalogSeparator { get; set; } // // Summary: // Specifies which System.Data.ConflictOption is to be used by the System.Data.Common.DbCommandBuilder. // // Returns: // Returns one of the System.Data.ConflictOption values describing the behavior // of this System.Data.Common.DbCommandBuilder. //[ResDescription("DbCommandBuilder_ConflictOption")] //[ResCategory("DataCategory_Update")] //public virtual ConflictOption ConflictOption { get; set; } //// // Summary: // Gets or sets a System.Data.Common.DbDataAdapter object for which Transact-SQL // statements are automatically generated. // // Returns: // A System.Data.Common.DbDataAdapter object. //[Browsable(false)] //[ResDescription("DbCommandBuilder_DataAdapter")] //[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] //public DbDataAdapter DataAdapter { get; set; } // // Summary: // Gets or sets the beginning character or characters to use when specifying // database objects (for example, tables or columns) whose names contain characters // such as spaces or reserved tokens. // // Returns: // The beginning character or characters to use. The default is an empty string. // // Exceptions: // System.InvalidOperationException: // This property cannot be changed after an insert, update, or delete command // has been generated. //[ResCategory("DataCategory_Schema")] //[DefaultValue("")] //[ResDescription("DbCommandBuilder_QuotePrefix")] //public virtual string QuotePrefix { get; set; } // // Summary: // Gets or sets the beginning character or characters to use when specifying // database objects (for example, tables or columns) whose names contain characters // such as spaces or reserved tokens. // // Returns: // The ending character or characters to use. The default is an empty string. //[DefaultValue("")] //[ResCategory("DataCategory_Schema")] //[ResDescription("DbCommandBuilder_QuoteSuffix")] //public virtual string QuoteSuffix { get; set; } // // Summary: // Gets or sets the character to be used for the separator between the schema // identifier and any other identifiers. // // Returns: // The character to be used as the schema separator. //[ResCategory("DataCategory_Schema")] //[DefaultValue(".")] //[ResDescription("DbCommandBuilder_SchemaSeparator")] //public virtual string SchemaSeparator { get; set; } // // Summary: // Specifies whether all column values in an update statement are included or // only changed ones. // // Returns: // true if the UPDATE statement generated by the System.Data.Common.DbCommandBuilder // includes all columns; false if it includes only changed columns. //[ResCategory("DataCategory_Schema")] //[ResDescription("DbCommandBuilder_SetAllValues")] //[DefaultValue(false)] //public bool SetAllValues { get; set; } // Summary: // Allows the provider implementation of the System.Data.Common.DbCommandBuilder // class to handle additional parameter properties. // // Parameters: // parameter: // A System.Data.Common.DbParameter to which the additional modifications are // applied. // // row: // The System.Data.DataRow from the schema table provided by System.Data.Common.DbDataReader.GetSchemaTable(). // // statementType: // The type of command being generated; INSERT, UPDATE or DELETE. // // whereClause: // true if the parameter is part of the update or delete WHERE clause, false // if it is part of the insert or update values. //protected abstract void ApplyParameterInfo(DbParameter parameter, DataRow row, StatementType statementType, bool whereClause); // // Summary: // Gets the automatically generated System.Data.Common.DbCommand object required // to perform deletions at the data source. // // Returns: // The automatically generated System.Data.Common.DbCommand object required // to perform deletions. public DbCommand GetDeleteCommand() { Contract.Ensures(Contract.Result<DbCommand>() != null); return default(DbCommand); } // // Summary: // Gets the automatically generated System.Data.Common.DbCommand object required // to perform deletions at the data source, optionally using columns for parameter // names. // // Parameters: // useColumnsForParameterNames: // If true, generate parameter names matching column names, if possible. If // false, generate @p1, @p2, and so on. // // Returns: // The automatically generated System.Data.Common.DbCommand object required // to perform deletions. public DbCommand GetDeleteCommand(bool useColumnsForParameterNames) { Contract.Ensures(Contract.Result<DbCommand>() != null); return default(DbCommand); } // // Summary: // Gets the automatically generated System.Data.Common.DbCommand object required // to perform insertions at the data source. // // Returns: // The automatically generated System.Data.Common.DbCommand object required // to perform insertions. public DbCommand GetInsertCommand() { Contract.Ensures(Contract.Result<DbCommand>() != null); return default(DbCommand); } // // Summary: // Gets the automatically generated System.Data.Common.DbCommand object required // to perform insertions at the data source, optionally using columns for parameter // names. // // Parameters: // useColumnsForParameterNames: // If true, generate parameter names matching column names, if possible. If // false, generate @p1, @p2, and so on. // // Returns: // The automatically generated System.Data.Common.DbCommand object required // to perform insertions. public DbCommand GetInsertCommand(bool useColumnsForParameterNames) { Contract.Ensures(Contract.Result<DbCommand>() != null); return default(DbCommand); } // // Summary: // Returns the name of the specified parameter in the format of @p#. Use when // building a custom command builder. // // Parameters: // parameterOrdinal: // The number to be included as part of the parameter's name.. // // Returns: // The name of the parameter with the specified number appended as part of the // parameter name. //protected abstract string GetParameterName(int parameterOrdinal); // // Summary: // Returns the full parameter name, given the partial parameter name. // // Parameters: // parameterName: // The partial name of the parameter. // // Returns: // The full parameter name corresponding to the partial parameter name requested. //protected abstract string GetParameterName(string parameterName); // // Summary: // Returns the placeholder for the parameter in the associated SQL statement. // // Parameters: // parameterOrdinal: // The number to be included as part of the parameter's name. // // Returns: // The name of the parameter with the specified number appended. //protected abstract string GetParameterPlaceholder(int parameterOrdinal); // // Summary: // Returns the schema table for the System.Data.Common.DbCommandBuilder. // // Parameters: // sourceCommand: // The System.Data.Common.DbCommand for which to retrieve the corresponding // schema table. // // Returns: // A System.Data.DataTable that represents the schema for the specific System.Data.Common.DbCommand. //protected virtual DataTable GetSchemaTable(DbCommand sourceCommand); // // Summary: // Gets the automatically generated System.Data.Common.DbCommand object required // to perform updates at the data source. // // Returns: // The automatically generated System.Data.Common.DbCommand object required // to perform updates. public DbCommand GetUpdateCommand() { Contract.Ensures(Contract.Result<DbCommand>() != null); return default(DbCommand); } // // Summary: // Gets the automatically generated System.Data.Common.DbCommand object required // to perform updates at the data source, optionally using columns for parameter // names. // // Parameters: // useColumnsForParameterNames: // If true, generate parameter names matching column names, if possible. If // false, generate @p1, @p2, and so on. // // Returns: // The automatically generated System.Data.Common.DbCommand object required // to perform updates. public DbCommand GetUpdateCommand(bool useColumnsForParameterNames) { Contract.Ensures(Contract.Result<DbCommand>() != null); return default(DbCommand); } // // Summary: // Resets the System.Data.Common.DbCommand.CommandTimeout, System.Data.Common.DbCommand.Transaction, // System.Data.Common.DbCommand.CommandType, and System.Data.UpdateRowSource // properties on the System.Data.Common.DbCommand. // // Parameters: // command: // The System.Data.Common.DbCommand to be used by the command builder for the // corresponding insert, update, or delete command. // // Returns: // A System.Data.Common.DbCommand instance to use for each insert, update, or // delete operation. Passing a null value allows the System.Data.Common.DbCommandBuilder.InitializeCommand(System.Data.Common.DbCommand) // method to create a System.Data.Common.DbCommand object based on the Select // command associated with the System.Data.Common.DbCommandBuilder. protected virtual DbCommand InitializeCommand(DbCommand command) { // command can be null Contract.Ensures(Contract.Result<DbCommand>() != null); return default(DbCommand); } // // Summary: // Given an unquoted identifier in the correct catalog case, returns the correct // quoted form of that identifier, including properly escaping any embedded // quotes in the identifier. // // Parameters: // unquotedIdentifier: // The original unquoted identifier. // // Returns: // The quoted version of the identifier. Embedded quotes within the identifier // are properly escaped. //public virtual string QuoteIdentifier(string unquotedIdentifier); // // Summary: // Clears the commands associated with this System.Data.Common.DbCommandBuilder. //public virtual void RefreshSchema(); // // Summary: // Adds an event handler for the System.Data.OleDb.OleDbDataAdapter.RowUpdating // event. // // Parameters: // rowUpdatingEvent: // A System.Data.Common.RowUpdatingEventArgs instance containing information // about the event. //protected void RowUpdatingHandler(RowUpdatingEventArgs rowUpdatingEvent); // // Summary: // Registers the System.Data.Common.DbCommandBuilder to handle the System.Data.OleDb.OleDbDataAdapter.RowUpdating // event for a System.Data.Common.DbDataAdapter. // // Parameters: // adapter: // The System.Data.Common.DbDataAdapter to be used for the update. //protected abstract void SetRowUpdatingHandler(DbDataAdapter adapter); // // Summary: // Given a quoted identifier, returns the correct unquoted form of that identifier, // including properly un-escaping any embedded quotes in the identifier. // // Parameters: // quotedIdentifier: // The identifier that will have its embedded quotes removed. // // Returns: // The unquoted identifier, with embedded quotes properly un-escaped. //public virtual string UnquoteIdentifier(string quotedIdentifier); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("ElementAccessExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal sealed class ElementAccessExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) { return IsTriggerCharacterInternal(ch); } private static bool IsTriggerCharacterInternal(char ch) { return ch == '[' || ch == ','; } public override bool IsRetriggerCharacter(char ch) { return ch == ']'; } private static bool TryGetElementAccessExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { return CompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || IncompleteElementAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace) || ConditionalAccessExpression.TryGetSyntax(root, position, syntaxFacts, triggerReason, cancellationToken, out identifier, out openBrace); } protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); ExpressionSyntax expression; SyntaxToken openBrace; if (!TryGetElementAccessExpression(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out expression, out openBrace)) { return null; } var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).GetAnySymbol(); if (expressionSymbol is INamedTypeSymbol) { // foo?[$$] var namedType = (INamedTypeSymbol)expressionSymbol; if (namedType.ConstructedFrom.SpecialType == SpecialType.System_Nullable_T && expression.IsKind(SyntaxKind.NullableType) && expression.IsChildNode<ArrayTypeSyntax>(a => a.ElementType)) { // Speculatively bind the type part of the nullable as an expression var nullableTypeSyntax = (NullableTypeSyntax)expression; var speculativeBinding = semanticModel.GetSpeculativeSymbolInfo(position, nullableTypeSyntax.ElementType, SpeculativeBindingOption.BindAsExpression); expressionSymbol = speculativeBinding.GetAnySymbol(); expression = nullableTypeSyntax.ElementType; } } if (expressionSymbol != null && expressionSymbol is INamedTypeSymbol) { return null; } ImmutableArray<IPropertySymbol> indexers; ITypeSymbol expressionType; if (!TryGetIndexers(position, semanticModel, expression, cancellationToken, out indexers, out expressionType) && !TryGetComIndexers(semanticModel, expression, cancellationToken, out indexers, out expressionType)) { return null; } var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } var accessibleIndexers = indexers.WhereAsArray( m => m.IsAccessibleWithin(within, throughTypeOpt: expressionType)); if (!accessibleIndexers.Any()) { return null; } var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>(); accessibleIndexers = accessibleIndexers.FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(symbolDisplayService, semanticModel, expression.SpanStart); var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>(); var textSpan = GetTextSpan(expression, openBrace); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); return CreateSignatureHelpItems(accessibleIndexers.Select(p => Convert(p, openBrace, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } private TextSpan GetTextSpan(ExpressionSyntax expression, SyntaxToken openBracket) { if (openBracket.Parent is BracketedArgumentListSyntax) { var conditional = expression.Parent as ConditionalAccessExpressionSyntax; if (conditional != null) { return TextSpan.FromBounds(conditional.Span.Start, openBracket.FullSpan.End); } else { return CompleteElementAccessExpression.GetTextSpan(expression, openBracket); } } else if (openBracket.Parent is ArrayRankSpecifierSyntax) { return IncompleteElementAccessExpression.GetTextSpan(expression, openBracket); } throw ExceptionUtilities.Unreachable; } public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { ExpressionSyntax expression; SyntaxToken openBracket; if (!TryGetElementAccessExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out expression, out openBracket) || currentSpan.Start != expression.SpanStart) { return null; } // If the user is actively typing, it's likely that we're in a broken state and the // syntax tree will be incorrect. Because of this we need to synthesize a new // bracketed argument list so we can correctly map the cursor to the current argument // and then we need to account for this and offset the position check accordingly. int offset; BracketedArgumentListSyntax argumentList; var newBracketedArgumentList = SyntaxFactory.ParseBracketedArgumentList(openBracket.Parent.ToString()); if (expression.Parent is ConditionalAccessExpressionSyntax) { // The typed code looks like: <expression>?[ var conditional = (ConditionalAccessExpressionSyntax)expression.Parent; var elementBinding = SyntaxFactory.ElementBindingExpression(newBracketedArgumentList); var conditionalAccessExpression = SyntaxFactory.ConditionalAccessExpression(expression, elementBinding); offset = expression.SpanStart - conditionalAccessExpression.SpanStart; argumentList = ((ElementBindingExpressionSyntax)conditionalAccessExpression.WhenNotNull).ArgumentList; } else { // The typed code looks like: // <expression>[ // or // <identifier>?[ ElementAccessExpressionSyntax elementAccessExpression = SyntaxFactory.ElementAccessExpression(expression, newBracketedArgumentList); offset = expression.SpanStart - elementAccessExpression.SpanStart; argumentList = elementAccessExpression.ArgumentList; } position -= offset; return SignatureHelpUtilities.GetSignatureHelpState(argumentList, position); } private bool TryGetComIndexers( SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out ImmutableArray<IPropertySymbol> indexers, out ITypeSymbol expressionType) { indexers = semanticModel.GetMemberGroup(expression, cancellationToken) .OfType<IPropertySymbol>() .ToImmutableArray(); if (indexers.Any() && expression is MemberAccessExpressionSyntax) { expressionType = semanticModel.GetTypeInfo(((MemberAccessExpressionSyntax)expression).Expression, cancellationToken).Type; return true; } expressionType = null; return false; } private bool TryGetIndexers( int position, SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken, out ImmutableArray<IPropertySymbol> indexers, out ITypeSymbol expressionType) { expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type; if (expressionType == null) { indexers = ImmutableArray<IPropertySymbol>.Empty; return false; } if (expressionType is IErrorTypeSymbol) { // If `expression` is a QualifiedNameSyntax then GetTypeInfo().Type won't have any CandidateSymbols, so // we should then fall back to getting the actual symbol for the expression. expressionType = (expressionType as IErrorTypeSymbol).CandidateSymbols.FirstOrDefault().GetSymbolType() ?? semanticModel.GetSymbolInfo(expression).GetAnySymbol().GetSymbolType(); } indexers = semanticModel.LookupSymbols(position, expressionType, WellKnownMemberNames.Indexer) .OfType<IPropertySymbol>() .ToImmutableArray(); return true; } private SignatureHelpItem Convert( IPropertySymbol indexer, SyntaxToken openToken, SemanticModel semanticModel, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService, CancellationToken cancellationToken) { var position = openToken.SpanStart; var item = CreateItem(indexer, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService, indexer.IsParams(), indexer.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(indexer, position, semanticModel), GetSeparatorParts(), GetPostambleParts(indexer), indexer.Parameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken)).ToList()); return item; } private IList<SymbolDisplayPart> GetPreambleParts( IPropertySymbol indexer, int position, SemanticModel semanticModel) { var result = new List<SymbolDisplayPart>(); result.AddRange(indexer.Type.ToMinimalDisplayParts(semanticModel, position)); result.Add(Space()); result.AddRange(indexer.ContainingType.ToMinimalDisplayParts(semanticModel, position)); if (indexer.Name != WellKnownMemberNames.Indexer) { result.Add(Punctuation(SyntaxKind.DotToken)); result.Add(new SymbolDisplayPart(SymbolDisplayPartKind.PropertyName, indexer, indexer.Name)); } result.Add(Punctuation(SyntaxKind.OpenBracketToken)); return result; } private IList<SymbolDisplayPart> GetPostambleParts(IPropertySymbol indexer) { return SpecializedCollections.SingletonList( Punctuation(SyntaxKind.CloseBracketToken)); } private static class CompleteElementAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementAccessExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is BracketedArgumentListSyntax && (openBracket.Parent.Parent is ElementAccessExpressionSyntax || openBracket.Parent.Parent is ElementBindingExpressionSyntax)); return SignatureHelpUtilities.GetSignatureHelpSpan((BracketedArgumentListSyntax)openBracket.Parent); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { ElementAccessExpressionSyntax elementAccessExpression; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out elementAccessExpression)) { identifier = elementAccessExpression.Expression; openBrace = elementAccessExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default(SyntaxToken); return false; } } /// Error tolerance case for /// "foo[$$]" or "foo?[$$]" /// which is parsed as an ArrayTypeSyntax variable declaration instead of an ElementAccessExpression private static class IncompleteElementAccessExpression { internal static bool IsArgumentListToken(ArrayTypeSyntax node, SyntaxToken token) { return node.RankSpecifiers.Span.Contains(token.SpanStart) && token != node.RankSpecifiers.First().CloseBracketToken; } internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is ArrayRankSpecifierSyntax; } internal static TextSpan GetTextSpan(SyntaxNode expression, SyntaxToken openBracket) { Contract.ThrowIfFalse(openBracket.Parent is ArrayRankSpecifierSyntax && openBracket.Parent.Parent is ArrayTypeSyntax); return TextSpan.FromBounds(expression.SpanStart, openBracket.Parent.Span.End); } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { ArrayTypeSyntax arrayTypeSyntax; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out arrayTypeSyntax)) { identifier = arrayTypeSyntax.ElementType; openBrace = arrayTypeSyntax.RankSpecifiers.First().OpenBracketToken; return true; } identifier = null; openBrace = default(SyntaxToken); return false; } } /// Error tolerance case for /// "new String()?[$$]" /// which is parsed as a BracketedArgumentListSyntax parented by an ElementBindingExpressionSyntax parented by a ConditionalAccessExpressionSyntax private static class ConditionalAccessExpression { internal static bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacterInternal(token.ValueText[0]) && token.Parent is BracketedArgumentListSyntax && token.Parent.Parent is ElementBindingExpressionSyntax && token.Parent.Parent.Parent is ConditionalAccessExpressionSyntax; } internal static bool IsArgumentListToken(ElementBindingExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseBracketToken; } internal static bool TryGetSyntax(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out ExpressionSyntax identifier, out SyntaxToken openBrace) { ElementBindingExpressionSyntax elementBindingExpression; if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out elementBindingExpression)) { identifier = ((ConditionalAccessExpressionSyntax)elementBindingExpression.Parent).Expression; openBrace = elementBindingExpression.ArgumentList.OpenBracketToken; return true; } identifier = null; openBrace = default(SyntaxToken); return false; } } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using NUnit.Framework; namespace SequelocityDotNet.Tests.SqlServer.DatabaseCommandExtensionsTests { [TestFixture] public class ExecuteReaderTests { [Test] public void Should_Call_The_DataRecordCall_Action_For_Each_Record_In_The_Result_Set() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var list = new List<object>(); // Act Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ) .ExecuteReader( record => { var obj = new { SuperHeroId = record.GetValue( 0 ), SuperHeroName = record.GetValue( 1 ) }; list.Add( obj ); } ); // Assert Assert.That( list.Count == 2 ); } [Test] public void Should_Null_The_DbCommand_By_Default() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ); var list = new List<object>(); // Act databaseCommand.ExecuteReader( record => { var obj = new { SuperHeroId = record.GetValue( 0 ), SuperHeroName = record.GetValue( 1 ) }; list.Add( obj ); } ); // Assert Assert.IsNull( databaseCommand.DbCommand ); } [Test] public void Should_Keep_The_Database_Connection_Open_If_keepConnectionOpen_Parameter_Was_True() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ); var list = new List<object>(); // Act databaseCommand.ExecuteReader( record => { var obj = new { SuperHeroId = record.GetValue( 0 ), SuperHeroName = record.GetValue( 1 ) }; list.Add( obj ); }, true ); // Assert Assert.That( databaseCommand.DbCommand.Connection.State == ConnectionState.Open ); // Cleanup databaseCommand.Dispose(); } [Test] public void Should_Call_The_DatabaseCommandPreExecuteEventHandler() { // Arrange bool wasPreExecuteEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPreExecuteEventHandlers.Add( command => wasPreExecuteEventHandlerCalled = true ); // Act Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( "SELECT 1" ) .ExecuteReader( record => { } ); // Assert Assert.IsTrue( wasPreExecuteEventHandlerCalled ); } [Test] public void Should_Call_The_DatabaseCommandPostExecuteEventHandler() { // Arrange bool wasPostExecuteEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPostExecuteEventHandlers.Add( command => wasPostExecuteEventHandlerCalled = true ); // Act Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( "SELECT 1" ) .ExecuteReader( record => { } ); // Assert Assert.IsTrue( wasPostExecuteEventHandlerCalled ); } [Test] public void Should_Call_The_DatabaseCommandUnhandledExceptionEventHandler() { // Arrange bool wasUnhandledExceptionEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandUnhandledExceptionEventHandlers.Add( ( exception, command ) => { wasUnhandledExceptionEventHandlerCalled = true; } ); // Act TestDelegate action = () => Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( "asdf;lkj" ) .ExecuteReader( record => { } ); // Assert Assert.Throws<System.Data.SqlClient.SqlException>( action ); Assert.IsTrue( wasUnhandledExceptionEventHandlerCalled ); } } [TestFixture] public class ExecuteReader_Of_Type_T_Tests { [Test] public void Should_Call_The_DataRecordCall_Func_For_Each_Record_In_The_Result_Set() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; List<object> list; // Act list = Sequelocity.GetDatabaseCommand(ConnectionStringsNames.SqlServerConnectionString) .SetCommandText(sql) .ExecuteReader<object>(record => new { SuperHeroId = record.GetValue(0), SuperHeroName = record.GetValue(1) }) .ToList(); // Assert Assert.That(list.Count == 2); } [Test] public void Should_Null_The_DbCommand_By_Default() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommand(ConnectionStringsNames.SqlServerConnectionString) .SetCommandText(sql); List<object> list; // Act list = databaseCommand .ExecuteReader<object>(record => new { SuperHeroId = record.GetValue(0), SuperHeroName = record.GetValue(1) }) .ToList(); // Assert Assert.IsNull(databaseCommand.DbCommand); } [Test] public void Should_Keep_The_Database_Connection_Open_If_keepConnectionOpen_Parameter_Was_True() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommand(ConnectionStringsNames.SqlServerConnectionString) .SetCommandText(sql); List<object> list; // Act list = databaseCommand .ExecuteReader<object>(record => new { SuperHeroId = record.GetValue(0), SuperHeroName = record.GetValue(1) }, true) .ToList(); // Assert Assert.That(databaseCommand.DbCommand.Connection.State == ConnectionState.Open); // Cleanup databaseCommand.Dispose(); } [Test] public void Should_Call_The_DatabaseCommandPreExecuteEventHandler() { // Arrange bool wasPreExecuteEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPreExecuteEventHandlers.Add(command => wasPreExecuteEventHandlerCalled = true); // Act Sequelocity.GetDatabaseCommand(ConnectionStringsNames.SqlServerConnectionString) .SetCommandText("SELECT 1") .ExecuteReader<object>(record => new { }) .ToList(); // Assert Assert.IsTrue(wasPreExecuteEventHandlerCalled); } [Test] public void Should_Call_The_DatabaseCommandPostExecuteEventHandler() { // Arrange bool wasPostExecuteEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandPostExecuteEventHandlers.Add(command => wasPostExecuteEventHandlerCalled = true); // Act Sequelocity.GetDatabaseCommand(ConnectionStringsNames.SqlServerConnectionString) .SetCommandText("SELECT 1") .ExecuteReader<object>(record => new { }) .ToList(); // Assert Assert.IsTrue(wasPostExecuteEventHandlerCalled); } [Test] public void Should_Call_The_DatabaseCommandUnhandledExceptionEventHandler() { // Arrange bool wasUnhandledExceptionEventHandlerCalled = false; Sequelocity.ConfigurationSettings.EventHandlers.DatabaseCommandUnhandledExceptionEventHandlers.Add((exception, command) => { wasUnhandledExceptionEventHandlerCalled = true; }); // Act TestDelegate action = () => Sequelocity.GetDatabaseCommand(ConnectionStringsNames.SqlServerConnectionString) .SetCommandText("asdf;lkj") .ExecuteReader<object>(record => new { }) .ToList(); // Assert Assert.Throws<System.Data.SqlClient.SqlException>(action); Assert.IsTrue(wasUnhandledExceptionEventHandlerCalled); } [Test] public void Should_Null_The_DbCommand_If_Iteration_Ends_Before_Full_Enumeration() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ); // Act databaseCommand .ExecuteReader( record => new { SuperHeroId = record.GetValue( 0 ), SuperHeroName = record.GetValue( 1 ) } ) .First(); // Assert Assert.IsNull( databaseCommand.DbCommand ); } [Test] public void Should_Null_The_DbCommand_If_Exception_Occurs_During_Iteration() { // Arrange const string sql = @" CREATE TABLE #SuperHero ( SuperHeroId INT NOT NULL IDENTITY(1,1) PRIMARY KEY, SuperHeroName NVARCHAR(120) NOT NULL ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Superman' ); INSERT INTO #SuperHero ( SuperHeroName ) VALUES ( 'Batman' ); SELECT SuperHeroId, SuperHeroName FROM #SuperHero; "; var databaseCommand = Sequelocity.GetDatabaseCommand( ConnectionStringsNames.SqlServerConnectionString ) .SetCommandText( sql ); var iter = databaseCommand.ExecuteReader( record => new { SuperHeroId = record.GetValue( 0 ), SuperHeroName = record.GetValue( 1 ) } ); // Act try { foreach ( var item in iter ) { throw new Exception( "Exception occured during iteration." ); } } catch { } // Assert Assert.IsNull( databaseCommand.DbCommand ); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="LabelServiceClient"/> instances.</summary> public sealed partial class LabelServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="LabelServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="LabelServiceSettings"/>.</returns> public static LabelServiceSettings GetDefault() => new LabelServiceSettings(); /// <summary>Constructs a new <see cref="LabelServiceSettings"/> object with default settings.</summary> public LabelServiceSettings() { } private LabelServiceSettings(LabelServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetLabelSettings = existing.GetLabelSettings; MutateLabelsSettings = existing.MutateLabelsSettings; OnCopy(existing); } partial void OnCopy(LabelServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to <c>LabelServiceClient.GetLabel</c> /// and <c>LabelServiceClient.GetLabelAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetLabelSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>LabelServiceClient.MutateLabels</c> and <c>LabelServiceClient.MutateLabelsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateLabelsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="LabelServiceSettings"/> object.</returns> public LabelServiceSettings Clone() => new LabelServiceSettings(this); } /// <summary> /// Builder class for <see cref="LabelServiceClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> internal sealed partial class LabelServiceClientBuilder : gaxgrpc::ClientBuilderBase<LabelServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public LabelServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public LabelServiceClientBuilder() { UseJwtAccessWithScopes = LabelServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref LabelServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<LabelServiceClient> task); /// <summary>Builds the resulting client.</summary> public override LabelServiceClient Build() { LabelServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<LabelServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<LabelServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private LabelServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return LabelServiceClient.Create(callInvoker, Settings); } private async stt::Task<LabelServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return LabelServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => LabelServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => LabelServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => LabelServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>LabelService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage labels. /// </remarks> public abstract partial class LabelServiceClient { /// <summary> /// The default endpoint for the LabelService service, which is a host of "googleads.googleapis.com" and a port /// of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default LabelService scopes.</summary> /// <remarks> /// The default LabelService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="LabelServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="LabelServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="LabelServiceClient"/>.</returns> public static stt::Task<LabelServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new LabelServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="LabelServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="LabelServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="LabelServiceClient"/>.</returns> public static LabelServiceClient Create() => new LabelServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="LabelServiceClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="LabelServiceSettings"/>.</param> /// <returns>The created <see cref="LabelServiceClient"/>.</returns> internal static LabelServiceClient Create(grpccore::CallInvoker callInvoker, LabelServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } LabelService.LabelServiceClient grpcClient = new LabelService.LabelServiceClient(callInvoker); return new LabelServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC LabelService client</summary> public virtual LabelService.LabelServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::Label GetLabel(GetLabelRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Label> GetLabelAsync(GetLabelRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Label> GetLabelAsync(GetLabelRequest request, st::CancellationToken cancellationToken) => GetLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the label to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::Label GetLabel(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetLabel(new GetLabelRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the label to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Label> GetLabelAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetLabelAsync(new GetLabelRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the label to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Label> GetLabelAsync(string resourceName, st::CancellationToken cancellationToken) => GetLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the label to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::Label GetLabel(gagvr::LabelName resourceName, gaxgrpc::CallSettings callSettings = null) => GetLabel(new GetLabelRequest { ResourceNameAsLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the label to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Label> GetLabelAsync(gagvr::LabelName resourceName, gaxgrpc::CallSettings callSettings = null) => GetLabelAsync(new GetLabelRequest { ResourceNameAsLabelName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the label to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::Label> GetLabelAsync(gagvr::LabelName resourceName, st::CancellationToken cancellationToken) => GetLabelAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes labels. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateLabelsResponse MutateLabels(MutateLabelsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes labels. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateLabelsResponse> MutateLabelsAsync(MutateLabelsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates, updates, or removes labels. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateLabelsResponse> MutateLabelsAsync(MutateLabelsRequest request, st::CancellationToken cancellationToken) => MutateLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates, updates, or removes labels. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on labels. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateLabelsResponse MutateLabels(string customerId, scg::IEnumerable<LabelOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateLabels(new MutateLabelsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes labels. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on labels. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateLabelsResponse> MutateLabelsAsync(string customerId, scg::IEnumerable<LabelOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateLabelsAsync(new MutateLabelsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates, updates, or removes labels. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. ID of the customer whose labels are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on labels. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateLabelsResponse> MutateLabelsAsync(string customerId, scg::IEnumerable<LabelOperation> operations, st::CancellationToken cancellationToken) => MutateLabelsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>LabelService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage labels. /// </remarks> public sealed partial class LabelServiceClientImpl : LabelServiceClient { private readonly gaxgrpc::ApiCall<GetLabelRequest, gagvr::Label> _callGetLabel; private readonly gaxgrpc::ApiCall<MutateLabelsRequest, MutateLabelsResponse> _callMutateLabels; /// <summary> /// Constructs a client wrapper for the LabelService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="LabelServiceSettings"/> used within this client.</param> public LabelServiceClientImpl(LabelService.LabelServiceClient grpcClient, LabelServiceSettings settings) { GrpcClient = grpcClient; LabelServiceSettings effectiveSettings = settings ?? LabelServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetLabel = clientHelper.BuildApiCall<GetLabelRequest, gagvr::Label>(grpcClient.GetLabelAsync, grpcClient.GetLabel, effectiveSettings.GetLabelSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetLabel); Modify_GetLabelApiCall(ref _callGetLabel); _callMutateLabels = clientHelper.BuildApiCall<MutateLabelsRequest, MutateLabelsResponse>(grpcClient.MutateLabelsAsync, grpcClient.MutateLabels, effectiveSettings.MutateLabelsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateLabels); Modify_MutateLabelsApiCall(ref _callMutateLabels); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetLabelApiCall(ref gaxgrpc::ApiCall<GetLabelRequest, gagvr::Label> call); partial void Modify_MutateLabelsApiCall(ref gaxgrpc::ApiCall<MutateLabelsRequest, MutateLabelsResponse> call); partial void OnConstruction(LabelService.LabelServiceClient grpcClient, LabelServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC LabelService client</summary> public override LabelService.LabelServiceClient GrpcClient { get; } partial void Modify_GetLabelRequest(ref GetLabelRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateLabelsRequest(ref MutateLabelsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::Label GetLabel(GetLabelRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetLabelRequest(ref request, ref callSettings); return _callGetLabel.Sync(request, callSettings); } /// <summary> /// Returns the requested label in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::Label> GetLabelAsync(GetLabelRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetLabelRequest(ref request, ref callSettings); return _callGetLabel.Async(request, callSettings); } /// <summary> /// Creates, updates, or removes labels. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateLabelsResponse MutateLabels(MutateLabelsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateLabelsRequest(ref request, ref callSettings); return _callMutateLabels.Sync(request, callSettings); } /// <summary> /// Creates, updates, or removes labels. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [DatabaseError]() /// [DateError]() /// [DistinctError]() /// [FieldError]() /// [FieldMaskError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [LabelError]() /// [MutateError]() /// [NewResourceCreationError]() /// [NotEmptyError]() /// [NullError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [ResourceCountLimitExceededError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateLabelsResponse> MutateLabelsAsync(MutateLabelsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateLabelsRequest(ref request, ref callSettings); return _callMutateLabels.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using gView.Framework.Geometry; using gView.Framework.Data; using gView.Framework.UI.Controls; using gView.Framework.FDB; namespace gView.Framework.UI.Dialogs { public partial class FormNewFeatureclass : Form { //private List<IField> _fields = new List<IField>(); public FormNewFeatureclass(IFeatureClass fc) { InitializeComponent(); tabControl1.TabPages.Remove(tabGeometry); if (fc == null) return; foreach (FieldType fieldType in Enum.GetValues(typeof(FieldType))) { if (fieldType == FieldType.unknown || fieldType == FieldType.ID || fieldType == FieldType.Shape) continue; colFieldtype.Items.Add(fieldType); } this.Fields = fc.Fields; tabControl1.Invalidate(); this.IndexTypeIsEditable = false; if (fc.Dataset is IFDBDataset) this.SpatialIndexDef = ((IFDBDataset)fc.Dataset).SpatialIndexDef; } public FormNewFeatureclass(IFeatureDataset dataset) { InitializeComponent(); if (dataset == null) return; cmbGeometry.SelectedIndex = 0; spatialIndexControl.SpatialReference = dataset.SpatialReference; foreach (FieldType fieldType in Enum.GetValues(typeof(FieldType))) { if (fieldType == FieldType.unknown || fieldType == FieldType.ID || fieldType == FieldType.Shape) continue; colFieldtype.Items.Add(fieldType); } tabControl1.Invalidate(); this.IndexTypeIsEditable = false; if (dataset is IFDBDataset) this.SpatialIndexDef = ((IFDBDataset)dataset).SpatialIndexDef; } #region Properties public string FeatureclassName { get { return txtFCName.Text; } set { txtFCName.Text = value; } } public IGeometryDef GeometryDef { get { geometryType gType = geometryType.Unknown; switch (cmbGeometry.SelectedIndex) { case 0: gType = geometryType.Point; break; case 1: gType = geometryType.Polyline; break; case 2: gType = geometryType.Polygon; break; } GeometryDef geomDef = new GeometryDef(gType, null, chkHasZ.Checked); return geomDef; } } public IEnvelope SpatialIndexExtents { get { return spatialIndexControl.Extent; } set { spatialIndexControl.Extent = value; } } public int SpatialIndexLevels { get { return spatialIndexControl.Levels; } set { spatialIndexControl.Levels = value; } } public MSSpatialIndex MSSpatialIndexDef { get { return spatialIndexControl.MSIndex; } set { spatialIndexControl.MSIndex = value; } } public IFields Fields { get { Fields fields = new Fields(); foreach (DataRow row in dsFields.Tables[0].Rows) { if (row["FieldField"] is IField) fields.Add(row["FieldField"] as IField); } return fields; } set { if (value == null) return; foreach (IField field in value.ToEnumerable()) { if (field.type == FieldType.ID || field.type == FieldType.Shape) continue; Field f = new Field(field); DataRow row = dsFields.Tables[0].NewRow(); row["FieldName"] = f.name; row["FieldType"] = f.type; row["FieldField"] = f; dsFields.Tables[0].Rows.Add(row); } } } public ISpatialIndexDef SpatialIndexDef { get { return spatialIndexControl.SpatialIndexDef; } set { spatialIndexControl.SpatialIndexDef = value; } } public bool IndexTypeIsEditable { get { return spatialIndexControl.IndexTypeIsEditable; } set { spatialIndexControl.IndexTypeIsEditable = value; } } #endregion private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e) { //if (e.ColumnIndex == 1) // dataGridView1[e.ColumnIndex, e.RowIndex].Value = FieldType.String; } private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { SetFieldProperties(e.RowIndex); } private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e) { SetFieldProperties(e.RowIndex); } private void SetFieldProperties(int index) { if (index >= dsFields.Tables[0].Rows.Count) return; DataRow row = dsFields.Tables[0].Rows[index]; if (row["FieldField"] == null || row["FieldField"] == DBNull.Value) row["FieldField"] = new Field(); ((Field)row["FieldField"]).name = (string)dataGridView1[0, index].Value; ((Field)row["FieldField"]).type = (FieldType)dataGridView1[1, index].Value; if (((Field)row["FieldField"]).type == FieldType.String && ((Field)row["FieldField"]).size <= 0) ((Field)row["FieldField"]).size = 100; pgField.SelectedObject = ((Field)row["FieldField"]).type == FieldType.String ? new StringFieldPropertyObject((Field)row["FieldField"]) : new FieldPropertyObject((Field)row["FieldField"]); } private void FormNewFeatureclass_Shown(object sender, EventArgs e) { txtFCName.Text = "NewFeatureclass"; txtFCName.Focus(); txtFCName.Select(0, txtFCName.Text.Length); } } internal class FieldPropertyObject { protected Field _field; public FieldPropertyObject(Field field) { _field = field; } public string Aliasname { get { return _field.aliasname; } set { _field.aliasname = value; } } } internal class StringFieldPropertyObject : FieldPropertyObject { public StringFieldPropertyObject(Field field) : base(field) { } public int Size { get { return _field.size; } set { _field.size = value; } } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.SS.UserModel; using NPOI.XSSF.Model; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.Util; using System; using NPOI.SS.Formula.PTG; using NPOI.SS.Formula; using NPOI.SS; using NPOI.Util; using NPOI.SS.Formula.Eval; using System.Globalization; namespace NPOI.XSSF.UserModel { /** * High level representation of a cell in a row of a spreadsheet. * <p> * Cells can be numeric, formula-based or string-based (text). The cell type * specifies this. String cells cannot conatin numbers and numeric cells cannot * contain strings (at least according to our model). Client apps should do the * conversions themselves. Formula cells have the formula string, as well as * the formula result, which can be numeric or string. * </p> * <p> * Cells should have their number (0 based) before being Added to a row. Only * cells that have values should be Added. * </p> */ public class XSSFCell : ICell { private static String FALSE_AS_STRING = "0"; private static String TRUE_AS_STRING = "1"; /** * the xml bean Containing information about the cell's location, value, * data type, formatting, and formula */ private CT_Cell _cell; /** * the XSSFRow this cell belongs to */ private XSSFRow _row; /** * 0-based column index */ private int _cellNum; /** * Table of strings shared across this workbook. * If two cells contain the same string, then the cell value is the same index into SharedStringsTable */ private SharedStringsTable _sharedStringSource; /** * Table of cell styles shared across all cells in a workbook. */ private StylesTable _stylesSource; /** * Construct a XSSFCell. * * @param row the parent row. * @param cell the xml bean Containing information about the cell. */ public XSSFCell(XSSFRow row, CT_Cell cell) { _cell = cell; _row = row; if (cell.r != null) { _cellNum = new CellReference(cell.r).Col; } else { int prevNum = row.LastCellNum; if (prevNum != -1) { _cellNum = row.GetCell(prevNum - 1).ColumnIndex + 1; } } _sharedStringSource = ((XSSFWorkbook)row.Sheet.Workbook).GetSharedStringSource(); _stylesSource = ((XSSFWorkbook)row.Sheet.Workbook).GetStylesSource(); } /** * @return table of strings shared across this workbook */ protected SharedStringsTable GetSharedStringSource() { return _sharedStringSource; } /** * @return table of cell styles shared across this workbook */ protected StylesTable GetStylesSource() { return _stylesSource; } /** * Returns the sheet this cell belongs to * * @return the sheet this cell belongs to */ public ISheet Sheet { get { return _row.Sheet; } } /** * Returns the row this cell belongs to * * @return the row this cell belongs to */ public IRow Row { get { return _row; } } /** * Get the value of the cell as a bool. * <p> * For strings, numbers, and errors, we throw an exception. For blank cells we return a false. * </p> * @return the value of the cell as a bool * @throws InvalidOperationException if the cell type returned by {@link #CellType} * is not CellType.Boolean, CellType.Blank or CellType.Formula */ public bool BooleanCellValue { get { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return false; case CellType.Boolean: return _cell.IsSetV() && TRUE_AS_STRING.Equals(_cell.v); case CellType.Formula: //YK: should throw an exception if requesting bool value from a non-bool formula return _cell.IsSetV() && TRUE_AS_STRING.Equals(_cell.v); default: throw TypeMismatch(CellType.Boolean, cellType, false); } } } /** * Set a bool value for the cell * * @param value the bool value to Set this cell to. For formulas we'll Set the * precalculated value, for bools we'll Set its value. For other types we * will change the cell to a bool cell and Set its value. */ public void SetCellValue(bool value) { _cell.t = (ST_CellType.b); _cell.v = (value ? TRUE_AS_STRING : FALSE_AS_STRING); } /** * Get the value of the cell as a number. * <p> * For strings we throw an exception. For blank cells we return a 0. * For formulas or error cells we return the precalculated value; * </p> * @return the value of the cell as a number * @throws InvalidOperationException if the cell type returned by {@link #CellType} is CellType.String * @exception NumberFormatException if the cell value isn't a parsable <code>double</code>. * @see DataFormatter for turning this number into a string similar to that which Excel would render this number as. */ public double NumericCellValue { get { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return 0.0; case CellType.Formula: case CellType.Numeric: if (_cell.IsSetV()) { try { return Double.Parse(_cell.v, CultureInfo.InvariantCulture); } catch (FormatException) { throw TypeMismatch(CellType.Numeric, CellType.String, false); } } else { return 0.0; } default: throw TypeMismatch(CellType.Numeric, cellType, false); } } } /** * Set a numeric value for the cell * * @param value the numeric value to Set this cell to. For formulas we'll Set the * precalculated value, for numerics we'll Set its value. For other types we * will change the cell to a numeric cell and Set its value. */ public void SetCellValue(double value) { if (Double.IsInfinity(value)) { // Excel does not support positive/negative infInities, // rather, it gives a #DIV/0! error in these cases. _cell.t = (ST_CellType.e); _cell.v = (FormulaError.DIV0.String); } else if (Double.IsNaN(value)) { // Excel does not support Not-a-Number (NaN), // instead it immediately generates an #NUM! error. _cell.t = (ST_CellType.e); _cell.v = (FormulaError.NUM.String); } else { _cell.t = (ST_CellType.n); _cell.v = (value.ToString(CultureInfo.InvariantCulture)); } } /** * Get the value of the cell as a string * <p> * For numeric cells we throw an exception. For blank cells we return an empty string. * For formulaCells that are not string Formulas, we throw an exception * </p> * @return the value of the cell as a string */ public String StringCellValue { get { IRichTextString str = this.RichStringCellValue; return str == null ? null : str.String; } } /** * Get the value of the cell as a XSSFRichTextString * <p> * For numeric cells we throw an exception. For blank cells we return an empty string. * For formula cells we return the pre-calculated value if a string, otherwise an exception * </p> * @return the value of the cell as a XSSFRichTextString */ public IRichTextString RichStringCellValue { get { CellType cellType = CellType; XSSFRichTextString rt; switch (cellType) { case CellType.Blank: rt = new XSSFRichTextString(""); break; case CellType.String: if (_cell.t == ST_CellType.inlineStr) { if (_cell.IsSetIs()) { //string is expressed directly in the cell defInition instead of implementing the shared string table. rt = new XSSFRichTextString(_cell.@is); } else if (_cell.IsSetV()) { //cached result of a formula rt = new XSSFRichTextString(_cell.v); } else { rt = new XSSFRichTextString(""); } } else if (_cell.t == ST_CellType.str) { //cached formula value rt = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : ""); } else { if (_cell.IsSetV()) { int idx = Int32.Parse(_cell.v); rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(idx)); } else { rt = new XSSFRichTextString(""); } } break; case CellType.Formula: CheckFormulaCachedValueType(CellType.String, GetBaseCellType(false)); rt = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : ""); break; default: throw TypeMismatch(CellType.String, cellType, false); } rt.SetStylesTableReference(_stylesSource); return rt; } } private static void CheckFormulaCachedValueType(CellType expectedTypeCode, CellType cachedValueType) { if (cachedValueType != expectedTypeCode) { throw TypeMismatch(expectedTypeCode, cachedValueType, true); } } /** * Set a string value for the cell. * * @param str value to Set the cell to. For formulas we'll Set the formula * cached string result, for String cells we'll Set its value. For other types we will * change the cell to a string cell and Set its value. * If value is null then we will change the cell to a Blank cell. */ public void SetCellValue(String str) { SetCellValue(str == null ? null : new XSSFRichTextString(str)); } /** * Set a string value for the cell. * * @param str value to Set the cell to. For formulas we'll Set the 'pre-Evaluated result string, * for String cells we'll Set its value. For other types we will * change the cell to a string cell and Set its value. * If value is null then we will change the cell to a Blank cell. */ public void SetCellValue(IRichTextString str) { if (str == null || string.IsNullOrEmpty(str.String)) { SetCellType(CellType.Blank); return; } CellType cellType = CellType; switch (cellType) { case CellType.Formula: _cell.v = (str.String); _cell.t= (ST_CellType.str); break; default: if (_cell.t == ST_CellType.inlineStr) { //set the 'pre-Evaluated result _cell.v = str.String; } else { _cell.t = ST_CellType.s; XSSFRichTextString rt = (XSSFRichTextString)str; rt.SetStylesTableReference(_stylesSource); int sRef = _sharedStringSource.AddEntry(rt.GetCTRst()); _cell.v=sRef.ToString(); } break; } } /// <summary> /// Return a formula for the cell, for example, <code>SUM(C4:E4)</code> /// </summary> public String CellFormula { get { CellType cellType = CellType; if (cellType != CellType.Formula) throw TypeMismatch(CellType.Formula, cellType, false); CT_CellFormula f = _cell.f; if (IsPartOfArrayFormulaGroup && f == null) { ICell cell = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this); return cell.CellFormula; } if (f.t == ST_CellFormulaType.shared) { return ConvertSharedFormula((int)f.si); } return f.Value; } set { SetCellFormula(value); } } /// <summary> /// Creates a non shared formula from the shared formula counterpart /// </summary> /// <param name="si">Shared Group Index</param> /// <returns>non shared formula created for the given shared formula and this cell</returns> private String ConvertSharedFormula(int si) { XSSFSheet sheet = (XSSFSheet)Sheet; CT_CellFormula f = sheet.GetSharedFormula(si); if (f == null) throw new InvalidOperationException( "Master cell of a shared formula with sid=" + si + " was not found"); String sharedFormula = f.Value; //Range of cells which the shared formula applies to String sharedFormulaRange = f.@ref; CellRangeAddress ref1 = CellRangeAddress.ValueOf(sharedFormulaRange); int sheetIndex = sheet.Workbook.GetSheetIndex(sheet); XSSFEvaluationWorkbook fpb = XSSFEvaluationWorkbook.Create(sheet.Workbook); SharedFormula sf = new SharedFormula(SpreadsheetVersion.EXCEL2007); Ptg[] ptgs = FormulaParser.Parse(sharedFormula, fpb, FormulaType.Cell, sheetIndex); Ptg[] fmla = sf.ConvertSharedFormulas(ptgs, RowIndex - ref1.FirstRow, ColumnIndex - ref1.FirstColumn); return FormulaRenderer.ToFormulaString(fpb, fmla); } /** * Sets formula for this cell. * <p> * Note, this method only Sets the formula string and does not calculate the formula value. * To Set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)} * </p> * * @param formula the formula to Set, e.g. <code>"SUM(C4:E4)"</code>. * If the argument is <code>null</code> then the current formula is Removed. * @throws NPOI.ss.formula.FormulaParseException if the formula has incorrect syntax or is otherwise invalid * @throws InvalidOperationException if the operation is not allowed, for example, * when the cell is a part of a multi-cell array formula */ public void SetCellFormula(String formula) { if (IsPartOfArrayFormulaGroup) { NotifyArrayFormulaChanging(); } SetFormula(formula, FormulaType.Cell); } internal void SetCellArrayFormula(String formula, CellRangeAddress range) { SetFormula(formula, FormulaType.Array); CT_CellFormula cellFormula = _cell.f; cellFormula.t = (ST_CellFormulaType.array); cellFormula.@ref = (range.FormatAsString()); } private void SetFormula(String formula, FormulaType formulaType) { IWorkbook wb = _row.Sheet.Workbook; if (formula == null) { ((XSSFWorkbook)wb).OnDeleteFormula(this); if (_cell.IsSetF()) _cell.unsetF(); return; } IFormulaParsingWorkbook fpb = XSSFEvaluationWorkbook.Create(wb); //validate through the FormulaParser FormulaParser.Parse(formula, fpb, formulaType, wb.GetSheetIndex(this.Sheet)); CT_CellFormula f = new CT_CellFormula(); f.Value = formula; _cell.f= (f); if (_cell.IsSetV()) _cell.unsetV(); } /// <summary> /// Returns zero-based column index of this cell /// </summary> public int ColumnIndex { get { return this._cellNum; } } /// <summary> /// Returns zero-based row index of a row in the sheet that contains this cell /// </summary> public int RowIndex { get { return _row.RowNum; } } /// <summary> /// Returns an A1 style reference to the location of this cell /// </summary> /// <returns>A1 style reference to the location of this cell</returns> public String GetReference() { String ref1 = _cell.r; if (ref1 == null) { return new CellReference(this).FormatAsString(); } return ref1; } /// <summary> /// Return the cell's style. /// </summary> public ICellStyle CellStyle { get { XSSFCellStyle style = null; if ((null != _stylesSource) && (_stylesSource.NumCellStyles > 0)) { long idx = _cell.IsSetS() ? _cell.s : 0; style = _stylesSource.GetStyleAt((int)idx); } return style; } set { if (value == null) { if (_cell.IsSetS()) _cell.unsetS(); } else { XSSFCellStyle xStyle = (XSSFCellStyle)value; xStyle.VerifyBelongsToStylesSource(_stylesSource); long idx = _stylesSource.PutStyle(xStyle); _cell.s = (uint)idx; } } } /// <summary> /// Return the cell type. /// </summary> public CellType CellType { get { if (_cell.f != null || ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this)) { return CellType.Formula; } return GetBaseCellType(true); } } /// <summary> /// Only valid for formula cells /// </summary> public CellType CachedFormulaResultType { get { if (_cell.f == null) { throw new InvalidOperationException("Only formula cells have cached results"); } return GetBaseCellType(false); } } /// <summary> /// Detect cell type based on the "t" attribute of the CT_Cell bean /// </summary> /// <param name="blankCells"></param> /// <returns></returns> private CellType GetBaseCellType(bool blankCells) { switch (_cell.t) { case ST_CellType.b: return CellType.Boolean; case ST_CellType.n: if (!_cell.IsSetV() && blankCells) { // ooxml does have a separate cell type of 'blank'. A blank cell Gets encoded as // (either not present or) a numeric cell with no value Set. // The formula Evaluator (and perhaps other clients of this interface) needs to // distinguish blank values which sometimes Get translated into zero and sometimes // empty string, depending on context return CellType.Blank; } return CellType.Numeric; case ST_CellType.e: return CellType.Error; case ST_CellType.s: // String is in shared strings case ST_CellType.inlineStr: // String is inline in cell case ST_CellType.str: return CellType.String; default: throw new InvalidOperationException("Illegal cell type: " + this._cell.t); } } /// <summary> /// Get the value of the cell as a date. /// </summary> public DateTime DateCellValue { get { CellType cellType = CellType; if (cellType == CellType.Blank) { return DateTime.MinValue; } double value = NumericCellValue; bool date1904 = ((XSSFWorkbook)Sheet.Workbook).IsDate1904(); return DateUtil.GetJavaDate(value, date1904); } } /// <summary> /// Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as a date. /// </summary> /// <param name="value">the date value to Set this cell to. For formulas we'll set the precalculated value, /// for numerics we'll Set its value. For other types we will change the cell to a numeric cell and Set its value. </param> public void SetCellValue(DateTime value) { bool date1904 = ((XSSFWorkbook)Sheet.Workbook).IsDate1904(); SetCellValue(DateUtil.GetExcelDate(value, date1904)); } /// <summary> /// Returns the error message, such as #VALUE! /// </summary> public String ErrorCellString { get { CellType cellType = GetBaseCellType(true); if (cellType != CellType.Error) throw TypeMismatch(CellType.Error, cellType, false); return _cell.v; } } /// <summary> /// Get the value of the cell as an error code. /// For strings, numbers, and bools, we throw an exception. /// For blank cells we return a 0. /// </summary> public byte ErrorCellValue { get { String code = this.ErrorCellString; if (code == null) { return 0; } return FormulaError.ForString(code).Code; } } public void SetCellErrorValue(byte errorCode) { FormulaError error = FormulaError.ForInt(errorCode); SetCellErrorValue(error); } /// <summary> /// Set a error value for the cell /// </summary> /// <param name="error">the error value to Set this cell to. /// For formulas we'll Set the precalculated value , for errors we'll set /// its value. For other types we will change the cell to an error cell and Set its value. /// </param> public void SetCellErrorValue(FormulaError error) { _cell.t = (ST_CellType.e); _cell.v = (error.String); } /// <summary> /// Sets this cell as the active cell for the worksheet. /// </summary> public void SetAsActiveCell() { ((XSSFSheet)Sheet).SetActiveCell(GetReference()); } /// <summary> /// Blanks this cell. Blank cells have no formula or value but may have styling. /// This method erases all the data previously associated with this cell. /// </summary> private void SetBlank() { CT_Cell blank = new CT_Cell(); blank.r = (_cell.r); if (_cell.IsSetS()) blank.s=(_cell.s); _cell.Set(blank); } /// <summary> /// Sets column index of this cell /// </summary> /// <param name="num"></param> internal void SetCellNum(int num) { CheckBounds(num); _cellNum = num; String ref1 = new CellReference(RowIndex, ColumnIndex).FormatAsString(); _cell.r = (ref1); } /// <summary> /// Set the cells type (numeric, formula or string) /// </summary> /// <param name="cellType"></param> public void SetCellType(CellType cellType) { CellType prevType = CellType; if (IsPartOfArrayFormulaGroup) { NotifyArrayFormulaChanging(); } if (prevType == CellType.Formula && cellType != CellType.Formula) { ((XSSFWorkbook)Sheet.Workbook).OnDeleteFormula(this); } switch (cellType) { case CellType.Blank: SetBlank(); break; case CellType.Boolean: String newVal = ConvertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING; _cell.t= (ST_CellType.b); _cell.v= (newVal); break; case CellType.Numeric: _cell.t = (ST_CellType.n); break; case CellType.Error: _cell.t = (ST_CellType.e); break; case CellType.String: if (prevType != CellType.String) { String str = ConvertCellValueToString(); XSSFRichTextString rt = new XSSFRichTextString(str); rt.SetStylesTableReference(_stylesSource); int sRef = _sharedStringSource.AddEntry(rt.GetCTRst()); _cell.v= sRef.ToString(); } _cell.t= (ST_CellType.s); break; case CellType.Formula: if (!_cell.IsSetF()) { CT_CellFormula f = new CT_CellFormula(); f.Value = "0"; _cell.f = (f); if (_cell.IsSetT()) _cell.unsetT(); } break; default: throw new ArgumentException("Illegal cell type: " + cellType); } if (cellType != CellType.Formula && _cell.IsSetF()) { _cell.unsetF(); } } /// <summary> /// Returns a string representation of the cell /// </summary> /// <returns>Formula cells return the formula string, rather than the formula result. /// Dates are displayed in dd-MMM-yyyy format /// Errors are displayed as #ERR&lt;errIdx&gt; /// </returns> public override String ToString() { switch (CellType) { case CellType.Blank: return ""; case CellType.Boolean: return BooleanCellValue ? "TRUE" : "FALSE"; case CellType.Error: return ErrorEval.GetText(ErrorCellValue); case CellType.Formula: return CellFormula; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(this)) { FormatBase sdf = new SimpleDateFormat("dd-MMM-yyyy"); return sdf.Format(DateCellValue, CultureInfo.CurrentCulture); } return NumericCellValue + ""; case CellType.String: return RichStringCellValue.ToString(); default: return "Unknown Cell Type: " + CellType; } } /** * Returns the raw, underlying ooxml value for the cell * <p> * If the cell Contains a string, then this value is an index into * the shared string table, pointing to the actual string value. Otherwise, * the value of the cell is expressed directly in this element. Cells Containing formulas express * the last calculated result of the formula in this element. * </p> * * @return the raw cell value as Contained in the underlying CT_Cell bean, * <code>null</code> for blank cells. */ public String GetRawValue() { return _cell.v; } /// <summary> /// Used to help format error messages /// </summary> /// <param name="cellTypeCode"></param> /// <returns></returns> private static String GetCellTypeName(CellType cellTypeCode) { switch (cellTypeCode) { case CellType.Blank: return "blank"; case CellType.String: return "text"; case CellType.Boolean: return "bool"; case CellType.Error: return "error"; case CellType.Numeric: return "numeric"; case CellType.Formula: return "formula"; } return "#unknown cell type (" + cellTypeCode + ")#"; } /** * Used to help format error messages */ private static Exception TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool IsFormulaCell) { String msg = "Cannot get a " + GetCellTypeName(expectedTypeCode) + " value from a " + GetCellTypeName(actualTypeCode) + " " + (IsFormulaCell ? "formula " : "") + "cell"; return new InvalidOperationException(msg); } /** * @throws RuntimeException if the bounds are exceeded. */ private static void CheckBounds(int cellIndex) { SpreadsheetVersion v = SpreadsheetVersion.EXCEL2007; int maxcol = SpreadsheetVersion.EXCEL2007.LastColumnIndex; if (cellIndex < 0 || cellIndex > maxcol) { throw new ArgumentException("Invalid column index (" + cellIndex + "). Allowable column range for " + v.ToString() + " is (0.." + maxcol + ") or ('A'..'" + v.LastColumnName + "')"); } } /// <summary> /// Returns cell comment associated with this cell /// </summary> public IComment CellComment { get { return Sheet.GetCellComment(_row.RowNum, ColumnIndex); } set { if (value == null) { RemoveCellComment(); return; } value.Row = (RowIndex); value.Column = (ColumnIndex); } } /// <summary> /// Removes the comment for this cell, if there is one. /// </summary> public void RemoveCellComment() { IComment comment = this.CellComment; if (comment != null) { String ref1 = GetReference(); XSSFSheet sh = (XSSFSheet)Sheet; sh.GetCommentsTable(false).RemoveComment(ref1); sh.GetVMLDrawing(false).RemoveCommentShape(RowIndex, ColumnIndex); } } /// <summary> /// Returns hyperlink associated with this cell /// </summary> public IHyperlink Hyperlink { get { return ((XSSFSheet)Sheet).GetHyperlink(_row.RowNum, _cellNum); } set { XSSFHyperlink link = (XSSFHyperlink)value; // Assign to us link.SetCellReference(new CellReference(_row.RowNum, _cellNum).FormatAsString()); // Add to the lists ((XSSFSheet)Sheet).AddHyperlink(link); } } /** * Returns the xml bean containing information about the cell's location (reference), value, * data type, formatting, and formula * * @return the xml bean containing information about this cell */ internal CT_Cell GetCTCell() { return _cell; } /** * Chooses a new bool value for the cell when its type is changing.<p/> * * Usually the caller is calling SetCellType() with the intention of calling * SetCellValue(bool) straight afterwards. This method only exists to give * the cell a somewhat reasonable value until the SetCellValue() call (if at all). * TODO - perhaps a method like SetCellTypeAndValue(int, Object) should be introduced to avoid this */ private bool ConvertCellValueToBoolean() { CellType cellType = CellType; if (cellType == CellType.Formula) { cellType = GetBaseCellType(false); } switch (cellType) { case CellType.Boolean: return TRUE_AS_STRING.Equals(_cell.v); case CellType.String: int sstIndex = Int32.Parse(_cell.v); XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(sstIndex)); String text = rt.String; return Boolean.Parse(text); case CellType.Numeric: return Double.Parse(_cell.v, CultureInfo.InvariantCulture) != 0; case CellType.Error: case CellType.Blank: return false; } throw new RuntimeException("Unexpected cell type (" + cellType + ")"); } private String ConvertCellValueToString() { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return ""; case CellType.Boolean: return TRUE_AS_STRING.Equals(_cell.v) ? "TRUE" : "FALSE"; case CellType.String: int sstIndex = Int32.Parse(_cell.v); XSSFRichTextString rt = new XSSFRichTextString(_sharedStringSource.GetEntryAt(sstIndex)); return rt.String; case CellType.Numeric: case CellType.Error: return _cell.v; case CellType.Formula: // should really Evaluate, but HSSFCell can't call HSSFFormulaEvaluator // just use cached formula result instead break; default: throw new InvalidOperationException("Unexpected cell type (" + cellType + ")"); } cellType = GetBaseCellType(false); String textValue = _cell.v; switch (cellType) { case CellType.Boolean: if (TRUE_AS_STRING.Equals(textValue)) { return "TRUE"; } if (FALSE_AS_STRING.Equals(textValue)) { return "FALSE"; } throw new InvalidOperationException("Unexpected bool cached formula value '" + textValue + "'."); case CellType.String: case CellType.Numeric: case CellType.Error: return textValue; } throw new InvalidOperationException("Unexpected formula result type (" + cellType + ")"); } public CellRangeAddress ArrayFormulaRange { get { XSSFCell cell = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this); if (cell == null) { throw new InvalidOperationException("Cell " + GetReference() + " is not part of an array formula."); } String formulaRef = cell._cell.f.@ref; return CellRangeAddress.ValueOf(formulaRef); } } public bool IsPartOfArrayFormulaGroup { get { return ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this); } } /** * The purpose of this method is to validate the cell state prior to modification * * @see #NotifyArrayFormulaChanging() */ internal void NotifyArrayFormulaChanging(String msg) { if (IsPartOfArrayFormulaGroup) { CellRangeAddress cra = this.ArrayFormulaRange; if (cra.NumberOfCells > 1) { throw new InvalidOperationException(msg); } //un-register the Single-cell array formula from the parent XSSFSheet Row.Sheet.RemoveArrayFormula(this); } } /// <summary> /// Called when this cell is modified.The purpose of this method is to validate the cell state prior to modification. /// </summary> /// <exception cref="InvalidOperationException">if modification is not allowed</exception> internal void NotifyArrayFormulaChanging() { CellReference ref1 = new CellReference(this); String msg = "Cell " + ref1.FormatAsString() + " is part of a multi-cell array formula. " + "You cannot change part of an array."; NotifyArrayFormulaChanging(msg); } #region ICell Members public bool IsMergedCell { get { return this.Sheet.IsMergedRegion(new CellRangeAddress(this.RowIndex, this.RowIndex, this.ColumnIndex, this.ColumnIndex)); } } #endregion public ICell CopyCellTo(int targetIndex) { return CellUtil.CopyCell(this.Row, this.ColumnIndex, targetIndex); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using Microsoft.Build.BackEnd; using Microsoft.Build.Construction; using Microsoft.Build.Definition; using Microsoft.Build.Evaluation; using Microsoft.Build.Execution; using Microsoft.Build.Framework; using Microsoft.Build.Shared; using Microsoft.Build.UnitTests.BackEnd; using Shouldly; using Xunit; using Xunit.Abstractions; using static Microsoft.Build.Engine.UnitTests.TestComparers.ProjectInstanceModelTestComparers; namespace Microsoft.Build.UnitTests.OM.Instance { /// <summary> /// Tests for ProjectInstance internal members /// </summary> public class ProjectInstance_Internal_Tests { private readonly ITestOutputHelper _output; public ProjectInstance_Internal_Tests(ITestOutputHelper output) { _output = output; } /// <summary> /// Read task registrations /// </summary> [Fact] public void GetTaskRegistrations() { try { string projectFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <UsingTask TaskName='t0' AssemblyFile='af0'/> <UsingTask TaskName='t1' AssemblyFile='af1a'/> <ItemGroup> <i Include='i0'/> </ItemGroup> <Import Project='{0}'/> </Project>"; string importContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <UsingTask TaskName='t1' AssemblyName='an1' Condition=""'$(p)'=='v'""/> <UsingTask TaskName='t2' AssemblyName='an2' Condition=""'@(i)'=='i0'""/> <UsingTask TaskName='t3' AssemblyFile='af' Condition='false'/> <PropertyGroup> <p>v</p> </PropertyGroup> </Project>"; string importPath = ObjectModelHelpers.CreateFileInTempProjectDirectory("import.targets", importContent); projectFileContent = String.Format(projectFileContent, importPath); ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance(); Assert.Equal(3, project.TaskRegistry.TaskRegistrations.Count); Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), "af0"), project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t0", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyFile); Assert.Equal(Path.Combine(Directory.GetCurrentDirectory(), "af1a"), project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t1", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyFile); Assert.Equal("an1", project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t1", null)][1].TaskFactoryAssemblyLoadInfo.AssemblyName); Assert.Equal("an2", project.TaskRegistry.TaskRegistrations[new TaskRegistry.RegisteredTaskIdentity("t2", null)][0].TaskFactoryAssemblyLoadInfo.AssemblyName); } finally { ObjectModelHelpers.DeleteTempProjectDirectory(); } } /// <summary> /// InitialTargets and DefaultTargets with imported projects. /// DefaultTargets are not read from imported projects. /// InitialTargets are gathered from imports depth-first. /// </summary> [Fact] public void InitialTargetsDefaultTargets() { try { string projectFileContent = @" <Project DefaultTargets='d0a;d0b' InitialTargets='i0a;i0b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='{0}'/> <Import Project='{1}'/> </Project>"; string import1Content = @" <Project DefaultTargets='d1a;d1b' InitialTargets='i1a;i1b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='{0}'/> </Project>"; string import2Content = @"<Project DefaultTargets='d2a;2db' InitialTargets='i2a;i2b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>"; string import3Content = @"<Project DefaultTargets='d3a;d3b' InitialTargets='i3a;i3b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'/>"; string import2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import2.targets", import2Content); string import3Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import3.targets", import3Content); import1Content = String.Format(import1Content, import3Path); string import1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import1.targets", import1Content); projectFileContent = String.Format(projectFileContent, import1Path, import2Path); ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance(); Helpers.AssertListsValueEqual(new string[] { "d0a", "d0b" }, project.DefaultTargets); Helpers.AssertListsValueEqual(new string[] { "i0a", "i0b", "i1a", "i1b", "i3a", "i3b", "i2a", "i2b" }, project.InitialTargets); } finally { ObjectModelHelpers.DeleteTempProjectDirectory(); } } /// <summary> /// InitialTargets and DefaultTargets with imported projects. /// DefaultTargets are not read from imported projects. /// InitialTargets are gathered from imports depth-first. /// </summary> [Fact] public void InitialTargetsDefaultTargetsEscaped() { try { string projectFileContent = @" <Project DefaultTargets='d0a%3bd0b' InitialTargets='i0a%3bi0b' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> </Project>"; ProjectInstance project = new Project(ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent)))).CreateProjectInstance(); Helpers.AssertListsValueEqual(new string[] { "d0a;d0b" }, project.DefaultTargets); Helpers.AssertListsValueEqual(new string[] { "i0a;i0b" }, project.InitialTargets); } finally { ObjectModelHelpers.DeleteTempProjectDirectory(); } } /// <summary> /// Read property group under target /// </summary> [Fact] public void GetPropertyGroupUnderTarget() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='t'> <PropertyGroup Condition='c1'> <p1 Condition='c2'>v1</p1> <p2/> </PropertyGroup> </Target> </Project> "; ProjectInstance p = GetProjectInstance(content); ProjectPropertyGroupTaskInstance propertyGroup = (ProjectPropertyGroupTaskInstance)(p.Targets["t"].Children[0]); Assert.Equal("c1", propertyGroup.Condition); List<ProjectPropertyGroupTaskPropertyInstance> properties = Helpers.MakeList(propertyGroup.Properties); Assert.Equal(2, properties.Count); Assert.Equal("c2", properties[0].Condition); Assert.Equal("v1", properties[0].Value); Assert.Equal(String.Empty, properties[1].Condition); Assert.Equal(String.Empty, properties[1].Value); } /// <summary> /// Read item group under target /// </summary> [Fact] public void GetItemGroupUnderTarget() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='t'> <ItemGroup Condition='c1'> <i Include='i1' Exclude='e1' Condition='c2'> <m Condition='c3'>m1</m> <n>n1</n> </i> <j Remove='r1'/> <k> <o>o1</o> </k> </ItemGroup> </Target> </Project> "; ProjectInstance p = GetProjectInstance(content); ProjectItemGroupTaskInstance itemGroup = (ProjectItemGroupTaskInstance)(p.Targets["t"].Children[0]); Assert.Equal("c1", itemGroup.Condition); List<ProjectItemGroupTaskItemInstance> items = Helpers.MakeList(itemGroup.Items); Assert.Equal(3, items.Count); Assert.Equal("i1", items[0].Include); Assert.Equal("e1", items[0].Exclude); Assert.Equal(String.Empty, items[0].Remove); Assert.Equal("c2", items[0].Condition); Assert.Equal(String.Empty, items[1].Include); Assert.Equal(String.Empty, items[1].Exclude); Assert.Equal("r1", items[1].Remove); Assert.Equal(String.Empty, items[1].Condition); Assert.Equal(String.Empty, items[2].Include); Assert.Equal(String.Empty, items[2].Exclude); Assert.Equal(String.Empty, items[2].Remove); Assert.Equal(String.Empty, items[2].Condition); List<ProjectItemGroupTaskMetadataInstance> metadata1 = Helpers.MakeList(items[0].Metadata); List<ProjectItemGroupTaskMetadataInstance> metadata2 = Helpers.MakeList(items[1].Metadata); List<ProjectItemGroupTaskMetadataInstance> metadata3 = Helpers.MakeList(items[2].Metadata); Assert.Equal(2, metadata1.Count); Assert.Empty(metadata2); Assert.Single(metadata3); Assert.Equal("c3", metadata1[0].Condition); Assert.Equal("m1", metadata1[0].Value); Assert.Equal(String.Empty, metadata1[1].Condition); Assert.Equal("n1", metadata1[1].Value); Assert.Equal(String.Empty, metadata3[0].Condition); Assert.Equal("o1", metadata3[0].Value); } /// <summary> /// Task registry accessor /// </summary> [Fact] public void GetTaskRegistry() { ProjectInstance p = GetSampleProjectInstance(); Assert.True(p.TaskRegistry != null); } /// <summary> /// Global properties accessor /// </summary> [Fact] public void GetGlobalProperties() { ProjectInstance p = GetSampleProjectInstance(); Assert.Equal("v1", p.GlobalPropertiesDictionary["g1"].EvaluatedValue); Assert.Equal("v2", p.GlobalPropertiesDictionary["g2"].EvaluatedValue); } /// <summary> /// ToolsVersion accessor /// </summary> [Fact] public void GetToolsVersion() { ProjectInstance p = GetSampleProjectInstance(); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); } [Fact] public void UsingExplicitToolsVersionShouldBeFalseWhenNoToolsetIsReferencedInProject() { var projectInstance = new ProjectInstance( new ProjectRootElement( XmlReader.Create(new StringReader("<Project></Project>")), ProjectCollection.GlobalProjectCollection.ProjectRootElementCache, false, false) ); projectInstance.UsingDifferentToolsVersionFromProjectFile.ShouldBeFalse(); } /// <summary> /// Toolset data is cloned properly /// </summary> [Fact] public void CloneToolsetData() { var projectCollection = new ProjectCollection(); CreateMockToolsetIfNotExists("TESTTV", projectCollection); ProjectInstance first = GetSampleProjectInstance(null, null, projectCollection, toolsVersion: "TESTTV"); ProjectInstance second = first.DeepCopy(); Assert.Equal(first.ToolsVersion, second.ToolsVersion); Assert.Equal(first.ExplicitToolsVersion, second.ExplicitToolsVersion); Assert.Equal(first.ExplicitToolsVersionSpecified, second.ExplicitToolsVersionSpecified); } /// <summary> /// Test ProjectInstance's surfacing of the sub-toolset version /// </summary> [Fact] public void GetSubToolsetVersion() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); ProjectInstance p = GetSampleProjectInstance(null, null, new ProjectCollection()); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); Assert.Equal(p.Toolset.DefaultSubToolsetVersion, p.SubToolsetVersion); if (p.Toolset.DefaultSubToolsetVersion == null) { Assert.Equal(MSBuildConstants.CurrentVisualStudioVersion, p.GetPropertyValue("VisualStudioVersion")); } else { Assert.Equal(p.Toolset.DefaultSubToolsetVersion, p.GetPropertyValue("VisualStudioVersion")); } } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } /// <summary> /// Test ProjectInstance's surfacing of the sub-toolset version when it is overridden by a value in the /// environment /// </summary> [Fact] [Trait("Category", "mono-osx-failing")] public void GetSubToolsetVersion_FromEnvironment() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "ABCD"); ProjectInstance p = GetSampleProjectInstance(null, null, new ProjectCollection()); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); Assert.Equal("ABCD", p.SubToolsetVersion); Assert.Equal("ABCD", p.GetPropertyValue("VisualStudioVersion")); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } /// <summary> /// Test ProjectInstance's surfacing of the sub-toolset version when it is overridden by a global property /// </summary> [Fact] public void GetSubToolsetVersion_FromProjectGlobalProperties() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", null); IDictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("VisualStudioVersion", "ABCDE"); ProjectInstance p = GetSampleProjectInstance(null, globalProperties, new ProjectCollection()); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); Assert.Equal("ABCDE", p.SubToolsetVersion); Assert.Equal("ABCDE", p.GetPropertyValue("VisualStudioVersion")); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } /// <summary> /// Verify that if a sub-toolset version is passed to the constructor, it all other heuristic methods for /// getting the sub-toolset version. /// </summary> [Fact] public void GetSubToolsetVersion_FromConstructor() { string originalVisualStudioVersion = Environment.GetEnvironmentVariable("VisualStudioVersion"); try { Environment.SetEnvironmentVariable("VisualStudioVersion", "ABC"); string projectContent = @"<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Target Name='t'> <Message Text='Hello'/> </Target> </Project>"; ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectContent))); IDictionary<string, string> globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("VisualStudioVersion", "ABCD"); IDictionary<string, string> projectCollectionGlobalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); projectCollectionGlobalProperties.Add("VisualStudioVersion", "ABCDE"); ProjectInstance p = new ProjectInstance(xml, globalProperties, ObjectModelHelpers.MSBuildDefaultToolsVersion, "ABCDEF", new ProjectCollection(projectCollectionGlobalProperties)); Assert.Equal(ObjectModelHelpers.MSBuildDefaultToolsVersion, p.Toolset.ToolsVersion); Assert.Equal("ABCDEF", p.SubToolsetVersion); Assert.Equal("ABCDEF", p.GetPropertyValue("VisualStudioVersion")); } finally { Environment.SetEnvironmentVariable("VisualStudioVersion", originalVisualStudioVersion); } } /// <summary> /// DefaultTargets accessor /// </summary> [Fact] public void GetDefaultTargets() { ProjectInstance p = GetSampleProjectInstance(); Helpers.AssertListsValueEqual(new string[] { "dt" }, p.DefaultTargets); } /// <summary> /// InitialTargets accessor /// </summary> [Fact] public void GetInitialTargets() { ProjectInstance p = GetSampleProjectInstance(); Helpers.AssertListsValueEqual(new string[] { "it" }, p.InitialTargets); } /// <summary> /// Cloning project clones targets /// </summary> [Fact] public void CloneTargets() { var hostServices = new HostServices(); ProjectInstance first = GetSampleProjectInstance(hostServices); ProjectInstance second = first.DeepCopy(); // Targets, tasks are immutable so we can expect the same objects Assert.True(Object.ReferenceEquals(first.Targets, second.Targets)); Assert.True(Object.ReferenceEquals(first.Targets["t"], second.Targets["t"])); var firstTasks = first.Targets["t"]; var secondTasks = second.Targets["t"]; Assert.True(Object.ReferenceEquals(firstTasks.Children[0], secondTasks.Children[0])); } /// <summary> /// Cloning project copies task registry /// </summary> [Fact] public void CloneTaskRegistry() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); // Task registry object should be immutable Assert.Same(first.TaskRegistry, second.TaskRegistry); } /// <summary> /// Cloning project copies global properties /// </summary> [Fact] public void CloneGlobalProperties() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Assert.Equal("v1", second.GlobalPropertiesDictionary["g1"].EvaluatedValue); Assert.Equal("v2", second.GlobalPropertiesDictionary["g2"].EvaluatedValue); } /// <summary> /// Cloning project copies default targets /// </summary> [Fact] public void CloneDefaultTargets() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Helpers.AssertListsValueEqual(new string[] { "dt" }, second.DefaultTargets); } /// <summary> /// Cloning project copies initial targets /// </summary> [Fact] public void CloneInitialTargets() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Helpers.AssertListsValueEqual(new string[] { "it" }, second.InitialTargets); } /// <summary> /// Cloning project copies toolsversion /// </summary> [Fact] public void CloneToolsVersion() { ProjectInstance first = GetSampleProjectInstance(); ProjectInstance second = first.DeepCopy(); Assert.Equal(first.Toolset, second.Toolset); } /// <summary> /// Cloning project copies toolsversion /// </summary> [Fact] public void CloneStateTranslation() { ProjectInstance first = GetSampleProjectInstance(); first.TranslateEntireState = true; ProjectInstance second = first.DeepCopy(); Assert.True(second.TranslateEntireState); } /// <summary> /// Tests building a simple project and verifying the log looks as expected. /// </summary> [Fact] public void Build() { // Setting the current directory to the MSBuild running location. It *should* be this // already, but if it's not some other test changed it and didn't change it back. If // the directory does not include the reference dlls the compilation will fail. Directory.SetCurrentDirectory(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory); string projectFileContent = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <UsingTask TaskName='Microsoft.Build.Tasks.Message' AssemblyFile='Microsoft.Build.Tasks.Core.dll'/> <ItemGroup> <i Include='i0'/> </ItemGroup> <Target Name='Build'> <Message Text='Building...'/> <Message Text='Completed!'/> </Target> </Project>"; ProjectInstance projectInstance = GetProjectInstance(projectFileContent); List<ILogger> loggers = new List<ILogger>(); MockLogger mockLogger = new MockLogger(_output); loggers.Add(mockLogger); bool success = projectInstance.Build("Build", loggers); Assert.True(success); mockLogger.AssertLogContains(new string[] { "Building...", "Completed!" }); } [Theory] [InlineData( @" <Project> </Project> ")] // Project with one of each direct child(indirect children trees are tested separately) [InlineData( @" <Project InitialTargets=`t1` DefaultTargets=`t2` ToolsVersion=`{0}`> <UsingTask TaskName=`t1` AssemblyFile=`f1`/> <ItemDefinitionGroup> <i> <n>n1</n> </i> </ItemDefinitionGroup> <PropertyGroup> <p1>v1</p1> </PropertyGroup> <ItemGroup> <i Include='i0'/> </ItemGroup> <Target Name='t1'> <t1/> </Target> <Target Name='t2' BeforeTargets=`t1`> <t2/> </Target> <Target Name='t3' AfterTargets=`t2`> <t3/> </Target> </Project> ")] // Project with at least two instances of each direct child. Tests that collections serialize well. [InlineData( @" <Project InitialTargets=`t1` DefaultTargets=`t2` ToolsVersion=`{0}`> <UsingTask TaskName=`t1` AssemblyFile=`f1`/> <UsingTask TaskName=`t2` AssemblyFile=`f2`/> <ItemDefinitionGroup> <i> <n>n1</n> </i> </ItemDefinitionGroup> <ItemDefinitionGroup> <i2> <n2>n2</n2> </i2> </ItemDefinitionGroup> <PropertyGroup> <p1>v1</p1> </PropertyGroup> <PropertyGroup> <p2>v2</p2> </PropertyGroup> <ItemGroup> <i Include='i1'/> </ItemGroup> <ItemGroup> <i2 Include='i2'> <m1 Condition=`1==1`>m1</m1> <m2>m2</m2> </i2> </ItemGroup> <Target Name='t1'> <t1/> </Target> <Target Name='t2' BeforeTargets=`t1`> <t2/> </Target> <Target Name='t3' AfterTargets=`t1`> <t3/> </Target> <Target Name='t4' BeforeTargets=`t1`> <t4/> </Target> <Target Name='t5' AfterTargets=`t1`> <t5/> </Target> </Project> ")] public void ProjectInstanceCanSerializeEntireStateViaTranslator(string projectContents) { projectContents = string.Format(projectContents, MSBuildConstants.CurrentToolsVersion); var original = new ProjectInstance(ProjectRootElement.Create(XmlReader.Create(new StringReader(ObjectModelHelpers.CleanupFileContents(projectContents))))); original.TranslateEntireState = true; ((ITranslatable) original).Translate(TranslationHelpers.GetWriteTranslator()); var copy = ProjectInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); Assert.Equal(original, copy, new ProjectInstanceComparer()); } public delegate ProjectInstance ProjectInstanceFactory(string file, ProjectRootElement xml, ProjectCollection collection); public static IEnumerable<object[]> ProjectInstanceHasEvaluationIdTestData() { // from file (new) yield return new ProjectInstanceFactory[] { (f, xml, c) => new ProjectInstance(f, null, null, c) }; // from file (factory method) yield return new ProjectInstanceFactory[] { (f, xml, c) => ProjectInstance.FromFile(f, new ProjectOptions { ProjectCollection = c }) }; // from Project yield return new ProjectInstanceFactory[] { (f, xml, c) => new Project(f, null, null, c).CreateProjectInstance() }; // from DeepCopy yield return new ProjectInstanceFactory[] { (f, xml, c) => new ProjectInstance(f, null, null, c).DeepCopy() }; // from ProjectRootElement (new) yield return new ProjectInstanceFactory[] { (f, xml, c) => new ProjectInstance(xml, null, null, c) }; // from ProjectRootElement (factory method) yield return new ProjectInstanceFactory[] { (f, xml, c) => ProjectInstance.FromProjectRootElement(xml, new ProjectOptions { ProjectCollection = c }) }; // from translated project instance yield return new ProjectInstanceFactory[] { (f, xml, c) => { var pi = new ProjectInstance(f, null, null, c); pi.AddItem("foo", "bar"); pi.TranslateEntireState = true; ((ITranslatable) pi).Translate(TranslationHelpers.GetWriteTranslator()); var copy = ProjectInstance.FactoryForDeserialization(TranslationHelpers.GetReadTranslator()); return copy; } }; } [Theory] [MemberData(nameof(ProjectInstanceHasEvaluationIdTestData))] public void ProjectInstanceHasEvaluationId(ProjectInstanceFactory projectInstanceFactory) { using (var env = TestEnvironment.Create()) { var file = env.CreateFile().Path; var projectCollection = env.CreateProjectCollection().Collection; var xml = ProjectRootElement.Create(projectCollection); xml.Save(file); var projectInstance = projectInstanceFactory.Invoke(file, xml, projectCollection); Assert.NotEqual(BuildEventContext.InvalidEvaluationId, projectInstance.EvaluationId); } } [Fact] public void AddTargetAddsNewTarget() { string projectFileContent = @" <Project> <Target Name='a' /> </Project>"; ProjectRootElement rootElement = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); ProjectInstance projectInstance = new ProjectInstance(rootElement); ProjectTargetInstance targetInstance = projectInstance.AddTarget("b", "1==1", "inputs", "outputs", "returns", "keepDuplicateOutputs", "dependsOnTargets", "beforeTargets", "afterTargets", true); Assert.Equal(2, projectInstance.Targets.Count); Assert.Equal(targetInstance, projectInstance.Targets["b"]); Assert.Equal("b", targetInstance.Name); Assert.Equal("1==1", targetInstance.Condition); Assert.Equal("inputs", targetInstance.Inputs); Assert.Equal("outputs", targetInstance.Outputs); Assert.Equal("returns", targetInstance.Returns); Assert.Equal("keepDuplicateOutputs", targetInstance.KeepDuplicateOutputs); Assert.Equal("dependsOnTargets", targetInstance.DependsOnTargets); Assert.Equal("beforeTargets", targetInstance.BeforeTargets); Assert.Equal("afterTargets", targetInstance.AfterTargets); Assert.Equal(projectInstance.ProjectFileLocation, targetInstance.Location); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.ConditionLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.InputsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.OutputsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.ReturnsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.KeepDuplicateOutputsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.DependsOnTargetsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.BeforeTargetsLocation); Assert.Equal(ElementLocation.EmptyLocation, targetInstance.AfterTargetsLocation); Assert.True(targetInstance.ParentProjectSupportsReturnsAttribute); } [Fact] public void AddTargetThrowsWithExistingTarget() { string projectFileContent = @" <Project> <Target Name='a' /> </Project>"; ProjectRootElement rootElement = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); ProjectInstance projectInstance = new ProjectInstance(rootElement); Assert.Throws<InternalErrorException>(() => projectInstance.AddTarget("a", "1==1", "inputs", "outputs", "returns", "keepDuplicateOutputs", "dependsOnTargets", "beforeTargets", "afterTargets", true)); } [Theory] [InlineData(false, ProjectLoadSettings.Default)] [InlineData(false, ProjectLoadSettings.RecordDuplicateButNotCircularImports)] [InlineData(true, ProjectLoadSettings.Default)] [InlineData(true, ProjectLoadSettings.RecordDuplicateButNotCircularImports)] public void GetImportPathsAndImportPathsIncludingDuplicates(bool useDirectConstruction, ProjectLoadSettings projectLoadSettings) { try { string projectFileContent = @" <Project> <Import Project='{0}'/> <Import Project='{1}'/> <Import Project='{0}'/> </Project>"; string import1Content = @" <Project> <Import Project='{0}'/> <Import Project='{1}'/> </Project>"; string import2Content = @"<Project />"; string import3Content = @"<Project />"; string import2Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import2.targets", import2Content); string import3Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import3.targets", import3Content); import1Content = string.Format(import1Content, import2Path, import3Path); string import1Path = ObjectModelHelpers.CreateFileInTempProjectDirectory("import1.targets", import1Content); projectFileContent = string.Format(projectFileContent, import1Path, import2Path); ProjectCollection projectCollection = new ProjectCollection(); BuildParameters buildParameters = new BuildParameters(projectCollection) { ProjectLoadSettings = projectLoadSettings }; BuildEventContext buildEventContext = new BuildEventContext(0, BuildEventContext.InvalidTargetId, BuildEventContext.InvalidProjectContextId, BuildEventContext.InvalidTaskId); ProjectRootElement rootElement = ProjectRootElement.Create(XmlReader.Create(new StringReader(projectFileContent))); ProjectInstance projectInstance = useDirectConstruction ? new ProjectInstance(rootElement, globalProperties: null, toolsVersion: null, buildParameters, projectCollection.LoggingService, buildEventContext, sdkResolverService: null, 0) : new Project(rootElement, globalProperties: null, toolsVersion: null, projectCollection, projectLoadSettings).CreateProjectInstance(); string[] expectedImportPaths = new string[] { import1Path, import2Path, import3Path }; string[] expectedImportPathsIncludingDuplicates = projectLoadSettings.HasFlag(ProjectLoadSettings.RecordDuplicateButNotCircularImports) ? new string[] { import1Path, import2Path, import3Path, import2Path, import1Path } : expectedImportPaths; Helpers.AssertListsValueEqual(expectedImportPaths, projectInstance.ImportPaths.ToList()); Helpers.AssertListsValueEqual(expectedImportPathsIncludingDuplicates, projectInstance.ImportPathsIncludingDuplicates.ToList()); } finally { ObjectModelHelpers.DeleteTempProjectDirectory(); } } /// <summary> /// Create a ProjectInstance from provided project content /// </summary> private static ProjectInstance GetProjectInstance(string content) { return GetProjectInstance(content, null); } /// <summary> /// Create a ProjectInstance from provided project content and host services object /// </summary> private static ProjectInstance GetProjectInstance(string content, HostServices hostServices) { return GetProjectInstance(content, hostServices, null, null); } /// <summary> /// Create a ProjectInstance from provided project content and host services object /// </summary> private static ProjectInstance GetProjectInstance(string content, HostServices hostServices, IDictionary<string, string> globalProperties, ProjectCollection projectCollection, string toolsVersion = null) { XmlReader reader = XmlReader.Create(new StringReader(content)); if (globalProperties == null) { // choose some interesting defaults if we weren't explicitly asked to use a set. globalProperties = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); globalProperties.Add("g1", "v1"); globalProperties.Add("g2", "v2"); } Project project = new Project(reader, globalProperties, toolsVersion ?? ObjectModelHelpers.MSBuildDefaultToolsVersion, projectCollection ?? ProjectCollection.GlobalProjectCollection); ProjectInstance instance = project.CreateProjectInstance(); return instance; } /// <summary> /// Create a ProjectInstance with some items and properties and targets /// </summary> private static ProjectInstance GetSampleProjectInstance() { return GetSampleProjectInstance(null); } /// <summary> /// Create a ProjectInstance with some items and properties and targets /// </summary> private static ProjectInstance GetSampleProjectInstance(HostServices hostServices) { return GetSampleProjectInstance(hostServices, null, null); } /// <summary> /// Create a ProjectInstance with some items and properties and targets /// </summary> private static ProjectInstance GetSampleProjectInstance(HostServices hostServices, IDictionary<string, string> globalProperties, ProjectCollection projectCollection, string toolsVersion = null) { string toolsVersionSubstring = toolsVersion != null ? "ToolsVersion=\"" + toolsVersion + "\" " : String.Empty; string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' InitialTargets='it' DefaultTargets='dt' " + toolsVersionSubstring + @"> <PropertyGroup> <p1>v1</p1> <p2>v2</p2> <p2>$(p2)X$(p)</p2> </PropertyGroup> <ItemGroup> <i Include='i0'/> <i Include='i1'> <m>m1</m> </i> <i Include='$(p1)'/> </ItemGroup> <Target Name='t'> <t1 a='a1' b='b1' ContinueOnError='coe' Condition='c'/> <t2/> </Target> <Target Name='tt'/> </Project> "; ProjectInstance p = GetProjectInstance(content, hostServices, globalProperties, projectCollection, toolsVersion); return p; } /// <summary> /// Creates a toolset with the given tools version if one does not already exist. /// </summary> private static void CreateMockToolsetIfNotExists(string toolsVersion, ProjectCollection projectCollection) { ProjectCollection pc = projectCollection; if (!pc.Toolsets.Any(t => String.Equals(t.ToolsVersion, toolsVersion, StringComparison.OrdinalIgnoreCase))) { Toolset template = pc.Toolsets.First(t => String.Equals(t.ToolsVersion, pc.DefaultToolsVersion, StringComparison.OrdinalIgnoreCase)); var toolset = new Toolset( toolsVersion, template.ToolsPath, template.Properties.ToDictionary(p => p.Key, p => p.Value.EvaluatedValue), pc, null); pc.AddToolset(toolset); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.ObjectModel; using System.Threading.Tasks; namespace System.ServiceModel.Channels { public abstract class TransportChannelFactory<TChannel> : ChannelFactoryBase<TChannel>, ITransportFactorySettings { private BufferManager _bufferManager; private long _maxBufferPoolSize; private long _maxReceivedMessageSize; private MessageEncoderFactory _messageEncoderFactory; private bool _manualAddressing; private MessageVersion _messageVersion; protected TransportChannelFactory(TransportBindingElement bindingElement, BindingContext context) : this(bindingElement, context, TransportDefaults.GetDefaultMessageEncoderFactory()) { } protected TransportChannelFactory(TransportBindingElement bindingElement, BindingContext context, MessageEncoderFactory defaultMessageEncoderFactory) : base(context.Binding) { _manualAddressing = bindingElement.ManualAddressing; _maxBufferPoolSize = bindingElement.MaxBufferPoolSize; _maxReceivedMessageSize = bindingElement.MaxReceivedMessageSize; Collection<MessageEncodingBindingElement> messageEncoderBindingElements = context.BindingParameters.FindAll<MessageEncodingBindingElement>(); if (messageEncoderBindingElements.Count > 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.MultipleMebesInParameters)); } else if (messageEncoderBindingElements.Count == 1) { _messageEncoderFactory = messageEncoderBindingElements[0].CreateMessageEncoderFactory(); context.BindingParameters.Remove<MessageEncodingBindingElement>(); } else { _messageEncoderFactory = defaultMessageEncoderFactory; } if (null != _messageEncoderFactory) _messageVersion = _messageEncoderFactory.MessageVersion; else _messageVersion = MessageVersion.None; } public BufferManager BufferManager { get { return _bufferManager; } } public long MaxBufferPoolSize { get { return _maxBufferPoolSize; } } public long MaxReceivedMessageSize { get { return _maxReceivedMessageSize; } } public MessageEncoderFactory MessageEncoderFactory { get { return _messageEncoderFactory; } } public MessageVersion MessageVersion { get { return _messageVersion; } } public bool ManualAddressing { get { return _manualAddressing; } } public abstract string Scheme { get; } public override T GetProperty<T>() { if (typeof(T) == typeof(MessageVersion)) { return (T)(object)this.MessageVersion; } if (typeof(T) == typeof(FaultConverter)) { if (null == this.MessageEncoderFactory) return null; else return this.MessageEncoderFactory.Encoder.GetProperty<T>(); } if (typeof(T) == typeof(ITransportFactorySettings)) { return (T)(object)this; } return base.GetProperty<T>(); } protected override void OnAbort() { OnCloseOrAbort(); base.OnAbort(); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { OnCloseOrAbort(); return base.OnBeginClose(timeout, callback, state); } protected override void OnClose(TimeSpan timeout) { OnCloseOrAbort(); base.OnClose(timeout); } internal protected override Task OnCloseAsync(TimeSpan timeout) { OnCloseOrAbort(); return base.OnCloseAsync(timeout); } private void OnCloseOrAbort() { if (_bufferManager != null) { _bufferManager.Clear(); } } public virtual int GetMaxBufferSize() { if (MaxReceivedMessageSize > int.MaxValue) return int.MaxValue; else return (int)MaxReceivedMessageSize; } protected override void OnOpening() { base.OnOpening(); _bufferManager = BufferManager.CreateBufferManager(MaxBufferPoolSize, GetMaxBufferSize()); } public void ValidateScheme(Uri via) { if (via.Scheme != this.Scheme) { // URI schemes are case-insensitive, so try a case insensitive compare now if (string.Compare(via.Scheme, this.Scheme, StringComparison.OrdinalIgnoreCase) != 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("via", SR.Format(SR.InvalidUriScheme, via.Scheme, this.Scheme)); } } } long ITransportFactorySettings.MaxReceivedMessageSize { get { return MaxReceivedMessageSize; } } BufferManager ITransportFactorySettings.BufferManager { get { return BufferManager; } } bool ITransportFactorySettings.ManualAddressing { get { return ManualAddressing; } } MessageEncoderFactory ITransportFactorySettings.MessageEncoderFactory { get { return MessageEncoderFactory; } } } }
/* * Swagger Petstore * * This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. * * OpenAPI spec version: 1.0.0 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; using Newtonsoft.Json; namespace IO.Swagger.Models { /// <summary> /// /// </summary> [DataContract] public partial class Order : IEquatable<Order> { /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id")] public long? Id { get; set; } /// <summary> /// Gets or Sets PetId /// </summary> [DataMember(Name="petId")] public long? PetId { get; set; } /// <summary> /// Gets or Sets Quantity /// </summary> [DataMember(Name="quantity")] public int? Quantity { get; set; } /// <summary> /// Gets or Sets ShipDate /// </summary> [DataMember(Name="shipDate")] public DateTime? ShipDate { get; set; } /// <summary> /// Order Status /// </summary> /// <value>Order Status</value> public enum StatusEnum { /// <summary> /// Enum PlacedEnum for placed /// </summary> [EnumMember(Value = "placed")] Placed = 1, /// <summary> /// Enum ApprovedEnum for approved /// </summary> [EnumMember(Value = "approved")] Approved = 2, /// <summary> /// Enum DeliveredEnum for delivered /// </summary> [EnumMember(Value = "delivered")] Delivered = 3 } /// <summary> /// Order Status /// </summary> /// <value>Order Status</value> [DataMember(Name="status")] public StatusEnum? Status { get; set; } /// <summary> /// Gets or Sets Complete /// </summary> [DataMember(Name="complete")] public bool? Complete { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((Order)obj); } /// <summary> /// Returns true if Order instances are equal /// </summary> /// <param name="other">Instance of Order to be compared</param> /// <returns>Boolean</returns> public bool Equals(Order other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return ( Id == other.Id || Id != null && Id.Equals(other.Id) ) && ( PetId == other.PetId || PetId != null && PetId.Equals(other.PetId) ) && ( Quantity == other.Quantity || Quantity != null && Quantity.Equals(other.Quantity) ) && ( ShipDate == other.ShipDate || ShipDate != null && ShipDate.Equals(other.ShipDate) ) && ( Status == other.Status || Status != null && Status.Equals(other.Status) ) && ( Complete == other.Complete || Complete != null && Complete.Equals(other.Complete) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Id != null) hashCode = hashCode * 59 + Id.GetHashCode(); if (PetId != null) hashCode = hashCode * 59 + PetId.GetHashCode(); if (Quantity != null) hashCode = hashCode * 59 + Quantity.GetHashCode(); if (ShipDate != null) hashCode = hashCode * 59 + ShipDate.GetHashCode(); if (Status != null) hashCode = hashCode * 59 + Status.GetHashCode(); if (Complete != null) hashCode = hashCode * 59 + Complete.GetHashCode(); return hashCode; } } #region Operators #pragma warning disable 1591 public static bool operator ==(Order left, Order right) { return Equals(left, right); } public static bool operator !=(Order left, Order right) { return !Equals(left, right); } #pragma warning restore 1591 #endregion Operators } }
#region License // Copyright (c) 2010-2019, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License using Bam.Core; namespace Python { [Bam.Core.ModuleGroup("Thirdparty/Python/DynamicModules")] class DynamicExtensionModule : C.Plugin { private readonly string ModuleName; private readonly Bam.Core.StringArray SourceFiles; private readonly Bam.Core.StringArray LibsToLink; private readonly Bam.Core.Module.PrivatePatchDelegate CompilationPatch; private readonly Bam.Core.Module.PrivatePatchDelegate LinkerPatch; private readonly Bam.Core.StringArray AssemblerFiles; private readonly Bam.Core.Module.PrivatePatchDelegate AssemblerPatch; protected C.CObjectFileCollection moduleSourceModules; protected DynamicExtensionModule( string moduleName, Bam.Core.StringArray sourceFiles, Bam.Core.StringArray libraries, Bam.Core.Module.PrivatePatchDelegate compilationPatch, Bam.Core.Module.PrivatePatchDelegate linkerPatch, Bam.Core.StringArray assemblerFiles, Bam.Core.Module.PrivatePatchDelegate assemberPatch) { this.ModuleName = moduleName; this.SourceFiles = sourceFiles; this.LibsToLink = libraries; this.CompilationPatch = compilationPatch; this.LinkerPatch = linkerPatch; this.AssemblerFiles = (null != assemblerFiles) ? assemblerFiles : null; this.AssemblerPatch = assemberPatch; } protected DynamicExtensionModule( string moduleName, Bam.Core.StringArray sourceFiles) : this(moduleName, sourceFiles, null, null, null, null, null) {} protected DynamicExtensionModule( string moduleName, string sourceFile) : this(moduleName, new Bam.Core.StringArray(sourceFile)) {} protected DynamicExtensionModule( string moduleName, string sourceFile, Bam.Core.Module.PrivatePatchDelegate compilationPatch, Bam.Core.Module.PrivatePatchDelegate linkerPatch) : this(moduleName, new Bam.Core.StringArray(sourceFile), null, compilationPatch, linkerPatch, null, null) { } protected DynamicExtensionModule( string moduleName, Bam.Core.StringArray sourceFiles, Bam.Core.Module.PrivatePatchDelegate compilationPatch) : this(moduleName, sourceFiles, null, compilationPatch, null, null, null) { } protected DynamicExtensionModule( string moduleName, Bam.Core.StringArray sourceFiles, Bam.Core.Module.PrivatePatchDelegate compilationPatch, Bam.Core.Module.PrivatePatchDelegate linkerPatch) : this(moduleName, sourceFiles, null, compilationPatch, linkerPatch, null, null) { } protected DynamicExtensionModule( string moduleName) : this(moduleName, new Bam.Core.StringArray(System.String.Format("Modules/{0}", moduleName))) {} protected override void Init() { base.Init(); if (this.BuildEnvironment.Platform.Includes(Bam.Core.EPlatform.Windows)) { this.Macros[C.ModuleMacroNames.PluginFileExtension] = Bam.Core.TokenizedString.CreateVerbatim(".pyd"); var pyConfigHeader = Bam.Core.Graph.Instance.FindReferencedModule<PyConfigHeader>(); if ((pyConfigHeader.Configuration as IConfigurePython).PyDEBUG) { this.Macros[Bam.Core.ModuleMacroNames.OutputName] = Bam.Core.TokenizedString.CreateVerbatim(this.ModuleName + "_d"); } else { this.Macros[Bam.Core.ModuleMacroNames.OutputName] = Bam.Core.TokenizedString.CreateVerbatim(this.ModuleName); } } else { this.Macros[Bam.Core.ModuleMacroNames.OutputName] = Bam.Core.TokenizedString.CreateVerbatim(this.ModuleName); this.Macros[C.ModuleMacroNames.PluginPrefix] = Bam.Core.TokenizedString.CreateVerbatim(string.Empty); this.Macros[C.ModuleMacroNames.PluginFileExtension] = Bam.Core.TokenizedString.CreateVerbatim(".so"); } this.SetSemanticVersion(Version.Major, Version.Minor, Version.Patch); this.moduleSourceModules = this.CreateCSourceCollection(); foreach (var basename in this.SourceFiles) { this.moduleSourceModules.AddFiles(System.String.Format("$(packagedir)/{0}.c", basename)); } this.moduleSourceModules.PrivatePatch(settings => { var preprocessor = settings as C.ICommonPreprocessorSettings; preprocessor.PreprocessorDefines.Add("Py_ENABLE_SHARED"); var cCompiler = settings as C.ICOnlyCompilerSettings; cCompiler.LanguageStandard = C.ELanguageStandard.C99; // // some C99 features are now used from 3.6 (https://www.python.org/dev/peps/pep-0007/#c-dialect) if (settings is C.ICommonCompilerSettingsWin winCompiler) { winCompiler.CharacterSet = C.ECharacterSet.NotSet; } if (settings is VisualCCommon.ICommonCompilerSettings vcCompiler) { vcCompiler.WarningLevel = VisualCCommon.EWarningLevel.Level4; } if (settings is GccCommon.ICommonCompilerSettings gccCompiler) { gccCompiler.AllWarnings = true; gccCompiler.ExtraWarnings = true; gccCompiler.Pedantic = true; if ((settings.Module.Tool as C.CompilerTool).Version.AtLeast(GccCommon.ToolchainVersion.GCC_8)) { var compiler = settings as C.ICommonCompilerSettings; compiler.DisableWarnings.AddUnique("cast-function-type"); } } if (settings is ClangCommon.ICommonCompilerSettings clangCompiler) { clangCompiler.AllWarnings = true; clangCompiler.ExtraWarnings = true; clangCompiler.Pedantic = true; } }); if (null != this.CompilationPatch) { this.moduleSourceModules.PrivatePatch(this.CompilationPatch); } if (null != this.AssemblerFiles) { var assemblerSource = this.CreateAssemblerSourceCollection(); foreach (var leafname in this.AssemblerFiles) { assemblerSource.AddFiles($"$(packagedir)/{leafname}"); } if (null != this.AssemblerPatch) { assemblerSource.PrivatePatch(this.AssemblerPatch); } } this.CompileAndLinkAgainst<PythonLibrary>(this.moduleSourceModules); if (this.LibsToLink != null) { this.PrivatePatch(settings => { var linker = settings as C.ICommonLinkerSettings; foreach (var lib in this.LibsToLink) { linker.Libraries.AddUnique(lib); } }); } if (null != this.LinkerPatch) { this.PrivatePatch(this.LinkerPatch); } } } }
using System; using Newtonsoft.Json.Linq; namespace Helios.Web.Authentication.External.Facebook { /* THIS CLASS IS GOT FROM https://github.com/aspnet/Security/blob/rel/1.1.3/src/Microsoft.AspNetCore.Authentication.Facebook/FacebookHelper.cs */ /// <summary> /// Contains static methods that allow to extract user's information from a <see cref="JObject"/> /// instance retrieved from Facebook after a successful authentication process. /// </summary> public static class FacebookHelper { /// <summary> /// Gets the Facebook user ID. /// </summary> public static string GetId(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("id"); } /// <summary> /// Gets the user's min age. /// </summary> public static string GetAgeRangeMin(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return TryGetValue(user, "age_range", "min"); } /// <summary> /// Gets the user's max age. /// </summary> public static string GetAgeRangeMax(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return TryGetValue(user, "age_range", "max"); } /// <summary> /// Gets the user's birthday. /// </summary> public static string GetBirthday(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("birthday"); } /// <summary> /// Gets the Facebook email. /// </summary> public static string GetEmail(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("email"); } /// <summary> /// Gets the user's first name. /// </summary> public static string GetFirstName(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("first_name"); } /// <summary> /// Gets the user's gender. /// </summary> public static string GetGender(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("gender"); } /// <summary> /// Gets the user's family name. /// </summary> public static string GetLastName(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("last_name"); } /// <summary> /// Gets the user's link. /// </summary> public static string GetLink(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("link"); } /// <summary> /// Gets the user's location. /// </summary> public static string GetLocation(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return TryGetValue(user, "location", "name"); } /// <summary> /// Gets the user's locale. /// </summary> public static string GetLocale(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("locale"); } /// <summary> /// Gets the user's middle name. /// </summary> public static string GetMiddleName(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("middle_name"); } /// <summary> /// Gets the user's name. /// </summary> public static string GetName(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("name"); } /// <summary> /// Gets the user's timezone. /// </summary> public static string GetTimeZone(JObject user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } return user.Value<string>("timezone"); } // Get the given subProperty from a property. private static string TryGetValue(JObject user, string propertyName, string subProperty) { JToken value; if (user.TryGetValue(propertyName, out value)) { var subObject = JObject.Parse(value.ToString()); if (subObject != null && subObject.TryGetValue(subProperty, out value)) { return value.ToString(); } } return null; } } }
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.IO; using Android.App; using Android.Content; using CouchbaseSample.Android; using Couchbase.Lite; using Couchbase.Lite.Android; using Couchbase.Lite.Auth; using Couchbase.Lite.Replicator; using Couchbase.Lite.Util; using Sharpen; namespace CouchbaseSample.Android { public class Application : global::Android.App.Application { public const string Tag = "ToDoLite"; private const string DatabaseName = "todos"; private const string SyncUrl = "http://sync.couchbasecloud.com:4984/todos4/"; private const string PrefCurrentListId = "CurrentListId"; private const string PrefCurrentUserId = "CurrentUserId"; private Manager manager; private Database database; private int syncCompletedChangedCount; private int syncTotalChangedCount; private Application.OnSyncProgressChangeObservable onSyncProgressChangeObservable; private Application.OnSyncUnauthorizedObservable onSyncUnauthorizedObservable; public enum AuthenticationType { Facebook, CustomCookie } private Application.AuthenticationType authenticationType = Application.AuthenticationType .Facebook; // By default, this should be set to FACEBOOK. To test "custom cookie" auth, // set this to CUSTOM_COOKIE. private void InitDatabase() { try { // Manager.EnableLogging(Log.Tag, Log.Verbose); // Manager.EnableLogging(Log.TagSync, Log.Debug); // Manager.EnableLogging(Log.TagQuery, Log.Debug); // Manager.EnableLogging(Log.TagView, Log.Debug); // Manager.EnableLogging(Log.TagDatabase, Log.Debug); // manager = new Manager(new AndroidContext(GetApplicationContext()), Manager.DefaultOptions // ); } catch (IOException e) { Log.E(Tag, "Cannot create Manager object", e); return; } try { database = manager.GetDatabase(DatabaseName); } catch (CouchbaseLiteException e) { Log.E(Tag, "Cannot get Database", e); return; } } private void InitObservable() { onSyncProgressChangeObservable = new Application.OnSyncProgressChangeObservable(); onSyncUnauthorizedObservable = new Application.OnSyncUnauthorizedObservable(); } private void UpdateSyncProgress(int completedCount, int totalCount) { lock (this) { onSyncProgressChangeObservable.NotifyChanges(completedCount, totalCount); } } public virtual void StartReplicationSyncWithCustomCookie(string name, string value , string path, DateTime expirationDate, bool secure, bool httpOnly) { Replication[] replications = CreateReplications(); Replication pullRep = replications[0]; Replication pushRep = replications[1]; pullRep.SetCookie(name, value, path, expirationDate, secure, httpOnly); pushRep.SetCookie(name, value, path, expirationDate, secure, httpOnly); pullRep.Start(); pushRep.Start(); Log.V(Tag, "Start Replication Sync ..."); } public virtual void StartReplicationSyncWithStoredCustomCookie() { Replication[] replications = CreateReplications(); Replication pullRep = replications[0]; Replication pushRep = replications[1]; pullRep.Start(); pushRep.Start(); Log.V(Tag, "Start Replication Sync ..."); } public virtual void StartReplicationSyncWithFacebookLogin(string accessToken, string email) { Authenticator facebookAuthenticator = AuthenticatorFactory.CreateFacebookAuthenticator (accessToken); Replication[] replications = CreateReplications(); Replication pullRep = replications[0]; Replication pushRep = replications[1]; pullRep.SetAuthenticator(facebookAuthenticator); pushRep.SetAuthenticator(facebookAuthenticator); pullRep.Start(); pushRep.Start(); Log.V(Tag, "Start Replication Sync ..."); } public virtual Replication[] CreateReplications() { Uri syncUrl; try { syncUrl = new Uri(SyncUrl); } catch (UriFormatException e) { Log.E(Tag, "Invalid Sync Url", e); throw new RuntimeException(e); } Replication pullRep = database.CreatePullReplication(syncUrl); pullRep.SetContinuous(true); pullRep.AddChangeListener(GetReplicationChangeListener()); Replication pushRep = database.CreatePushReplication(syncUrl); pushRep.SetContinuous(true); pushRep.AddChangeListener(GetReplicationChangeListener()); return new Replication[] { pullRep, pushRep }; } private Replication.ChangeListener GetReplicationChangeListener() { return new _ChangeListener_151(this); } private sealed class _ChangeListener_151 : Replication.ChangeListener { public _ChangeListener_151(Application _enclosing) { this._enclosing = _enclosing; } public void Changed(Replication.ChangeEvent @event) { Replication replication = @event.GetSource(); if (replication.GetLastError() != null) { Exception lastError = replication.GetLastError(); if (lastError is HttpResponseException) { HttpResponseException responseException = (HttpResponseException)lastError; if (responseException.GetStatusCode() == 401) { this._enclosing.onSyncUnauthorizedObservable.NotifyChanges(); } } } this._enclosing.UpdateSyncProgress(replication.GetCompletedChangesCount(), replication .GetChangesCount()); } private readonly Application _enclosing; } public override void OnCreate() { base.OnCreate(); InitDatabase(); InitObservable(); } public virtual Database GetDatabase() { return this.database; } public virtual string GetCurrentListId() { SharedPreferences sp = PreferenceManager.GetDefaultSharedPreferences(GetApplicationContext ()); return sp.GetString(PrefCurrentListId, null); } public virtual void SetCurrentListId(string id) { SharedPreferences sp = PreferenceManager.GetDefaultSharedPreferences(GetApplicationContext ()); if (id != null) { sp.Edit().PutString(PrefCurrentListId, id).Apply(); } else { sp.Edit().Remove(PrefCurrentListId); } } public virtual string GetCurrentUserId() { SharedPreferences sp = PreferenceManager.GetDefaultSharedPreferences(GetApplicationContext ()); string userId = sp.GetString(PrefCurrentUserId, null); return userId; } public virtual void SetCurrentUserId(string id) { SharedPreferences sp = PreferenceManager.GetDefaultSharedPreferences(GetApplicationContext ()); if (id != null) { sp.Edit().PutString(PrefCurrentUserId, id).Apply(); } else { sp.Edit().Remove(PrefCurrentUserId).Apply(); } } public virtual Application.OnSyncProgressChangeObservable GetOnSyncProgressChangeObservable () { return onSyncProgressChangeObservable; } public virtual Application.OnSyncUnauthorizedObservable GetOnSyncUnauthorizedObservable () { return onSyncUnauthorizedObservable; } public virtual Application.AuthenticationType GetAuthenticationType() { return authenticationType; } internal class OnSyncProgressChangeObservable : Observable { private void NotifyChanges(int completedCount, int totalCount) { Application.SyncProgress progress = new Application.SyncProgress(); progress.completedCount = completedCount; progress.totalCount = totalCount; SetChanged(); NotifyObservers(progress); } } internal class OnSyncUnauthorizedObservable : Observable { private void NotifyChanges() { SetChanged(); NotifyObservers(); } } internal class SyncProgress { public int completedCount; public int totalCount; } } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.3 * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal * or internal use. Without the written permission of Esoteric Software (see * Section 2 of the Spine Software License Agreement), you may not (a) modify, * translate, adapt or otherwise create derivative works, improvements of the * Software or develop new applications using the Software or (b) remove, * delete, alter or obscure any trademarks or any copyright, trademark, patent * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; using System.Collections.Generic; using UnityEngine; using Spine; /// <summary>Renders a skeleton.</summary> [ExecuteInEditMode, RequireComponent(typeof(MeshFilter), typeof(MeshRenderer))] public class SkeletonRenderer : MonoBehaviour { public delegate void SkeletonRendererDelegate (SkeletonRenderer skeletonRenderer); public SkeletonRendererDelegate OnReset; [System.NonSerialized] public bool valid; [System.NonSerialized] public Skeleton skeleton; public SkeletonDataAsset skeletonDataAsset; public String initialSkinName; public bool calculateNormals, calculateTangents; public float zSpacing; public bool renderMeshes = true, immutableTriangles; public bool frontFacing; public bool logErrors = false; [SpineSlot] public string[] submeshSeparators = new string[0]; [HideInInspector] public List<Slot> submeshSeparatorSlots = new List<Slot>(); private MeshRenderer meshRenderer; private MeshFilter meshFilter; private Mesh mesh1, mesh2; private bool useMesh1; private float[] tempVertices = new float[8]; private Vector3[] vertices; private Color32[] colors; private Vector2[] uvs; private Material[] sharedMaterials = new Material[0]; private readonly ExposedList<Material> submeshMaterials = new ExposedList<Material>(); private readonly ExposedList<Submesh> submeshes = new ExposedList<Submesh>(); private SkeletonUtilitySubmeshRenderer[] submeshRenderers; private LastState lastState = new LastState(); public virtual void Reset () { if (meshFilter != null) meshFilter.sharedMesh = null; meshRenderer = GetComponent<MeshRenderer>(); if (meshRenderer != null) meshRenderer.sharedMaterial = null; if (mesh1 != null) { if (Application.isPlaying) Destroy(mesh1); else DestroyImmediate(mesh1); } if (mesh2 != null) { if (Application.isPlaying) Destroy(mesh2); else DestroyImmediate(mesh2); } lastState = new LastState(); mesh1 = null; mesh2 = null; vertices = null; colors = null; uvs = null; sharedMaterials = new Material[0]; submeshMaterials.Clear(); submeshes.Clear(); skeleton = null; valid = false; if (!skeletonDataAsset) { if (logErrors) Debug.LogError("Missing SkeletonData asset.", this); return; } SkeletonData skeletonData = skeletonDataAsset.GetSkeletonData(false); if (skeletonData == null) return; valid = true; meshFilter = GetComponent<MeshFilter>(); meshRenderer = GetComponent<MeshRenderer>(); mesh1 = newMesh(); mesh2 = newMesh(); vertices = new Vector3[0]; skeleton = new Skeleton(skeletonData); if (initialSkinName != null && initialSkinName.Length > 0 && initialSkinName != "default") skeleton.SetSkin(initialSkinName); submeshSeparatorSlots.Clear(); for (int i = 0; i < submeshSeparators.Length; i++) { submeshSeparatorSlots.Add(skeleton.FindSlot(submeshSeparators[i])); } CollectSubmeshRenderers(); LateUpdate(); if (OnReset != null) OnReset(this); } public void CollectSubmeshRenderers () { submeshRenderers = GetComponentsInChildren<SkeletonUtilitySubmeshRenderer>(); } public virtual void Awake () { Reset(); } public virtual void OnDestroy () { if (mesh1 != null) { if (Application.isPlaying) Destroy(mesh1); else DestroyImmediate(mesh1); } if (mesh2 != null) { if (Application.isPlaying) Destroy(mesh2); else DestroyImmediate(mesh2); } mesh1 = null; mesh2 = null; } private Mesh newMesh () { Mesh mesh = new Mesh(); mesh.name = "Skeleton Mesh"; mesh.hideFlags = HideFlags.HideAndDontSave; mesh.MarkDynamic(); return mesh; } public virtual void LateUpdate () { if (!valid) return; // Exit early if there is nothing to render if (!meshRenderer.enabled && submeshRenderers.Length == 0) return; // Count vertices and submesh triangles. int vertexCount = 0; int submeshTriangleCount = 0, submeshFirstVertex = 0, submeshStartSlotIndex = 0; Material lastMaterial = null; ExposedList<Slot> drawOrder = skeleton.drawOrder; int drawOrderCount = drawOrder.Count; int submeshSeparatorSlotsCount = submeshSeparatorSlots.Count; bool renderMeshes = this.renderMeshes; // Clear last state of attachments and submeshes ExposedList<int> attachmentsTriangleCountTemp = lastState.attachmentsTriangleCountTemp; attachmentsTriangleCountTemp.GrowIfNeeded(drawOrderCount); attachmentsTriangleCountTemp.Count = drawOrderCount; ExposedList<bool> attachmentsFlipStateTemp = lastState.attachmentsFlipStateTemp; attachmentsFlipStateTemp.GrowIfNeeded(drawOrderCount); attachmentsFlipStateTemp.Count = drawOrderCount; ExposedList<LastState.AddSubmeshArguments> addSubmeshArgumentsTemp = lastState.addSubmeshArgumentsTemp; addSubmeshArgumentsTemp.Clear(false); for (int i = 0; i < drawOrderCount; i++) { Slot slot = drawOrder.Items[i]; Bone bone = slot.bone; Attachment attachment = slot.attachment; object rendererObject; int attachmentVertexCount, attachmentTriangleCount; bool worldScaleXIsPositive = bone.worldScaleX >= 0f; bool worldScaleYIsPositive = bone.worldScaleY >= 0f; bool worldScaleIsSameSigns = (worldScaleXIsPositive && worldScaleYIsPositive) || (!worldScaleXIsPositive && !worldScaleYIsPositive); bool flip = frontFacing && ((bone.worldFlipX != bone.worldFlipY) == worldScaleIsSameSigns); attachmentsFlipStateTemp.Items[i] = flip; attachmentsTriangleCountTemp.Items[i] = -1; RegionAttachment regionAttachment = attachment as RegionAttachment; if (regionAttachment != null) { rendererObject = regionAttachment.RendererObject; attachmentVertexCount = 4; attachmentTriangleCount = 6; } else { if (!renderMeshes) continue; MeshAttachment meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) { rendererObject = meshAttachment.RendererObject; attachmentVertexCount = meshAttachment.vertices.Length >> 1; attachmentTriangleCount = meshAttachment.triangles.Length; } else { SkinnedMeshAttachment skinnedMeshAttachment = attachment as SkinnedMeshAttachment; if (skinnedMeshAttachment != null) { rendererObject = skinnedMeshAttachment.RendererObject; attachmentVertexCount = skinnedMeshAttachment.uvs.Length >> 1; attachmentTriangleCount = skinnedMeshAttachment.triangles.Length; } else continue; } } // Populate submesh when material changes. #if !SPINE_TK2D Material material = (Material)((AtlasRegion)rendererObject).page.rendererObject; #else Material material = (rendererObject.GetType() == typeof(Material)) ? (Material)rendererObject : (Material)((AtlasRegion)rendererObject).page.rendererObject; #endif if ((lastMaterial != null && lastMaterial.GetInstanceID() != material.GetInstanceID()) || (submeshSeparatorSlotsCount > 0 && submeshSeparatorSlots.Contains(slot))) { addSubmeshArgumentsTemp.Add( new LastState.AddSubmeshArguments(lastMaterial, submeshStartSlotIndex, i, submeshTriangleCount, submeshFirstVertex, false) ); submeshTriangleCount = 0; submeshFirstVertex = vertexCount; submeshStartSlotIndex = i; } lastMaterial = material; submeshTriangleCount += attachmentTriangleCount; vertexCount += attachmentVertexCount; attachmentsTriangleCountTemp.Items[i] = attachmentTriangleCount; } addSubmeshArgumentsTemp.Add( new LastState.AddSubmeshArguments(lastMaterial, submeshStartSlotIndex, drawOrderCount, submeshTriangleCount, submeshFirstVertex, true) ); bool mustUpdateMeshStructure = CheckIfMustUpdateMeshStructure(attachmentsTriangleCountTemp, attachmentsFlipStateTemp, addSubmeshArgumentsTemp); if (mustUpdateMeshStructure) { submeshMaterials.Clear(); for (int i = 0, n = addSubmeshArgumentsTemp.Count; i < n; i++) { LastState.AddSubmeshArguments arguments = addSubmeshArgumentsTemp.Items[i]; AddSubmesh( arguments.material, arguments.startSlot, arguments.endSlot, arguments.triangleCount, arguments.firstVertex, arguments.lastSubmesh, attachmentsFlipStateTemp ); } // Set materials. if (submeshMaterials.Count == sharedMaterials.Length) submeshMaterials.CopyTo(sharedMaterials); else sharedMaterials = submeshMaterials.ToArray(); meshRenderer.sharedMaterials = sharedMaterials; } // Ensure mesh data is the right size. Vector3[] vertices = this.vertices; bool newTriangles = vertexCount > vertices.Length; if (newTriangles) { // Not enough vertices, increase size. this.vertices = vertices = new Vector3[vertexCount]; this.colors = new Color32[vertexCount]; this.uvs = new Vector2[vertexCount]; mesh1.Clear(); mesh2.Clear(); } else { // Too many vertices, zero the extra. Vector3 zero = Vector3.zero; for (int i = vertexCount, n = lastState.vertexCount ; i < n; i++) vertices[i] = zero; } lastState.vertexCount = vertexCount; // Setup mesh. float zSpacing = this.zSpacing; float[] tempVertices = this.tempVertices; Vector2[] uvs = this.uvs; Color32[] colors = this.colors; int vertexIndex = 0; Color32 color; float a = skeleton.a * 255, r = skeleton.r, g = skeleton.g, b = skeleton.b; Vector3 meshBoundsMin; meshBoundsMin.x = float.MaxValue; meshBoundsMin.y = float.MaxValue; meshBoundsMin.z = zSpacing > 0f ? 0f : zSpacing * (drawOrderCount - 1); Vector3 meshBoundsMax; meshBoundsMax.x = float.MinValue; meshBoundsMax.y = float.MinValue; meshBoundsMax.z = zSpacing < 0f ? 0f : zSpacing * (drawOrderCount - 1); for (int i = 0; i < drawOrderCount; i++) { Slot slot = drawOrder.Items[i]; Attachment attachment = slot.attachment; RegionAttachment regionAttachment = attachment as RegionAttachment; if (regionAttachment != null) { regionAttachment.ComputeWorldVertices(slot.bone, tempVertices); float z = i * zSpacing; vertices[vertexIndex].x = tempVertices[RegionAttachment.X1]; vertices[vertexIndex].y = tempVertices[RegionAttachment.Y1]; vertices[vertexIndex].z = z; vertices[vertexIndex + 1].x = tempVertices[RegionAttachment.X4]; vertices[vertexIndex + 1].y = tempVertices[RegionAttachment.Y4]; vertices[vertexIndex + 1].z = z; vertices[vertexIndex + 2].x = tempVertices[RegionAttachment.X2]; vertices[vertexIndex + 2].y = tempVertices[RegionAttachment.Y2]; vertices[vertexIndex + 2].z = z; vertices[vertexIndex + 3].x = tempVertices[RegionAttachment.X3]; vertices[vertexIndex + 3].y = tempVertices[RegionAttachment.Y3]; vertices[vertexIndex + 3].z = z; color.a = (byte)(a * slot.a * regionAttachment.a); color.r = (byte)(r * slot.r * regionAttachment.r * color.a); color.g = (byte)(g * slot.g * regionAttachment.g * color.a); color.b = (byte)(b * slot.b * regionAttachment.b * color.a); if (slot.data.blendMode == BlendMode.additive) color.a = 0; colors[vertexIndex] = color; colors[vertexIndex + 1] = color; colors[vertexIndex + 2] = color; colors[vertexIndex + 3] = color; float[] regionUVs = regionAttachment.uvs; uvs[vertexIndex].x = regionUVs[RegionAttachment.X1]; uvs[vertexIndex].y = regionUVs[RegionAttachment.Y1]; uvs[vertexIndex + 1].x = regionUVs[RegionAttachment.X4]; uvs[vertexIndex + 1].y = regionUVs[RegionAttachment.Y4]; uvs[vertexIndex + 2].x = regionUVs[RegionAttachment.X2]; uvs[vertexIndex + 2].y = regionUVs[RegionAttachment.Y2]; uvs[vertexIndex + 3].x = regionUVs[RegionAttachment.X3]; uvs[vertexIndex + 3].y = regionUVs[RegionAttachment.Y3]; // Calculate min/max X if (tempVertices[RegionAttachment.X1] < meshBoundsMin.x) meshBoundsMin.x = tempVertices[RegionAttachment.X1]; else if (tempVertices[RegionAttachment.X1] > meshBoundsMax.x) meshBoundsMax.x = tempVertices[RegionAttachment.X1]; if (tempVertices[RegionAttachment.X2] < meshBoundsMin.x) meshBoundsMin.x = tempVertices[RegionAttachment.X2]; else if (tempVertices[RegionAttachment.X2] > meshBoundsMax.x) meshBoundsMax.x = tempVertices[RegionAttachment.X2]; if (tempVertices[RegionAttachment.X3] < meshBoundsMin.x) meshBoundsMin.x = tempVertices[RegionAttachment.X3]; else if (tempVertices[RegionAttachment.X3] > meshBoundsMax.x) meshBoundsMax.x = tempVertices[RegionAttachment.X3]; if (tempVertices[RegionAttachment.X4] < meshBoundsMin.x) meshBoundsMin.x = tempVertices[RegionAttachment.X4]; else if (tempVertices[RegionAttachment.X4] > meshBoundsMax.x) meshBoundsMax.x = tempVertices[RegionAttachment.X4]; // Calculate min/max Y if (tempVertices[RegionAttachment.Y1] < meshBoundsMin.y) meshBoundsMin.y = tempVertices[RegionAttachment.Y1]; else if (tempVertices[RegionAttachment.Y1] > meshBoundsMax.y) meshBoundsMax.y = tempVertices[RegionAttachment.Y1]; if (tempVertices[RegionAttachment.Y2] < meshBoundsMin.y) meshBoundsMin.y = tempVertices[RegionAttachment.Y2]; else if (tempVertices[RegionAttachment.Y2] > meshBoundsMax.y) meshBoundsMax.y = tempVertices[RegionAttachment.Y2]; if (tempVertices[RegionAttachment.Y3] < meshBoundsMin.y) meshBoundsMin.y = tempVertices[RegionAttachment.Y3]; else if (tempVertices[RegionAttachment.Y3] > meshBoundsMax.y) meshBoundsMax.y = tempVertices[RegionAttachment.Y3]; if (tempVertices[RegionAttachment.Y4] < meshBoundsMin.y) meshBoundsMin.y = tempVertices[RegionAttachment.Y4]; else if (tempVertices[RegionAttachment.Y4] > meshBoundsMax.y) meshBoundsMax.y = tempVertices[RegionAttachment.Y4]; vertexIndex += 4; } else { if (!renderMeshes) continue; MeshAttachment meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) { int meshVertexCount = meshAttachment.vertices.Length; if (tempVertices.Length < meshVertexCount) this.tempVertices = tempVertices = new float[meshVertexCount]; meshAttachment.ComputeWorldVertices(slot, tempVertices); color.a = (byte)(a * slot.a * meshAttachment.a); color.r = (byte)(r * slot.r * meshAttachment.r * color.a); color.g = (byte)(g * slot.g * meshAttachment.g * color.a); color.b = (byte)(b * slot.b * meshAttachment.b * color.a); if (slot.data.blendMode == BlendMode.additive) color.a = 0; float[] meshUVs = meshAttachment.uvs; float z = i * zSpacing; for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) { vertices[vertexIndex].x = tempVertices[ii]; vertices[vertexIndex].y = tempVertices[ii + 1]; vertices[vertexIndex].z = z; colors[vertexIndex] = color; uvs[vertexIndex].x = meshUVs[ii]; uvs[vertexIndex].y = meshUVs[ii + 1]; if (tempVertices[ii] < meshBoundsMin.x) meshBoundsMin.x = tempVertices[ii]; else if (tempVertices[ii] > meshBoundsMax.x) meshBoundsMax.x = tempVertices[ii]; if (tempVertices[ii + 1]< meshBoundsMin.y) meshBoundsMin.y = tempVertices[ii + 1]; else if (tempVertices[ii + 1] > meshBoundsMax.y) meshBoundsMax.y = tempVertices[ii + 1]; } } else { SkinnedMeshAttachment skinnedMeshAttachment = attachment as SkinnedMeshAttachment; if (skinnedMeshAttachment != null) { int meshVertexCount = skinnedMeshAttachment.uvs.Length; if (tempVertices.Length < meshVertexCount) this.tempVertices = tempVertices = new float[meshVertexCount]; skinnedMeshAttachment.ComputeWorldVertices(slot, tempVertices); color.a = (byte)(a * slot.a * skinnedMeshAttachment.a); color.r = (byte)(r * slot.r * skinnedMeshAttachment.r * color.a); color.g = (byte)(g * slot.g * skinnedMeshAttachment.g * color.a); color.b = (byte)(b * slot.b * skinnedMeshAttachment.b * color.a); if (slot.data.blendMode == BlendMode.additive) color.a = 0; float[] meshUVs = skinnedMeshAttachment.uvs; float z = i * zSpacing; for (int ii = 0; ii < meshVertexCount; ii += 2, vertexIndex++) { vertices[vertexIndex].x = tempVertices[ii]; vertices[vertexIndex].y = tempVertices[ii + 1]; vertices[vertexIndex].z = z; colors[vertexIndex] = color; uvs[vertexIndex].x = meshUVs[ii]; uvs[vertexIndex].y = meshUVs[ii + 1]; if (tempVertices[ii] < meshBoundsMin.x) meshBoundsMin.x = tempVertices[ii]; else if (tempVertices[ii] > meshBoundsMax.x) meshBoundsMax.x = tempVertices[ii]; if (tempVertices[ii + 1]< meshBoundsMin.y) meshBoundsMin.y = tempVertices[ii + 1]; else if (tempVertices[ii + 1] > meshBoundsMax.y) meshBoundsMax.y = tempVertices[ii + 1]; } } } } } // Double buffer mesh. Mesh mesh = useMesh1 ? mesh1 : mesh2; meshFilter.sharedMesh = mesh; mesh.vertices = vertices; mesh.colors32 = colors; mesh.uv = uvs; if (mustUpdateMeshStructure) { int submeshCount = submeshMaterials.Count; mesh.subMeshCount = submeshCount; for (int i = 0; i < submeshCount; ++i) mesh.SetTriangles(submeshes.Items[i].triangles, i); } Vector3 meshBoundsExtents = meshBoundsMax - meshBoundsMin; Vector3 meshBoundsCenter = meshBoundsMin + meshBoundsExtents * 0.5f; mesh.bounds = new Bounds(meshBoundsCenter, meshBoundsExtents); if (newTriangles && calculateNormals) { Vector3[] normals = new Vector3[vertexCount]; Vector3 normal = new Vector3(0, 0, -1); for (int i = 0; i < vertexCount; i++) normals[i] = normal; (useMesh1 ? mesh2 : mesh1).vertices = vertices; // Set other mesh vertices. mesh1.normals = normals; mesh2.normals = normals; if (calculateTangents) { Vector4[] tangents = new Vector4[vertexCount]; Vector3 tangent = new Vector3(0, 0, 1); for (int i = 0; i < vertexCount; i++) tangents[i] = tangent; mesh1.tangents = tangents; mesh2.tangents = tangents; } } // Update previous state ExposedList<int> attachmentsTriangleCountCurrentMesh; ExposedList<bool> attachmentsFlipStateCurrentMesh; ExposedList<LastState.AddSubmeshArguments> addSubmeshArgumentsCurrentMesh; if (useMesh1) { attachmentsTriangleCountCurrentMesh = lastState.attachmentsTriangleCountMesh1; addSubmeshArgumentsCurrentMesh = lastState.addSubmeshArgumentsMesh1; attachmentsFlipStateCurrentMesh = lastState.attachmentsFlipStateMesh1; lastState.immutableTrianglesMesh1 = immutableTriangles; } else { attachmentsTriangleCountCurrentMesh = lastState.attachmentsTriangleCountMesh2; addSubmeshArgumentsCurrentMesh = lastState.addSubmeshArgumentsMesh2; attachmentsFlipStateCurrentMesh = lastState.attachmentsFlipStateMesh2; lastState.immutableTrianglesMesh2 = immutableTriangles; } attachmentsTriangleCountCurrentMesh.GrowIfNeeded(attachmentsTriangleCountTemp.Capacity); attachmentsTriangleCountCurrentMesh.Count = attachmentsTriangleCountTemp.Count; attachmentsTriangleCountTemp.CopyTo(attachmentsTriangleCountCurrentMesh.Items, 0); attachmentsFlipStateCurrentMesh.GrowIfNeeded(attachmentsFlipStateTemp.Capacity); attachmentsFlipStateCurrentMesh.Count = attachmentsFlipStateTemp.Count; attachmentsFlipStateTemp.CopyTo(attachmentsFlipStateCurrentMesh.Items, 0); addSubmeshArgumentsCurrentMesh.GrowIfNeeded(addSubmeshArgumentsTemp.Count); addSubmeshArgumentsCurrentMesh.Count = addSubmeshArgumentsTemp.Count; addSubmeshArgumentsTemp.CopyTo(addSubmeshArgumentsCurrentMesh.Items); if (submeshRenderers.Length > 0) { for (int i = 0; i < submeshRenderers.Length; i++) { SkeletonUtilitySubmeshRenderer submeshRenderer = submeshRenderers[i]; if (submeshRenderer.submeshIndex < sharedMaterials.Length) { submeshRenderer.SetMesh(meshRenderer, useMesh1 ? mesh1 : mesh2, sharedMaterials[submeshRenderer.submeshIndex]); } else { submeshRenderer.GetComponent<Renderer>().enabled = false; } } } useMesh1 = !useMesh1; } private bool CheckIfMustUpdateMeshStructure(ExposedList<int> attachmentsTriangleCountTemp, ExposedList<bool> attachmentsFlipStateTemp, ExposedList<LastState.AddSubmeshArguments> addSubmeshArgumentsTemp) { // Check if any mesh settings were changed bool mustUpdateMeshStructure = immutableTriangles != (useMesh1 ? lastState.immutableTrianglesMesh1 : lastState.immutableTrianglesMesh2); #if UNITY_EDITOR mustUpdateMeshStructure |= !Application.isPlaying; #endif if (mustUpdateMeshStructure) return true; // Check if any attachments were enabled/disabled // or submesh structures has changed ExposedList<int> attachmentsTriangleCountCurrentMesh; ExposedList<bool> attachmentsFlipStateCurrentMesh; ExposedList<LastState.AddSubmeshArguments> addSubmeshArgumentsCurrentMesh; if (useMesh1) { attachmentsTriangleCountCurrentMesh = lastState.attachmentsTriangleCountMesh1; addSubmeshArgumentsCurrentMesh = lastState.addSubmeshArgumentsMesh1; attachmentsFlipStateCurrentMesh = lastState.attachmentsFlipStateMesh1; } else { attachmentsTriangleCountCurrentMesh = lastState.attachmentsTriangleCountMesh2; addSubmeshArgumentsCurrentMesh = lastState.addSubmeshArgumentsMesh2; attachmentsFlipStateCurrentMesh = lastState.attachmentsFlipStateMesh2; } // Check attachments int attachmentCount = attachmentsTriangleCountTemp.Count; if (attachmentsTriangleCountCurrentMesh.Count != attachmentCount) return true; for (int i = 0; i < attachmentCount; i++) { if (attachmentsTriangleCountCurrentMesh.Items[i] != attachmentsTriangleCountTemp.Items[i]) return true; } // Check flip state for (int i = 0; i < attachmentCount; i++) { if (attachmentsFlipStateCurrentMesh.Items[i] != attachmentsFlipStateTemp.Items[i]) return true; } // Check submeshes int submeshCount = addSubmeshArgumentsTemp.Count; if (addSubmeshArgumentsCurrentMesh.Count != submeshCount) return true; for (int i = 0; i < submeshCount; i++) { if (!addSubmeshArgumentsCurrentMesh.Items[i].Equals(ref addSubmeshArgumentsTemp.Items[i])) return true; } return false; } /** Stores vertices and triangles for a single material. */ private void AddSubmesh (Material material, int startSlot, int endSlot, int triangleCount, int firstVertex, bool lastSubmesh, ExposedList<bool> flipStates) { int submeshIndex = submeshMaterials.Count; submeshMaterials.Add(material); if (submeshes.Count <= submeshIndex) submeshes.Add(new Submesh()); else if (immutableTriangles) return; Submesh submesh = submeshes.Items[submeshIndex]; int[] triangles = submesh.triangles; int trianglesCapacity = triangles.Length; if (lastSubmesh && trianglesCapacity > triangleCount) { // Last submesh may have more triangles than required, so zero triangles to the end. for (int i = triangleCount; i < trianglesCapacity; i++) triangles[i] = 0; submesh.triangleCount = triangleCount; } else if (trianglesCapacity != triangleCount) { // Reallocate triangles when not the exact size needed. submesh.triangles = triangles = new int[triangleCount]; submesh.triangleCount = 0; } if (!renderMeshes && !frontFacing) { // Use stored triangles if possible. if (submesh.firstVertex != firstVertex || submesh.triangleCount < triangleCount) { submesh.triangleCount = triangleCount; submesh.firstVertex = firstVertex; int drawOrderIndex = 0; for (int i = 0; i < triangleCount; i += 6, firstVertex += 4, drawOrderIndex++) { triangles[i] = firstVertex; triangles[i + 1] = firstVertex + 2; triangles[i + 2] = firstVertex + 1; triangles[i + 3] = firstVertex + 2; triangles[i + 4] = firstVertex + 3; triangles[i + 5] = firstVertex + 1; } } return; } // Store triangles. ExposedList<Slot> drawOrder = skeleton.DrawOrder; for (int i = startSlot, triangleIndex = 0; i < endSlot; i++) { Slot slot = drawOrder.Items[i]; Attachment attachment = slot.attachment; bool flip = flipStates.Items[i]; if (attachment is RegionAttachment) { if (!flip) { triangles[triangleIndex] = firstVertex; triangles[triangleIndex + 1] = firstVertex + 2; triangles[triangleIndex + 2] = firstVertex + 1; triangles[triangleIndex + 3] = firstVertex + 2; triangles[triangleIndex + 4] = firstVertex + 3; triangles[triangleIndex + 5] = firstVertex + 1; } else { triangles[triangleIndex] = firstVertex + 1; triangles[triangleIndex + 1] = firstVertex + 2; triangles[triangleIndex + 2] = firstVertex; triangles[triangleIndex + 3] = firstVertex + 1; triangles[triangleIndex + 4] = firstVertex + 3; triangles[triangleIndex + 5] = firstVertex + 2; } triangleIndex += 6; firstVertex += 4; continue; } int[] attachmentTriangles; int attachmentVertexCount; MeshAttachment meshAttachment = attachment as MeshAttachment; if (meshAttachment != null) { attachmentVertexCount = meshAttachment.vertices.Length >> 1; attachmentTriangles = meshAttachment.triangles; } else { SkinnedMeshAttachment skinnedMeshAttachment = attachment as SkinnedMeshAttachment; if (skinnedMeshAttachment != null) { attachmentVertexCount = skinnedMeshAttachment.uvs.Length >> 1; attachmentTriangles = skinnedMeshAttachment.triangles; } else continue; } if (flip) { for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii += 3, triangleIndex += 3) { triangles[triangleIndex + 2] = firstVertex + attachmentTriangles[ii]; triangles[triangleIndex + 1] = firstVertex + attachmentTriangles[ii + 1]; triangles[triangleIndex] = firstVertex + attachmentTriangles[ii + 2]; } } else { for (int ii = 0, nn = attachmentTriangles.Length; ii < nn; ii++, triangleIndex++) { triangles[triangleIndex] = firstVertex + attachmentTriangles[ii]; } } firstVertex += attachmentVertexCount; } } #if UNITY_EDITOR void OnDrawGizmos () { // Make selection easier by drawing a clear gizmo over the skeleton. meshFilter = GetComponent<MeshFilter>(); if (meshFilter == null) return; Mesh mesh = meshFilter.sharedMesh; if (mesh == null) return; Bounds meshBounds = mesh.bounds; Gizmos.color = Color.clear; Gizmos.matrix = transform.localToWorldMatrix; Gizmos.DrawCube(meshBounds.center, meshBounds.size); } #endif private class LastState { public bool immutableTrianglesMesh1; public bool immutableTrianglesMesh2; public int vertexCount; public readonly ExposedList<bool> attachmentsFlipStateTemp = new ExposedList<bool>(); public readonly ExposedList<bool> attachmentsFlipStateMesh1 = new ExposedList<bool>(); public readonly ExposedList<bool> attachmentsFlipStateMesh2 = new ExposedList<bool>(); public readonly ExposedList<int> attachmentsTriangleCountTemp = new ExposedList<int>(); public readonly ExposedList<int> attachmentsTriangleCountMesh1 = new ExposedList<int>(); public readonly ExposedList<int> attachmentsTriangleCountMesh2 = new ExposedList<int>(); public readonly ExposedList<AddSubmeshArguments> addSubmeshArgumentsTemp = new ExposedList<AddSubmeshArguments>(); public readonly ExposedList<AddSubmeshArguments> addSubmeshArgumentsMesh1 = new ExposedList<AddSubmeshArguments>(); public readonly ExposedList<AddSubmeshArguments> addSubmeshArgumentsMesh2 = new ExposedList<AddSubmeshArguments>(); public struct AddSubmeshArguments { public Material material; public int startSlot; public int endSlot; public int triangleCount; public int firstVertex; public bool lastSubmesh; public AddSubmeshArguments(Material material, int startSlot, int endSlot, int triangleCount, int firstVertex, bool lastSubmesh) { this.material = material; this.startSlot = startSlot; this.endSlot = endSlot; this.triangleCount = triangleCount; this.firstVertex = firstVertex; this.lastSubmesh = lastSubmesh; } public bool Equals(ref AddSubmeshArguments other) { return !ReferenceEquals(material, null) && !ReferenceEquals(other.material, null) && material.GetInstanceID() == other.material.GetInstanceID() && startSlot == other.startSlot && endSlot == other.endSlot && triangleCount == other.triangleCount && firstVertex == other.firstVertex; } } } } class Submesh { public int[] triangles = new int[0]; public int triangleCount; public int firstVertex = -1; }
//------------------------------------------------------------------------------ // <copyright file="SoapServerMethod.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Services.Protocols { using System; using System.Collections.Generic; using System.Reflection; using System.Web.Services; using System.Web.Services.Description; using System.Xml; using System.Xml.Serialization; using System.Security; using System.Security.Permissions; using System.Security.Policy; using System.Web.Services.Diagnostics; [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public sealed class SoapServerMethod { // // Internal field visibility is maintained for // compatibility with existing code. // internal LogicalMethodInfo methodInfo; internal XmlSerializer returnSerializer; internal XmlSerializer parameterSerializer; internal XmlSerializer inHeaderSerializer; internal XmlSerializer outHeaderSerializer; internal SoapHeaderMapping[] inHeaderMappings; internal SoapHeaderMapping[] outHeaderMappings; internal SoapReflectedExtension[] extensions; internal object[] extensionInitializers; internal string action; internal bool oneWay; internal bool rpc; internal SoapBindingUse use; internal SoapParameterStyle paramStyle; internal WsiProfiles wsiClaims; public SoapServerMethod() { } public SoapServerMethod(Type serverType, LogicalMethodInfo methodInfo) { this.methodInfo = methodInfo; // // Set up the XmlImporter, the SoapImporter, and acquire // the ServiceAttribute on the serverType for use in // creating a SoapReflectedMethod. // WebServiceAttribute serviceAttribute = WebServiceReflector.GetAttribute(serverType); string serviceNamespace = serviceAttribute.Namespace; bool serviceDefaultIsEncoded = SoapReflector.ServiceDefaultIsEncoded(serverType); SoapReflectionImporter soapImporter = SoapReflector.CreateSoapImporter(serviceNamespace, serviceDefaultIsEncoded); XmlReflectionImporter xmlImporter = SoapReflector.CreateXmlImporter(serviceNamespace, serviceDefaultIsEncoded); // // Add some types relating to the methodInfo into the two importers // SoapReflector.IncludeTypes(methodInfo, soapImporter); WebMethodReflector.IncludeTypes(methodInfo, xmlImporter); // // Create a SoapReflectedMethod by reflecting on the // LogicalMethodInfo passed to us. // SoapReflectedMethod soapMethod = SoapReflector.ReflectMethod(methodInfo, false, xmlImporter, soapImporter, serviceNamespace); // // Most of the fields in this class are ----ed in from the reflected information // ImportReflectedMethod(soapMethod); ImportSerializers(soapMethod, GetServerTypeEvidence(serverType)); ImportHeaderSerializers(soapMethod); } public LogicalMethodInfo MethodInfo { get { return methodInfo; } } public XmlSerializer ReturnSerializer { get { return returnSerializer; } } public XmlSerializer ParameterSerializer { get { return parameterSerializer; } } public XmlSerializer InHeaderSerializer { get { return inHeaderSerializer; } } public XmlSerializer OutHeaderSerializer { get { return outHeaderSerializer; } } // // public SoapHeaderMapping[] InHeaderMappings { get { return inHeaderMappings; } } // // public SoapHeaderMapping[] OutHeaderMappings { get { return outHeaderMappings; } } /* * WSE3 does not require access to Extension data * public SoapReflectedExtension[] Extensions { get { return extensions; } } public object[] ExtensionInitializers { get { return extensionInitializers; } } */ public string Action { get { return action; } } public bool OneWay { get { return oneWay; } } public bool Rpc { get { return rpc; } } public SoapBindingUse BindingUse { get { return use; } } public SoapParameterStyle ParameterStyle { get { return paramStyle; } } public WsiProfiles WsiClaims { get { return wsiClaims; } } [SecurityPermission(SecurityAction.Assert, ControlEvidence = true)] private Evidence GetServerTypeEvidence(Type type) { return type.Assembly.Evidence; } private List<XmlMapping> GetXmlMappingsForMethod(SoapReflectedMethod soapMethod) { List<XmlMapping> mappings = new List<XmlMapping>(); mappings.Add(soapMethod.requestMappings); if (soapMethod.responseMappings != null) { mappings.Add(soapMethod.responseMappings); } mappings.Add(soapMethod.inHeaderMappings); if (soapMethod.outHeaderMappings != null) { mappings.Add(soapMethod.outHeaderMappings); } return mappings; } private void ImportReflectedMethod(SoapReflectedMethod soapMethod) { this.action = soapMethod.action; this.extensions = soapMethod.extensions; this.extensionInitializers = SoapReflectedExtension.GetInitializers(this.methodInfo, soapMethod.extensions); this.oneWay = soapMethod.oneWay; this.rpc = soapMethod.rpc; this.use = soapMethod.use; this.paramStyle = soapMethod.paramStyle; this.wsiClaims = soapMethod.binding == null ? WsiProfiles.None : soapMethod.binding.ConformsTo; } private void ImportHeaderSerializers(SoapReflectedMethod soapMethod) { List<SoapHeaderMapping> inHeaders = new List<SoapHeaderMapping>(); List<SoapHeaderMapping> outHeaders = new List<SoapHeaderMapping>(); for (int j = 0; j < soapMethod.headers.Length; j++) { SoapHeaderMapping mapping = new SoapHeaderMapping(); SoapReflectedHeader soapHeader = soapMethod.headers[j]; mapping.memberInfo = soapHeader.memberInfo; mapping.repeats = soapHeader.repeats; mapping.custom = soapHeader.custom; mapping.direction = soapHeader.direction; mapping.headerType = soapHeader.headerType; if (mapping.direction == SoapHeaderDirection.In) inHeaders.Add(mapping); else if (mapping.direction == SoapHeaderDirection.Out) outHeaders.Add(mapping); else { inHeaders.Add(mapping); outHeaders.Add(mapping); } } this.inHeaderMappings = inHeaders.ToArray(); if (this.outHeaderSerializer != null) this.outHeaderMappings = outHeaders.ToArray(); } private void ImportSerializers(SoapReflectedMethod soapMethod, Evidence serverEvidence) { // // Keep track of all XmlMapping instances we need for this method. // List<XmlMapping> mappings = GetXmlMappingsForMethod(soapMethod); // // Generate serializers from those XmlMappings // XmlMapping[] xmlMappings = mappings.ToArray(); TraceMethod caller = Tracing.On ? new TraceMethod(this, "ImportSerializers") : null; if (Tracing.On) Tracing.Enter(Tracing.TraceId(Res.TraceCreateSerializer), caller, new TraceMethod(typeof(XmlSerializer), "FromMappings", xmlMappings, serverEvidence)); XmlSerializer[] serializers = null; if (AppDomain.CurrentDomain.IsHomogenous) { serializers = XmlSerializer.FromMappings(xmlMappings); } else { #pragma warning disable 618 // If we're in a non-homogenous domain, legacy CAS mode is enabled, so passing through evidence will not fail serializers = XmlSerializer.FromMappings(xmlMappings, serverEvidence); #pragma warning restore 618 } if (Tracing.On) Tracing.Exit(Tracing.TraceId(Res.TraceCreateSerializer), caller); int i = 0; this.parameterSerializer = serializers[i++]; if (soapMethod.responseMappings != null) { this.returnSerializer = serializers[i++]; } this.inHeaderSerializer = serializers[i++]; if (soapMethod.outHeaderMappings != null) { this.outHeaderSerializer = serializers[i++]; } } } }
// // NSData.cs: // Author: // Miguel de Icaza // // Copyright 2010, Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using MonoMac.ObjCRuntime; using System.IO; using System.Runtime.InteropServices; using System.Collections; using System.Collections.Generic; namespace MonoMac.Foundation { public partial class NSData : IEnumerable, IEnumerable<byte> { IEnumerator IEnumerable.GetEnumerator () { IntPtr source = Bytes; int top = (int) Length; for (int i = 0; i < top; i++){ yield return Marshal.ReadByte (source, i); } } IEnumerator<byte> IEnumerable<byte>.GetEnumerator () { IntPtr source = Bytes; int top = (int) Length; for (int i = 0; i < top; i++) yield return Marshal.ReadByte (source, i); } public static NSData FromString (string s) { if (s == null) throw new ArgumentNullException ("s"); return new NSString (s).Encode (NSStringEncoding.UTF8); } public static NSData FromArray (byte [] buffer) { if (buffer == null) throw new ArgumentNullException ("buffer"); unsafe { fixed (byte *ptr = &buffer [0]){ return FromBytes ((IntPtr) ptr, (uint) buffer.Length); } } } public static NSData FromStream (Stream stream) { if (stream == null) throw new ArgumentNullException ("stream"); if (!stream.CanRead) return null; NSMutableData ret = null; long len; try { len = stream.Length; } catch { len = 8192; } ret = NSMutableData.FromCapacity ((int)len); byte [] buffer = new byte [32*1024]; int n; try { unsafe { while ((n = stream.Read (buffer, 0, buffer.Length)) != 0){ fixed (byte *ptr = &buffer [0]) ret.AppendBytes ((IntPtr) ptr, (uint) n); } } } catch { return null; } return ret; } // // Keeps a ref to the source NSData // unsafe class UnmanagedMemoryStreamWithRef : UnmanagedMemoryStream { NSData source; public UnmanagedMemoryStreamWithRef (NSData source, byte *pointer, long length) : base (pointer, length) { this.source = source; } protected override void Dispose (bool disposing) { source = null; base.Dispose (disposing); } } public virtual Stream AsStream () { if (this is NSMutableData) throw new Exception ("Wrapper for NSMutableData is not supported, call new UnmanagedMemoryStream ((Byte*) mutableData.Bytes, mutableData.Length) instead"); unsafe { return new UnmanagedMemoryStreamWithRef (this, (byte *) Bytes, Length); } } public static NSData FromString (string s, NSStringEncoding encoding) { return new NSString (s).Encode (encoding); } public static implicit operator NSData (string s) { return new NSString (s).Encode (NSStringEncoding.UTF8); } public NSString ToString (NSStringEncoding encoding) { return NSString.FromData (this, encoding); } public override string ToString () { return ToString (NSStringEncoding.UTF8); } public bool Save (string file, bool auxiliaryFile, out NSError error) { unsafe { IntPtr val; IntPtr val_addr = (IntPtr) ((IntPtr *) &val); bool ret = _Save (file, auxiliaryFile ? 1 : 0, val_addr); error = (NSError) Runtime.GetNSObject (val); return ret; } } public bool Save (string file, NSDataWritingOptions options, out NSError error) { unsafe { IntPtr val; IntPtr val_addr = (IntPtr) ((IntPtr *) &val); bool ret = _Save (file, (int) options, val_addr); error = (NSError) Runtime.GetNSObject (val); return ret; } } public bool Save (NSUrl url, bool auxiliaryFile, out NSError error) { unsafe { IntPtr val; IntPtr val_addr = (IntPtr) ((IntPtr *) &val); bool ret = _Save (url, auxiliaryFile ? 1 : 0, val_addr); error = (NSError) Runtime.GetNSObject (val); return ret; } } public virtual byte this [int idx] { get { if (idx < 0 || idx >= Int32.MaxValue || idx > (int) Length) throw new ArgumentException ("idx"); return Marshal.ReadByte (Bytes, idx); } set { throw new NotImplementedException ("NSData arrays can not be modified, use an NSMUtableData instead"); } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Ntfs { using System; using System.Globalization; using System.IO; internal class BiosParameterBlock { public string OemId; public ushort BytesPerSector; public byte SectorsPerCluster; public ushort ReservedSectors; // Must be 0 public byte NumFats; // Must be 0 public ushort FatRootEntriesCount; // Must be 0 public ushort TotalSectors16; // Must be 0 public byte Media; // Must be 0xF8 public ushort FatSize16; // Must be 0 public ushort SectorsPerTrack; // Value: 0x3F 0x00 public ushort NumHeads; // Value: 0xFF 0x00 public uint HiddenSectors; // Value: 0x3F 0x00 0x00 0x00 public uint TotalSectors32; // Must be 0 public byte BiosDriveNumber; // Value: 0x80 (first hard disk) public byte ChkDskFlags; // Value: 0x00 public byte SignatureByte; // Value: 0x80 public byte PaddingByte; // Value: 0x00 public long TotalSectors64; public long MftCluster; public long MftMirrorCluster; public byte RawMftRecordSize; public byte RawIndexBufferSize; public ulong VolumeSerialNumber; public int MftRecordSize { get { return CalcRecordSize(RawMftRecordSize); } } public int IndexBufferSize { get { return CalcRecordSize(RawIndexBufferSize); } } public int BytesPerCluster { get { return ((int)BytesPerSector) * ((int)SectorsPerCluster); } } public void Dump(TextWriter writer, string linePrefix) { writer.WriteLine(linePrefix + "BIOS PARAMETER BLOCK (BPB)"); writer.WriteLine(linePrefix + " OEM ID: " + OemId); writer.WriteLine(linePrefix + " Bytes per Sector: " + BytesPerSector); writer.WriteLine(linePrefix + " Sectors per Cluster: " + SectorsPerCluster); writer.WriteLine(linePrefix + " Reserved Sectors: " + ReservedSectors); writer.WriteLine(linePrefix + " # FATs: " + NumFats); writer.WriteLine(linePrefix + " # FAT Root Entries: " + FatRootEntriesCount); writer.WriteLine(linePrefix + " Total Sectors (16b): " + TotalSectors16); writer.WriteLine(linePrefix + " Media: " + Media.ToString("X", CultureInfo.InvariantCulture) + "h"); writer.WriteLine(linePrefix + " FAT size (16b): " + FatSize16); writer.WriteLine(linePrefix + " Sectors per Track: " + SectorsPerTrack); writer.WriteLine(linePrefix + " # Heads: " + NumHeads); writer.WriteLine(linePrefix + " Hidden Sectors: " + HiddenSectors); writer.WriteLine(linePrefix + " Total Sectors (32b): " + TotalSectors32); writer.WriteLine(linePrefix + " BIOS Drive Number: " + BiosDriveNumber); writer.WriteLine(linePrefix + " Chkdsk Flags: " + ChkDskFlags); writer.WriteLine(linePrefix + " Signature Byte: " + SignatureByte); writer.WriteLine(linePrefix + " Total Sectors (64b): " + TotalSectors64); writer.WriteLine(linePrefix + " MFT Record Size: " + RawMftRecordSize); writer.WriteLine(linePrefix + " Index Buffer Size: " + RawIndexBufferSize); writer.WriteLine(linePrefix + " Volume Serial Number: " + VolumeSerialNumber); } internal static BiosParameterBlock Initialized(Geometry diskGeometry, int clusterSize, uint partitionStartLba, long partitionSizeLba, int mftRecordSize, int indexBufferSize) { BiosParameterBlock bpb = new BiosParameterBlock(); bpb.OemId = "NTFS "; bpb.BytesPerSector = Sizes.Sector; bpb.SectorsPerCluster = (byte)(clusterSize / bpb.BytesPerSector); bpb.ReservedSectors = 0; bpb.NumFats = 0; bpb.FatRootEntriesCount = 0; bpb.TotalSectors16 = 0; bpb.Media = 0xF8; bpb.FatSize16 = 0; bpb.SectorsPerTrack = (ushort)diskGeometry.SectorsPerTrack; bpb.NumHeads = (ushort)diskGeometry.HeadsPerCylinder; bpb.HiddenSectors = partitionStartLba; bpb.TotalSectors32 = 0; bpb.BiosDriveNumber = 0x80; bpb.ChkDskFlags = 0; bpb.SignatureByte = 0x80; bpb.PaddingByte = 0; bpb.TotalSectors64 = partitionSizeLba - 1; bpb.RawMftRecordSize = bpb.CodeRecordSize(mftRecordSize); bpb.RawIndexBufferSize = bpb.CodeRecordSize(indexBufferSize); bpb.VolumeSerialNumber = GenSerialNumber(); return bpb; } internal static BiosParameterBlock FromBytes(byte[] bytes, int offset) { BiosParameterBlock bpb = new BiosParameterBlock(); bpb.OemId = Utilities.BytesToString(bytes, offset + 0x03, 8); bpb.BytesPerSector = Utilities.ToUInt16LittleEndian(bytes, offset + 0x0B); bpb.SectorsPerCluster = bytes[offset + 0x0D]; bpb.ReservedSectors = Utilities.ToUInt16LittleEndian(bytes, offset + 0x0E); bpb.NumFats = bytes[offset + 0x10]; bpb.FatRootEntriesCount = Utilities.ToUInt16LittleEndian(bytes, offset + 0x11); bpb.TotalSectors16 = Utilities.ToUInt16LittleEndian(bytes, offset + 0x13); bpb.Media = bytes[offset + 0x15]; bpb.FatSize16 = Utilities.ToUInt16LittleEndian(bytes, offset + 0x16); bpb.SectorsPerTrack = Utilities.ToUInt16LittleEndian(bytes, offset + 0x18); bpb.NumHeads = Utilities.ToUInt16LittleEndian(bytes, offset + 0x1A); bpb.HiddenSectors = Utilities.ToUInt32LittleEndian(bytes, offset + 0x1C); bpb.TotalSectors32 = Utilities.ToUInt32LittleEndian(bytes, offset + 0x20); bpb.BiosDriveNumber = bytes[offset + 0x24]; bpb.ChkDskFlags = bytes[offset + 0x25]; bpb.SignatureByte = bytes[offset + 0x26]; bpb.PaddingByte = bytes[offset + 0x27]; bpb.TotalSectors64 = Utilities.ToInt64LittleEndian(bytes, offset + 0x28); bpb.MftCluster = Utilities.ToInt64LittleEndian(bytes, offset + 0x30); bpb.MftMirrorCluster = Utilities.ToInt64LittleEndian(bytes, offset + 0x38); bpb.RawMftRecordSize = bytes[offset + 0x40]; bpb.RawIndexBufferSize = bytes[offset + 0x44]; bpb.VolumeSerialNumber = Utilities.ToUInt64LittleEndian(bytes, offset + 0x48); return bpb; } internal void ToBytes(byte[] buffer, int offset) { Utilities.StringToBytes(OemId, buffer, offset + 0x03, 8); Utilities.WriteBytesLittleEndian(BytesPerSector, buffer, offset + 0x0B); buffer[offset + 0x0D] = SectorsPerCluster; Utilities.WriteBytesLittleEndian(ReservedSectors, buffer, offset + 0x0E); buffer[offset + 0x10] = NumFats; Utilities.WriteBytesLittleEndian(FatRootEntriesCount, buffer, offset + 0x11); Utilities.WriteBytesLittleEndian(TotalSectors16, buffer, offset + 0x13); buffer[offset + 0x15] = Media; Utilities.WriteBytesLittleEndian(FatSize16, buffer, offset + 0x16); Utilities.WriteBytesLittleEndian(SectorsPerTrack, buffer, offset + 0x18); Utilities.WriteBytesLittleEndian(NumHeads, buffer, offset + 0x1A); Utilities.WriteBytesLittleEndian(HiddenSectors, buffer, offset + 0x1C); Utilities.WriteBytesLittleEndian(TotalSectors32, buffer, offset + 0x20); buffer[offset + 0x24] = BiosDriveNumber; buffer[offset + 0x25] = ChkDskFlags; buffer[offset + 0x26] = SignatureByte; buffer[offset + 0x27] = PaddingByte; Utilities.WriteBytesLittleEndian(TotalSectors64, buffer, offset + 0x28); Utilities.WriteBytesLittleEndian(MftCluster, buffer, offset + 0x30); Utilities.WriteBytesLittleEndian(MftMirrorCluster, buffer, offset + 0x38); buffer[offset + 0x40] = RawMftRecordSize; buffer[offset + 0x44] = RawIndexBufferSize; Utilities.WriteBytesLittleEndian(VolumeSerialNumber, buffer, offset + 0x48); } internal int CalcRecordSize(byte rawSize) { if ((rawSize & 0x80) != 0) { return 1 << (-(sbyte)rawSize); } else { return rawSize * SectorsPerCluster * BytesPerSector; } } private static ulong GenSerialNumber() { byte[] buffer = new byte[8]; Random rng = new Random(); rng.NextBytes(buffer); return Utilities.ToUInt64LittleEndian(buffer, 0); } private byte CodeRecordSize(int size) { if (size >= BytesPerCluster) { return (byte)(size / BytesPerCluster); } else { sbyte val = 0; while (size != 1) { size = (size >> 1) & 0x7FFFFFFF; val++; } return (byte)-val; } } } }
// Copyright 2016 Mark Raasveldt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; namespace Tibialyzer { class HouseForm : NotificationForm { public House house; private System.Windows.Forms.PictureBox mapUpLevel; private System.Windows.Forms.PictureBox mapDownLevel; private Label routeButton; private Label expHourLabel; private Label cityLabel; private Label sizeLabel; private Label label1; private Label label2; private Label bedLabel; private Label tibiaButton; private Label statusHeader; private Label statusLabel; private Label timeLeftHeader; private Label timeLeftLabel; private static Font text_font = new Font(FontFamily.GenericSansSerif, 11, FontStyle.Bold); public HouseForm() { InitializeComponent(); } private const int headerLength = 5; private string[] headers = { "Sell To", "Buy From", "Spells", "Transport", "Quests" }; private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HouseForm)); this.mapBox = new Tibialyzer.MapPictureBox(); this.houseName = new System.Windows.Forms.Label(); this.mapUpLevel = new System.Windows.Forms.PictureBox(); this.mapDownLevel = new System.Windows.Forms.PictureBox(); this.routeButton = new System.Windows.Forms.Label(); this.expHourLabel = new System.Windows.Forms.Label(); this.cityLabel = new System.Windows.Forms.Label(); this.sizeLabel = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.bedLabel = new System.Windows.Forms.Label(); this.tibiaButton = new System.Windows.Forms.Label(); this.statusHeader = new System.Windows.Forms.Label(); this.statusLabel = new System.Windows.Forms.Label(); this.timeLeftHeader = new System.Windows.Forms.Label(); this.timeLeftLabel = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.mapBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.mapUpLevel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.mapDownLevel)).BeginInit(); this.SuspendLayout(); // // mapBox // this.mapBox.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.mapBox.Location = new System.Drawing.Point(121, 12); this.mapBox.Name = "mapBox"; this.mapBox.Size = new System.Drawing.Size(195, 190); this.mapBox.TabIndex = 0; this.mapBox.TabStop = false; // // houseName // this.houseName.BackColor = System.Drawing.Color.Transparent; this.houseName.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.houseName.ForeColor = System.Drawing.SystemColors.ControlLight; this.houseName.Location = new System.Drawing.Point(11, 27); this.houseName.MaximumSize = new System.Drawing.Size(100, 28); this.houseName.Name = "houseName"; this.houseName.Size = new System.Drawing.Size(100, 28); this.houseName.TabIndex = 2; this.houseName.Text = "Rashid"; this.houseName.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // mapUpLevel // this.mapUpLevel.Location = new System.Drawing.Point(121, 13); this.mapUpLevel.Name = "mapUpLevel"; this.mapUpLevel.Size = new System.Drawing.Size(21, 21); this.mapUpLevel.TabIndex = 3; this.mapUpLevel.TabStop = false; // // mapDownLevel // this.mapDownLevel.Location = new System.Drawing.Point(121, 34); this.mapDownLevel.Name = "mapDownLevel"; this.mapDownLevel.Size = new System.Drawing.Size(21, 21); this.mapDownLevel.TabIndex = 4; this.mapDownLevel.TabStop = false; // // routeButton // this.routeButton.BackColor = System.Drawing.Color.Transparent; this.routeButton.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.routeButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.routeButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.routeButton.Location = new System.Drawing.Point(12, 180); this.routeButton.Name = "routeButton"; this.routeButton.Padding = new System.Windows.Forms.Padding(2); this.routeButton.Size = new System.Drawing.Size(103, 21); this.routeButton.TabIndex = 16; this.routeButton.Text = "Route"; this.routeButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.routeButton.Click += new System.EventHandler(this.routeButton_Click); // // expHourLabel // this.expHourLabel.AutoSize = true; this.expHourLabel.BackColor = System.Drawing.Color.Transparent; this.expHourLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.expHourLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.expHourLabel.Location = new System.Drawing.Point(6, 79); this.expHourLabel.Name = "expHourLabel"; this.expHourLabel.Size = new System.Drawing.Size(28, 13); this.expHourLabel.TabIndex = 45; this.expHourLabel.Text = "City"; // // cityLabel // this.cityLabel.BackColor = System.Drawing.Color.Transparent; this.cityLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cityLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.cityLabel.Location = new System.Drawing.Point(40, 79); this.cityLabel.Name = "cityLabel"; this.cityLabel.Size = new System.Drawing.Size(80, 13); this.cityLabel.TabIndex = 46; this.cityLabel.Text = "Edron"; this.cityLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; // // sizeLabel // this.sizeLabel.BackColor = System.Drawing.Color.Transparent; this.sizeLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.sizeLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.sizeLabel.Location = new System.Drawing.Point(40, 95); this.sizeLabel.Name = "sizeLabel"; this.sizeLabel.Size = new System.Drawing.Size(80, 13); this.sizeLabel.TabIndex = 48; this.sizeLabel.Text = "50 sqm"; this.sizeLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.label1.Location = new System.Drawing.Point(6, 95); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(31, 13); this.label1.TabIndex = 47; this.label1.Text = "Size"; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.label2.Location = new System.Drawing.Point(6, 110); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(35, 13); this.label2.TabIndex = 49; this.label2.Text = "Beds"; // // bedLabel // this.bedLabel.BackColor = System.Drawing.Color.Transparent; this.bedLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.bedLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.bedLabel.Location = new System.Drawing.Point(40, 110); this.bedLabel.Name = "bedLabel"; this.bedLabel.Size = new System.Drawing.Size(80, 13); this.bedLabel.TabIndex = 50; this.bedLabel.Text = "3"; this.bedLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; // // tibiaButton // this.tibiaButton.BackColor = System.Drawing.Color.Transparent; this.tibiaButton.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.tibiaButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tibiaButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.tibiaButton.Location = new System.Drawing.Point(6, 57); this.tibiaButton.Name = "tibiaButton"; this.tibiaButton.Size = new System.Drawing.Size(110, 21); this.tibiaButton.TabIndex = 51; this.tibiaButton.Text = "View On Tibia.com"; this.tibiaButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.tibiaButton.Click += new System.EventHandler(this.tibiaButton_Click); // // statusHeader // this.statusHeader.AutoSize = true; this.statusHeader.BackColor = System.Drawing.Color.Transparent; this.statusHeader.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.statusHeader.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.statusHeader.Location = new System.Drawing.Point(6, 125); this.statusHeader.Name = "statusHeader"; this.statusHeader.Size = new System.Drawing.Size(43, 13); this.statusHeader.TabIndex = 52; this.statusHeader.Text = "Status"; // // statusLabel // this.statusLabel.BackColor = System.Drawing.Color.Transparent; this.statusLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.statusLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.statusLabel.Location = new System.Drawing.Point(40, 125); this.statusLabel.Name = "statusLabel"; this.statusLabel.Size = new System.Drawing.Size(80, 13); this.statusLabel.TabIndex = 53; this.statusLabel.Text = "Rented"; this.statusLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; // // timeLeftHeader // this.timeLeftHeader.AutoSize = true; this.timeLeftHeader.BackColor = System.Drawing.Color.Transparent; this.timeLeftHeader.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.timeLeftHeader.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.timeLeftHeader.Location = new System.Drawing.Point(6, 140); this.timeLeftHeader.Name = "timeLeftHeader"; this.timeLeftHeader.Size = new System.Drawing.Size(60, 13); this.timeLeftHeader.TabIndex = 54; this.timeLeftHeader.Text = "Time Left"; // // timeLeftLabel // this.timeLeftLabel.BackColor = System.Drawing.Color.Transparent; this.timeLeftLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.timeLeftLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.timeLeftLabel.Location = new System.Drawing.Point(40, 140); this.timeLeftLabel.Name = "timeLeftLabel"; this.timeLeftLabel.Size = new System.Drawing.Size(80, 13); this.timeLeftLabel.TabIndex = 55; this.timeLeftLabel.Text = "0h"; this.timeLeftLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; // // HouseForm // this.ClientSize = new System.Drawing.Size(328, 209); this.Controls.Add(this.timeLeftHeader); this.Controls.Add(this.timeLeftLabel); this.Controls.Add(this.statusHeader); this.Controls.Add(this.statusLabel); this.Controls.Add(this.tibiaButton); this.Controls.Add(this.label2); this.Controls.Add(this.bedLabel); this.Controls.Add(this.label1); this.Controls.Add(this.sizeLabel); this.Controls.Add(this.expHourLabel); this.Controls.Add(this.cityLabel); this.Controls.Add(this.routeButton); this.Controls.Add(this.mapDownLevel); this.Controls.Add(this.mapUpLevel); this.Controls.Add(this.houseName); this.Controls.Add(this.mapBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "HouseForm"; this.Text = "NPC Form"; ((System.ComponentModel.ISupportInitialize)(this.mapBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.mapUpLevel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.mapDownLevel)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } private MapPictureBox mapBox; private System.Windows.Forms.Label houseName; protected override bool ShowWithoutActivation { get { return true; } } public override void LoadForm() { if (house == null) return; this.SuspendForm(); NotificationInitialize(); houseName.Text = house.GetName().ToTitle(); Font f = StyleManager.FontList[0]; for (int i = 0; i < StyleManager.FontList.Count; i++) { Font font = StyleManager.FontList[i]; Size size = TextRenderer.MeasureText(this.houseName.Text, font); if (size.Width < houseName.MaximumSize.Width && size.Height < houseName.MaximumSize.Height) { f = font; } else { break; } } this.houseName.Font = f; cityLabel.Text = house.city.ToString(); sizeLabel.Text = String.Format("{0} sqm", house.sqm); bedLabel.Text = house.beds.ToString(); if (house.world != null) { statusLabel.Text = house.occupied ? "rented" : (house.hoursleft <= 0 ? "free" : "auctioned"); if (house.occupied || house.hoursleft < 0) { timeLeftLabel.Visible = false; timeLeftHeader.Visible = false; } else { timeLeftLabel.Text = String.Format("{0}{1}", house.hoursleft > 24 ? house.hoursleft / 24 : house.hoursleft, house.hoursleft > 24 ? "D" : "h"); } } else { timeLeftHeader.Visible = false; statusHeader.Visible = false; timeLeftLabel.Visible = false; statusLabel.Visible = false; } Map m = StorageManager.getMap(house.pos.z); mapBox.map = m; mapBox.mapImage = null; Target t = new Target(); t.coordinate = new Coordinate(house.pos); t.image = house.GetImage(); t.size = 20; mapBox.targets.Add(t); mapBox.sourceWidth = mapBox.Width; mapBox.mapCoordinate = new Coordinate(house.pos); mapBox.zCoordinate = house.pos.z; mapBox.UpdateMap(); UnregisterControl(mapBox); this.mapUpLevel.Image = StyleManager.GetImage("mapup.png"); this.UnregisterControl(mapUpLevel); this.mapUpLevel.Click += mapUpLevel_Click; this.mapDownLevel.Image = StyleManager.GetImage("mapdown.png"); this.UnregisterControl(mapDownLevel); this.mapDownLevel.Click += mapDownLevel_Click; base.NotificationFinalize(); this.ResumeForm(); } void mapUpLevel_Click(object sender, EventArgs e) { mapBox.mapCoordinate.z--; mapBox.UpdateMap(); base.ResetTimer(); } void mapDownLevel_Click(object sender, EventArgs e) { mapBox.mapCoordinate.z++; mapBox.UpdateMap(); base.ResetTimer(); } public override string FormName() { return "HouseForm"; } private void routeButton_Click(object sender, EventArgs e) { CommandManager.ExecuteCommand(String.Format("route{0}{1},{2},{3}{0}{4}", Constants.CommandSymbol, house.pos.x, house.pos.y, house.pos.z, house.GetName())); } private void tibiaButton_Click(object sender, EventArgs e) { MainForm.OpenUrl(String.Format("https://secure.tibia.com/community/?subtopic=houses&page=view&world={0}&houseid={1}", house.world == null ? "Antica" : house.world.ToTitle(), house.id)); } } }
using NuKeeper.Abstractions; using NuKeeper.Abstractions.CollaborationModels; using NuKeeper.Abstractions.CollaborationPlatform; using NuKeeper.Abstractions.Configuration; using NuKeeper.Abstractions.Formats; using NuKeeper.Abstractions.Logging; using Octokit; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Organization = NuKeeper.Abstractions.CollaborationModels.Organization; using PullRequestRequest = NuKeeper.Abstractions.CollaborationModels.PullRequestRequest; using Repository = NuKeeper.Abstractions.CollaborationModels.Repository; using SearchCodeRequest = NuKeeper.Abstractions.CollaborationModels.SearchCodeRequest; using SearchCodeResult = NuKeeper.Abstractions.CollaborationModels.SearchCodeResult; using User = NuKeeper.Abstractions.CollaborationModels.User; using Newtonsoft.Json; namespace NuKeeper.GitHub { public class OctokitClient : ICollaborationPlatform { private readonly INuKeeperLogger _logger; private bool _initialised; private IGitHubClient _client; private Uri _apiBase; public OctokitClient(INuKeeperLogger logger) { _logger = logger; } public void Initialise(AuthSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } _apiBase = settings.ApiBase; _client = new GitHubClient(new ProductHeaderValue("NuKeeper"), _apiBase) { Credentials = new Credentials(settings.Token) }; _initialised = true; } private void CheckInitialised() { if (!_initialised) { throw new NuKeeperException("Github has not been initialised"); } } public async Task<User> GetCurrentUser() { CheckInitialised(); return await ExceptionHandler(async () => { var user = await _client.User.Current(); var emails = await _client.User.Email.GetAll(); var primaryEmail = emails.FirstOrDefault(e => e.Primary); _logger.Detailed($"Read github user '{user?.Login}'"); return new User(user?.Login, user?.Name, primaryEmail?.Email ?? user?.Email); }); } public async Task<IReadOnlyList<Organization>> GetOrganizations() { CheckInitialised(); return await ExceptionHandler(async () => { var githubOrgs = await _client.Organization.GetAll(); _logger.Normal($"Read {githubOrgs.Count} organisations"); return githubOrgs .Select(org => new Organization(org.Name ?? org.Login)) .ToList(); }); } public async Task<IReadOnlyList<Repository>> GetRepositoriesForOrganisation(string organisationName) { CheckInitialised(); return await ExceptionHandler(async () => { var repos = await _client.Repository.GetAllForOrg(organisationName); _logger.Normal($"Read {repos.Count} repos for org '{organisationName}'"); return repos.Select(repo => new GitHubRepository(repo)).ToList(); }); } public async Task<Repository> GetUserRepository(string userName, string repositoryName) { CheckInitialised(); _logger.Detailed($"Looking for user fork for {userName}/{repositoryName}"); return await ExceptionHandler(async () => { try { var result = await _client.Repository.Get(userName, repositoryName); _logger.Normal($"User fork found at {result.GitUrl} for {result.Owner.Login}"); return new GitHubRepository(result); } catch (NotFoundException) { _logger.Detailed("User fork not found"); return null; } }); } public async Task<Repository> MakeUserFork(string owner, string repositoryName) { CheckInitialised(); _logger.Detailed($"Making user fork for {repositoryName}"); return await ExceptionHandler(async () => { var result = await _client.Repository.Forks.Create(owner, repositoryName, new NewRepositoryFork()); _logger.Normal($"User fork created at {result.GitUrl} for {result.Owner.Login}"); return new GitHubRepository(result); }); } public async Task<bool> RepositoryBranchExists(string userName, string repositoryName, string branchName) { CheckInitialised(); return await ExceptionHandler(async () => { try { await _client.Repository.Branch.Get(userName, repositoryName, branchName); _logger.Detailed($"Branch found for {userName} / {repositoryName} / {branchName}"); return true; } catch (NotFoundException) { _logger.Detailed($"No branch found for {userName} / {repositoryName} / {branchName}"); return false; } }); } public async Task<bool> PullRequestExists(ForkData target, string headBranch, string baseBranch) { CheckInitialised(); return await ExceptionHandler(async () => { _logger.Normal($"Checking if PR exists onto '{_apiBase} {target.Owner}/{target.Name}: {baseBranch} <= {headBranch}"); var prRequest = new Octokit.PullRequestRequest { State = ItemStateFilter.Open, SortDirection = SortDirection.Descending, SortProperty = PullRequestSort.Created, Head = $"{target.Owner}:{headBranch}", }; var pullReqList = await _client.PullRequest.GetAllForRepository(target.Owner, target.Name, prRequest).ConfigureAwait(false); return pullReqList.Any(pr => pr.Base.Ref.EndsWith(baseBranch, StringComparison.InvariantCultureIgnoreCase)); }); } public async Task OpenPullRequest(ForkData target, PullRequestRequest request, IEnumerable<string> labels) { CheckInitialised(); await ExceptionHandler(async () => { _logger.Normal($"Making PR onto '{_apiBase} {target.Owner}/{target.Name} from {request.Head}"); _logger.Detailed($"PR title: {request.Title}"); var createdPullRequest = await _client.PullRequest.Create(target.Owner, target.Name, new NewPullRequest(request.Title, request.Head, request.BaseRef) { Body = request.Body }); await AddLabelsToIssue(target, createdPullRequest.Number, labels); return Task.CompletedTask; }); } public async Task<SearchCodeResult> Search(SearchCodeRequest search) { CheckInitialised(); return await ExceptionHandler(async () => { var repos = new RepositoryCollection(); foreach (var repo in search.Repos) { repos.Add(repo.Owner, repo.Name); } var result = await _client.Search.SearchCode( new Octokit.SearchCodeRequest(search.Term) { Repos = repos, In = new[] { CodeInQualifier.Path }, PerPage = search.PerPage }); return new SearchCodeResult(result.TotalCount); }); } private async Task AddLabelsToIssue(ForkData target, int issueNumber, IEnumerable<string> labels) { var labelsToApply = labels? .Where(l => !string.IsNullOrWhiteSpace(l)) .ToArray(); if (labelsToApply != null && labelsToApply.Any()) { _logger.Normal( $"Adding label(s) '{labelsToApply.JoinWithCommas()}' to issue " + $"'{_apiBase} {target.Owner}/{target.Name} {issueNumber}'"); try { await _client.Issue.Labels.AddToIssue(target.Owner, target.Name, issueNumber, labelsToApply); } catch (ApiException ex) { _logger.Error("Failed to add labels. Continuing", ex); } } } private static async Task<T> ExceptionHandler<T>(Func<Task<T>> funcToCheck) { try { return await funcToCheck(); } catch (ApiException ex) { if (ex.HttpResponse?.Body != null) { dynamic response = JsonConvert.DeserializeObject(ex.HttpResponse.Body.ToString()); if (response?.errors != null && response.errors.Count > 0) { throw new NuKeeperException(response.errors.First.message.ToString(), ex); } } throw new NuKeeperException(ex.Message, ex); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; //using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using MonoFlixel; namespace MonoFlixel { public class FlxGamepad { private GamePadState old; private GamePadState current; private PlayerIndex index; private float leftVibe; private float rightVibe; private float vibeDuration; static public Buttons buttons; public float leftAnalogX; public float leftAnalogY; public float rightAnalogX; public float rightAnalogY; public float leftTrigger; public float rightTrigger; public FlxGamepad(PlayerIndex IndexOfPlayer) { index = IndexOfPlayer; leftVibe = 0; rightVibe = 0; vibeDuration = 0; } public void update() { old = current; current = GamePad.GetState(index); leftAnalogX = current.ThumbSticks.Left.X; leftAnalogY = current.ThumbSticks.Left.Y; rightAnalogX = current.ThumbSticks.Right.X; rightAnalogY = current.ThumbSticks.Right.Y; leftTrigger = current.Triggers.Left; rightTrigger = current.Triggers.Right; if (vibeDuration > 0) { vibeDuration -= FlxG.elapsed; if (vibeDuration <= 0) { leftVibe = rightVibe = 0; } GamePad.SetVibration(index, leftVibe, rightVibe); } } /// <summary> /// Returns true if the Left Analog is pushed right by any amount /// </summary> /// <returns>bool</returns> public bool leftAnalogPushedRight() { return leftAnalogX > 0f; } /// <summary> /// Returns true if the Left Analog is pushed left by any amount /// </summary> /// <returns>bool</returns> public bool leftAnalogPushedLeft() { return leftAnalogX < 0f; } /// <summary> /// Returns true if the Left Analog is pushed up by any amount /// </summary> /// <returns>bool</returns> public bool leftAnalogPushedUp() { return leftAnalogY > 0f; } /// <summary> /// Returns true if the Left Analog is pushed down by any amount /// </summary> /// <returns>bool</returns> public bool leftAnalogPushedDown() { return leftAnalogY < 0f; } /// <summary> /// Returns true if the Left Analog is centered and not being pushed in any direction /// </summary> /// <returns>bool</returns> public bool leftAnalogStill() { return (leftAnalogX == 0) && (leftAnalogY == 0); } /// <summary> /// Returns true if the Right Analog is pushed right by any amount /// </summary> /// <returns>bool</returns> public bool rightAnalogPushedRight() { return rightAnalogX > 0f; } /// <summary> /// Returns true if the Right Analog is pushed left by any amount /// </summary> /// <returns>bool</returns> public bool rightAnalogPushedLeft() { return rightAnalogX < 0f; } /// <summary> /// Returns true if the Right Analog is pushed up by any amount /// </summary> /// <returns>bool</returns> public bool rightAnalogPushedUp() { return rightAnalogY > 0f; } /// <summary> /// Returns true if the Right Analog is pushed down by any amount /// </summary> /// <returns>bool</returns> public bool rightAnalogPushedDown() { return rightAnalogY < 0f; } /// <summary> /// Returns true if the Right Analog is centered and not being pushed in any direction /// </summary> /// <returns>bool</returns> public bool rightAnalogStill() { return (rightAnalogX == 0) && (rightAnalogY == 0); } /// <summary> /// Simple Controller vibration /// </summary> /// <param name="Duration">The length in seconds the vibration should last</param> public void vibrate(float Duration = 0.5f) { vibrate(Duration, 0.15f, 0.15f); } /// <summary> /// Simple Controller vibration /// </summary> /// <param name="Duration">The length in seconds the vibration should last</param> /// <param name="Intensity">The intensity of the vibration for both Motors</param> public void vibrate(float Duration=0.5f, float Intensity=0.15f) { vibrate(Duration, Intensity, Intensity); } /// <summary> /// Simple Controller vibration /// </summary> /// <param name="Duration">The length in seconds the vibration should last</param> /// <param name="IntensityLeftMotor">The intensity of the Left Motor vibration</param> /// <param name="IntensityRightMotor">The intensity of the Right Motor vibration</param> /// <param name="ShakeScreen">Should the screen shake in unison with the controller vibration</param> public void vibrate(float Duration=0.5f, float IntensityLeftMotor=0.15f, float IntensityRightMotor=0.15f, bool ShakeScreen=false) { vibeDuration = Duration; leftVibe = IntensityLeftMotor; rightVibe = IntensityRightMotor; if (ShakeScreen) FlxG.shake(IntensityLeftMotor/20, Duration); } /// <summary> /// Returrns true if the specified button was just pressed /// </summary> /// <param name="Button">Buttons Button</param> /// <returns>bool</returns> public bool justPressed(Buttons Button) { if ((current.IsButtonDown(Button) && old.IsButtonUp(Button))) return true; else return false; } /// <summary> /// Returrns true if the specified button was just released /// </summary> /// <param name="Button">Buttons Button</param> /// <returns>bool</returns> public bool justReleased(Buttons button) { if ((old.IsButtonDown(button) && current.IsButtonUp(button))) return true; else return false; } /// <summary> /// Returrns true if the specified button is held down /// </summary> /// <param name="Button">Buttons Button</param> /// <returns>bool</returns> public bool pressed(Buttons button) { if (current.IsButtonDown(button)) return true; else return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //////////////////////////////////////////////////////////////////////////// // // // Purpose: This class represents settings specified by de jure or // de facto standards for a particular country/region. In // contrast to CultureInfo, the RegionInfo does not represent // preferences of the user and does not depend on the user's // language or culture. // // //////////////////////////////////////////////////////////////////////////// using System.Diagnostics; using System.Runtime.Serialization; namespace System.Globalization { public class RegionInfo { //--------------------------------------------------------------------// // Internal Information // //--------------------------------------------------------------------// // // Variables. // // // Name of this region (ie: es-US): serialized, the field used for deserialization // internal String _name; // // The CultureData instance that we are going to read data from. // internal CultureData _cultureData; // // The RegionInfo for our current region // internal static volatile RegionInfo s_currentRegionInfo; //////////////////////////////////////////////////////////////////////// // // RegionInfo Constructors // // Note: We prefer that a region be created with a full culture name (ie: en-US) // because otherwise the native strings won't be right. // // In Silverlight we enforce that RegionInfos must be created with a full culture name // //////////////////////////////////////////////////////////////////////// public RegionInfo(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); if (name.Length == 0) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture, nameof(name)); } // // For CoreCLR we only want the region names that are full culture names // _cultureData = CultureData.GetCultureDataForRegion(name, true); if (_cultureData == null) throw new ArgumentException( String.Format( CultureInfo.CurrentCulture, SR.Argument_InvalidCultureName, name), nameof(name)); // Not supposed to be neutral if (_cultureData.IsNeutralCulture) throw new ArgumentException(SR.Format(SR.Argument_InvalidNeutralRegionName, name), nameof(name)); SetName(name); } public RegionInfo(int culture) { if (culture == CultureInfo.LOCALE_INVARIANT) //The InvariantCulture has no matching region { throw new ArgumentException(SR.Argument_NoRegionInvariantCulture); } if (culture == CultureInfo.LOCALE_NEUTRAL) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } if (culture == CultureInfo.LOCALE_CUSTOM_DEFAULT) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CustomCultureCannotBePassedByNumber, culture), nameof(culture)); } _cultureData = CultureData.GetCultureData(culture, true); _name = _cultureData.SREGIONNAME; if (_cultureData.IsNeutralCulture) { // Not supposed to be neutral throw new ArgumentException(SR.Format(SR.Argument_CultureIsNeutral, culture), nameof(culture)); } } internal RegionInfo(CultureData cultureData) { _cultureData = cultureData; _name = _cultureData.SREGIONNAME; } private void SetName(string name) { // when creating region by culture name, we keep the region name as the culture name so regions // created by custom culture names can be differentiated from built in regions. this._name = name.Equals(_cultureData.SREGIONNAME, StringComparison.OrdinalIgnoreCase) ? _cultureData.SREGIONNAME : _cultureData.CultureName; } //////////////////////////////////////////////////////////////////////// // // GetCurrentRegion // // This instance provides methods based on the current user settings. // These settings are volatile and may change over the lifetime of the // thread. // //////////////////////////////////////////////////////////////////////// public static RegionInfo CurrentRegion { get { RegionInfo temp = s_currentRegionInfo; if (temp == null) { temp = new RegionInfo(CultureInfo.CurrentCulture._cultureData); // Need full name for custom cultures temp._name = temp._cultureData.SREGIONNAME; s_currentRegionInfo = temp; } return temp; } } //////////////////////////////////////////////////////////////////////// // // GetName // // Returns the name of the region (ie: en-US) // //////////////////////////////////////////////////////////////////////// public virtual String Name { get { Debug.Assert(_name != null, "Expected RegionInfo._name to be populated already"); return (_name); } } //////////////////////////////////////////////////////////////////////// // // GetEnglishName // // Returns the name of the region in English. (ie: United States) // //////////////////////////////////////////////////////////////////////// public virtual String EnglishName { get { return (_cultureData.SENGCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetDisplayName // // Returns the display name (localized) of the region. (ie: United States // if the current UI language is en-US) // //////////////////////////////////////////////////////////////////////// public virtual String DisplayName { get { return (_cultureData.SLOCALIZEDCOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // GetNativeName // // Returns the native name of the region. (ie: Deutschland) // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual String NativeName { get { return (_cultureData.SNATIVECOUNTRY); } } //////////////////////////////////////////////////////////////////////// // // TwoLetterISORegionName // // Returns the two letter ISO region name (ie: US) // //////////////////////////////////////////////////////////////////////// public virtual String TwoLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterISORegionName // // Returns the three letter ISO region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterISORegionName { get { return (_cultureData.SISO3166CTRYNAME2); } } //////////////////////////////////////////////////////////////////////// // // ThreeLetterWindowsRegionName // // Returns the three letter windows region name (ie: USA) // //////////////////////////////////////////////////////////////////////// public virtual String ThreeLetterWindowsRegionName { get { // ThreeLetterWindowsRegionName is really same as ThreeLetterISORegionName return ThreeLetterISORegionName; } } //////////////////////////////////////////////////////////////////////// // // IsMetric // // Returns true if this region uses the metric measurement system // //////////////////////////////////////////////////////////////////////// public virtual bool IsMetric { get { int value = _cultureData.IMEASURE; return (value == 0); } } public virtual int GeoId { get { return (_cultureData.IGEOID); } } //////////////////////////////////////////////////////////////////////// // // CurrencyEnglishName // // English name for this region's currency, ie: Swiss Franc // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyEnglishName { get { return (_cultureData.SENGLISHCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencyNativeName // // Native name for this region's currency, ie: Schweizer Franken // WARNING: You need a full locale name for this to make sense. // //////////////////////////////////////////////////////////////////////// public virtual string CurrencyNativeName { get { return (_cultureData.SNATIVECURRENCY); } } //////////////////////////////////////////////////////////////////////// // // CurrencySymbol // // Currency Symbol for this locale, ie: Fr. or $ // //////////////////////////////////////////////////////////////////////// public virtual String CurrencySymbol { get { return (_cultureData.SCURRENCY); } } //////////////////////////////////////////////////////////////////////// // // ISOCurrencySymbol // // ISO Currency Symbol for this locale, ie: CHF // //////////////////////////////////////////////////////////////////////// public virtual String ISOCurrencySymbol { get { return (_cultureData.SINTLSYMBOL); } } //////////////////////////////////////////////////////////////////////// // // Equals // // Implements Object.Equals(). Returns a boolean indicating whether // or not object refers to the same RegionInfo as the current instance. // // RegionInfos are considered equal if and only if they have the same name // (ie: en-US) // //////////////////////////////////////////////////////////////////////// public override bool Equals(Object value) { RegionInfo that = value as RegionInfo; if (that != null) { return this.Name.Equals(that.Name); } return (false); } //////////////////////////////////////////////////////////////////////// // // GetHashCode // // Implements Object.GetHashCode(). Returns the hash code for the // CultureInfo. The hash code is guaranteed to be the same for RegionInfo // A and B where A.Equals(B) is true. // //////////////////////////////////////////////////////////////////////// public override int GetHashCode() { return (this.Name.GetHashCode()); } //////////////////////////////////////////////////////////////////////// // // ToString // // Implements Object.ToString(). Returns the name of the Region, ie: es-US // //////////////////////////////////////////////////////////////////////// public override String ToString() { return (Name); } } }
// // MethodDefinition.cs // // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using ScriptSharp.Importer.IL.Cil; using ScriptSharp.Collections.Generic; using RVA = System.UInt32; namespace ScriptSharp.Importer.IL { internal /* public */ sealed class MethodDefinition : MethodReference, IMemberDefinition, ISecurityDeclarationProvider { ushort attributes; ushort impl_attributes; internal MethodSemanticsAttributes? sem_attrs; Collection<CustomAttribute> custom_attributes; Collection<SecurityDeclaration> security_declarations; internal RVA rva; internal PInvokeInfo pinvoke; Collection<MethodReference> overrides; internal MethodBody body; public MethodAttributes Attributes { get { return (MethodAttributes) attributes; } set { attributes = (ushort) value; } } public MethodImplAttributes ImplAttributes { get { return (MethodImplAttributes) impl_attributes; } set { impl_attributes = (ushort) value; } } public MethodSemanticsAttributes SemanticsAttributes { get { if (sem_attrs.HasValue) return sem_attrs.Value; if (HasImage) { ReadSemantics (); return sem_attrs.Value; } sem_attrs = MethodSemanticsAttributes.None; return sem_attrs.Value; } set { sem_attrs = value; } } internal void ReadSemantics () { if (sem_attrs.HasValue) return; var module = this.Module; if (module == null) return; if (!module.HasImage) return; module.Read (this, (method, reader) => reader.ReadAllSemantics (method)); } public bool HasSecurityDeclarations { get { if (security_declarations != null) return security_declarations.Count > 0; return this.GetHasSecurityDeclarations (Module); } } public Collection<SecurityDeclaration> SecurityDeclarations { get { return security_declarations ?? (security_declarations = this.GetSecurityDeclarations (Module)); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (custom_attributes = this.GetCustomAttributes (Module)); } } public int RVA { get { return (int) rva; } } public bool HasBody { get { return (attributes & (ushort) MethodAttributes.Abstract) == 0 && (attributes & (ushort) MethodAttributes.PInvokeImpl) == 0 && (impl_attributes & (ushort) MethodImplAttributes.InternalCall) == 0 && (impl_attributes & (ushort) MethodImplAttributes.Native) == 0 && (impl_attributes & (ushort) MethodImplAttributes.Unmanaged) == 0 && (impl_attributes & (ushort) MethodImplAttributes.Runtime) == 0; } } public MethodBody Body { get { if (body != null) return body; if (!HasBody) return null; if (HasImage && rva != 0) return body = Module.Read (this, (method, reader) => reader.ReadMethodBody (method)); return body = new MethodBody (this); } set { body = value; } } public bool HasPInvokeInfo { get { if (pinvoke != null) return true; return IsPInvokeImpl; } } public PInvokeInfo PInvokeInfo { get { if (pinvoke != null) return pinvoke; if (HasImage && IsPInvokeImpl) return pinvoke = Module.Read (this, (method, reader) => reader.ReadPInvokeInfo (method)); return null; } set { IsPInvokeImpl = true; pinvoke = value; } } public bool HasOverrides { get { if (overrides != null) return overrides.Count > 0; if (HasImage) return Module.Read (this, (method, reader) => reader.HasOverrides (method)); return false; } } public Collection<MethodReference> Overrides { get { if (overrides != null) return overrides; if (HasImage) return overrides = Module.Read (this, (method, reader) => reader.ReadOverrides (method)); return overrides = new Collection<MethodReference> (); } } public override bool HasGenericParameters { get { if (generic_parameters != null) return generic_parameters.Count > 0; return this.GetHasGenericParameters (Module); } } public override Collection<GenericParameter> GenericParameters { get { return generic_parameters ?? (generic_parameters = this.GetGenericParameters (Module)); } } #region MethodAttributes public bool IsCompilerControlled { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.CompilerControlled, value); } } public bool IsPrivate { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Private, value); } } public bool IsFamilyAndAssembly { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamANDAssem, value); } } public bool IsAssembly { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Assembly, value); } } public bool IsFamily { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Family, value); } } public bool IsFamilyOrAssembly { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.FamORAssem, value); } } public bool IsPublic { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.MemberAccessMask, (ushort) MethodAttributes.Public, value); } } public bool IsStatic { get { return attributes.GetAttributes ((ushort) MethodAttributes.Static); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Static, value); } } public bool IsFinal { get { return attributes.GetAttributes ((ushort) MethodAttributes.Final); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Final, value); } } public bool IsVirtual { get { return attributes.GetAttributes ((ushort) MethodAttributes.Virtual); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Virtual, value); } } public bool IsHideBySig { get { return attributes.GetAttributes ((ushort) MethodAttributes.HideBySig); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HideBySig, value); } } public bool IsReuseSlot { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.ReuseSlot, value); } } public bool IsNewSlot { get { return attributes.GetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot); } set { attributes = attributes.SetMaskedAttributes ((ushort) MethodAttributes.VtableLayoutMask, (ushort) MethodAttributes.NewSlot, value); } } public bool IsCheckAccessOnOverride { get { return attributes.GetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.CheckAccessOnOverride, value); } } public bool IsAbstract { get { return attributes.GetAttributes ((ushort) MethodAttributes.Abstract); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.Abstract, value); } } public bool IsSpecialName { get { return attributes.GetAttributes ((ushort) MethodAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.SpecialName, value); } } public bool IsPInvokeImpl { get { return attributes.GetAttributes ((ushort) MethodAttributes.PInvokeImpl); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.PInvokeImpl, value); } } public bool IsUnmanagedExport { get { return attributes.GetAttributes ((ushort) MethodAttributes.UnmanagedExport); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.UnmanagedExport, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((ushort) MethodAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.RTSpecialName, value); } } public bool HasSecurity { get { return attributes.GetAttributes ((ushort) MethodAttributes.HasSecurity); } set { attributes = attributes.SetAttributes ((ushort) MethodAttributes.HasSecurity, value); } } #endregion #region MethodImplAttributes public bool IsIL { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.IL, value); } } public bool IsNative { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Native, value); } } public bool IsRuntime { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.CodeTypeMask, (ushort) MethodImplAttributes.Runtime, value); } } public bool IsUnmanaged { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Unmanaged, value); } } public bool IsManaged { get { return impl_attributes.GetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed); } set { impl_attributes = impl_attributes.SetMaskedAttributes ((ushort) MethodImplAttributes.ManagedMask, (ushort) MethodImplAttributes.Managed, value); } } public bool IsForwardRef { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.ForwardRef); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.ForwardRef, value); } } public bool IsPreserveSig { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.PreserveSig); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.PreserveSig, value); } } public bool IsInternalCall { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.InternalCall); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.InternalCall, value); } } public bool IsSynchronized { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.Synchronized); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.Synchronized, value); } } public bool NoInlining { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoInlining); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoInlining, value); } } public bool NoOptimization { get { return impl_attributes.GetAttributes ((ushort) MethodImplAttributes.NoOptimization); } set { impl_attributes = impl_attributes.SetAttributes ((ushort) MethodImplAttributes.NoOptimization, value); } } #endregion #region MethodSemanticsAttributes public bool IsSetter { get { return this.GetSemantics (MethodSemanticsAttributes.Setter); } set { this.SetSemantics (MethodSemanticsAttributes.Setter, value); } } public bool IsGetter { get { return this.GetSemantics (MethodSemanticsAttributes.Getter); } set { this.SetSemantics (MethodSemanticsAttributes.Getter, value); } } public bool IsOther { get { return this.GetSemantics (MethodSemanticsAttributes.Other); } set { this.SetSemantics (MethodSemanticsAttributes.Other, value); } } public bool IsAddOn { get { return this.GetSemantics (MethodSemanticsAttributes.AddOn); } set { this.SetSemantics (MethodSemanticsAttributes.AddOn, value); } } public bool IsRemoveOn { get { return this.GetSemantics (MethodSemanticsAttributes.RemoveOn); } set { this.SetSemantics (MethodSemanticsAttributes.RemoveOn, value); } } public bool IsFire { get { return this.GetSemantics (MethodSemanticsAttributes.Fire); } set { this.SetSemantics (MethodSemanticsAttributes.Fire, value); } } #endregion public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public bool IsConstructor { get { return this.IsRuntimeSpecialName && this.IsSpecialName && (this.Name == ".cctor" || this.Name == ".ctor"); } } public override bool IsDefinition { get { return true; } } internal MethodDefinition () { this.token = new MetadataToken (TokenType.Method); } public MethodDefinition (string name, MethodAttributes attributes, TypeReference returnType) : base (name, returnType) { this.attributes = (ushort) attributes; this.HasThis = !this.IsStatic; this.token = new MetadataToken (TokenType.Method); } public override MethodDefinition Resolve () { return this; } } static partial class Mixin { public static ParameterDefinition GetParameter (this MethodBody self, int index) { var method = self.method; if (method.HasThis) { if (index == 0) return self.ThisParameter; index--; } var parameters = method.Parameters; if (index < 0 || index >= parameters.size) return null; return parameters [index]; } public static VariableDefinition GetVariable (this MethodBody self, int index) { var variables = self.Variables; if (index < 0 || index >= variables.size) return null; return variables [index]; } public static bool GetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics) { return (self.SemanticsAttributes & semantics) != 0; } public static void SetSemantics (this MethodDefinition self, MethodSemanticsAttributes semantics, bool value) { if (value) self.SemanticsAttributes |= semantics; else self.SemanticsAttributes &= ~semantics; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. /*============================================================ ** ** ** Purpose: ** This internal class exposes a limited set of cached Provider ** metadata information. It is meant to support the Metadata ** ============================================================*/ using System.Globalization; using System.Collections.Generic; namespace System.Diagnostics.Eventing.Reader { // // this class does not expose underlying Provider metadata objects. Instead it // exposes a limited set of Provider metadata information from the cache. The reason // for this is so the cache can easily Dispose the metadata object without worrying // about who is using it. // internal class ProviderMetadataCachedInformation { private Dictionary<ProviderMetadataId, CacheItem> _cache; private int _maximumCacheSize; private EventLogSession _session; private string _logfile; private class ProviderMetadataId { private string _providerName; private CultureInfo _cultureInfo; public ProviderMetadataId(string providerName, CultureInfo cultureInfo) { _providerName = providerName; _cultureInfo = cultureInfo; } public override bool Equals(object obj) { ProviderMetadataId rhs = obj as ProviderMetadataId; if (rhs == null) return false; if (_providerName.Equals(rhs._providerName) && (_cultureInfo == rhs._cultureInfo)) return true; return false; } public override int GetHashCode() { return _providerName.GetHashCode() ^ _cultureInfo.GetHashCode(); } public string ProviderName { get { return _providerName; } } public CultureInfo TheCultureInfo { get { return _cultureInfo; } } } private class CacheItem { private ProviderMetadata _pm; private DateTime _theTime; public CacheItem(ProviderMetadata pm) { _pm = pm; _theTime = DateTime.Now; } public DateTime TheTime { get { return _theTime; } set { _theTime = value; } } public ProviderMetadata ProviderMetadata { get { return _pm; } } } public ProviderMetadataCachedInformation(EventLogSession session, string logfile, int maximumCacheSize) { Debug.Assert(session != null); _session = session; _logfile = logfile; _cache = new Dictionary<ProviderMetadataId, CacheItem>(); _maximumCacheSize = maximumCacheSize; } private bool IsCacheFull() { return _cache.Count == _maximumCacheSize; } private bool IsProviderinCache(ProviderMetadataId key) { return _cache.ContainsKey(key); } private void DeleteCacheEntry(ProviderMetadataId key) { if (!IsProviderinCache(key)) return; CacheItem value = _cache[key]; _cache.Remove(key); value.ProviderMetadata.Dispose(); } private void AddCacheEntry(ProviderMetadataId key, ProviderMetadata pm) { if (IsCacheFull()) FlushOldestEntry(); CacheItem value = new CacheItem(pm); _cache.Add(key, value); return; } private void FlushOldestEntry() { double maxPassedTime = -10; DateTime timeNow = DateTime.Now; ProviderMetadataId keyToDelete = null; // get the entry in the cache which was not accessed for the longest time. foreach (KeyValuePair<ProviderMetadataId, CacheItem> kvp in _cache) { // the time difference (in ms) between the timeNow and the last used time of each entry TimeSpan timeDifference = timeNow.Subtract(kvp.Value.TheTime); // for the "unused" items (with ReferenceCount == 0) -> can possible be deleted. if (timeDifference.TotalMilliseconds >= maxPassedTime) { maxPassedTime = timeDifference.TotalMilliseconds; keyToDelete = kvp.Key; } } if (keyToDelete != null) DeleteCacheEntry(keyToDelete); } private static void UpdateCacheValueInfoForHit(CacheItem cacheItem) { cacheItem.TheTime = DateTime.Now; } private ProviderMetadata GetProviderMetadata(ProviderMetadataId key) { if (!IsProviderinCache(key)) { ProviderMetadata pm; try { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile); } catch (EventLogNotFoundException) { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } AddCacheEntry(key, pm); return pm; } else { CacheItem cacheItem = _cache[key]; ProviderMetadata pm = cacheItem.ProviderMetadata; // // check Provider metadata to be sure it's hasn't been // uninstalled since last time it was used. // try { pm.CheckReleased(); UpdateCacheValueInfoForHit(cacheItem); } catch (EventLogException) { DeleteCacheEntry(key); try { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo, _logfile); } catch (EventLogNotFoundException) { pm = new ProviderMetadata(key.ProviderName, _session, key.TheCultureInfo); } AddCacheEntry(key, pm); } return pm; } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); try { ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageEvent); } catch (EventLogNotFoundException) { return null; } } } public string GetFormatDescription(string ProviderName, EventLogHandle eventHandle, string[] values) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); try { return NativeWrapper.EvtFormatMessageFormatDescription(pm.Handle, eventHandle, values); } catch (EventLogNotFoundException) { return null; } } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public string GetLevelDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageLevel); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public string GetOpcodeDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageOpcode); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public string GetTaskDisplayName(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderName(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageTask); } } // marking as TreatAsSafe because just passing around a reference to an EventLogHandle is safe. [System.Security.SecuritySafeCritical] public IEnumerable<string> GetKeywordDisplayNames(string ProviderName, EventLogHandle eventHandle) { lock (this) { ProviderMetadataId key = new ProviderMetadataId(ProviderName, CultureInfo.CurrentCulture); ProviderMetadata pm = GetProviderMetadata(key); return NativeWrapper.EvtFormatMessageRenderKeywords(pm.Handle, eventHandle, UnsafeNativeMethods.EvtFormatMessageFlags.EvtFormatMessageKeyword); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System; using System.Data; using System.Data.Common; using System.Data.ProviderBase; using System.Data.SqlTypes; using System.Data.SqlClient; using System.Diagnostics; namespace Microsoft.SqlServer.Server { public class SqlDataRecord : IDataRecord { private SmiRecordBuffer _recordBuffer; private SmiExtendedMetaData[] _columnSmiMetaData; private SmiEventSink_Default _eventSink; private SqlMetaData[] _columnMetaData; private FieldNameLookup _fieldNameLookup; private bool _usesStringStorageForXml; private static readonly SmiMetaData s_maxNVarCharForXml = new SmiMetaData(SqlDbType.NVarChar, SmiMetaData.UnlimitedMaxLengthIndicator, SmiMetaData.DefaultNVarChar_NoCollation.Precision, SmiMetaData.DefaultNVarChar_NoCollation.Scale, SmiMetaData.DefaultNVarChar.LocaleId, SmiMetaData.DefaultNVarChar.CompareOptions, null); public virtual int FieldCount { get { EnsureSubclassOverride(); return _columnMetaData.Length; } } public virtual string GetName(int ordinal) { EnsureSubclassOverride(); return GetSqlMetaData(ordinal).Name; } public virtual string GetDataTypeName(int ordinal) { EnsureSubclassOverride(); SqlMetaData metaData = GetSqlMetaData(ordinal); if (SqlDbType.Udt == metaData.SqlDbType) { return metaData.UdtTypeName; } else { return MetaType.GetMetaTypeFromSqlDbType(metaData.SqlDbType, false).TypeName; } } public virtual Type GetFieldType(int ordinal) { EnsureSubclassOverride(); { SqlMetaData md = GetSqlMetaData(ordinal); return MetaType.GetMetaTypeFromSqlDbType(md.SqlDbType, false).ClassType; } } public virtual object GetValue(int ordinal) { EnsureSubclassOverride(); SmiMetaData metaData = GetSmiMetaData(ordinal); return ValueUtilsSmi.GetValue200( _eventSink, _recordBuffer, ordinal, metaData ); } public virtual int GetValues(object[] values) { EnsureSubclassOverride(); if (null == values) { throw ADP.ArgumentNull(nameof(values)); } int copyLength = (values.Length < FieldCount) ? values.Length : FieldCount; for (int i = 0; i < copyLength; i++) { values[i] = GetValue(i); } return copyLength; } public virtual int GetOrdinal(string name) { EnsureSubclassOverride(); if (null == _fieldNameLookup) { string[] names = new string[FieldCount]; for (int i = 0; i < names.Length; i++) { names[i] = GetSqlMetaData(i).Name; } _fieldNameLookup = new FieldNameLookup(names, -1); } return _fieldNameLookup.GetOrdinal(name); } public virtual object this[int ordinal] { get { EnsureSubclassOverride(); return GetValue(ordinal); } } public virtual object this[string name] { get { EnsureSubclassOverride(); return GetValue(GetOrdinal(name)); } } public virtual bool GetBoolean(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual byte GetByte(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual long GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) { EnsureSubclassOverride(); return ValueUtilsSmi.GetBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length, true); } public virtual char GetChar(int ordinal) { EnsureSubclassOverride(); throw ADP.NotSupported(); } public virtual long GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) { EnsureSubclassOverride(); return ValueUtilsSmi.GetChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length); } public virtual Guid GetGuid(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual short GetInt16(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual int GetInt32(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual long GetInt64(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual float GetFloat(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual double GetDouble(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual string GetString(int ordinal) { EnsureSubclassOverride(); SmiMetaData colMeta = GetSmiMetaData(ordinal); if (_usesStringStorageForXml && SqlDbType.Xml == colMeta.SqlDbType) { return ValueUtilsSmi.GetString(_eventSink, _recordBuffer, ordinal, s_maxNVarCharForXml); } else { return ValueUtilsSmi.GetString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } } public virtual decimal GetDecimal(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual DateTime GetDateTime(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual DateTimeOffset GetDateTimeOffset(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual TimeSpan GetTimeSpan(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetTimeSpan(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual bool IsDBNull(int ordinal) { EnsureSubclassOverride(); ThrowIfInvalidOrdinal(ordinal); return ValueUtilsSmi.IsDBNull(_eventSink, _recordBuffer, ordinal); } // // ISqlRecord implementation // public virtual SqlMetaData GetSqlMetaData(int ordinal) { EnsureSubclassOverride(); return _columnMetaData[ordinal]; } public virtual Type GetSqlFieldType(int ordinal) { EnsureSubclassOverride(); SqlMetaData md = GetSqlMetaData(ordinal); return MetaType.GetMetaTypeFromSqlDbType(md.SqlDbType, false).SqlType; } public virtual object GetSqlValue(int ordinal) { EnsureSubclassOverride(); SmiMetaData metaData = GetSmiMetaData(ordinal); return ValueUtilsSmi.GetSqlValue200(_eventSink, _recordBuffer, ordinal, metaData); } public virtual int GetSqlValues(object[] values) { EnsureSubclassOverride(); if (null == values) { throw ADP.ArgumentNull(nameof(values)); } int copyLength = (values.Length < FieldCount) ? values.Length : FieldCount; for (int i = 0; i < copyLength; i++) { values[i] = GetSqlValue(i); } return copyLength; } public virtual SqlBinary GetSqlBinary(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlBinary(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlBytes GetSqlBytes(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlXml GetSqlXml(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlXml(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlBoolean GetSqlBoolean(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlByte GetSqlByte(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlChars GetSqlChars(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlInt16 GetSqlInt16(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlInt32 GetSqlInt32(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlInt64 GetSqlInt64(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlSingle GetSqlSingle(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlDouble GetSqlDouble(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlMoney GetSqlMoney(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlMoney(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlDateTime GetSqlDateTime(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlDecimal GetSqlDecimal(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlString GetSqlString(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } public virtual SqlGuid GetSqlGuid(int ordinal) { EnsureSubclassOverride(); return ValueUtilsSmi.GetSqlGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal)); } // // ISqlUpdateableRecord Implementation // public virtual int SetValues(params object[] values) { EnsureSubclassOverride(); if (null == values) { throw ADP.ArgumentNull(nameof(values)); } // Allow values array longer than FieldCount, just ignore the extra cells. int copyLength = (values.Length > FieldCount) ? FieldCount : values.Length; ExtendedClrTypeCode[] typeCodes = new ExtendedClrTypeCode[copyLength]; // Verify all data values as acceptable before changing current state. for (int i = 0; i < copyLength; i++) { SqlMetaData metaData = GetSqlMetaData(i); typeCodes[i] = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType( metaData.SqlDbType, false /* isMultiValued */, values[i], metaData.Type); if (ExtendedClrTypeCode.Invalid == typeCodes[i]) { throw ADP.InvalidCast(); } } // Now move the data (it'll only throw if someone plays with the values array between // the validation loop and here, or if an invalid UDT was sent). for (int i = 0; i < copyLength; i++) { ValueUtilsSmi.SetCompatibleValueV200(_eventSink, _recordBuffer, i, GetSmiMetaData(i), values[i], typeCodes[i], 0, 0, null); } return copyLength; } public virtual void SetValue(int ordinal, object value) { EnsureSubclassOverride(); SqlMetaData metaData = GetSqlMetaData(ordinal); ExtendedClrTypeCode typeCode = MetaDataUtilsSmi.DetermineExtendedTypeCodeForUseWithSqlDbType( metaData.SqlDbType, false /* isMultiValued */, value, metaData.Type); if (ExtendedClrTypeCode.Invalid == typeCode) { throw ADP.InvalidCast(); } ValueUtilsSmi.SetCompatibleValueV200(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value, typeCode, 0, 0, null); } public virtual void SetBoolean(int ordinal, bool value) { EnsureSubclassOverride(); ValueUtilsSmi.SetBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetByte(int ordinal, byte value) { EnsureSubclassOverride(); ValueUtilsSmi.SetByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) { EnsureSubclassOverride(); ValueUtilsSmi.SetBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length); } public virtual void SetChar(int ordinal, char value) { EnsureSubclassOverride(); throw ADP.NotSupported(); } public virtual void SetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) { EnsureSubclassOverride(); ValueUtilsSmi.SetChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), fieldOffset, buffer, bufferOffset, length); } public virtual void SetInt16(int ordinal, short value) { EnsureSubclassOverride(); ValueUtilsSmi.SetInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetInt32(int ordinal, int value) { EnsureSubclassOverride(); ValueUtilsSmi.SetInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetInt64(int ordinal, long value) { EnsureSubclassOverride(); ValueUtilsSmi.SetInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetFloat(int ordinal, float value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDouble(int ordinal, double value) { EnsureSubclassOverride(); ValueUtilsSmi.SetDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetString(int ordinal, string value) { EnsureSubclassOverride(); ValueUtilsSmi.SetString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDecimal(int ordinal, decimal value) { EnsureSubclassOverride(); ValueUtilsSmi.SetDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDateTime(int ordinal, DateTime value) { EnsureSubclassOverride(); ValueUtilsSmi.SetDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetTimeSpan(int ordinal, TimeSpan value) { EnsureSubclassOverride(); ValueUtilsSmi.SetTimeSpan(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDateTimeOffset(int ordinal, DateTimeOffset value) { EnsureSubclassOverride(); ValueUtilsSmi.SetDateTimeOffset(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetDBNull(int ordinal) { EnsureSubclassOverride(); ValueUtilsSmi.SetDBNull(_eventSink, _recordBuffer, ordinal, true); } public virtual void SetGuid(int ordinal, Guid value) { EnsureSubclassOverride(); ValueUtilsSmi.SetGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlBoolean(int ordinal, SqlBoolean value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlBoolean(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlByte(int ordinal, SqlByte value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlByte(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlInt16(int ordinal, SqlInt16 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlInt16(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlInt32(int ordinal, SqlInt32 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlInt32(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlInt64(int ordinal, SqlInt64 value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlInt64(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlSingle(int ordinal, SqlSingle value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlSingle(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlDouble(int ordinal, SqlDouble value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlDouble(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlMoney(int ordinal, SqlMoney value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlMoney(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlDateTime(int ordinal, SqlDateTime value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlDateTime(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlXml(int ordinal, SqlXml value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlXml(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlDecimal(int ordinal, SqlDecimal value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlDecimal(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlString(int ordinal, SqlString value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlString(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlBinary(int ordinal, SqlBinary value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlBinary(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlGuid(int ordinal, SqlGuid value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlGuid(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlChars(int ordinal, SqlChars value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlChars(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } public virtual void SetSqlBytes(int ordinal, SqlBytes value) { EnsureSubclassOverride(); ValueUtilsSmi.SetSqlBytes(_eventSink, _recordBuffer, ordinal, GetSmiMetaData(ordinal), value); } // // SqlDataRecord public API // public SqlDataRecord(params SqlMetaData[] metaData) { // Initial consistency check if (null == metaData) { throw ADP.ArgumentNull(nameof(metaData)); } _columnMetaData = new SqlMetaData[metaData.Length]; _columnSmiMetaData = new SmiExtendedMetaData[metaData.Length]; for (int i = 0; i < _columnSmiMetaData.Length; i++) { if (null == metaData[i]) { throw ADP.ArgumentNull($"{nameof(metaData)}[{i}]"); } _columnMetaData[i] = metaData[i]; _columnSmiMetaData[i] = MetaDataUtilsSmi.SqlMetaDataToSmiExtendedMetaData(_columnMetaData[i]); } _eventSink = new SmiEventSink_Default(); _recordBuffer = new MemoryRecordBuffer(_columnSmiMetaData); _usesStringStorageForXml = true; _eventSink.ProcessMessagesAndThrow(); } internal SqlDataRecord(SmiRecordBuffer recordBuffer, params SmiExtendedMetaData[] metaData) { Debug.Assert(null != recordBuffer, "invalid attempt to instantiate SqlDataRecord with null SmiRecordBuffer"); Debug.Assert(null != metaData, "invalid attempt to instantiate SqlDataRecord with null SmiExtendedMetaData[]"); _columnMetaData = new SqlMetaData[metaData.Length]; _columnSmiMetaData = new SmiExtendedMetaData[metaData.Length]; for (int i = 0; i < _columnSmiMetaData.Length; i++) { _columnSmiMetaData[i] = metaData[i]; _columnMetaData[i] = MetaDataUtilsSmi.SmiExtendedMetaDataToSqlMetaData(_columnSmiMetaData[i]); } _eventSink = new SmiEventSink_Default(); _recordBuffer = recordBuffer; _eventSink.ProcessMessagesAndThrow(); } // // SqlDataRecord private members // internal SmiRecordBuffer RecordBuffer { // used by SqlPipe get { return _recordBuffer; } } internal SqlMetaData[] InternalGetMetaData() { return _columnMetaData; } internal SmiExtendedMetaData[] InternalGetSmiMetaData() { return _columnSmiMetaData; } internal SmiExtendedMetaData GetSmiMetaData(int ordinal) { return _columnSmiMetaData[ordinal]; } internal void ThrowIfInvalidOrdinal(int ordinal) { if (0 > ordinal || FieldCount <= ordinal) { throw ADP.IndexOutOfRange(ordinal); } } private void EnsureSubclassOverride() { if (null == _recordBuffer) { throw SQL.SubclassMustOverride(); } } IDataReader System.Data.IDataRecord.GetData(int ordinal) { throw ADP.NotSupported(); } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Box = OpenSim.Framework.Geom.Box; using System.Collections.Generic; using System.Linq; using System.Threading; using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.CoreModules.Agent.SceneView { /// <summary> /// A Culling Module for ScenePresences. /// </summary> /// <remarks> /// Cull updates for ScenePresences. This does simple Draw Distance culling but could be expanded to work /// off of other scene parameters as well; /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class SceneViewModule : ISceneViewModule, INonSharedRegionModule { #region Declares private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool UseCulling { get; set; } #endregion #region ISharedRegionModule Members public SceneViewModule() { UseCulling = false; } public string Name { get { return "SceneViewModule"; } } public Type ReplaceableInterface { get { return null; } } public void Initialize(IConfigSource source) { IConfig config = source.Configs["SceneView"]; if (config != null) { UseCulling = config.GetBoolean("UseCulling", true); } else { UseCulling = true; } m_log.DebugFormat("[SCENE VIEW]: INITIALIZED MODULE, CULLING is {0}", (UseCulling ? "ENABLED" : "DISABLED")); } public void Close() { } public void AddRegion(Scene scene) { scene.RegisterModuleInterface<ISceneViewModule>(this); } public void RemoveRegion(Scene scene) { } public void RegionLoaded(Scene scene) { } #endregion #region ICullerModule Members /// <summary> /// Create a scene view for the given presence /// </summary> /// <param name="presence"></param> /// <returns></returns> public ISceneView CreateSceneView(ScenePresence presence) { return new SceneView(presence, UseCulling); } #endregion } public class SceneView : ISceneView { #region Declares private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int _MINIMUM_DRAW_DISTANCE = 32; private ScenePresence m_presence; private int m_perfMonMS; private int m_timeBeforeChildAgentUpdate; private OpenSim.Region.Framework.Scenes.Types.UpdateQueue m_partsUpdateQueue = new OpenSim.Region.Framework.Scenes.Types.UpdateQueue(); private Dictionary<uint, ScenePartUpdate> m_updateTimes = new Dictionary<uint, ScenePartUpdate>(); private List<UUID> m_presencesInView = new List<UUID>(); private bool[,] m_TerrainCulling = new bool[16, 16]; public bool UseCulling { get; set; } public float DistanceBeforeCullingRequired { get; set; } public bool NeedsFullSceneUpdate { get; set; } public bool HasFinishedInitialUpdate { get; set; } #endregion #region Constructor public SceneView(ScenePresence presence, bool useCulling) { UseCulling = useCulling; NeedsFullSceneUpdate = true; HasFinishedInitialUpdate = false; m_presence = presence; //Update every 1/4th a draw distance DistanceBeforeCullingRequired = _MINIMUM_DRAW_DISTANCE / 8; } #endregion #region Culler Methods /// <summary> /// Checks to see whether any prims, avatars, or terrain have come into view since the last culling check /// </summary> public void CheckForDistantEntitiesToShow() { if (UseCulling == false) return; //Bots don't get to check for updates if (m_presence.IsBot) return; //With 25K objects, this method takes around 10ms if the client has seen none of the objects in the sim if (m_presence.DrawDistance <= 0) return; if (m_presence.IsInTransit) return; // disable prim updates during a crossing, but leave them queued for after transition if (m_presence.Closed) { //Don't check if we are closed, and clear the update queues ClearAllTracking(); return; } Util.FireAndForget((o) => { CheckForDistantTerrainToShow(); CheckForDistantPrimsToShow(); CheckForDistantAvatarsToShow(); HasFinishedInitialUpdate = true; }); } #endregion #region Avatar Culling /// <summary> /// Checks to see whether any new avatars have come into view since the last time culling checks were done /// </summary> private void CheckForDistantAvatarsToShow() { List<ScenePresence> SPs; lock (m_presence.Scene.SyncRoot) { if (!m_presence.IsChildAgent || m_presence.Scene.m_seeIntoRegionFromNeighbor) SPs = m_presence.Scene.GetScenePresences(); else return; } Vector3 clientAbsPosition = m_presence.AbsolutePosition; foreach (ScenePresence presence in SPs) { if (m_presence.Closed) { ClearAllTracking(); return; } if (presence.UUID != m_presence.UUID) { if (ShowEntityToClient(clientAbsPosition, presence) || ShowEntityToClient(m_presence.CameraPosition, presence)) { if (!m_presencesInView.Contains(presence.UUID)) { //Send the update both ways SendPresenceToUs(presence); presence.SceneView.SendPresenceToUs(m_presence); } else { //Check to see whether any attachments have changed for both users CheckWhetherAttachmentsHaveChanged(presence); if (!m_presence.IsChildAgent) presence.SceneView.CheckWhetherAttachmentsHaveChanged(m_presence); } } } } } public void CheckWhetherAttachmentsHaveChanged(ScenePresence presence) { foreach (SceneObjectGroup grp in presence.GetAttachments()) { if (CheckWhetherAttachmentShouldBeSent(grp)) SendGroupUpdate(grp, PrimUpdateFlags.ForcedFullUpdate); } } public void ClearFromScene(ScenePresence presence) { m_presencesInView.Remove(presence.UUID); } public void ClearScene() { m_presencesInView.Clear(); } /// <summary> /// Tests to see whether the given avatar can be seen by the client at the given position /// </summary> /// <param name="clientAbsPosition">Position to check from</param> /// <param name="presence">The avatar to check</param> /// <returns></returns> public bool ShowEntityToClient(Vector3 clientAbsPosition, ScenePresence presence) { if (UseCulling == false) return true; Vector3 avpos; if (!presence.HasSafePosition(out avpos)) return false; float drawDistance = m_presence.DrawDistance; if (m_presence.DrawDistance < _MINIMUM_DRAW_DISTANCE) drawDistance = _MINIMUM_DRAW_DISTANCE; //Smallest distance we will check return Vector3.DistanceSquared(clientAbsPosition, avpos) <= drawDistance * drawDistance; } #region Avatar Update Sending methods public void SendAvatarTerseUpdate(ScenePresence scenePresence) { //if (!ShowEntityToClient(m_presence.AbsolutePosition, scenePresence)) // return;//When they move around, they will trigger more updates, so when they get into the other avatar's DD, they will update Vector3 vPos = Vector3.Zero; Quaternion vRot = Quaternion.Identity; uint vParentID = 0; m_perfMonMS = Environment.TickCount; scenePresence.RecalcVisualPosition(out vPos, out vRot, out vParentID); // vParentID is not used in terse updates. o.O PhysicsActor physActor = scenePresence.PhysicsActor; Vector3 accel = (physActor != null) ? physActor.Acceleration : Vector3.Zero; // m_log.InfoFormat("[SCENE PRESENCE]: SendTerseUpdateToClient sit at {0} vel {1} rot {2} ", pos.ToString(),vel.ToString(), rot.ToString()); m_presence.ControllingClient.SendAvatarTerseUpdate(scenePresence.Scene.RegionInfo.RegionHandle, (ushort)(scenePresence.Scene.TimeDilation * ushort.MaxValue), scenePresence.LocalId, vPos, scenePresence.Velocity, accel, vRot, scenePresence.UUID, physActor != null ? physActor.CollisionPlane : Vector4.UnitW); m_presence.Scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS); m_presence.Scene.StatsReporter.AddAgentUpdates(1); } /// <summary> /// Tell other client about this avatar (The client previously didn't know or had outdated details about this avatar) /// </summary> /// <param name="remoteAvatar"></param> public void SendFullUpdateToOtherClient(ScenePresence otherClient) { if (m_presence.IsChildAgent) return;//Never send data from a child client // 2 stage check is needed. if (otherClient == null) return; if (otherClient.IsBot) return; if (otherClient.ControllingClient == null) return; if (m_presence.Appearance.Texture == null) return; //if (ShowEntityToClient(otherClient.AbsolutePosition, m_presence)) m_presence.SendAvatarData(otherClient.ControllingClient, false); } /// <summary> /// Tell *ALL* agents about this agent /// </summary> public void SendInitialFullUpdateToAllClients() { m_perfMonMS = Environment.TickCount; List<ScenePresence> avatars = m_presence.Scene.GetScenePresences(); Vector3 clientAbsPosition = m_presence.AbsolutePosition; foreach (ScenePresence avatar in avatars) { // don't notify self of self (confuses the viewer). if (avatar.UUID == m_presence.UUID) continue; // okay, send the other avatar to our client // if (ShowEntityToClient(clientAbsPosition, avatar)) SendPresenceToUs(avatar); // also show our avatar to the others, including those in other child regions if (avatar.IsDeleted || avatar.IsInTransit) continue; // if (ShowEntityToClient(avatar.AbsolutePosition, m_presence)) avatar.SceneView.SendPresenceToUs(m_presence); } m_presence.Scene.StatsReporter.AddAgentUpdates(avatars.Count); m_presence.Scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS); } /// <summary> /// Tell our client about other client's avatar (includes appearance and full object update) /// </summary> /// <param name="m_presence"></param> public void SendPresenceToUs(ScenePresence avatar) { if (m_presence.IsBot) return; if (avatar.IsChildAgent) return; // uint inRegion = (uint)avatar.AgentInRegion; if (!avatar.IsFullyInRegion) { // m_log.WarnFormat("[SendPresenceToUs]: AgentInRegion={0:x2}",inRegion); return; // don't send to them yet, they aren't ready } if (avatar.IsDeleted) return; // don't send them, they're on their way outta here // Witnessed an exception internal to the .Add method with the list resizing. The avatar.UUID was // already in the list inside the .Add call, so it should be safe to ignore here (already added). try { if (!m_presencesInView.Contains(avatar.UUID)) m_presencesInView.Add(avatar.UUID); } catch(Exception) { m_log.InfoFormat("[SCENEVIEW]: Exception adding presence, probably race with it already added. Ignoring."); } avatar.SceneView.SendFullUpdateToOtherClient(m_presence); avatar.SendAppearanceToOtherAgent(m_presence); avatar.SendAnimPackToClient(m_presence.ControllingClient); avatar.SendFullUpdateForAttachments(m_presence); } /// <summary> /// Sends a full update for our client to all clients in the scene /// </summary> public void SendFullUpdateToAllClients() { m_perfMonMS = Environment.TickCount; // only send update from root agents to other clients; children are only "listening posts" List<ScenePresence> avatars = m_presence.Scene.GetAvatars(); foreach (ScenePresence avatar in avatars) { if (avatar.IsDeleted) continue; if (avatar.IsInTransit) continue; SendFullUpdateToOtherClient(avatar); } m_presence.Scene.StatsReporter.AddAgentUpdates(avatars.Count); m_presence.Scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS); // Thread.Sleep(100); m_presence.SendAnimPack(); } #endregion #endregion #region Prim Culling /// <summary> /// Checks to see whether any new prims have come into view since the last time culling checks were done /// </summary> private void CheckForDistantPrimsToShow() { List<EntityBase> SOGs; lock (m_presence.Scene.SyncRoot) { if (!m_presence.IsChildAgent || m_presence.Scene.m_seeIntoRegionFromNeighbor) SOGs = m_presence.Scene.Entities.GetAllByType<SceneObjectGroup>(); else return; } Vector3 clientAbsPosition = m_presence.AbsolutePosition; List<KeyValuePair<double, SceneObjectGroup>> grps = new List<KeyValuePair<double, SceneObjectGroup>>(); foreach (EntityBase sog in SOGs) { SceneObjectGroup e = (SceneObjectGroup)sog; if (m_presence.Closed) { ClearAllTracking(); return; } if ((e).IsAttachment) { if(CheckWhetherAttachmentShouldBeSent(e)) grps.Add(new KeyValuePair<double, SceneObjectGroup>(0, e)); continue; } if ((e).IsAttachedHUD && (e).OwnerID != m_presence.UUID) continue;//Don't ever send HUD attachments to non-owners IReadOnlyCollection<SceneObjectPart> sogParts = null; bool needsParts = false; lock (m_updateTimes) { if (m_updateTimes.ContainsKey(e.LocalId)) { needsParts = true; } } if (needsParts) sogParts = e.GetParts(); lock (m_updateTimes) { if (m_updateTimes.ContainsKey(e.LocalId)) { bool hasBeenUpdated = false; if (sogParts == null) sogParts = e.GetParts(); foreach (SceneObjectPart part in sogParts) { if (!m_updateTimes.ContainsKey(part.LocalId)) { //Threading issue? Shouldn't happen unless this method is called // while a group is being sent, but hasn't sent all prims yet // so... let's ignore the prim that is missing for now, and if // any other parts change, it'll re-send it all hasBeenUpdated = true; break; } ScenePartUpdate update = m_updateTimes[part.LocalId]; if (update.LastFullUpdateTimeRequested == update.LastFullUpdateTime && update.LastTerseUpdateTime == update.LastTerseUpdateTimeRequested) continue;//Only if we haven't sent them this prim before and it hasn't changed //It's changed, check again hasBeenUpdated = true; break; } if (!hasBeenUpdated) continue;//Only if we haven't sent them this prim before and it hasn't changed } } double distance; if (!ShowEntityToClient(clientAbsPosition, e, out distance) && !ShowEntityToClient(m_presence.CameraPosition, e, out distance)) continue; grps.Add(new KeyValuePair<double, SceneObjectGroup>(distance, e)); } KeyValuePair<double, SceneObjectGroup>[] arry = grps.ToArray(); C5.Sorting.IntroSort<KeyValuePair<double, SceneObjectGroup>>(arry, 0, arry.Length, new DoubleComparer()); //Sort by distance here, so that we send the closest updates first foreach (KeyValuePair<double, SceneObjectGroup> kvp in arry) { if (m_presence.Closed) { ClearAllTracking(); return; } SendGroupUpdate(kvp.Value, PrimUpdateFlags.FindBest); } } private bool CheckWhetherAttachmentShouldBeSent(SceneObjectGroup e) { bool hasBeenUpdated = false; var attParts = e.GetParts(); lock (m_updateTimes) { foreach (SceneObjectPart part in attParts) { if (!m_updateTimes.ContainsKey(part.LocalId)) { //Threading issue? Shouldn't happen unless this method is called // while a group is being sent, but hasn't sent all prims yet // so... let's ignore the prim that is missing for now, and if // any other parts change, it'll re-send it all hasBeenUpdated = true; continue; } ScenePartUpdate update = m_updateTimes[part.LocalId]; if (update.LastFullUpdateTimeRequested == update.LastFullUpdateTime && update.LastTerseUpdateTime == update.LastTerseUpdateTimeRequested) continue;//Only if we haven't sent them this prim before and it hasn't changed //It's changed, check again hasBeenUpdated = true; break; } } return hasBeenUpdated; } private class DoubleComparer : IComparer<KeyValuePair<double, SceneObjectGroup>> { public int Compare(KeyValuePair<double, SceneObjectGroup> x, KeyValuePair<double, SceneObjectGroup> y) { //ensure objects with avatars on them are shown first followed by everything else if (x.Value.HasSittingAvatars && !y.Value.HasSittingAvatars) { return -1; } return x.Key.CompareTo(y.Key); } } /// <summary> /// Tests to see whether the given group can be seen by the client at the given position /// </summary> /// <param name="clientAbsPosition">Position to check from</param> /// <param name="group">Object to check</param> /// <param name="distance">The distance to the group</param> /// <returns></returns> public bool ShowEntityToClient(Vector3 clientAbsPosition, SceneObjectGroup group, out double distance) { distance = 0; if (UseCulling == false) return true; if (m_presence.DrawDistance <= 0) return (true); if (group.IsAttachedHUD) { if (group.OwnerID != m_presence.UUID) return false; // Never show attached HUDs return true; } if (group.IsAttachment) return true; if (group.HasSittingAvatars) return true;//Send objects that avatars are sitting on var box = group.BoundingBox(); float drawDistance = m_presence.DrawDistance; if (m_presence.DrawDistance < _MINIMUM_DRAW_DISTANCE) drawDistance = _MINIMUM_DRAW_DISTANCE; //Smallest distance we will check if ((distance = Vector3.DistanceSquared(clientAbsPosition, group.AbsolutePosition)) <= drawDistance * drawDistance) return (true); //If the basic check fails, we then want to check whether the object is large enough that we would // want to start doing more agressive checks if (box.Size.X >= DistanceBeforeCullingRequired || box.Size.Y >= DistanceBeforeCullingRequired || box.Size.Z >= DistanceBeforeCullingRequired) { //Any side of the box is larger than the distance that // we check for, run tests on the bounding box to see // whether it is actually needed to be sent box = group.BoundingBox(); float closestX; float closestY; float closestZ; float boxLeft = box.Center.X - box.Extent.X; float boxRight = box.Center.X + box.Extent.X; float boxFront = box.Center.Y - box.Extent.Y; float boxRear = box.Center.Y + box.Extent.Y; float boxBottom = box.Center.Z - box.Extent.Z; float boxTop = box.Center.Z + box.Extent.Z; if (clientAbsPosition.X < boxLeft) { closestX = boxLeft; } else if (clientAbsPosition.X > boxRight) { closestX = boxRight; } else { closestX = clientAbsPosition.X; } if (clientAbsPosition.Y < boxFront) { closestY = boxFront; } else if (clientAbsPosition.Y > boxRear) { closestY = boxRear; } else { closestY = clientAbsPosition.Y; } if (clientAbsPosition.Z < boxBottom) { closestZ = boxBottom; } else if (clientAbsPosition.Z > boxTop) { closestZ = boxTop; } else { closestZ = clientAbsPosition.Z; } if (Vector3.DistanceSquared(clientAbsPosition, new Vector3(closestX, closestY, closestZ)) <= drawDistance * drawDistance) return (true); } return false; } #endregion #region Prim Update Sending /// <summary> /// Send updates to the client about prims which have been placed on the update queue. We don't /// necessarily send updates for all the parts on the queue, e.g. if an updates with a more recent /// timestamp has already been sent. /// /// SHOULD ONLY BE CALLED WITHIN THE SCENE LOOP /// </summary> public void SendPrimUpdates() { if (m_presence.Closed) { ClearAllTracking(); return; } //Bots don't get to check for updates if (m_presence.IsBot) return; if (m_presence.IsInTransit) return; // disable prim updates during a crossing, but leave them queued for after transition // uint inRegion = (uint)m_presence.AgentInRegion; if (!m_presence.IsChildAgent && !m_presence.IsFullyInRegion) { // m_log.WarnFormat("[SendPrimUpdates]: AgentInRegion={0:x2}",inRegion); return; // don't send to them yet, they aren't ready } m_perfMonMS = Environment.TickCount; if (((UseCulling == false) || (m_presence.DrawDistance != 0)) && NeedsFullSceneUpdate) { NeedsFullSceneUpdate = false; if (UseCulling == false)//Send the entire heightmap m_presence.ControllingClient.SendLayerData(m_presence.Scene.Heightmap.GetFloatsSerialized()); if (UseCulling == true && !m_presence.IsChildAgent) m_timeBeforeChildAgentUpdate = Environment.TickCount; CheckForDistantEntitiesToShow(); } if (m_timeBeforeChildAgentUpdate != 0 && (Environment.TickCount - m_timeBeforeChildAgentUpdate) >= 5000) { m_log.Debug("[SCENE VIEW]: Sending child agent update to update all child regions about fully established user"); //Send out an initial child agent update so that the child region can add their objects accordingly now that we are all set up m_presence.SendChildAgentUpdate(); //Don't ever send another child update from here again m_timeBeforeChildAgentUpdate = 0; } // Before pulling the AbsPosition, since this isn't locked, make sure it's a good position. Vector3 clientAbsPosition = Vector3.Zero; if (!m_presence.HasSafePosition(out clientAbsPosition)) return; // this one has gone into late transit or something, or the prim it's on has. int queueCount = m_partsUpdateQueue.Count; int time = Environment.TickCount; SceneObjectGroup lastSog = null; bool lastParentObjectWasCulled = false; IReadOnlyCollection<SceneObjectPart> lastParentGroupParts = null; while (m_partsUpdateQueue.Count > 0 && HasFinishedInitialUpdate) { if (m_presence.Closed) { ClearAllTracking(); return; } KeyValuePair<SceneObjectPart, PrimUpdateFlags>? kvp = m_partsUpdateQueue.Dequeue(); if (!kvp.HasValue || kvp.Value.Key.ParentGroup == null || kvp.Value.Key.ParentGroup.IsDeleted) continue; SceneObjectPart part = kvp.Value.Key; double distance; // Cull part updates based on the position of the SOP. if ((lastSog == part.ParentGroup && lastParentObjectWasCulled) || (lastSog != part.ParentGroup && UseCulling && !ShowEntityToClient(clientAbsPosition, part.ParentGroup, out distance) && !ShowEntityToClient(m_presence.CameraPosition, part.ParentGroup, out distance))) { bool sendKill = false; lastParentObjectWasCulled = true; lock (m_updateTimes) { if (m_updateTimes.ContainsKey(part.LocalId)) { sendKill = true; // If we are going to send a kill, it is for the complete object. // We are telling the viewer to nuke everything it knows about ALL of // the prims, not just the child prim. So we need to remove ALL of the // prims from m_updateTimes before continuing. IReadOnlyCollection<SceneObjectPart> sogPrims = part.ParentGroup.GetParts(); foreach (SceneObjectPart prim in sogPrims) { m_updateTimes.Remove(prim.LocalId); } } } //Only send the kill object packet if we have seen this object //Note: I'm not sure we should be sending a kill at all in this case. -Jim // The viewer has already hidden the object if outside DD, and the // KillObject causes the viewer to discard its cache of the objects. if (sendKill) m_presence.ControllingClient.SendNonPermanentKillObject(m_presence.Scene.RegionInfo.RegionHandle, part.ParentGroup.RootPart.LocalId); lastSog = part.ParentGroup; continue; } else { lastParentObjectWasCulled = false; } IReadOnlyCollection<SceneObjectPart> parentGroupParts = null; bool needsParentGroupParts = false; lock (m_updateTimes) { if (m_updateTimes.ContainsKey(part.ParentGroup.LocalId)) { needsParentGroupParts = true; } } if (!needsParentGroupParts) { lastParentGroupParts = null; } else if (needsParentGroupParts && lastSog == part.ParentGroup && lastParentGroupParts != null) { parentGroupParts = lastParentGroupParts; } else { parentGroupParts = part.ParentGroup.GetParts(); lastParentGroupParts = parentGroupParts; } lock (m_updateTimes) { bool hasBeenUpdated = false; if (m_updateTimes.ContainsKey(part.ParentGroup.LocalId)) { if (parentGroupParts == null) { if (lastSog == part.ParentGroup && lastParentGroupParts != null) { parentGroupParts = lastParentGroupParts; } else { parentGroupParts = part.ParentGroup.GetParts(); lastParentGroupParts = parentGroupParts; } } foreach (SceneObjectPart p in parentGroupParts) { ScenePartUpdate update; if (!m_updateTimes.TryGetValue(p.LocalId, out update)) { //Threading issue? Shouldn't happen unless this method is called // while a group is being sent, but hasn't sent all prims yet // so... let's ignore the prim that is missing for now, and if // any other parts change, it'll re-send it all hasBeenUpdated = true; break; } if (update.LastFullUpdateTimeRequested == update.LastFullUpdateTime && update.LastTerseUpdateTime == update.LastTerseUpdateTimeRequested) { continue;//Only if we haven't sent them this prim before and it hasn't changed } //It's changed, check again hasBeenUpdated = true; break; } } else { hasBeenUpdated = true; } if (hasBeenUpdated) { SendGroupUpdate(part.ParentGroup, kvp.Value.Value); lastSog = part.ParentGroup; continue; } } lastSog = part.ParentGroup; SendPartUpdate(part, kvp.Value.Value); } /*if (queueCount > 0) { m_log.DebugFormat("Update queue flush of {0} objects took {1}", queueCount, Environment.TickCount - time); }*/ //ControllingClient.FlushPrimUpdates(); m_presence.Scene.StatsReporter.AddAgentTime(Environment.TickCount - m_perfMonMS); } public void SendGroupUpdate(SceneObjectGroup sceneObjectGroup, PrimUpdateFlags updateFlags) { //Bots don't get to send updates if (m_presence.IsBot) return; SendPartUpdate(sceneObjectGroup.RootPart, updateFlags); foreach (SceneObjectPart part in sceneObjectGroup.GetParts()) { if (!part.IsRootPart()) SendPartUpdate(part, updateFlags); } } public void SendPartUpdate(SceneObjectPart part, PrimUpdateFlags updateFlags) { ScenePartUpdate update = null; int partFullUpdateCounter = part.FullUpdateCounter; int partTerseUpdateCounter = part.TerseUpdateCounter; bool sendFullUpdate = false, sendFullInitialUpdate = false, sendTerseUpdate = false; lock(m_updateTimes) { if (m_updateTimes.TryGetValue(part.LocalId, out update)) { if ((update.LastFullUpdateTime != partFullUpdateCounter) || part.ParentGroup.IsAttachment) { // m_log.DebugFormat( // "[SCENE PRESENCE]: Fully updating prim {0}, {1} - part timestamp {2}", // part.Name, part.UUID, part.TimeStampFull); update.LastFullUpdateTime = partFullUpdateCounter; update.LastFullUpdateTimeRequested = partFullUpdateCounter; //also cancel any pending terses since the full covers it update.LastTerseUpdateTime = partTerseUpdateCounter; update.LastTerseUpdateTimeRequested = partTerseUpdateCounter; sendFullUpdate = true; } else if (update.LastTerseUpdateTime != partTerseUpdateCounter) { // m_log.DebugFormat( // "[SCENE PRESENCE]: Tersely updating prim {0}, {1} - part timestamp {2}", // part.Name, part.UUID, part.TimeStampTerse); update.LastTerseUpdateTime = partTerseUpdateCounter; update.LastTerseUpdateTimeRequested = partTerseUpdateCounter; sendTerseUpdate = true; } } else { //never been sent to client before so do full update ScenePartUpdate newUpdate = new ScenePartUpdate(); newUpdate.FullID = part.UUID; newUpdate.LastFullUpdateTime = partFullUpdateCounter; newUpdate.LastFullUpdateTimeRequested = partFullUpdateCounter; m_updateTimes.Add(part.LocalId, newUpdate); sendFullInitialUpdate = true; } } if (sendFullUpdate) { part.SendFullUpdate(m_presence.ControllingClient, m_presence.GenerateClientFlags(part.UUID), updateFlags); } else if (sendTerseUpdate) { part.SendTerseUpdateToClient(m_presence.ControllingClient); } else if (sendFullInitialUpdate) { // Attachment handling // if (part.ParentGroup.IsAttachment) { if (part != part.ParentGroup.RootPart) return; part.ParentGroup.SendFullUpdateToClient(m_presence.ControllingClient, PrimUpdateFlags.FullUpdate); return; } part.SendFullUpdate(m_presence.ControllingClient, m_presence.GenerateClientFlags(part.UUID), PrimUpdateFlags.FullUpdate); } } /// <summary> /// Add the part to the queue of parts for which we need to send an update to the client /// /// THIS METHOD SHOULD ONLY BE CALLED FROM WITHIN THE SCENE LOOP!! /// </summary> /// <param name="part"></param> public void QueuePartForUpdate(SceneObjectPart part, PrimUpdateFlags updateFlags) { if (m_presence.IsBot) return; // m_log.WarnFormat("[ScenePresence]: {0} Queuing update for {1} {2} {3}", part.ParentGroup.Scene.RegionInfo.RegionName, part.UUID.ToString(), part.LocalId.ToString(), part.ParentGroup.Name); m_partsUpdateQueue.Enqueue(part, updateFlags); } /// <summary> /// Clears all data we have about the region /// /// SHOULD ONLY BE CALLED FROM CHILDREN OF THE SCENE LOOP!! /// </summary> public void ClearAllTracking() { if (m_partsUpdateQueue.Count > 0) m_partsUpdateQueue.Clear(); lock (m_updateTimes) { if (m_updateTimes.Count > 0) m_updateTimes.Clear(); } if (m_presencesInView.Count > 0) m_presencesInView.Clear(); m_TerrainCulling = new bool[16, 16]; } /// <summary> /// Sends kill packets if the given object is within the draw distance of the avatar /// </summary> /// <param name="grp"></param> /// <param name="localIds"></param> public void SendKillObjects(SceneObjectGroup grp, List<uint> localIds) { //Bots don't get to check for updates if (m_presence.IsBot) return; //Only send the kill object packet if we have seen this object lock (m_updateTimes) { if (m_updateTimes.ContainsKey(grp.LocalId)) m_presence.ControllingClient.SendKillObjects(m_presence.Scene.RegionInfo.RegionHandle, localIds.ToArray()); } } #endregion #region Terrain Patch Sending /// <summary> /// Informs the SceneView that the given patch has been modified and must be resent /// </summary> /// <param name="serialized"></param> /// <param name="x"></param> /// <param name="y"></param> public void TerrainPatchUpdated(float[] serialized, int x, int y) { //Bots don't get to check for updates if (m_presence.IsBot) return; //Check to make sure that we only send it if we can see it or culling is disabled if ((UseCulling == false) || ShowTerrainPatchToClient(x, y)) m_presence.ControllingClient.SendLayerData(x, y, serialized); else if (UseCulling == true) m_TerrainCulling[x, y] = false;//Resend it next time it comes back into draw distance } /// <summary> /// Checks to see whether any new terrain has come into view since the last time culling checks were done /// </summary> private void CheckForDistantTerrainToShow() { const int FUDGE_FACTOR = 2; //Use a fudge factor, as we can see slightly farther than the draw distance const int MAX_PATCH = 16; int startX = Math.Min((((int)(m_presence.AbsolutePosition.X - m_presence.DrawDistance)) / Constants.TerrainPatchSize) - FUDGE_FACTOR, (((int)(m_presence.CameraPosition.X - m_presence.DrawDistance)) / Constants.TerrainPatchSize) - FUDGE_FACTOR); int startY = Math.Min((((int)(m_presence.AbsolutePosition.Y - m_presence.DrawDistance)) / Constants.TerrainPatchSize) - FUDGE_FACTOR, (((int)(m_presence.CameraPosition.Y - m_presence.DrawDistance)) / Constants.TerrainPatchSize) - FUDGE_FACTOR); int endX = Math.Max((((int)(m_presence.AbsolutePosition.X + m_presence.DrawDistance)) / Constants.TerrainPatchSize) + FUDGE_FACTOR, (((int)(m_presence.CameraPosition.X + m_presence.DrawDistance)) / Constants.TerrainPatchSize) + FUDGE_FACTOR); int endY = Math.Max((((int)(m_presence.AbsolutePosition.Y + m_presence.DrawDistance)) / Constants.TerrainPatchSize) + FUDGE_FACTOR, (((int)(m_presence.CameraPosition.Y + m_presence.DrawDistance)) / Constants.TerrainPatchSize) + FUDGE_FACTOR); float[] serializedMap = m_presence.Scene.Heightmap.GetFloatsSerialized(); if (startX < 0) startX = 0; if (startY < 0) startY = 0; if (endX > MAX_PATCH) endX = MAX_PATCH; if (endY > MAX_PATCH) endY = MAX_PATCH; for (int x = startX; x < endX; x++) { for (int y = startY; y < endY; y++) { //Need to make sure we don't send the same ones over and over if (!m_TerrainCulling[x, y]) { if (ShowTerrainPatchToClient(x, y)) { //They can see it, send it to them m_TerrainCulling[x, y] = true; m_presence.ControllingClient.SendLayerData(x, y, serializedMap); } } } } } /// <summary> /// Check to see whether a specific terrain patch is in view /// </summary> /// <param name="x">Terrain patch X</param> /// <param name="y">Terrain patch Y</param> /// <returns></returns> private bool ShowTerrainPatchToClient(int x, int y) { Vector3 clientAbsPosition = m_presence.AbsolutePosition; clientAbsPosition.Z = 0;//Force to the ground, we only want the 2D distance bool success = Util.DistanceLessThan( clientAbsPosition, new Vector3(x * Constants.TerrainPatchSize, y * Constants.TerrainPatchSize, 0), m_presence.DrawDistance + (16*2)); if (!success) { Vector3 clientCamPos = m_presence.CameraPosition; clientCamPos.Z = 0;//Force to the ground, we only want the 2D distance success = Util.DistanceLessThan( clientCamPos, new Vector3(x * Constants.TerrainPatchSize, y * Constants.TerrainPatchSize, 0), m_presence.DrawDistance + (16 * 2)); } return success; } #endregion #region Private classes public class ScenePartUpdate { public UUID FullID; public int LastFullUpdateTime; public int LastFullUpdateTimeRequested; public int LastTerseUpdateTime; public int LastTerseUpdateTimeRequested; public ScenePartUpdate() { FullID = UUID.Zero; LastFullUpdateTime = 0; LastFullUpdateTimeRequested = 0; LastTerseUpdateTime = 0; LastTerseUpdateTimeRequested = 0; } } #endregion } }
#pragma warning disable using System.Collections.Generic; using XPT.Games.Generic.Entities; using XPT.Games.Generic.Maps; using XPT.Games.Yserbius; using XPT.Games.Yserbius.Entities; namespace XPT.Games.Yserbius.Maps { class YserMap08 : YsMap { public override int MapIndex => 8; protected override int RandomEncounterChance => 10; protected override int RandomEncounterExtraCount => 0; public YserMap08() { MapEvent01 = FnSTRSTELE_01; MapEvent02 = FnKEYDOOR_02; MapEvent03 = FnGOLDAENC_03; MapEvent04 = FnGOLDBENC_04; MapEvent05 = FnCROWN_05; MapEvent06 = FnITEMBENC_06; MapEvent07 = FnITEMCENC_07; MapEvent08 = FnSTRMNSTR_08; MapEvent09 = FnTUFMNSTR_09; MapEvent0A = FnSTRSMESS_0A; MapEvent0B = FnNPCCHATA_0B; MapEvent0C = FnNPCCHATB_0C; } // === Strings ================================================ private const string String03FC = "The O Rune Key unlocked the door."; private const string String041E = "The door is locked. It requires a special key."; private const string String044D = "Skeletons on the floor stir to life."; private const string String0472 = "Among the bones on the floor are pieces of gold. The bones begin to move."; private const string String04BC = "A clutch of Large-Uns growl at you."; private const string String04E0 = "A Large-Un tosses a piece of wood aside as he and his friends attack."; private const string String0526 = "You have interrupted a Lizardite religious service."; private const string String055A = "As you enter the room, the O Rune Key vanishes."; private const string String058A = "You see a Lizardite proudly wearing the Crown of King Cleowyn."; private const string String05C9 = "You run into the living skeletons of King Cleowyn's guards."; private const string String0605 = "One of the skeletons approaching you holds a piece of paper in its bony hand."; private const string String0653 = "Reptilian bodies stir as you draw near."; private const string String067B = "The stairs through the west gateway lead down a level."; private const string String06B2 = "A Human Wizard teleports into the room you occupy."; private const string String06E5 = "Be careful when you find the way to open the door that leads to the nether depths of this dungeon."; private const string String0748 = "All quest items from Cleowyn's Palace levels will be stripped from you."; private const string String0790 = "But if you are indeed ready to enter the lower depths, you will no longer need Cleowyn's toys."; private const string String07EF = "The Human Wizard smiles sheepishly and teleports somewhere else."; private const string String0830 = "You encounter a sleepy Troll Knight."; private const string String0855 = "The Galabryan kings brought the great wizard Arnakkian Slowfoot to Twinion. The island grew famous and rich thanks to this wizard."; private const string String08D8 = "But the wizard had his own schemes, and soon he and good King Leowyn Galabryan were at loggerheads. Supposedly, the wizard had the king assassinated."; private const string String096E = "The Troll Knight blinks at you dumbly and falls asleep."; // === Functions ================================================ private void FnSTRSTELE_01(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: TeleportParty(player, 0x03, 0x01, 0xC2, 0x03, type); L001E: return; // RETURN; } private void FnKEYDOOR_02(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasUsedItem(player, type, ref doMsgs, YsIndexes.ItemRuneVowelKeyO, YsIndexes.ItemRuneVowelKeyO); L0016: if (JumpEqual) goto L0063; L0018: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x01); L0036: SetWallItem(player, 0x01, GetCurrentTile(player), GetFacing(player)); L0054: ShowMessage(player, doMsgs, String03FC); // The O Rune Key unlocked the door. L0061: goto L008D; L0063: SetWallPassable(player, GetCurrentTile(player), GetFacing(player), 0x00); L0080: ShowMessage(player, doMsgs, String041E); // The door is locked. It requires a special key. L008D: return; // RETURN; } private void FnGOLDAENC_03(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(GetFlag(player, FlagTypeDungeon, YsIndexes.FlagSecretRoom1Gold), 0x0001); L0017: if (JumpNotEqual) goto L0047; L0019: ShowMessage(player, doMsgs, String044D); // Skeletons on the floor stir to life. L0026: AddTreasure(player, 0x03E8, 0x00, 0x00, 0x00, 0x00, 0xB6); L0045: goto L0088; L0047: AddTreasure(player, 0x1388, 0x00, 0x00, 0x00, 0x00, 0xCF); L0066: SetFlag(player, FlagTypeDungeon, YsIndexes.FlagSecretRoom1Gold, 0x01); L007B: ShowMessage(player, doMsgs, String0472); // Among the bones on the floor are pieces of gold. The bones begin to move. L0088: Compare(PartyCount(player), 0x0001); L0093: if (JumpNotEqual) goto L00AA; L0095: AddEncounter(player, 0x01, 0x01); L00A7: goto L0144; L00AA: Compare(PartyCount(player), 0x0002); L00B5: if (JumpEqual) goto L00C4; L00B7: Compare(PartyCount(player), 0x0003); L00C2: if (JumpNotEqual) goto L00FC; L00C4: AddEncounter(player, 0x01, 0x02); L00D6: AddEncounter(player, 0x02, 0x04); L00E8: AddEncounter(player, 0x03, 0x06); L00FA: goto L0144; L00FC: AddEncounter(player, 0x01, 0x01); L010E: AddEncounter(player, 0x02, 0x02); L0120: AddEncounter(player, 0x03, 0x03); L0132: AddEncounter(player, 0x04, 0x04); L0144: return; // RETURN; } private void FnGOLDBENC_04(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasItem(player, 0xC6); L0011: if (JumpEqual) goto L0041; L0013: ShowMessage(player, doMsgs, String04BC); // A clutch of Large-Uns growl at you. L0020: AddTreasure(player, 0x07D0, 0x00, 0x00, 0x00, 0x00, 0xD1); L003F: goto L006D; L0041: AddTreasure(player, 0x1770, 0x00, 0x00, 0x00, 0x00, 0xC6); L0060: ShowMessage(player, doMsgs, String04E0); // A Large-Un tosses a piece of wood aside as he and his friends attack. L006D: Compare(PartyCount(player), 0x0001); L0078: if (JumpNotEqual) goto L00A1; L007A: AddEncounter(player, 0x01, 0x19); L008C: AddEncounter(player, 0x02, 0x1A); L009E: goto L0198; L00A1: Compare(PartyCount(player), 0x0002); L00AC: if (JumpNotEqual) goto L00E7; L00AE: AddEncounter(player, 0x01, 0x19); L00C0: AddEncounter(player, 0x02, 0x1A); L00D2: AddEncounter(player, 0x03, 0x19); L00E4: goto L0198; L00E7: Compare(PartyCount(player), 0x0003); L00F2: if (JumpNotEqual) goto L013E; L00F4: AddEncounter(player, 0x01, 0x1A); L0106: AddEncounter(player, 0x02, 0x1A); L0118: AddEncounter(player, 0x03, 0x1B); L012A: AddEncounter(player, 0x04, 0x1B); L013C: goto L0198; L013E: AddEncounter(player, 0x01, 0x1B); L0150: AddEncounter(player, 0x02, 0x1B); L0162: AddEncounter(player, 0x03, 0x1B); L0174: AddEncounter(player, 0x04, 0x1B); L0186: AddEncounter(player, 0x05, 0x1C); L0198: return; // RETURN; } private void FnCROWN_05(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasItem(player, 0x69); L0011: if (JumpEqual) goto L0041; L0013: ShowMessage(player, doMsgs, String0526); // You have interrupted a Lizardite religious service. L0020: AddTreasure(player, 0x01F4, 0x00, 0x00, 0x00, 0x00, 0xD0); L003F: goto L0087; L0041: AddTreasure(player, 0x07D0, 0x00, 0x00, 0x00, 0xCF, 0x69); L0061: RemoveItem(player, YsIndexes.ItemRuneVowelKeyO); L006D: ShowMessage(player, doMsgs, String055A); // As you enter the room, the O Rune Key vanishes. L007A: ShowMessage(player, doMsgs, String058A); // You see a Lizardite proudly wearing the Crown of King Cleowyn. L0087: Compare(PartyCount(player), 0x0001); L0092: if (JumpNotEqual) goto L00BB; L0094: AddEncounter(player, 0x01, 0x21); L00A6: AddEncounter(player, 0x02, 0x21); L00B8: goto L018B; L00BB: Compare(PartyCount(player), 0x0002); L00C6: if (JumpEqual) goto L00D5; L00C8: Compare(PartyCount(player), 0x0003); L00D3: if (JumpNotEqual) goto L011F; L00D5: AddEncounter(player, 0x01, 0x21); L00E7: AddEncounter(player, 0x02, 0x21); L00F9: AddEncounter(player, 0x03, 0x21); L010B: AddEncounter(player, 0x05, 0x21); L011D: goto L018B; L011F: AddEncounter(player, 0x01, 0x21); L0131: AddEncounter(player, 0x02, 0x21); L0143: AddEncounter(player, 0x03, 0x21); L0155: AddEncounter(player, 0x04, 0x21); L0167: AddEncounter(player, 0x05, 0x21); L0179: AddEncounter(player, 0x06, 0x21); L018B: return; // RETURN; } private void FnITEMBENC_06(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasItem(player, 0xBB); L0011: if (JumpEqual) goto L0041; L0013: ShowMessage(player, doMsgs, String05C9); // You run into the living skeletons of King Cleowyn's guards. L0020: AddTreasure(player, 0x0320, 0x00, 0x00, 0x00, 0x00, 0xBC); L003F: goto L006D; L0041: AddTreasure(player, 0x1B58, 0x00, 0x00, 0x00, 0x00, 0xBB); L0060: ShowMessage(player, doMsgs, String0605); // One of the skeletons approaching you holds a piece of paper in its bony hand. L006D: Compare(PartyCount(player), 0x0001); L0078: if (JumpNotEqual) goto L008F; L007A: AddEncounter(player, 0x01, 0x15); L008C: goto L0129; L008F: Compare(PartyCount(player), 0x0002); L009A: if (JumpEqual) goto L00A9; L009C: Compare(PartyCount(player), 0x0003); L00A7: if (JumpNotEqual) goto L00E1; L00A9: AddEncounter(player, 0x01, 0x15); L00BB: AddEncounter(player, 0x02, 0x16); L00CD: AddEncounter(player, 0x03, 0x17); L00DF: goto L0129; L00E1: AddEncounter(player, 0x01, 0x15); L00F3: AddEncounter(player, 0x02, 0x17); L0105: AddEncounter(player, 0x03, 0x16); L0117: AddEncounter(player, 0x04, 0x18); L0129: return; // RETURN; } private void FnITEMCENC_07(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ax = HasItem(player, 0x64); L0011: if (JumpEqual) goto L0065; L0013: ax = HasItem(player, 0x94); L0021: if (JumpEqual) goto L0044; L0023: AddTreasure(player, 0x01F4, 0x00, 0x00, 0x00, 0x00, 0xBD); L0042: goto L0063; L0044: AddTreasure(player, 0x07D0, 0x00, 0x00, 0x00, 0x00, 0x94); L0063: goto L00B6; L0065: ax = HasItem(player, 0x94); L0073: if (JumpEqual) goto L0096; L0075: AddTreasure(player, 0x07D0, 0x00, 0x00, 0x00, 0x00, 0x64); L0094: goto L00B6; L0096: AddTreasure(player, 0x07D0, 0x00, 0x00, 0x00, 0x64, 0x94); L00B6: ShowMessage(player, doMsgs, String0653); // Reptilian bodies stir as you draw near. L00C3: Compare(PartyCount(player), 0x0001); L00CE: if (JumpNotEqual) goto L00E5; L00D0: AddEncounter(player, 0x01, 0x23); L00E2: goto L017F; L00E5: Compare(PartyCount(player), 0x0002); L00F0: if (JumpEqual) goto L00FF; L00F2: Compare(PartyCount(player), 0x0003); L00FD: if (JumpNotEqual) goto L0137; L00FF: AddEncounter(player, 0x01, 0x23); L0111: AddEncounter(player, 0x02, 0x23); L0123: AddEncounter(player, 0x03, 0x23); L0135: goto L017F; L0137: AddEncounter(player, 0x01, 0x23); L0149: AddEncounter(player, 0x02, 0x23); L015B: AddEncounter(player, 0x03, 0x23); L016D: AddEncounter(player, 0x04, 0x23); L017F: return; // RETURN; } private void FnSTRMNSTR_08(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(PartyCount(player), 0x0001); L000E: if (JumpNotEqual) goto L0037; L0010: AddEncounter(player, 0x01, 0x19); L0022: AddEncounter(player, 0x02, 0x1A); L0034: goto L0152; L0037: Compare(PartyCount(player), 0x0002); L0042: if (JumpNotEqual) goto L007D; L0044: AddEncounter(player, 0x01, 0x19); L0056: AddEncounter(player, 0x02, 0x1A); L0068: AddEncounter(player, 0x03, 0x19); L007A: goto L0152; L007D: Compare(PartyCount(player), 0x0003); L0088: if (JumpNotEqual) goto L00E6; L008A: AddEncounter(player, 0x01, 0x1A); L009C: AddEncounter(player, 0x02, 0x1A); L00AE: AddEncounter(player, 0x03, 0x1B); L00C0: AddEncounter(player, 0x04, 0x1B); L00D2: AddEncounter(player, 0x05, 0x1C); L00E4: goto L0152; L00E6: AddEncounter(player, 0x01, 0x1B); L00F8: AddEncounter(player, 0x02, 0x1B); L010A: AddEncounter(player, 0x03, 0x1B); L011C: AddEncounter(player, 0x04, 0x1B); L012E: AddEncounter(player, 0x05, 0x1C); L0140: AddEncounter(player, 0x06, 0x1C); L0152: return; // RETURN; } private void FnTUFMNSTR_09(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: Compare(PartyCount(player), 0x0001); L000E: if (JumpNotEqual) goto L0025; L0010: AddEncounter(player, 0x01, 0x21); L0022: goto L010A; L0025: Compare(PartyCount(player), 0x0002); L0030: if (JumpNotEqual) goto L0059; L0032: AddEncounter(player, 0x01, 0x21); L0044: AddEncounter(player, 0x02, 0x21); L0056: goto L010A; L0059: Compare(PartyCount(player), 0x0003); L0064: if (JumpNotEqual) goto L00B0; L0066: AddEncounter(player, 0x01, 0x21); L0078: AddEncounter(player, 0x02, 0x21); L008A: AddEncounter(player, 0x03, 0x21); L009C: AddEncounter(player, 0x04, 0x21); L00AE: goto L010A; L00B0: AddEncounter(player, 0x01, 0x21); L00C2: AddEncounter(player, 0x02, 0x21); L00D4: AddEncounter(player, 0x03, 0x21); L00E6: AddEncounter(player, 0x04, 0x21); L00F8: AddEncounter(player, 0x05, 0x21); L010A: return; // RETURN; } private void FnSTRSMESS_0A(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String067B); // The stairs through the west gateway lead down a level. L0010: return; // RETURN; } private void FnNPCCHATA_0B(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String06B2); // A Human Wizard teleports into the room you occupy. L0010: ShowPortrait(player, 0x002B); L001D: Compare(GetRandom(0x000F), 0x000B); L002D: if (JumpAbove) goto L0058; L002F: ShowMessage(player, doMsgs, String06E5); // Be careful when you find the way to open the door that leads to the nether depths of this dungeon. L003C: ShowMessage(player, doMsgs, String0748); // All quest items from Cleowyn's Palace levels will be stripped from you. L0049: ShowMessage(player, doMsgs, String0790); // But if you are indeed ready to enter the lower depths, you will no longer need Cleowyn's toys. L0056: goto L0065; L0058: ShowMessage(player, doMsgs, String07EF); // The Human Wizard smiles sheepishly and teleports somewhere else. L0065: return; // RETURN; } private void FnNPCCHATB_0C(YsPlayerServer player, MapEventType type, bool doMsgs) { int ax = 0, bx = 0, cx = 0, dx = 0, si = 0, di = 0, tmp = 0; L0000: // BEGIN; L0003: ShowMessage(player, doMsgs, String0830); // You encounter a sleepy Troll Knight. L0010: ShowPortrait(player, 0x001B); L001D: Compare(GetRandom(0x000F), 0x0009); L002D: if (JumpAbove) goto L004B; L002F: ShowMessage(player, doMsgs, String0855); // The Galabryan kings brought the great wizard Arnakkian Slowfoot to Twinion. The island grew famous and rich thanks to this wizard. L003C: ShowMessage(player, doMsgs, String08D8); // But the wizard had his own schemes, and soon he and good King Leowyn Galabryan were at loggerheads. Supposedly, the wizard had the king assassinated. L0049: goto L0058; L004B: ShowMessage(player, doMsgs, String096E); // The Troll Knight blinks at you dumbly and falls asleep. L0058: return; // RETURN; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // // Licensed under the MIT License. See LICENSE.txt in the project root for license information. using System; using System.Runtime.InteropServices; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using System.Numerics; namespace NumericsTests { [TestClass()] public class QuaternionTest { // A test for Dot (Quaternion, Quaternion) [TestMethod] public void QuaternionDotTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); float expected = 70.0f; float actual; actual = Quaternion.Dot(a, b); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Dot did not return the expected value."); } // A test for Length () [TestMethod] public void QuaternionLengthTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); float expected = 5.477226f; float actual; actual = target.Length(); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Length did not return the expected value."); } // A test for LengthSquared () [TestMethod] public void QuaternionLengthSquaredTest() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); float expected = 30.0f; float actual; actual = target.LengthSquared(); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.LengthSquared did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) [TestMethod] public void QuaternionLerpTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.5f; Quaternion expected = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(20.0f)); Quaternion actual; actual = Quaternion.Lerp(a, b, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); // Case a and b are same. expected = a; actual = Quaternion.Lerp(a, a, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when t = 0 [TestMethod] public void QuaternionLerpTest1() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Lerp(a, b, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when t = 1 [TestMethod] public void QuaternionLerpTest2() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 1.0f; Quaternion expected = new Quaternion(b.X, b.Y, b.Z, b.W); Quaternion actual = Quaternion.Lerp(a, b, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Lerp did not return the expected value."); } // A test for Lerp (Quaternion, Quaternion, float) // Lerp test when the two quaternions are more than 90 degree (dot product <0) [TestMethod] public void QuaternionLerpTest3() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.Negate(a); float t = 1.0f; Quaternion actual = Quaternion.Lerp(a, b, t); // Note that in quaternion world, Q == -Q. In the case of quaternions dot product is zero, // one of the quaternion will be flipped to compute the shortest distance. When t = 1, we // expect the result to be the same as quaternion b but flipped. Assert.IsTrue(actual == a, "Quaternion.Lerp did not return the expected value."); } // A test for Conjugate(Quaternion) [TestMethod] public void QuaternionConjugateTest1() { Quaternion a = new Quaternion(1, 2, 3, 4); Quaternion expected = new Quaternion(-1, -2, -3, 4); Quaternion actual; actual = Quaternion.Conjugate(a); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Conjugate did not return the expected value."); } // A test for Normalize (Quaternion) [TestMethod] public void QuaternionNormalizeTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(0.182574168f, 0.365148336f, 0.5477225f, 0.7302967f); Quaternion actual; actual = Quaternion.Normalize(a); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Normalize did not return the expected value."); } // A test for Normalize (Quaternion) // Normalize zero length quaternion [TestMethod] public void QuaternionNormalizeTest1() { Quaternion a = new Quaternion(0.0f, 0.0f, -0.0f, 0.0f); Quaternion actual = Quaternion.Normalize(a); Assert.IsTrue(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z) && float.IsNaN(actual.W) , "Quaternion.Normalize did not return the expected value."); } // A test for Concatenate(Quaternion, Quaternion) [TestMethod] public void QuaternionConcatenateTest1() { Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion a = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = Quaternion.Concatenate(a, b); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Concatenate did not return the expected value."); } // A test for operator - (Quaternion, Quaternion) [TestMethod] public void QuaternionSubtractionTest() { Quaternion a = new Quaternion(1.0f, 6.0f, 7.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 2.0f, 3.0f, 8.0f); Quaternion expected = new Quaternion(-4.0f, 4.0f, 4.0f, -4.0f); Quaternion actual; actual = a - b; Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.operator - did not return the expected value."); } // A test for operator * (Quaternion, float) [TestMethod] public void QuaternionMultiplyTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); float factor = 0.5f; Quaternion expected = new Quaternion(0.5f, 1.0f, 1.5f, 2.0f); Quaternion actual; actual = a * factor; Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.operator * did not return the expected value."); } // A test for operator * (Quaternion, Quaternion) [TestMethod] public void QuaternionMultiplyTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = a * b; Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.operator * did not return the expected value."); } // A test for operator / (Quaternion, Quaternion) [TestMethod] public void QuaternionDivisionTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.045977015f, -0.09195402f, -7.450581E-9f, 0.402298868f); Quaternion actual; actual = a / b; Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.operator / did not return the expected value."); } // A test for operator + (Quaternion, Quaternion) [TestMethod] public void QuaternionAdditionTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(6.0f, 8.0f, 10.0f, 12.0f); Quaternion actual; actual = a + b; Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.operator + did not return the expected value."); } // A test for Quaternion (float, float, float, float) [TestMethod] public void QuaternionConstructorTest() { float x = 1.0f; float y = 2.0f; float z = 3.0f; float w = 4.0f; Quaternion target = new Quaternion(x, y, z, w); Assert.IsTrue(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z) && MathHelper.Equal(target.W, w), "Quaternion.constructor (x,y,z,w) did not return the expected value."); } // A test for Quaternion (Vector3, float) [TestMethod] public void QuaternionConstructorTest1() { Vector3 v = new Vector3(1.0f, 2.0f, 3.0f); float w = 4.0f; Quaternion target = new Quaternion(v, w); Assert.IsTrue(MathHelper.Equal(target.X, v.X) && MathHelper.Equal(target.Y, v.Y) && MathHelper.Equal(target.Z, v.Z) && MathHelper.Equal(target.W, w), "Quaternion.constructor (Vector3,w) did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3, float) [TestMethod] public void QuaternionCreateFromAxisAngleTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); float angle = MathHelper.ToRadians(30.0f); Quaternion expected = new Quaternion(0.0691723f, 0.1383446f, 0.207516879f, 0.9659258f); Quaternion actual; actual = Quaternion.CreateFromAxisAngle(axis, angle); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3, float) // CreateFromAxisAngle of zero vector [TestMethod] public void QuaternionCreateFromAxisAngleTest1() { Vector3 axis = new Vector3(); float angle = MathHelper.ToRadians(-30.0f); float cos = (float)System.Math.Cos(angle / 2.0f); Quaternion actual = Quaternion.CreateFromAxisAngle(axis, angle); Assert.IsTrue(actual.X == 0.0f && actual.Y == 0.0f && actual.Z == 0.0f && MathHelper.Equal(cos, actual.W) , "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3, float) // CreateFromAxisAngle of angle = 30 && 750 [TestMethod] public void QuaternionCreateFromAxisAngleTest2() { Vector3 axis = new Vector3(1, 0, 0); float angle1 = MathHelper.ToRadians(30.0f); float angle2 = MathHelper.ToRadians(750.0f); Quaternion actual1 = Quaternion.CreateFromAxisAngle(axis, angle1); Quaternion actual2 = Quaternion.CreateFromAxisAngle(axis, angle2); Assert.IsTrue(MathHelper.Equal(actual1, actual2), "Quaternion.CreateFromAxisAngle did not return the expected value."); } // A test for CreateFromAxisAngle (Vector3, float) // CreateFromAxisAngle of angle = 30 && 390 [TestMethod] public void QuaternionCreateFromAxisAngleTest3() { Vector3 axis = new Vector3(1, 0, 0); float angle1 = MathHelper.ToRadians(30.0f); float angle2 = MathHelper.ToRadians(390.0f); Quaternion actual1 = Quaternion.CreateFromAxisAngle(axis, angle1); Quaternion actual2 = Quaternion.CreateFromAxisAngle(axis, angle2); actual1.X = -actual1.X; actual1.W = -actual1.W; Assert.IsTrue(MathHelper.Equal(actual1, actual2), "Quaternion.CreateFromAxisAngle did not return the expected value."); } [TestMethod] public void QuaternionCreateFromYawPitchRollTest1() { float yawAngle = MathHelper.ToRadians(30.0f); float pitchAngle = MathHelper.ToRadians(40.0f); float rollAngle = MathHelper.ToRadians(50.0f); Quaternion yaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawAngle); Quaternion pitch = Quaternion.CreateFromAxisAngle(Vector3.UnitX, pitchAngle); Quaternion roll = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, rollAngle); Quaternion expected = yaw * pitch * roll; Quaternion actual = Quaternion.CreateFromYawPitchRoll(yawAngle, pitchAngle, rollAngle); Assert.IsTrue(MathHelper.Equal(expected, actual)); } // Covers more numeric rigions [TestMethod] public void QuaternionCreateFromYawPitchRollTest2() { const float step = 35.0f; for (float yawAngle = -720.0f; yawAngle <= 720.0f; yawAngle += step) { for (float pitchAngle = -720.0f; pitchAngle <= 720.0f; pitchAngle += step) { for (float rollAngle = -720.0f; rollAngle <= 720.0f; rollAngle += step) { float yawRad = MathHelper.ToRadians(yawAngle); float pitchRad = MathHelper.ToRadians(pitchAngle); float rollRad = MathHelper.ToRadians(rollAngle); Quaternion yaw = Quaternion.CreateFromAxisAngle(Vector3.UnitY, yawRad); Quaternion pitch = Quaternion.CreateFromAxisAngle(Vector3.UnitX, pitchRad); Quaternion roll = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, rollRad); Quaternion expected = yaw * pitch * roll; Quaternion actual = Quaternion.CreateFromYawPitchRoll(yawRad, pitchRad, rollRad); Assert.IsTrue(MathHelper.Equal(expected, actual), String.Format("Yaw:{0} Pitch:{1} Roll:{2}", yawAngle, pitchAngle, rollAngle)); } } } } // A test for Slerp (Quaternion, Quaternion, float) [TestMethod] public void QuaternionSlerpTest() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.5f; Quaternion expected = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(20.0f)); Quaternion actual; actual = Quaternion.Slerp(a, b, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); // Case a and b are same. expected = a; actual = Quaternion.Slerp(a, a, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where t = 0 [TestMethod] public void QuaternionSlerpTest1() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where t = 1 [TestMethod] public void QuaternionSlerpTest2() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 1.0f; Quaternion expected = new Quaternion(b.X, b.Y, b.Z, b.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where dot product is < 0 [TestMethod] public void QuaternionSlerpTest3() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = -a; float t = 1.0f; Quaternion expected = a; Quaternion actual = Quaternion.Slerp(a, b, t); // Note that in quaternion world, Q == -Q. In the case of quaternions dot product is zero, // one of the quaternion will be flipped to compute the shortest distance. When t = 1, we // expect the result to be the same as quaternion b but flipped. Assert.IsTrue(actual == expected, "Quaternion.Slerp did not return the expected value."); } // A test for Slerp (Quaternion, Quaternion, float) // Slerp test where the quaternion is flipped [TestMethod] public void QuaternionSlerpTest4() { Vector3 axis = Vector3.Normalize(new Vector3(1.0f, 2.0f, 3.0f)); Quaternion a = Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(10.0f)); Quaternion b = -Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(30.0f)); float t = 0.0f; Quaternion expected = new Quaternion(a.X, a.Y, a.Z, a.W); Quaternion actual = Quaternion.Slerp(a, b, t); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Slerp did not return the expected value."); } // A test for operator - (Quaternion) [TestMethod] public void QuaternionUnaryNegationTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(-1.0f, -2.0f, -3.0f, -4.0f); Quaternion actual; actual = -a; Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.operator - did not return the expected value."); } // A test for Inverse (Quaternion) [TestMethod] public void QuaternionInverseTest() { Quaternion a = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.0287356321f, -0.03448276f, -0.0402298868f, 0.04597701f); Quaternion actual; actual = Quaternion.Inverse(a); Assert.AreEqual(expected, actual, "Quaternion.Inverse did not return the expected value."); } // A test for Inverse (Quaternion) // Invert zero length quaternion [TestMethod] public void QuaternionInverseTest1() { Quaternion a = new Quaternion(); Quaternion actual = Quaternion.Inverse(a); Assert.IsTrue(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z) && float.IsNaN(actual.W) , "Quaternion.Inverse did not return the expected value."); } // A test for ToString () [TestMethod] public void QuaternionToStringTest() { Quaternion target = new Quaternion(-1.0f, 2.2f, 3.3f, -4.4f); string expected = "{X:-1 Y:2.2 Z:3.3 W:-4.4}"; string actual; actual = target.ToString(); Assert.AreEqual(expected, actual, "Quaternion.ToString did not return the expected value."); } // A test for Add (Quaternion, Quaternion) [TestMethod] public void QuaternionAddTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(6.0f, 8.0f, 10.0f, 12.0f); Quaternion actual; actual = Quaternion.Add(a, b); Assert.AreEqual(expected, actual, "Quaternion.Add did not return the expected value."); } // A test for Divide (Quaternion, Quaternion) [TestMethod] public void QuaternionDivideTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(-0.045977015f, -0.09195402f, -7.450581E-9f, 0.402298868f); Quaternion actual; actual = Quaternion.Divide(a, b); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Divide did not return the expected value."); } // A test for Equals (object) [TestMethod] public void QuaternionEqualsTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values object obj = b; bool expected = true; bool actual = a.Equals(obj); Assert.AreEqual(expected, actual, "Quaternion.Equals did not return the expected value."); // case 2: compare between different values b.X = 10.0f; obj = b; expected = false; actual = a.Equals(obj); Assert.AreEqual(expected, actual, "Quaternion.Equals did not return the expected value."); // case 3: compare between different types. obj = new Vector4(); expected = false; actual = a.Equals(obj); Assert.AreEqual(expected, actual, "Quaternion.Equals did not return the expected value."); // case 3: compare against null. obj = null; expected = false; actual = a.Equals(obj); Assert.AreEqual(expected, actual, "Quaternion.Equals did not return the expected value."); } // A test for GetHashCode () [TestMethod] public void QuaternionGetHashCodeTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); int expected = a.X.GetHashCode() + a.Y.GetHashCode() + a.Z.GetHashCode() + a.W.GetHashCode(); int actual = a.GetHashCode(); Assert.AreEqual(expected, actual, "Quaternion.GetHashCode did not return the expected value."); } // A test for Multiply (Quaternion, float) [TestMethod] public void QuaternionMultiplyTest2() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); float factor = 0.5f; Quaternion expected = new Quaternion(0.5f, 1.0f, 1.5f, 2.0f); Quaternion actual; actual = Quaternion.Multiply(a, factor); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Multiply did not return the expected value."); } // A test for Multiply (Quaternion, Quaternion) [TestMethod] public void QuaternionMultiplyTest3() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 6.0f, 7.0f, 8.0f); Quaternion expected = new Quaternion(24.0f, 48.0f, 48.0f, -6.0f); Quaternion actual; actual = Quaternion.Multiply(a, b); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.Multiply did not return the expected value."); } // A test for Negate (Quaternion) [TestMethod] public void QuaternionNegateTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion expected = new Quaternion(-1.0f, -2.0f, -3.0f, -4.0f); Quaternion actual; actual = Quaternion.Negate(a); Assert.AreEqual(expected, actual, "Quaternion.Negate did not return the expected value."); } // A test for Subtract (Quaternion, Quaternion) [TestMethod] public void QuaternionSubtractTest() { Quaternion a = new Quaternion(1.0f, 6.0f, 7.0f, 4.0f); Quaternion b = new Quaternion(5.0f, 2.0f, 3.0f, 8.0f); Quaternion expected = new Quaternion(-4.0f, 4.0f, 4.0f, -4.0f); Quaternion actual; actual = Quaternion.Subtract(a, b); Assert.AreEqual(expected, actual, "Quaternion.Subtract did not return the expected value."); } // A test for operator != (Quaternion, Quaternion) [TestMethod] public void QuaternionInequalityTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = false; bool actual = a != b; Assert.AreEqual(expected, actual, "Quaternion.operator != did not return the expected value."); // case 2: compare between different values b.X = 10.0f; expected = true; actual = a != b; Assert.AreEqual(expected, actual, "Quaternion.operator != did not return the expected value."); } // A test for operator == (Quaternion, Quaternion) [TestMethod] public void QuaternionEqualityTest() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = true; bool actual = a == b; Assert.AreEqual(expected, actual, "Quaternion.operator == did not return the expected value."); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a == b; Assert.AreEqual(expected, actual, "Quaternion.operator == did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Identity matrix test [TestMethod] public void QuaternionFromRotationMatrixTest1() { Matrix4x4 matrix = Matrix4x4.Identity; Quaternion expected = new Quaternion(0.0f, 0.0f, 0.0f, 1.0f); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.IsTrue(MathHelper.Equal(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.IsTrue(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert X axis rotation matrix [TestMethod] public void QuaternionFromRotationMatrixTest2() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.IsTrue(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString()); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.IsTrue(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString()); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Y axis rotation matrix [TestMethod] public void QuaternionFromRotationMatrixTest3() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationY(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.IsTrue(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0}", angle.ToString()); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.IsTrue(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0}", angle.ToString()); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert Z axis rotation matrix [TestMethod] public void QuaternionFromRotationMatrixTest4() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.IsTrue(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString()); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.IsTrue(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString()); } } // A test for CreateFromRotationMatrix (Matrix4x4) // Convert XYZ axis rotation matrix [TestMethod] public void QuaternionFromRotationMatrixTest5() { for (float angle = 0.0f; angle < 720.0f; angle += 10.0f) { Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationY(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.IsTrue(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), expected.ToString(), actual.ToString()); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.IsTrue(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value. angle:{0} expected:{1} actual:{2}", angle.ToString(), matrix.ToString(), m2.ToString()); } } // A test for CreateFromRotationMatrix (Matrix4x4) // X axis is most large axis case [TestMethod] public void QuaternionFromRotationMatrixWithScaledMatrixTest1() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationY(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.IsTrue(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.IsTrue(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Y axis is most large axis case [TestMethod] public void QuaternionFromRotationMatrixWithScaledMatrixTest2() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationZ(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitZ, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.IsTrue(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.IsTrue(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for CreateFromRotationMatrix (Matrix4x4) // Z axis is most large axis case [TestMethod] public void QuaternionFromRotationMatrixWithScaledMatrixTest3() { float angle = MathHelper.ToRadians(180.0f); Matrix4x4 matrix = Matrix4x4.CreateRotationX(angle) * Matrix4x4.CreateRotationY(angle); Quaternion expected = Quaternion.CreateFromAxisAngle(Vector3.UnitY, angle) * Quaternion.CreateFromAxisAngle(Vector3.UnitX, angle); Quaternion actual = Quaternion.CreateFromRotationMatrix(matrix); Assert.IsTrue(MathHelper.EqualRotation(expected, actual), "Quaternion.CreateFromRotationMatrix did not return the expected value."); // make sure convert back to matrix is same as we passed matrix. Matrix4x4 m2 = Matrix4x4.CreateFromQuaternion(actual); Assert.IsTrue(MathHelper.Equal(matrix, m2), "Quaternion.CreateFromRotationMatrix did not return the expected value."); } // A test for Equals (Quaternion) [TestMethod] public void QuaternionEqualsTest1() { Quaternion a = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); Quaternion b = new Quaternion(1.0f, 2.0f, 3.0f, 4.0f); // case 1: compare between same values bool expected = true; bool actual = a.Equals(b); Assert.AreEqual(expected, actual, "Quaternion.Equals did not return the expected value."); // case 2: compare between different values b.X = 10.0f; expected = false; actual = a.Equals(b); Assert.AreEqual(expected, actual, "Quaternion.Equals did not return the expected value."); } // A test for Identity [TestMethod] public void QuaternionIdentityTest() { Quaternion val = new Quaternion(0, 0, 0, 1); Assert.AreEqual(val, Quaternion.Identity, "Quaternion.Identity was not set correctly."); } // A test for IsIdentity [TestMethod] public void QuaternionIsIdentityTest() { Assert.IsTrue(Quaternion.Identity.IsIdentity); Assert.IsTrue(new Quaternion(0, 0, 0, 1).IsIdentity); Assert.IsFalse(new Quaternion(1, 0, 0, 1).IsIdentity); Assert.IsFalse(new Quaternion(0, 1, 0, 1).IsIdentity); Assert.IsFalse(new Quaternion(0, 0, 1, 1).IsIdentity); Assert.IsFalse(new Quaternion(0, 0, 0, 0).IsIdentity); } // A test for Quaternion comparison involving NaN values [TestMethod] public void QuaternionEqualsNanTest() { Quaternion a = new Quaternion(float.NaN, 0, 0, 0); Quaternion b = new Quaternion(0, float.NaN, 0, 0); Quaternion c = new Quaternion(0, 0, float.NaN, 0); Quaternion d = new Quaternion(0, 0, 0, float.NaN); Assert.IsFalse(a == new Quaternion(0, 0, 0, 0)); Assert.IsFalse(b == new Quaternion(0, 0, 0, 0)); Assert.IsFalse(c == new Quaternion(0, 0, 0, 0)); Assert.IsFalse(d == new Quaternion(0, 0, 0, 0)); Assert.IsTrue(a != new Quaternion(0, 0, 0, 0)); Assert.IsTrue(b != new Quaternion(0, 0, 0, 0)); Assert.IsTrue(c != new Quaternion(0, 0, 0, 0)); Assert.IsTrue(d != new Quaternion(0, 0, 0, 0)); Assert.IsFalse(a.Equals(new Quaternion(0, 0, 0, 0))); Assert.IsFalse(b.Equals(new Quaternion(0, 0, 0, 0))); Assert.IsFalse(c.Equals(new Quaternion(0, 0, 0, 0))); Assert.IsFalse(d.Equals(new Quaternion(0, 0, 0, 0))); Assert.IsFalse(a.IsIdentity); Assert.IsFalse(b.IsIdentity); Assert.IsFalse(c.IsIdentity); Assert.IsFalse(d.IsIdentity); // Counterintuitive result - IEEE rules for NaN comparison are weird! Assert.IsFalse(a.Equals(a)); Assert.IsFalse(b.Equals(b)); Assert.IsFalse(c.Equals(c)); Assert.IsFalse(d.Equals(d)); } // A test to make sure these types are blittable directly into GPU buffer memory layouts [TestMethod] public unsafe void QuaternionSizeofTest() { Assert.AreEqual(16, sizeof(Quaternion)); Assert.AreEqual(32, sizeof(Quaternion_2x)); Assert.AreEqual(20, sizeof(QuaternionPlusFloat)); Assert.AreEqual(40, sizeof(QuaternionPlusFloat_2x)); } [StructLayout(LayoutKind.Sequential)] struct Quaternion_2x { Quaternion a; Quaternion b; } [StructLayout(LayoutKind.Sequential)] struct QuaternionPlusFloat { Quaternion v; float f; } [StructLayout(LayoutKind.Sequential)] struct QuaternionPlusFloat_2x { QuaternionPlusFloat a; QuaternionPlusFloat b; } // A test to make sure the fields are laid out how we expect [TestMethod] public unsafe void QuaternionFieldOffsetTest() { Quaternion value; Assert.AreEqual(0 + new IntPtr(&value).ToInt64(), new IntPtr(&value.X).ToInt64()); Assert.AreEqual(4 + new IntPtr(&value).ToInt64(), new IntPtr(&value.Y).ToInt64()); Assert.AreEqual(8 + new IntPtr(&value).ToInt64(), new IntPtr(&value.Z).ToInt64()); Assert.AreEqual(12 + new IntPtr(&value).ToInt64(), new IntPtr(&value.W).ToInt64()); } // A test to validate interop between .NET (System.Numerics) and WinRT (Microsoft.Graphics.Canvas.Numerics) [TestMethod] public void QuaternionWinRTInteropTest() { Quaternion a = new Quaternion(23, 42, 100, -1); Microsoft.Graphics.Canvas.Numerics.Quaternion b = a; Assert.AreEqual(a.X, b.X); Assert.AreEqual(a.Y, b.Y); Assert.AreEqual(a.Z, b.Z); Assert.AreEqual(a.W, b.W); Quaternion c = b; Assert.AreEqual(a, c); } } }
using System.Globalization; using System.Text.RegularExpressions; using System.Collections.ObjectModel; using Signum.Utilities.NaturalLanguage; namespace Signum.Utilities; public static class NaturalLanguageTools { public static Dictionary<string, IPluralizer> Pluralizers = new Dictionary<string, IPluralizer> { {"es", new SpanishPluralizer()}, {"en", new EnglishPluralizer()}, {"de", new GermanPluralizer()}, }; public static Dictionary<string, IGenderDetector> GenderDetectors = new Dictionary<string, IGenderDetector> { {"es", new SpanishGenderDetector()}, {"de", new GermanGenderDetector()}, }; static Dictionary<string, string> SimpleDeterminers = new Dictionary<string, string>() { {"en", "the"} }; public static Dictionary<string, INumberWriter> NumberWriters = new Dictionary<string, INumberWriter> { {"es", new SpanishNumberWriter()}, {"de", new GermanNumberWriter()}, }; public static Dictionary<string, IDiacriticsRemover> DiacriticsRemover = new Dictionary<string, IDiacriticsRemover> { {"de", new GermanDiacriticsRemover()}, }; public static char? GetGender(string name, CultureInfo? culture = null) { var defCulture = culture ?? CultureInfo.CurrentUICulture; var detector = GenderDetectors.TryGetC(defCulture.TwoLetterISOLanguageName); if (detector == null) return null; return detector.GetGender(name); } public static bool HasGenders(CultureInfo cultureInfo) { var detector = GenderDetectors.TryGetC(cultureInfo.TwoLetterISOLanguageName); if (detector == null) return false; return !detector.Determiner.IsNullOrEmpty(); } public static string? GetDeterminer(char? gender, bool plural, CultureInfo? culture = null) { if (culture == null) culture = CultureInfo.CurrentUICulture; var detector = GenderDetectors.TryGetC(culture.TwoLetterISOLanguageName); if (detector == null) return SimpleDeterminers.TryGetC(culture.TwoLetterISOLanguageName); var pro = detector.Determiner.FirstOrDefault(a => a.Gender == gender); if (pro == null) return null; return plural ? pro.Plural : pro.Singular; } public static bool TryGetGenderFromDeterminer(string? determiner, bool plural, CultureInfo culture, out char? gender) { gender = null; if (culture == null) culture = CultureInfo.CurrentUICulture; if (determiner == null) return false; var detector = GenderDetectors.TryGetC(culture.TwoLetterISOLanguageName); if (detector == null) return SimpleDeterminers.TryGetC(culture.TwoLetterISOLanguageName) == determiner; var pro = detector.Determiner.FirstOrDefault(a => (plural ? a.Plural : a.Singular) == determiner); if (pro != null) { gender = pro.Gender; return true; } return false; } public static string Pluralize(string singularName, CultureInfo? culture = null) { if (culture == null) culture = CultureInfo.CurrentUICulture; var pluralizer = Pluralizers.TryGetC(culture.TwoLetterISOLanguageName); if (pluralizer == null) return singularName; return pluralizer.MakePlural(singularName); } public static string NiceName(this string memberName) { return memberName.Contains('_') ? memberName.Replace('_', ' ') : memberName.SpacePascal(); } public static string SpacePascal(this string pascalStr, CultureInfo? culture = null) { var defCulture = culture ?? CultureInfo.CurrentUICulture; return SpacePascal(pascalStr, false); } public static string SpacePascal(this string pascalStr, bool preserveUppercase) { if (string.IsNullOrEmpty(pascalStr)) return pascalStr; StringBuilder sb = new StringBuilder(); for (int i = 0; i < pascalStr.Length; i++) { switch (Kind(pascalStr, i)) { case CharKind.Lowecase: sb.Append(pascalStr[i]); break; case CharKind.StartOfWord: sb.Append(" "); sb.Append(preserveUppercase ? pascalStr[i] : char.ToLower(pascalStr[i])); break; case CharKind.StartOfSentence: sb.Append(pascalStr[i]); break; case CharKind.Abbreviation: sb.Append(pascalStr[i]); break; case CharKind.StartOfAbbreviation: sb.Append(" "); sb.Append(pascalStr[i]); break; default: break; } } return sb.ToString(); } static CharKind Kind(string pascalStr, int i) { if (i == 0) return CharKind.StartOfSentence; if (!char.IsUpper(pascalStr[i])) return CharKind.Lowecase; if (i + 1 == pascalStr.Length) { if (char.IsUpper(pascalStr[i - 1])) return CharKind.Abbreviation; return CharKind.StartOfWord; } if (char.IsLower(pascalStr[i + 1])) return CharKind.StartOfWord; // Xb if (!char.IsUpper(pascalStr[i - 1])) { if (i + 2 == pascalStr.Length) return CharKind.StartOfAbbreviation; //aXB| if (!char.IsUpper(pascalStr[i + 2])) return CharKind.StartOfWord; //aXBc return CharKind.StartOfAbbreviation; //aXBC } return CharKind.Abbreviation; //AXB } public enum CharKind { Lowecase, StartOfWord, StartOfSentence, StartOfAbbreviation, Abbreviation, } public static string ToPascal(this string str) { return str.ToPascal(true, false); } public static string ToPascal(this string str, bool firstUpper, bool keepUppercase) { str = str.RemoveDiacritics(); StringBuilder sb = new StringBuilder(str.Length); bool upper = true; for (int i = 0; i < str.Length; i++) { char c = str[i]; if (!char.IsLetter(c) && !char.IsNumber(c)) upper = true; else { sb.Append(upper ? char.ToUpper(c) : keepUppercase ? c : char.ToLower(c)); if (char.IsLetter(c)) upper = false; } } return sb.ToString(); } /// <param name="genderAwareText">Something like Line[s] or [1m:Man|m:Men|1f:Woman|f:Women]</param> /// <param name="gender">Masculine, Femenine, Neutrum, Inanimate, Animate</param> public static string ForGenderAndNumber(this string genderAwareText, char? gender = null, int? number = null) { if (gender == null && number == null) return genderAwareText; if (number == null) return GetPart(genderAwareText, gender + ":"); if (gender == null) { if (number.Value == 1) return GetPart(genderAwareText, "1:"); return GetPart(genderAwareText, number.Value + ":", ":", ""); } if (number.Value == 1) return GetPart(genderAwareText, "1" + gender.Value + ":", "1:"); return GetPart(genderAwareText, gender.Value + number.Value + ":", gender.Value + ":", number.Value + ":", ":"); } static string GetPart(string textToReplace, params string[] prefixes) { return Regex.Replace(textToReplace, @"\[(?<part>[^\|\]]+)(\|(?<part>[^\|\]]+))*\]", m => { var captures = m.Groups["part"].Captures.OfType<Capture>(); foreach (var pr in prefixes) { Capture? capture = captures.FirstOrDefault(c => c.Value.StartsWith(pr)); if (capture != null) return capture.Value.RemoveStart(pr.Length); } return ""; }); } } public interface IPluralizer { string MakePlural(string singularName); } public interface IGenderDetector { char? GetGender(string name); ReadOnlyCollection<PronomInfo> Determiner { get; } } public class PronomInfo { public char Gender { get; private set; } public string Singular { get; private set; } public string Plural { get; private set; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. public PronomInfo() { } #pragma warning restore CS8618 // Non-nullable field is uninitialized. public PronomInfo(char gender, string singular, string plural) { this.Gender = gender; this.Singular = singular; this.Plural = plural; } } public interface INumberWriter { string ToNumber(decimal number, NumberWriterSettings settings); } public interface IDiacriticsRemover { string RemoveDiacritics(string str); } #pragma warning disable CS8618 // Non-nullable field is uninitialized. public class NumberWriterSettings { public string Unit; public string UnitPlural; public char? UnitGender; public string DecimalUnit; public string DecimalUnitPlural; public char? DecimalUnitGender; public int NumberOfDecimals; public bool OmitDecimalZeros; } #pragma warning restore CS8618 // Non-nullable field is uninitialized.
// Lucene version compatibility level 4.8.1 using NUnit.Framework; using System.IO; using System.Text.RegularExpressions; namespace Lucene.Net.Analysis.Pattern { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public class TestPatternCaptureGroupTokenFilter : BaseTokenStreamTestCase { [Test] public virtual void TestNoPattern() { TestPatterns("foobarbaz", new string[] { }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, false); TestPatterns("foobarbaz", new string[] { }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, true); TestPatterns("foo bar baz", new string[] { }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("foo bar baz", new string[] { }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, true); } [Test] public virtual void TestNoMatch() { TestPatterns("foobarbaz", new string[] { "xx" }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, false); TestPatterns("foobarbaz", new string[] { "xx" }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, true); TestPatterns("foo bar baz", new string[] { "xx" }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("foo bar baz", new string[] { "xx" }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, true); } [Test] public virtual void TestNoCapture() { TestPatterns("foobarbaz", new string[] { ".." }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, false); TestPatterns("foobarbaz", new string[] { ".." }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, true); TestPatterns("foo bar baz", new string[] { ".." }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("foo bar baz", new string[] { ".." }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, true); } [Test] public virtual void TestEmptyCapture() { TestPatterns("foobarbaz", new string[] { ".(y*)" }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, false); TestPatterns("foobarbaz", new string[] { ".(y*)" }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, true); TestPatterns("foo bar baz", new string[] { ".(y*)" }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("foo bar baz", new string[] { ".(y*)" }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, true); } [Test] public virtual void TestCaptureAll() { TestPatterns("foobarbaz", new string[] { "(.+)" }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, false); TestPatterns("foobarbaz", new string[] { "(.+)" }, new string[] { "foobarbaz" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, true); TestPatterns("foo bar baz", new string[] { "(.+)" }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("foo bar baz", new string[] { "(.+)" }, new string[] { "foo", "bar", "baz" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, true); } [Test] public virtual void TestCaptureStart() { TestPatterns("foobarbaz", new string[] { "^(.)" }, new string[] { "f" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, false); TestPatterns("foobarbaz", new string[] { "^(.)" }, new string[] { "foobarbaz", "f" }, new int[] { 0, 0 }, new int[] { 9, 9 }, new int[] { 1, 0 }, true); TestPatterns("foo bar baz", new string[] { "^(.)" }, new string[] { "f", "b", "b" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("foo bar baz", new string[] { "^(.)" }, new string[] { "foo", "f", "bar", "b", "baz", "b" }, new int[] { 0, 0, 4, 4, 8, 8 }, new int[] { 3, 3, 7, 7, 11, 11 }, new int[] { 1, 0, 1, 0, 1, 0 }, true); } [Test] public virtual void TestCaptureMiddle() { TestPatterns("foobarbaz", new string[] { "^.(.)." }, new string[] { "o" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, false); TestPatterns("foobarbaz", new string[] { "^.(.)." }, new string[] { "foobarbaz", "o" }, new int[] { 0, 0 }, new int[] { 9, 9 }, new int[] { 1, 0 }, true); TestPatterns("foo bar baz", new string[] { "^.(.)." }, new string[] { "o", "a", "a" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("foo bar baz", new string[] { "^.(.)." }, new string[] { "foo", "o", "bar", "a", "baz", "a" }, new int[] { 0, 0, 4, 4, 8, 8 }, new int[] { 3, 3, 7, 7, 11, 11 }, new int[] { 1, 0, 1, 0, 1, 0 }, true); } [Test] public virtual void TestCaptureEnd() { TestPatterns("foobarbaz", new string[] { "(.)$" }, new string[] { "z" }, new int[] { 0 }, new int[] { 9 }, new int[] { 1 }, false); TestPatterns("foobarbaz", new string[] { "(.)$" }, new string[] { "foobarbaz", "z" }, new int[] { 0, 0 }, new int[] { 9, 9 }, new int[] { 1, 0 }, true); TestPatterns("foo bar baz", new string[] { "(.)$" }, new string[] { "o", "r", "z" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("foo bar baz", new string[] { "(.)$" }, new string[] { "foo", "o", "bar", "r", "baz", "z" }, new int[] { 0, 0, 4, 4, 8, 8 }, new int[] { 3, 3, 7, 7, 11, 11 }, new int[] { 1, 0, 1, 0, 1, 0 }, true); } [Test] public virtual void TestCaptureStartMiddle() { TestPatterns("foobarbaz", new string[] { "^(.)(.)" }, new string[] { "f", "o" }, new int[] { 0, 0 }, new int[] { 9, 9 }, new int[] { 1, 0 }, false); TestPatterns("foobarbaz", new string[] { "^(.)(.)" }, new string[] { "foobarbaz", "f", "o" }, new int[] { 0, 0, 0 }, new int[] { 9, 9, 9 }, new int[] { 1, 0, 0 }, true); TestPatterns("foo bar baz", new string[] { "^(.)(.)" }, new string[] { "f", "o", "b", "a", "b", "a" }, new int[] { 0, 0, 4, 4, 8, 8 }, new int[] { 3, 3, 7, 7, 11, 11 }, new int[] { 1, 0, 1, 0, 1, 0 }, false); TestPatterns("foo bar baz", new string[] { "^(.)(.)" }, new string[] { "foo", "f", "o", "bar", "b", "a", "baz", "b", "a" }, new int[] { 0, 0, 0, 4, 4, 4, 8, 8, 8 }, new int[] { 3, 3, 3, 7, 7, 7, 11, 11, 11 }, new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0 }, true); } [Test] public virtual void TestCaptureStartEnd() { TestPatterns("foobarbaz", new string[] { "^(.).+(.)$" }, new string[] { "f", "z" }, new int[] { 0, 0 }, new int[] { 9, 9 }, new int[] { 1, 0 }, false); TestPatterns("foobarbaz", new string[] { "^(.).+(.)$" }, new string[] { "foobarbaz", "f", "z" }, new int[] { 0, 0, 0 }, new int[] { 9, 9, 9 }, new int[] { 1, 0, 0 }, true); TestPatterns("foo bar baz", new string[] { "^(.).+(.)$" }, new string[] { "f", "o", "b", "r", "b", "z" }, new int[] { 0, 0, 4, 4, 8, 8 }, new int[] { 3, 3, 7, 7, 11, 11 }, new int[] { 1, 0, 1, 0, 1, 0 }, false); TestPatterns("foo bar baz", new string[] { "^(.).+(.)$" }, new string[] { "foo", "f", "o", "bar", "b", "r", "baz", "b", "z" }, new int[] { 0, 0, 0, 4, 4, 4, 8, 8, 8 }, new int[] { 3, 3, 3, 7, 7, 7, 11, 11, 11 }, new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0 }, true); } [Test] public virtual void TestCaptureMiddleEnd() { TestPatterns("foobarbaz", new string[] { "(.)(.)$" }, new string[] { "a", "z" }, new int[] { 0, 0 }, new int[] { 9, 9 }, new int[] { 1, 0 }, false); TestPatterns("foobarbaz", new string[] { "(.)(.)$" }, new string[] { "foobarbaz", "a", "z" }, new int[] { 0, 0, 0 }, new int[] { 9, 9, 9 }, new int[] { 1, 0, 0 }, true); TestPatterns("foo bar baz", new string[] { "(.)(.)$" }, new string[] { "o", "o", "a", "r", "a", "z" }, new int[] { 0, 0, 4, 4, 8, 8 }, new int[] { 3, 3, 7, 7, 11, 11 }, new int[] { 1, 0, 1, 0, 1, 0 }, false); TestPatterns("foo bar baz", new string[] { "(.)(.)$" }, new string[] { "foo", "o", "o", "bar", "a", "r", "baz", "a", "z" }, new int[] { 0, 0, 0, 4, 4, 4, 8, 8, 8 }, new int[] { 3, 3, 3, 7, 7, 7, 11, 11, 11 }, new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0 }, true); } [Test] public virtual void TestMultiCaptureOverlap() { TestPatterns("foobarbaz", new string[] { "(.(.(.)))" }, new string[] { "foo", "oo", "o", "bar", "ar", "r", "baz", "az", "z" }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 9, 9, 9, 9, 9, 9, 9, 9, 9 }, new int[] { 1, 0, 0, 0, 0, 0, 0, 0, 0 }, false); TestPatterns("foobarbaz", new string[] { "(.(.(.)))" }, new string[] { "foobarbaz", "foo", "oo", "o", "bar", "ar", "r", "baz", "az", "z" }, new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, new int[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }, new int[] { 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, true); TestPatterns("foo bar baz", new string[] { "(.(.(.)))" }, new string[] { "foo", "oo", "o", "bar", "ar", "r", "baz", "az", "z" }, new int[] { 0, 0, 0, 4, 4, 4, 8, 8, 8 }, new int[] { 3, 3, 3, 7, 7, 7, 11, 11, 11 }, new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0 }, false); TestPatterns("foo bar baz", new string[] { "(.(.(.)))" }, new string[] { "foo", "oo", "o", "bar", "ar", "r", "baz", "az", "z" }, new int[] { 0, 0, 0, 4, 4, 4, 8, 8, 8 }, new int[] { 3, 3, 3, 7, 7, 7, 11, 11, 11 }, new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0 }, true); } [Test] public virtual void TestMultiPattern() { TestPatterns("aaabbbaaa", new string[] { "(aaa)", "(bbb)", "(ccc)" }, new string[] { "aaa", "bbb", "aaa" }, new int[] { 0, 0, 0 }, new int[] { 9, 9, 9 }, new int[] { 1, 0, 0 }, false); TestPatterns("aaabbbaaa", new string[] { "(aaa)", "(bbb)", "(ccc)" }, new string[] { "aaabbbaaa", "aaa", "bbb", "aaa" }, new int[] { 0, 0, 0, 0 }, new int[] { 9, 9, 9, 9 }, new int[] { 1, 0, 0, 0 }, true); TestPatterns("aaa bbb aaa", new string[] { "(aaa)", "(bbb)", "(ccc)" }, new string[] { "aaa", "bbb", "aaa" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, false); TestPatterns("aaa bbb aaa", new string[] { "(aaa)", "(bbb)", "(ccc)" }, new string[] { "aaa", "bbb", "aaa" }, new int[] { 0, 4, 8 }, new int[] { 3, 7, 11 }, new int[] { 1, 1, 1 }, true); } [Test] public virtual void TestCamelCase() { TestPatterns("letsPartyLIKEits1999_dude", new string[] { "([A-Z]{2,})", "(?<![A-Z])([A-Z][a-z]+)", "(?:^|\\b|(?<=[0-9_])|(?<=[A-Z]{2}))([a-z]+)", "([0-9]+)" }, new string[] { "lets", "Party", "LIKE", "its", "1999", "dude" }, new int[] { 0, 0, 0, 0, 0, 0 }, new int[] { 25, 25, 25, 25, 25, 25 }, new int[] { 1, 0, 0, 0, 0, 0, 0 }, false); TestPatterns("letsPartyLIKEits1999_dude", new string[] { "([A-Z]{2,})", "(?<![A-Z])([A-Z][a-z]+)", "(?:^|\\b|(?<=[0-9_])|(?<=[A-Z]{2}))([a-z]+)", "([0-9]+)" }, new string[] { "letsPartyLIKEits1999_dude", "lets", "Party", "LIKE", "its", "1999", "dude" }, new int[] { 0, 0, 0, 0, 0, 0, 0 }, new int[] { 25, 25, 25, 25, 25, 25, 25 }, new int[] { 1, 0, 0, 0, 0, 0, 0, 0 }, true); } [Test] public virtual void TestRandomString() { Analyzer a = Analyzer.NewAnonymous(createComponents: (fieldName, reader) => { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false); return new TokenStreamComponents(tokenizer, new PatternCaptureGroupTokenFilter(tokenizer, false, new Regex("((..)(..))", RegexOptions.Compiled))); }); CheckRandomData(Random, a, 1000 * RandomMultiplier); } private void TestPatterns(string input, string[] regexes, string[] tokens, int[] startOffsets, int[] endOffsets, int[] positions, bool preserveOriginal) { Regex[] patterns = new Regex[regexes.Length]; for (int i = 0; i < regexes.Length; i++) { patterns[i] = new Regex(regexes[i], RegexOptions.Compiled); } TokenStream ts = new PatternCaptureGroupTokenFilter(new MockTokenizer(new StringReader(input), MockTokenizer.WHITESPACE, false), preserveOriginal, patterns); AssertTokenStreamContents(ts, tokens, startOffsets, endOffsets, positions); } } }
using System; using System.Buffers; using System.Buffers.Binary; using Orleans.Configuration; using Orleans.Networking.Shared; using Orleans.Serialization; namespace Orleans.Runtime.Messaging { internal sealed class MessageSerializer : IMessageSerializer { private const int FramingLength = Message.LENGTH_HEADER_SIZE; private const int MessageSizeHint = 4096; private readonly HeadersSerializer headersSerializer; private readonly OrleansSerializer<object> objectSerializer; private readonly MemoryPool<byte> memoryPool; private readonly int maxHeaderLength; private readonly int maxBodyLength; private object bufferWriter; public MessageSerializer( SerializationManager serializationManager, SharedMemoryPool memoryPool, int maxHeaderSize, int maxBodySize) { this.headersSerializer = new HeadersSerializer(serializationManager); this.objectSerializer = new OrleansSerializer<object>(serializationManager); this.memoryPool = memoryPool.Pool; this.maxHeaderLength = maxHeaderSize; this.maxBodyLength = maxBodySize; } public (int RequiredBytes, int HeaderLength, int BodyLength) TryRead(ref ReadOnlySequence<byte> input, out Message message) { message = default; if (input.Length < FramingLength) { return (FramingLength, 0, 0); } Span<byte> lengthBytes = stackalloc byte[FramingLength]; input.Slice(input.Start, FramingLength).CopyTo(lengthBytes); var headerLength = BinaryPrimitives.ReadInt32LittleEndian(lengthBytes); var bodyLength = BinaryPrimitives.ReadInt32LittleEndian(lengthBytes.Slice(4)); // Check lengths ThrowIfLengthsInvalid(headerLength, bodyLength); var requiredBytes = FramingLength + headerLength + bodyLength; if (input.Length < requiredBytes) { message = default; return (requiredBytes, 0, 0); } try { // decode header var header = input.Slice(FramingLength, headerLength); // decode body int bodyOffset = FramingLength + headerLength; var body = input.Slice(bodyOffset, bodyLength); // build message this.headersSerializer.Deserialize(header, out var headersContainer); message = new Message { Headers = headersContainer }; // Body deserialization is more likely to fail than header deserialization. // Separating the two allows for these kinds of errors to be propagated back to the caller. this.objectSerializer.Deserialize(body, out var bodyObject); message.BodyObject = bodyObject; return (0, headerLength, bodyLength); } finally { input = input.Slice(requiredBytes); } } public (int HeaderLength, int BodyLength) Write<TBufferWriter>(ref TBufferWriter writer, Message message) where TBufferWriter : IBufferWriter<byte> { if (!(this.bufferWriter is PrefixingBufferWriter<byte, TBufferWriter> buffer)) { this.bufferWriter = buffer = new PrefixingBufferWriter<byte, TBufferWriter>(FramingLength, MessageSizeHint, this.memoryPool); } buffer.Reset(writer); Span<byte> lengthFields = stackalloc byte[FramingLength]; this.headersSerializer.Serialize(buffer, message.Headers); var headerLength = buffer.CommittedBytes; this.objectSerializer.Serialize(buffer, message.BodyObject); // Write length prefixes, first header length then body length. BinaryPrimitives.WriteInt32LittleEndian(lengthFields, headerLength); var bodyLength = buffer.CommittedBytes - headerLength; BinaryPrimitives.WriteInt32LittleEndian(lengthFields.Slice(4), bodyLength); // Before completing, check lengths ThrowIfLengthsInvalid(headerLength, bodyLength); buffer.Complete(lengthFields); return (headerLength, bodyLength); } private void ThrowIfLengthsInvalid(int headerLength, int bodyLength) { if (headerLength <= 0 || headerLength > this.maxHeaderLength) throw new OrleansException($"Invalid header size: {headerLength} (max configured value is {this.maxHeaderLength}, see {nameof(MessagingOptions.MaxMessageHeaderSize)})"); if (bodyLength < 0 || bodyLength > this.maxBodyLength) throw new OrleansException($"Invalid body size: {bodyLength} (max configured value is {this.maxBodyLength}, see {nameof(MessagingOptions.MaxMessageBodySize)})"); } private sealed class OrleansSerializer<T> { private readonly SerializationManager serializationManager; private readonly BinaryTokenStreamReader2 reader = new BinaryTokenStreamReader2(); private readonly SerializationContext serializationContext; private readonly DeserializationContext deserializationContext; public OrleansSerializer(SerializationManager serializationManager) { this.serializationManager = serializationManager; this.serializationContext = new SerializationContext(serializationManager); this.deserializationContext = new DeserializationContext(serializationManager) { StreamReader = this.reader }; } public void Deserialize(ReadOnlySequence<byte> input, out T value) { reader.PartialReset(input); try { value = (T)SerializationManager.DeserializeInner(this.serializationManager, typeof(T), this.deserializationContext, this.reader); } finally { this.deserializationContext.Reset(); } } public void Serialize<TBufferWriter>(TBufferWriter output, T value) where TBufferWriter : IBufferWriter<byte> { var streamWriter = this.serializationContext.StreamWriter; if (streamWriter is BinaryTokenStreamWriter2<TBufferWriter> writer) { writer.PartialReset(output); } else { this.serializationContext.StreamWriter = writer = new BinaryTokenStreamWriter2<TBufferWriter>(output); } try { SerializationManager.SerializeInner(this.serializationManager, value, typeof(T), this.serializationContext, writer); } finally { writer.Commit(); this.serializationContext.Reset(); } } } private sealed class HeadersSerializer { private readonly BinaryTokenStreamReader2 reader = new BinaryTokenStreamReader2(); private readonly SerializationContext serializationContext; private readonly DeserializationContext deserializationContext; public HeadersSerializer(SerializationManager serializationManager) { this.serializationContext = new SerializationContext(serializationManager); this.deserializationContext = new DeserializationContext(serializationManager) { StreamReader = this.reader }; } public void Deserialize(ReadOnlySequence<byte> input, out Message.HeadersContainer value) { try { reader.PartialReset(input); value = (Message.HeadersContainer)Message.HeadersContainer.Deserializer(null, this.deserializationContext); } finally { this.deserializationContext.Reset(); } } public void Serialize<TBufferWriter>(TBufferWriter output, Message.HeadersContainer value) where TBufferWriter : IBufferWriter<byte> { var streamWriter = this.serializationContext.StreamWriter; if (streamWriter is BinaryTokenStreamWriter2<TBufferWriter> writer) { writer.PartialReset(output); } else { this.serializationContext.StreamWriter = writer = new BinaryTokenStreamWriter2<TBufferWriter>(output); } try { Message.HeadersContainer.Serializer(value, this.serializationContext, null); } finally { writer.Commit(); this.serializationContext.Reset(); } } } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reactive; using System.Reactive.Linq; using Avalonia.Data.Core.Parsers; using Avalonia.Data.Core.Plugins; using Avalonia.Reactive; namespace Avalonia.Data.Core { /// <summary> /// Observes and sets the value of an expression on an object. /// </summary> public class ExpressionObserver : LightweightObservableBase<object>, IDescription { /// <summary> /// An ordered collection of property accessor plugins that can be used to customize /// the reading and subscription of property values on a type. /// </summary> public static readonly List<IPropertyAccessorPlugin> PropertyAccessors = new List<IPropertyAccessorPlugin> { new AvaloniaPropertyAccessorPlugin(), new MethodAccessorPlugin(), new InpcPropertyAccessorPlugin(), }; /// <summary> /// An ordered collection of validation checker plugins that can be used to customize /// the validation of view model and model data. /// </summary> public static readonly List<IDataValidationPlugin> DataValidators = new List<IDataValidationPlugin> { new DataAnnotationsValidationPlugin(), new IndeiValidationPlugin(), new ExceptionValidationPlugin(), }; /// <summary> /// An ordered collection of stream plugins that can be used to customize the behavior /// of the '^' stream binding operator. /// </summary> public static readonly List<IStreamPlugin> StreamHandlers = new List<IStreamPlugin> { new TaskStreamPlugin(), new ObservableStreamPlugin(), }; private static readonly object UninitializedValue = new object(); private readonly ExpressionNode _node; private object _root; private IDisposable _rootSubscription; private WeakReference<object> _value; private IReadOnlyList<ITransformNode> _transformNodes; /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="root">The root object.</param> /// <param name="node">The expression.</param> /// <param name="description"> /// A description of the expression. /// </param> public ExpressionObserver( object root, ExpressionNode node, string description = null) { if (root == AvaloniaProperty.UnsetValue) { root = null; } _node = node; Description = description; _root = new WeakReference<object>(root); } /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="rootObservable">An observable which provides the root object.</param> /// <param name="node">The expression.</param> /// <param name="description"> /// A description of the expression. /// </param> public ExpressionObserver( IObservable<object> rootObservable, ExpressionNode node, string description) { Contract.Requires<ArgumentNullException>(rootObservable != null); _node = node; Description = description; _root = rootObservable; } /// <summary> /// Initializes a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="rootGetter">A function which gets the root object.</param> /// <param name="node">The expression.</param> /// <param name="update">An observable which triggers a re-read of the getter.</param> /// <param name="description"> /// A description of the expression. /// </param> public ExpressionObserver( Func<object> rootGetter, ExpressionNode node, IObservable<Unit> update, string description) { Contract.Requires<ArgumentNullException>(rootGetter != null); Contract.Requires<ArgumentNullException>(update != null); Description = description; _node = node; _node.Target = new WeakReference<object>(rootGetter()); _root = update.Select(x => rootGetter()); } /// <summary> /// Creates a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="root">The root object.</param> /// <param name="expression">The expression.</param> /// <param name="enableDataValidation">Whether or not to track data validation</param> /// <param name="description"> /// A description of the expression. If null, <paramref name="expression"/>'s string representation will be used. /// </param> public static ExpressionObserver Create<T, U>( T root, Expression<Func<T, U>> expression, bool enableDataValidation = false, string description = null) { return new ExpressionObserver(root, Parse(expression, enableDataValidation), description ?? expression.ToString()); } /// <summary> /// Creates a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="rootObservable">An observable which provides the root object.</param> /// <param name="expression">The expression.</param> /// <param name="enableDataValidation">Whether or not to track data validation</param> /// <param name="description"> /// A description of the expression. If null, <paramref name="expression"/>'s string representation will be used. /// </param> public static ExpressionObserver Create<T, U>( IObservable<T> rootObservable, Expression<Func<T, U>> expression, bool enableDataValidation = false, string description = null) { Contract.Requires<ArgumentNullException>(rootObservable != null); return new ExpressionObserver( rootObservable.Select(o => (object)o), Parse(expression, enableDataValidation), description ?? expression.ToString()); } /// <summary> /// Creates a new instance of the <see cref="ExpressionObserver"/> class. /// </summary> /// <param name="rootGetter">A function which gets the root object.</param> /// <param name="expression">The expression.</param> /// <param name="update">An observable which triggers a re-read of the getter.</param> /// <param name="enableDataValidation">Whether or not to track data validation</param> /// <param name="description"> /// A description of the expression. If null, <paramref name="expression"/>'s string representation will be used. /// </param> public static ExpressionObserver Create<T, U>( Func<T> rootGetter, Expression<Func<T, U>> expression, IObservable<Unit> update, bool enableDataValidation = false, string description = null) { Contract.Requires<ArgumentNullException>(rootGetter != null); return new ExpressionObserver( () => rootGetter(), Parse(expression, enableDataValidation), update, description ?? expression.ToString()); } private IReadOnlyList<ITransformNode> GetTransformNodesFromChain() { LinkedList<ITransformNode> transforms = new LinkedList<ITransformNode>(); var node = _node; while (node != null) { if (node is ITransformNode transform) { transforms.AddFirst(transform); } node = node.Next; } return new List<ITransformNode>(transforms); } private IReadOnlyList<ITransformNode> TransformNodes => (_transformNodes ?? (_transformNodes = GetTransformNodesFromChain())); /// <summary> /// Attempts to set the value of a property expression. /// </summary> /// <param name="value">The value to set.</param> /// <param name="priority">The binding priority to use.</param> /// <returns> /// True if the value could be set; false if the expression does not evaluate to a /// property. Note that the <see cref="ExpressionObserver"/> must be subscribed to /// before setting the target value can work, as setting the value requires the /// expression to be evaluated. /// </returns> public bool SetValue(object value, BindingPriority priority = BindingPriority.LocalValue) { if (Leaf is SettableNode settable) { foreach (var transform in TransformNodes) { value = transform.Transform(value); if (value is BindingNotification) { return false; } } return settable.SetTargetValue(value, priority); } return false; } /// <summary> /// Gets a description of the expression being observed. /// </summary> public string Description { get; } /// <summary> /// Gets the expression being observed. /// </summary> public string Expression { get; } /// <summary> /// Gets the type of the expression result or null if the expression could not be /// evaluated. /// </summary> public Type ResultType => (Leaf as SettableNode)?.PropertyType; /// <summary> /// Gets the leaf node. /// </summary> private ExpressionNode Leaf { get { var node = _node; while (node.Next != null) node = node.Next; return node; } } protected override void Initialize() { _value = null; _node.Subscribe(ValueChanged); StartRoot(); } protected override void Deinitialize() { _rootSubscription?.Dispose(); _rootSubscription = null; _node.Unsubscribe(); } protected override void Subscribed(IObserver<object> observer, bool first) { if (!first && _value != null && _value.TryGetTarget(out var value)) { observer.OnNext(value); } } private static ExpressionNode Parse(LambdaExpression expression, bool enableDataValidation) { return ExpressionTreeParser.Parse(expression, enableDataValidation); } private void StartRoot() { if (_root is IObservable<object> observable) { _rootSubscription = observable.Subscribe( x => _node.Target = new WeakReference<object>(x != AvaloniaProperty.UnsetValue ? x : null), x => PublishCompleted(), () => PublishCompleted()); } else { _node.Target = (WeakReference<object>)_root; } } private void ValueChanged(object value) { var broken = BindingNotification.ExtractError(value) as MarkupBindingChainException; broken?.Commit(Description); _value = new WeakReference<object>(value); PublishNext(value); } } }
namespace ArmdroidTools.ArmTest { partial class FormMain { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.serialPort = new System.IO.Ports.SerialPort(this.components); this.txtOutput = new System.Windows.Forms.TextBox(); this.contextMenuOutput = new System.Windows.Forms.ContextMenuStrip(this.components); this.clearMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.btnConnect = new System.Windows.Forms.Button(); this.btnSingleStepCW = new System.Windows.Forms.Button(); this.btnSingleStepCCW = new System.Windows.Forms.Button(); this.btnStepMotor = new System.Windows.Forms.Button(); this.comboMotorChannelSelector = new System.Windows.Forms.ComboBox(); this.groupMotorControl = new System.Windows.Forms.GroupBox(); this.lblSpeed = new System.Windows.Forms.Label(); this.comboMotorSpeedSelector = new System.Windows.Forms.ComboBox(); this.txtStepsRequired = new System.Windows.Forms.TextBox(); this.lblSteps = new System.Windows.Forms.Label(); this.lblMotorChannel = new System.Windows.Forms.Label(); this.comboPortName = new System.Windows.Forms.ComboBox(); this.lblPortName = new System.Windows.Forms.Label(); this.contextMenuOutput.SuspendLayout(); this.groupMotorControl.SuspendLayout(); this.SuspendLayout(); // // serialPort // this.serialPort.PortName = "COM5"; this.serialPort.ErrorReceived += new System.IO.Ports.SerialErrorReceivedEventHandler(this.serialPort_ErrorReceived); this.serialPort.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort_DataReceived); // // txtOutput // this.txtOutput.ContextMenuStrip = this.contextMenuOutput; this.txtOutput.Font = new System.Drawing.Font("Courier New", 7.8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtOutput.Location = new System.Drawing.Point(13, 227); this.txtOutput.Multiline = true; this.txtOutput.Name = "txtOutput"; this.txtOutput.ReadOnly = true; this.txtOutput.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.txtOutput.Size = new System.Drawing.Size(651, 243); this.txtOutput.TabIndex = 4; this.txtOutput.TabStop = false; // // contextMenuOutput // this.contextMenuOutput.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.clearMenuItem}); this.contextMenuOutput.Name = "contextMenuOutput"; this.contextMenuOutput.Size = new System.Drawing.Size(113, 28); // // clearMenuItem // this.clearMenuItem.Name = "clearMenuItem"; this.clearMenuItem.Size = new System.Drawing.Size(112, 24); this.clearMenuItem.Text = "Clear"; this.clearMenuItem.Click += new System.EventHandler(this.clearToolStripMenuItem_Click); // // btnConnect // this.btnConnect.Location = new System.Drawing.Point(13, 14); this.btnConnect.Name = "btnConnect"; this.btnConnect.Size = new System.Drawing.Size(110, 30); this.btnConnect.TabIndex = 0; this.btnConnect.Text = "Connect"; this.btnConnect.UseVisualStyleBackColor = true; this.btnConnect.Click += new System.EventHandler(this.btnConnect_Click); // // btnSingleStepCW // this.btnSingleStepCW.Location = new System.Drawing.Point(306, 96); this.btnSingleStepCW.Name = "btnSingleStepCW"; this.btnSingleStepCW.Size = new System.Drawing.Size(160, 30); this.btnSingleStepCW.TabIndex = 7; this.btnSingleStepCW.Text = "Single Step (CW)"; this.btnSingleStepCW.UseVisualStyleBackColor = true; this.btnSingleStepCW.Click += new System.EventHandler(this.btnSingleStepCW_Click); // // btnSingleStepCCW // this.btnSingleStepCCW.Location = new System.Drawing.Point(484, 96); this.btnSingleStepCCW.Name = "btnSingleStepCCW"; this.btnSingleStepCCW.Size = new System.Drawing.Size(157, 30); this.btnSingleStepCCW.TabIndex = 8; this.btnSingleStepCCW.Text = "Single Step (CCW)"; this.btnSingleStepCCW.UseVisualStyleBackColor = true; this.btnSingleStepCCW.Click += new System.EventHandler(this.btnSingleStepCCW_Click); // // btnStepMotor // this.btnStepMotor.Location = new System.Drawing.Point(531, 34); this.btnStepMotor.Name = "btnStepMotor"; this.btnStepMotor.Size = new System.Drawing.Size(110, 30); this.btnStepMotor.TabIndex = 4; this.btnStepMotor.Text = "Step"; this.btnStepMotor.UseVisualStyleBackColor = true; this.btnStepMotor.Click += new System.EventHandler(this.btnStepMotor_Click); // // comboMotorChannelSelector // this.comboMotorChannelSelector.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboMotorChannelSelector.FormattingEnabled = true; this.comboMotorChannelSelector.Items.AddRange(new object[] { "1", "2", "3", "4", "5", "6"}); this.comboMotorChannelSelector.Location = new System.Drawing.Point(131, 39); this.comboMotorChannelSelector.Name = "comboMotorChannelSelector"; this.comboMotorChannelSelector.Size = new System.Drawing.Size(71, 24); this.comboMotorChannelSelector.TabIndex = 1; this.comboMotorChannelSelector.SelectedIndexChanged += new System.EventHandler(this.comboMotorChannelSelector_SelectedIndexChanged); // // groupMotorControl // this.groupMotorControl.Controls.Add(this.lblSpeed); this.groupMotorControl.Controls.Add(this.comboMotorSpeedSelector); this.groupMotorControl.Controls.Add(this.txtStepsRequired); this.groupMotorControl.Controls.Add(this.lblSteps); this.groupMotorControl.Controls.Add(this.lblMotorChannel); this.groupMotorControl.Controls.Add(this.btnSingleStepCW); this.groupMotorControl.Controls.Add(this.btnSingleStepCCW); this.groupMotorControl.Controls.Add(this.comboMotorChannelSelector); this.groupMotorControl.Controls.Add(this.btnStepMotor); this.groupMotorControl.Enabled = false; this.groupMotorControl.Location = new System.Drawing.Point(13, 69); this.groupMotorControl.Name = "groupMotorControl"; this.groupMotorControl.Size = new System.Drawing.Size(651, 137); this.groupMotorControl.TabIndex = 3; this.groupMotorControl.TabStop = false; this.groupMotorControl.Text = "Motor Control"; // // lblSpeed // this.lblSpeed.AutoSize = true; this.lblSpeed.Location = new System.Drawing.Point(17, 84); this.lblSpeed.Name = "lblSpeed"; this.lblSpeed.Size = new System.Drawing.Size(101, 17); this.lblSpeed.TabIndex = 5; this.lblSpeed.Text = "Speed (RPM) :"; // // comboMotorSpeedSelector // this.comboMotorSpeedSelector.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboMotorSpeedSelector.FormattingEnabled = true; this.comboMotorSpeedSelector.Items.AddRange(new object[] { "5", "10", "15", "20", "30", "50", "100"}); this.comboMotorSpeedSelector.Location = new System.Drawing.Point(131, 82); this.comboMotorSpeedSelector.Name = "comboMotorSpeedSelector"; this.comboMotorSpeedSelector.Size = new System.Drawing.Size(71, 24); this.comboMotorSpeedSelector.TabIndex = 6; this.comboMotorSpeedSelector.SelectedIndexChanged += new System.EventHandler(this.comboMotorSpeedSelector_SelectedIndexChanged); // // txtStepsRequired // this.txtStepsRequired.Location = new System.Drawing.Point(306, 38); this.txtStepsRequired.Name = "txtStepsRequired"; this.txtStepsRequired.Size = new System.Drawing.Size(194, 22); this.txtStepsRequired.TabIndex = 3; this.txtStepsRequired.TextChanged += new System.EventHandler(this.txtStepsRequired_TextChanged); // // lblSteps // this.lblSteps.AutoSize = true; this.lblSteps.Location = new System.Drawing.Point(248, 41); this.lblSteps.Name = "lblSteps"; this.lblSteps.Size = new System.Drawing.Size(52, 17); this.lblSteps.TabIndex = 2; this.lblSteps.Text = "Steps :"; // // lblMotorChannel // this.lblMotorChannel.AutoSize = true; this.lblMotorChannel.Location = new System.Drawing.Point(17, 41); this.lblMotorChannel.Name = "lblMotorChannel"; this.lblMotorChannel.Size = new System.Drawing.Size(108, 17); this.lblMotorChannel.TabIndex = 0; this.lblMotorChannel.Text = "Motor Channel :"; // // comboPortName // this.comboPortName.DataBindings.Add(new System.Windows.Forms.Binding("Text", global::ArmdroidTools.ArmTest.Properties.Settings.Default, "LastPortUsed", true, System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged)); this.comboPortName.FormattingEnabled = true; this.comboPortName.Location = new System.Drawing.Point(221, 18); this.comboPortName.Name = "comboPortName"; this.comboPortName.Size = new System.Drawing.Size(156, 24); this.comboPortName.TabIndex = 2; this.comboPortName.Text = global::ArmdroidTools.ArmTest.Properties.Settings.Default.LastPortUsed; this.comboPortName.DropDown += new System.EventHandler(this.comboPortName_DropDown); // // lblPortName // this.lblPortName.AutoSize = true; this.lblPortName.Location = new System.Drawing.Point(170, 21); this.lblPortName.Name = "lblPortName"; this.lblPortName.Size = new System.Drawing.Size(42, 17); this.lblPortName.TabIndex = 1; this.lblPortName.Text = "Port :"; // // FormMain // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(672, 482); this.Controls.Add(this.lblPortName); this.Controls.Add(this.comboPortName); this.Controls.Add(this.groupMotorControl); this.Controls.Add(this.btnConnect); this.Controls.Add(this.txtOutput); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FormMain"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Armdroid Test"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.FormMain_FormClosing); this.contextMenuOutput.ResumeLayout(false); this.groupMotorControl.ResumeLayout(false); this.groupMotorControl.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.IO.Ports.SerialPort serialPort; private System.Windows.Forms.TextBox txtOutput; private System.Windows.Forms.Button btnConnect; private System.Windows.Forms.Button btnSingleStepCW; private System.Windows.Forms.Button btnSingleStepCCW; private System.Windows.Forms.Button btnStepMotor; private System.Windows.Forms.ComboBox comboMotorChannelSelector; private System.Windows.Forms.GroupBox groupMotorControl; private System.Windows.Forms.ComboBox comboPortName; private System.Windows.Forms.Label lblMotorChannel; private System.Windows.Forms.Label lblSteps; private System.Windows.Forms.Label lblPortName; private System.Windows.Forms.TextBox txtStepsRequired; private System.Windows.Forms.ContextMenuStrip contextMenuOutput; private System.Windows.Forms.ToolStripMenuItem clearMenuItem; private System.Windows.Forms.Label lblSpeed; private System.Windows.Forms.ComboBox comboMotorSpeedSelector; } }
//--------------------------------------------------------------------- // <copyright file="ODataJsonLightParameterReader.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Core.JsonLight { #region Namespaces using System.Diagnostics; using System.Diagnostics.CodeAnalysis; #if ODATALIB_ASYNC using System.Threading.Tasks; #endif using Microsoft.OData.Core.Metadata; using Microsoft.OData.Edm; using Microsoft.OData.Core.Json; #endregion Namespaces /// <summary> /// OData parameter reader for the Json Light format. /// </summary> internal sealed class ODataJsonLightParameterReader : ODataParameterReaderCoreAsync { /// <summary>The input to read the payload from.</summary> private readonly ODataJsonLightInputContext jsonLightInputContext; /// <summary>The parameter deserializer to read the parameter input with.</summary> private readonly ODataJsonLightParameterDeserializer jsonLightParameterDeserializer; /// <summary>The duplicate property names checker to use for the parameter payload.</summary> private DuplicatePropertyNamesChecker duplicatePropertyNamesChecker; /// <summary> /// Constructor. /// </summary> /// <param name="jsonLightInputContext">The input to read the payload from.</param> /// <param name="operation">The operation import whose parameters are being read.</param> internal ODataJsonLightParameterReader(ODataJsonLightInputContext jsonLightInputContext, IEdmOperation operation) : base(jsonLightInputContext, operation) { Debug.Assert(jsonLightInputContext != null, "jsonLightInputContext != null"); Debug.Assert(jsonLightInputContext.ReadingResponse == false, "jsonLightInputContext.ReadingResponse == false"); Debug.Assert(operation != null, "operationImport != null"); this.jsonLightInputContext = jsonLightInputContext; this.jsonLightParameterDeserializer = new ODataJsonLightParameterDeserializer(this, jsonLightInputContext); Debug.Assert(this.jsonLightInputContext.Model.IsUserModel(), "this.jsonLightInputContext.Model.IsUserModel()"); } /// <summary> /// Implementation of the reader logic when in state 'Start'. /// </summary> /// <returns>true if more items can be read from the reader; otherwise false.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.None: assumes that the JSON reader has not been used yet. /// Post-Condition: When the new state is Value, the reader is positioned at the closing '}' or at the name of the next parameter. /// When the new state is Entry, the reader is positioned at the starting '{' of the entry payload. /// When the new state is Feed or Collection, the reader is positioned at the starting '[' of the feed or collection payload. /// </remarks> protected override bool ReadAtStartImplementation() { Debug.Assert(this.State == ODataParameterReaderState.Start, "this.State == ODataParameterReaderState.Start"); Debug.Assert(this.jsonLightParameterDeserializer.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None"); // We use this to store annotations and check for duplicate annotation names, but we don't really store properties in it. this.duplicatePropertyNamesChecker = this.jsonLightInputContext.CreateDuplicatePropertyNamesChecker(); // The parameter payload looks like "{ param1 : value1, ..., paramN : valueN }", where each value can be primitive, complex, collection, entity, feed or collection. // Position the reader on the first node this.jsonLightParameterDeserializer.ReadPayloadStart( ODataPayloadKind.Parameter, this.duplicatePropertyNamesChecker, /*isReadingNestedPayload*/false, /*allowEmptyPayload*/true); return this.ReadAtStartImplementationSynchronously(); } #if ODATALIB_ASYNC /// <summary> /// Implementation of the parameter reader logic when in state 'Start'. /// </summary> /// <returns>true if more items can be read from the reader; otherwise false.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.None: assumes that the JSON reader has not been used yet. /// Post-Condition: When the new state is Value, the reader is positioned at the closing '}' or at the name of the next parameter. /// When the new state is Entry, the reader is positioned at the starting '{' of the entry payload. /// When the new state is Feed or Collection, the reader is positioned at the starting '[' of the feed or collection payload. /// </remarks> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] protected override Task<bool> ReadAtStartImplementationAsync() { Debug.Assert(this.State == ODataParameterReaderState.Start, "this.State == ODataParameterReaderState.Start"); Debug.Assert(this.jsonLightParameterDeserializer.JsonReader.NodeType == JsonNodeType.None, "Pre-Condition: expected JsonNodeType.None"); // We use this to store annotations and check for duplicate annotation names, but we don't really store properties in it. this.duplicatePropertyNamesChecker = this.jsonLightInputContext.CreateDuplicatePropertyNamesChecker(); // The parameter payload looks like "{ param1 : value1, ..., paramN : valueN }", where each value can be primitive, complex, collection, entity, feed or collection. // Position the reader on the first node return this.jsonLightParameterDeserializer.ReadPayloadStartAsync( ODataPayloadKind.Parameter, this.duplicatePropertyNamesChecker, /*isReadingNestedPayload*/false, /*allowEmptyPayload*/true) .FollowOnSuccessWith(t => this.ReadAtStartImplementationSynchronously()); } #endif /// <summary> /// Implementation of the reader logic on the subsequent reads after the first parameter is read. /// </summary> /// <returns>true if more items can be read from the reader; otherwise false.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.Property or JsonNodeType.EndObject: assumes the last read puts the reader at the begining of the next parameter or at the end of the payload. /// Post-Condition: When the new state is Value, the reader is positioned at the closing '}' or at the name of the next parameter. /// When the new state is Entry, the reader is positioned at the starting '{' of the entry payload. /// When the new state is Feed or Collection, the reader is positioned at the starting '[' of the feed or collection payload. /// </remarks> protected override bool ReadNextParameterImplementation() { return this.ReadNextParameterImplementationSynchronously(); } #if ODATALIB_ASYNC /// <summary> /// Implementation of the reader logic when in state Value, Entry, Feed or Collection state. /// </summary> /// <returns>true if more items can be read from the reader; otherwise false.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.Property or JsonNodeType.EndObject: assumes the last read puts the reader at the begining of the next parameter or at the end of the payload. /// Post-Condition: When the new state is Value, the reader is positioned at the closing '}' or at the name of the next parameter. /// When the new state is Entry, the reader is positioned at the starting '{' of the entry payload. /// When the new state is Feed or Collection, the reader is positioned at the starting '[' of the feed or collection payload. /// </remarks> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] protected override Task<bool> ReadNextParameterImplementationAsync() { return TaskUtils.GetTaskForSynchronousOperation<bool>(this.ReadNextParameterImplementationSynchronously); } #endif /// <summary> /// Creates an <see cref="ODataReader"/> to read the entry value of type <paramref name="expectedEntityType"/>. /// </summary> /// <param name="expectedEntityType">Expected entity type to read.</param> /// <returns>An <see cref="ODataReader"/> to read the entry value of type <paramref name="expectedEntityType"/>.</returns> protected override ODataReader CreateEntryReader(IEdmEntityType expectedEntityType) { return this.CreateEntryReaderSynchronously(expectedEntityType); } #if ODATALIB_ASYNC /// <summary> /// Creates an <see cref="ODataReader"/> to read the entry value of type <paramref name="expectedEntityType"/>. /// </summary> /// <param name="expectedEntityType">Expected entity type to read.</param> /// <returns>An <see cref="ODataReader"/> to read the entry value of type <paramref name="expectedEntityType"/>.</returns> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] protected override Task<ODataReader> CreateEntryReaderAsync(IEdmEntityType expectedEntityType) { return TaskUtils.GetTaskForSynchronousOperation<ODataReader>(() => this.CreateEntryReaderSynchronously(expectedEntityType)); } #endif /// <summary> /// Creates an <see cref="ODataReader"/> to read the feed value of type <paramref name="expectedEntityType"/>. /// </summary> /// <param name="expectedEntityType">Expected feed element type to read.</param> /// <returns>An <see cref="ODataReader"/> to read the feed value of type <paramref name="expectedEntityType"/>.</returns> protected override ODataReader CreateFeedReader(IEdmEntityType expectedEntityType) { return this.CreateFeedReaderSynchronously(expectedEntityType); } #if ODATALIB_ASYNC /// <summary> /// Cretes an <see cref="ODataReader"/> to read the feed value of type <paramref name="expectedEntityType"/>. /// </summary> /// <param name="expectedEntityType">Expected feed element type to read.</param> /// <returns>An <see cref="ODataReader"/> to read the feed value of type <paramref name="expectedEntityType"/>.</returns> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] protected override Task<ODataReader> CreateFeedReaderAsync(IEdmEntityType expectedEntityType) { return TaskUtils.GetTaskForSynchronousOperation<ODataReader>(() => this.CreateFeedReaderSynchronously(expectedEntityType)); } #endif /// <summary> /// Creates an <see cref="ODataCollectionReader"/> to read the collection with type <paramref name="expectedItemTypeReference"/>. /// </summary> /// <param name="expectedItemTypeReference">Expected item type reference of the collection to read.</param> /// <returns>An <see cref="ODataCollectionReader"/> to read the collection with type <paramref name="expectedItemTypeReference"/>.</returns> /// <remarks> /// Pre-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail. /// Post-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail. /// NOTE: this method does not move the reader. /// </remarks> protected override ODataCollectionReader CreateCollectionReader(IEdmTypeReference expectedItemTypeReference) { return this.CreateCollectionReaderSynchronously(expectedItemTypeReference); } #if ODATALIB_ASYNC /// <summary> /// Creates an <see cref="ODataCollectionReader"/> to read the collection with type <paramref name="expectedItemTypeReference"/>. /// </summary> /// <param name="expectedItemTypeReference">Expected item type reference of the collection to read.</param> /// <returns>An <see cref="ODataCollectionReader"/> to read the collection with type <paramref name="expectedItemTypeReference"/>.</returns> /// <remarks> /// Pre-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail. /// Post-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail. /// NOTE: this method does not move the reader. /// </remarks> [SuppressMessage("Microsoft.MSInternal", "CA908:AvoidTypesThatRequireJitCompilationInPrecompiledAssemblies", Justification = "API design calls for a bool being returned from the task here.")] protected override Task<ODataCollectionReader> CreateCollectionReaderAsync(IEdmTypeReference expectedItemTypeReference) { return TaskUtils.GetTaskForSynchronousOperation<ODataCollectionReader>(() => this.CreateCollectionReaderSynchronously(expectedItemTypeReference)); } #endif /// <summary> /// Implementation of the reader logic when in state 'Start'. /// </summary> /// <returns>true if more items can be read from the reader; otherwise false.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.None: assumes that the JSON reader has not been used yet. /// Post-Condition: When the new state is Value, the reader is positioned at the closing '}' or at the name of the next parameter. /// When the new state is Entry, the reader is positioned at the starting '{' of the entry payload. /// When the new state is Feed or Collection, the reader is positioned at the starting '[' of the feed or collection payload. /// </remarks> private bool ReadAtStartImplementationSynchronously() { if (this.jsonLightInputContext.JsonReader.NodeType == JsonNodeType.EndOfInput) { this.PopScope(ODataParameterReaderState.Start); this.EnterScope(ODataParameterReaderState.Completed, null, null); return false; } return this.jsonLightParameterDeserializer.ReadNextParameter(this.duplicatePropertyNamesChecker); } /// <summary> /// Implementation of the reader logic on the subsequent reads after the first parameter is read. /// </summary> /// <returns>true if more items can be read from the reader; otherwise false.</returns> /// <remarks> /// Pre-Condition: JsonNodeType.Property or JsonNodeType.EndObject: assumes the last read puts the reader at the begining of the next parameter or at the end of the payload. /// Post-Condition: When the new state is Value, the reader is positioned at the closing '}' or at the name of the next parameter. /// When the new state is Entry, the reader is positioned at the starting '{' of the entry payload. /// When the new state is Feed or Collection, the reader is positioned at the starting '[' of the feed or collection payload. /// </remarks> private bool ReadNextParameterImplementationSynchronously() { Debug.Assert( this.State != ODataParameterReaderState.Start && this.State != ODataParameterReaderState.Exception && this.State != ODataParameterReaderState.Completed, "The current state must not be Start, Exception or Completed."); this.PopScope(this.State); return this.jsonLightParameterDeserializer.ReadNextParameter(this.duplicatePropertyNamesChecker); } /// <summary> /// Creates an <see cref="ODataReader"/> to read the entry value of type <paramref name="expectedEntityType"/>. /// </summary> /// <param name="expectedEntityType">Expected entity type to read.</param> /// <returns>An <see cref="ODataReader"/> to read the entry value of type <paramref name="expectedEntityType"/>.</returns> private ODataReader CreateEntryReaderSynchronously(IEdmEntityType expectedEntityType) { Debug.Assert(expectedEntityType != null, "expectedEntityType != null"); return new ODataJsonLightReader(this.jsonLightInputContext, null, expectedEntityType, false /*readingFeed*/, true /*readingParameter*/, this /*IODataReaderListener*/); } /// <summary> /// Creates an <see cref="ODataReader"/> to read the feed value of type <paramref name="expectedEntityType"/>. /// </summary> /// <param name="expectedEntityType">Expected feed element type to read.</param> /// <returns>An <see cref="ODataReader"/> to read the feed value of type <paramref name="expectedEntityType"/>.</returns> private ODataReader CreateFeedReaderSynchronously(IEdmEntityType expectedEntityType) { Debug.Assert(expectedEntityType != null, "expectedEntityType != null"); return new ODataJsonLightReader(this.jsonLightInputContext, null, expectedEntityType, true /*readingFeed*/, true /*readingParameter*/, this /*IODataReaderListener*/); } /// <summary> /// Creates an <see cref="ODataCollectionReader"/> to read the collection with type <paramref name="expectedItemTypeReference"/>. /// </summary> /// <param name="expectedItemTypeReference">Expected item type reference of the collection to read.</param> /// <returns>An <see cref="ODataCollectionReader"/> to read the collection with type <paramref name="expectedItemTypeReference"/>.</returns> /// <remarks> /// Pre-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail. /// Post-Condition: Any: the reader should be on the start array node of the collection value; if it is not we let the collection reader fail. /// NOTE: this method does not move the reader. /// </remarks> private ODataCollectionReader CreateCollectionReaderSynchronously(IEdmTypeReference expectedItemTypeReference) { Debug.Assert(this.jsonLightInputContext.Model.IsUserModel(), "Should have verified that we created the parameter reader with a user model."); Debug.Assert(expectedItemTypeReference != null, "expectedItemTypeReference != null"); return new ODataJsonLightCollectionReader(this.jsonLightInputContext, expectedItemTypeReference, this /*IODataReaderListener*/); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Transactions; namespace Avalonia.Controls.Primitives.PopupPositioning { public interface IManagedPopupPositionerPopup { IReadOnlyList<ManagedPopupPositionerScreenInfo> Screens { get; } Rect ParentClientAreaScreenGeometry { get; } double Scaling { get; } void MoveAndResize(Point devicePoint, Size virtualSize); } public class ManagedPopupPositionerScreenInfo { public Rect Bounds { get; } public Rect WorkingArea { get; } public ManagedPopupPositionerScreenInfo(Rect bounds, Rect workingArea) { Bounds = bounds; WorkingArea = workingArea; } } /// <summary> /// An <see cref="IPopupPositioner"/> implementation for platforms on which a popup can be /// aritrarily positioned. /// </summary> public class ManagedPopupPositioner : IPopupPositioner { private readonly IManagedPopupPositionerPopup _popup; public ManagedPopupPositioner(IManagedPopupPositionerPopup popup) { _popup = popup; } private static Point GetAnchorPoint(Rect anchorRect, PopupAnchor edge) { double x, y; if ((edge & PopupAnchor.Left) != 0) x = anchorRect.X; else if ((edge & PopupAnchor.Right) != 0) x = anchorRect.Right; else x = anchorRect.X + anchorRect.Width / 2; if ((edge & PopupAnchor.Top) != 0) y = anchorRect.Y; else if ((edge & PopupAnchor.Bottom) != 0) y = anchorRect.Bottom; else y = anchorRect.Y + anchorRect.Height / 2; return new Point(x, y); } private static Point Gravitate(Point anchorPoint, Size size, PopupGravity gravity) { double x, y; if ((gravity & PopupGravity.Left) != 0) x = -size.Width; else if ((gravity & PopupGravity.Right) != 0) x = 0; else x = -size.Width / 2; if ((gravity & PopupGravity.Top) != 0) y = -size.Height; else if ((gravity & PopupGravity.Bottom) != 0) y = 0; else y = -size.Height / 2; return anchorPoint + new Point(x, y); } public void Update(PopupPositionerParameters parameters) { var rect = Calculate( parameters.Size * _popup.Scaling, new Rect( parameters.AnchorRectangle.TopLeft * _popup.Scaling, parameters.AnchorRectangle.Size * _popup.Scaling), parameters.Anchor, parameters.Gravity, parameters.ConstraintAdjustment, parameters.Offset * _popup.Scaling); _popup.MoveAndResize( rect.Position, rect.Size / _popup.Scaling); } private Rect Calculate(Size translatedSize, Rect anchorRect, PopupAnchor anchor, PopupGravity gravity, PopupPositionerConstraintAdjustment constraintAdjustment, Point offset) { var parentGeometry = _popup.ParentClientAreaScreenGeometry; anchorRect = anchorRect.Translate(parentGeometry.TopLeft); Rect GetBounds() { var screens = _popup.Screens; var targetScreen = screens.FirstOrDefault(s => s.Bounds.Contains(anchorRect.TopLeft)) ?? screens.FirstOrDefault(s => s.Bounds.Intersects(anchorRect)) ?? screens.FirstOrDefault(s => s.Bounds.Contains(parentGeometry.TopLeft)) ?? screens.FirstOrDefault(s => s.Bounds.Intersects(parentGeometry)) ?? screens.FirstOrDefault(); if (targetScreen != null && targetScreen.WorkingArea.IsEmpty) { return targetScreen.Bounds; } return targetScreen?.WorkingArea ?? new Rect(0, 0, double.MaxValue, double.MaxValue); } var bounds = GetBounds(); bool FitsInBounds(Rect rc, PopupAnchor edge = PopupAnchor.AllMask) { if ((edge & PopupAnchor.Left) != 0 && rc.X < bounds.X) return false; if ((edge & PopupAnchor.Top) != 0 && rc.Y < bounds.Y) return false; if ((edge & PopupAnchor.Right) != 0 && rc.Right > bounds.Right) return false; if ((edge & PopupAnchor.Bottom) != 0 && rc.Bottom > bounds.Bottom) return false; return true; } static bool IsValid(in Rect rc) => rc.Width > 0 && rc.Height > 0; Rect GetUnconstrained(PopupAnchor a, PopupGravity g) => new Rect(Gravitate(GetAnchorPoint(anchorRect, a), translatedSize, g) + offset, translatedSize); var geo = GetUnconstrained(anchor, gravity); // If flipping geometry and anchor is allowed and helps, use the flipped one, // otherwise leave it as is if (!FitsInBounds(geo, PopupAnchor.HorizontalMask) && (constraintAdjustment & PopupPositionerConstraintAdjustment.FlipX) != 0) { var flipped = GetUnconstrained(anchor.FlipX(), gravity.FlipX()); if (FitsInBounds(flipped, PopupAnchor.HorizontalMask)) geo = geo.WithX(flipped.X); } // If sliding is allowed, try moving the rect into the bounds if ((constraintAdjustment & PopupPositionerConstraintAdjustment.SlideX) != 0) { geo = geo.WithX(Math.Max(geo.X, bounds.X)); if (geo.Right > bounds.Right) geo = geo.WithX(bounds.Right - geo.Width); } // Resize the rect horizontally if allowed. if ((constraintAdjustment & PopupPositionerConstraintAdjustment.ResizeX) != 0) { var unconstrainedRect = geo; if (!FitsInBounds(unconstrainedRect, PopupAnchor.Left)) { unconstrainedRect = unconstrainedRect.WithX(bounds.X); } if (!FitsInBounds(unconstrainedRect, PopupAnchor.Right)) { unconstrainedRect = unconstrainedRect.WithWidth(bounds.Width - unconstrainedRect.X); } if (IsValid(unconstrainedRect)) { geo = unconstrainedRect; } } // If flipping geometry and anchor is allowed and helps, use the flipped one, // otherwise leave it as is if (!FitsInBounds(geo, PopupAnchor.VerticalMask) && (constraintAdjustment & PopupPositionerConstraintAdjustment.FlipY) != 0) { var flipped = GetUnconstrained(anchor.FlipY(), gravity.FlipY()); if (FitsInBounds(flipped, PopupAnchor.VerticalMask)) geo = geo.WithY(flipped.Y); } // If sliding is allowed, try moving the rect into the bounds if ((constraintAdjustment & PopupPositionerConstraintAdjustment.SlideY) != 0) { geo = geo.WithY(Math.Max(geo.Y, bounds.Y)); if (geo.Bottom > bounds.Bottom) geo = geo.WithY(bounds.Bottom - geo.Height); } // Resize the rect vertically if allowed. if ((constraintAdjustment & PopupPositionerConstraintAdjustment.ResizeY) != 0) { var unconstrainedRect = geo; if (!FitsInBounds(unconstrainedRect, PopupAnchor.Top)) { unconstrainedRect = unconstrainedRect.WithY(bounds.Y); } if (!FitsInBounds(unconstrainedRect, PopupAnchor.Bottom)) { unconstrainedRect = unconstrainedRect.WithHeight(bounds.Bottom - unconstrainedRect.Y); } if (IsValid(unconstrainedRect)) { geo = unconstrainedRect; } } return geo; } } }
using System; using System.Collections; using System.Collections.Generic; using Foundation; using UIKit; using System.CodeDom.Compiler; namespace UIKitEnhancements { public class MainMenuTableSource :UITableViewSource { #region Private Variables private MainMenuTableViewController _controller; private List<MenuItem> _items = new List<MenuItem>(); #endregion #region Computed Properties /// <summary> /// Returns the delegate of the current running application /// </summary> /// <value>The this app.</value> public AppDelegate ThisApp { get { return (AppDelegate)UIApplication.SharedApplication.Delegate; } } /// <summary> /// Gets or sets the <see cref="UIKitEnhancements.MenuItem"/> at the specified index. /// </summary> /// <param name="index">Index.</param> public MenuItem this[int index] { get { return _items[index]; } set { _items[index] = value; } } /// <summary> /// Gets the count. /// </summary> /// <value>The count.</value> public int Count { get { return _items.Count; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="UIKitEnhancements.MainMenuTableSource"/> class. /// </summary> /// <param name="controller">Controller.</param> public MainMenuTableSource (MainMenuTableViewController controller) { // Initialize this._controller = controller; LoadData (); } #endregion #region public Methods /// <summary> /// Loads the data. /// </summary> public void LoadData() { // Clear existing items _items.Clear (); // Setup list of data items _items.Add (new MenuItem ("Alert Controller", "Replaces Action Sheet & Alert View", "AlertSegue")); _items.Add (new MenuItem ("Collection View Changes", "New Collection View Features","WebSegue","http://blog.xamarin.com/new-collection-view-features-in-ios-8/")); _items.Add (new MenuItem ("Navigation Controller", "New Navigation Controller Options","NavBarSegue")); _items.Add (new MenuItem ("Notifications", "Required Notification Settings","NotificationSegue")); _items.Add (new MenuItem ("Popover Presentation Controller", "Handles Presentation in a Popover","PopoverSegue")); _items.Add (new MenuItem ("Split View Controller", "Now Supported on iPhone","WebSegue","https://developer.apple.com/library/prerelease/ios/documentation/UIKit/Reference/UISplitViewController_class/index.html#//apple_ref/occ/cl/UISplitViewController")); _items.Add (new MenuItem ("Visual Effects", "Adding Visual Effects in iOS 8","WebSegue","http://blog.xamarin.com/adding-view-effects-in-ios-8/")); } #endregion #region Override Methods /// <Docs>Table view displaying the sections.</Docs> /// <returns>Number of sections required to display the data. The default is 1 (a table must have at least one section).</returns> /// <para>Declared in [UITableViewDataSource]</para> /// <summary> /// Numbers the of sections. /// </summary> /// <param name="tableView">Table view.</param> public override nint NumberOfSections (UITableView tableView) { // Always one section return 1; } /// <Docs>Table view displaying the rows.</Docs> /// <summary> /// Rowses the in section. /// </summary> /// <returns>The in section.</returns> /// <param name="tableview">Tableview.</param> /// <param name="section">Section.</param> public override nint RowsInSection (UITableView tableview, nint section) { // Return number of items return _items.Count; } /// <Docs>Table view.</Docs> /// <summary> /// Gets the height for row. /// </summary> /// <returns>The height for row.</returns> /// <param name="tableView">Table view.</param> /// <param name="indexPath">Index path.</param> public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) { // Force height to 44 return 44; } /// <summary> /// Shoulds the highlight row. /// </summary> /// <returns><c>true</c>, if highlight row was shoulded, <c>false</c> otherwise.</returns> /// <param name="tableView">Table view.</param> /// <param name="rowIndexPath">Row index path.</param> public override bool ShouldHighlightRow (UITableView tableView, NSIndexPath rowIndexPath) { // Always allow highlighting return true; } /// <Docs>Table view containing the section.</Docs> /// <summary> /// Called to populate the header for the specified section. /// </summary> /// <see langword="null"></see> /// <returns>The for header.</returns> /// <param name="tableView">Table view.</param> /// <param name="section">Section.</param> public override string TitleForHeader (UITableView tableView, nint section) { // Return section title return "UIKit Enhancements"; } /// <Docs>Table view containing the section.</Docs> /// <summary> /// Called to populate the footer for the specified section. /// </summary> /// <see langword="null"></see> /// <returns>The for footer.</returns> /// <param name="tableView">Table view.</param> /// <param name="section">Section.</param> public override string TitleForFooter (UITableView tableView, nint section) { // None return ""; } /// <Docs>Table view requesting the cell.</Docs> /// <summary> /// Gets the cell. /// </summary> /// <returns>The cell.</returns> /// <param name="tableView">Table view.</param> /// <param name="indexPath">Index path.</param> public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { // Get new cell var cell = tableView.DequeueReusableCell (MainMenuTableCell.Key) as MainMenuTableCell; // Populate the cell cell.DisplayMenuItem (_items [indexPath.Row]); // Return cell return cell; } /// <Docs>Table view containing the row.</Docs> /// <summary> /// Rows the selected. /// </summary> /// <param name="tableView">Table view.</param> /// <param name="indexPath">Index path.</param> public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { // Note item accessory being displayed and // open it's details and services view _controller.MenuItem = _items[indexPath.Row]; // Performing a segue? if (_controller.MenuItem.Segue != "") { // Are we running on the iPad? if (ThisApp.iPadViewController == null) { // No, invoke segue against the table controller _controller.PerformSegue (_controller.MenuItem.Segue, _controller); } else { // Yes, invoke segue against the iPad default view ThisApp.iPadViewController.MenuItem = _items[indexPath.Row]; ThisApp.iPadViewController.PerformSegue (_controller.MenuItem.Segue, ThisApp.iPadViewController); } } } #endregion } }
using System; using System.Collections.Generic; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Geometry.Curves; using Microsoft.Msagl.Core.Layout; namespace Microsoft.Msagl.Drawing { /// <summary> /// the interface for the viewer which is able to edit the graph layout /// </summary> public interface IViewer { /// <summary> /// the scale to screen /// </summary> double CurrentScale { get; } /// <summary> /// creates a visual element for the node, and the corresponding geometry node is created according /// to the size of the visual element /// </summary> /// <param name="drawingNode">usually the drawing node has a label, and the visual element is created accordingly</param> /// <param name="center">the node center location</param> /// <param name="visualElement">if this value is not null then is should be a visual for the label, and the node width and height /// will be taken from this visual</param> /// <returns>new IViewerNode</returns> IViewerNode CreateIViewerNode(Node drawingNode, Point center, object visualElement); /// <summary> /// creates a default visual element for the node /// </summary> /// <param name="drawingNode"></param> /// <returns></returns> IViewerNode CreateIViewerNode(Node drawingNode); /// <summary> /// if set to true the Graph geometry is unchanged after the assignment viewer.Graph=graph; /// </summary> bool NeedToCalculateLayout { get; set; } /// <summary> /// the viewer signalls that the view, the transform or the viewport, has changed /// </summary> event EventHandler<EventArgs> ViewChangeEvent; /// <summary> /// signalling the mouse down event /// </summary> event EventHandler<MsaglMouseEventArgs> MouseDown; /// <summary> /// signalling the mouse move event /// </summary> event EventHandler<MsaglMouseEventArgs> MouseMove; /// <summary> /// signalling the mouse up event /// </summary> event EventHandler<MsaglMouseEventArgs> MouseUp; /// <summary> /// the event raised at a time when ObjectUnderMouseCursor changes /// </summary> event EventHandler<ObjectUnderMouseCursorChangedEventArgs> ObjectUnderMouseCursorChanged; /// <summary> /// Returns the object under the cursor and null if there is none /// </summary> IViewerObject ObjectUnderMouseCursor { get; } /// <summary> /// forcing redraw of the object /// </summary> /// <param name="objectToInvalidate"></param> void Invalidate(IViewerObject objectToInvalidate); /// <summary> /// invalidates everything /// </summary> void Invalidate(); /// <summary> /// is raised after the graph is changed /// </summary> event EventHandler GraphChanged; /// <summary> /// returns modifier keys; control, shift, or alt are pressed at the moments /// </summary> ModifierKeys ModifierKeys { get; } /// <summary> /// maps a point in screen coordinates to the point in the graph surface /// </summary> /// <param name="e"></param> /// <returns></returns> Point ScreenToSource(MsaglMouseEventArgs e); /// <summary> /// gets all entities which can be dragged /// </summary> IEnumerable<IViewerObject> Entities { get; } /// <summary> /// number of dots per inch in x direction /// </summary> double DpiX { get; } /// <summary> /// number of dots per inch in y direction /// </summary> double DpiY { get; } /// <summary> /// this method should be called on the end of the dragging /// </summary> /// <param name="changedObjects"></param> void OnDragEnd(IEnumerable<IViewerObject> changedObjects); /// <summary> /// The scale dependent width of an edited curve that should be clearly visible. /// Used in the default entity editing. /// </summary> double LineThicknessForEditing { get; } /// <summary> /// enables and disables the default editing of the viewer /// </summary> bool LayoutEditingEnabled { get; } /// <summary> /// if is set to true then the mouse left click on a node and dragging the cursor to /// another node will create an edge and add it to the graph /// </summary> bool InsertingEdge { get; set; } /// <summary> /// Pops up a pop up menu with a menu item for each couple, the string is the title and the delegate is the callback /// </summary> /// <param name="menuItems"></param> void PopupMenus(params Tuple<string, VoidDelegate>[] menuItems); /// <summary> /// The radius of the circle drawn around a polyline corner /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Polyline")] double UnderlyingPolylineCircleRadius { get; } /// <summary> /// gets or sets the graph /// </summary> Graph Graph { get; set; } /// <summary> /// prepare to draw the rubber line /// </summary> /// <param name="startingPoint"></param> void StartDrawingRubberLine(Point startingPoint); /// <summary> /// draw the rubber line to the current mouse position /// </summary> /// <param name="args"></param> void DrawRubberLine(MsaglMouseEventArgs args); /// <summary> /// draw rubber line to a given point /// </summary> /// <param name="point"></param> void DrawRubberLine(Point point); /// <summary> /// stop drawing the rubber line /// </summary> void StopDrawingRubberLine(); /// <summary> /// add an edge to the viewer graph /// </summary> /// <param name="edge"></param> /// <param name="registerForUndo"></param> /// <returns></returns> void AddEdge(IViewerEdge edge, bool registerForUndo); /// <summary> /// drawing edge already has its geometry in place /// </summary> /// <param name="drawingEdge"></param> /// <returns></returns> IViewerEdge CreateEdgeWithGivenGeometry(Edge drawingEdge); /// <summary> /// adds a node to the viewer graph /// </summary> /// <param name="node"></param> /// <param name="registerForUndo"></param> void AddNode(IViewerNode node, bool registerForUndo); /// <summary> /// removes an edge from the graph /// </summary> /// <param name="edge"></param> ///<param name="registerForUndo"></param> void RemoveEdge(IViewerEdge edge, bool registerForUndo); /// <summary> /// deletes node /// </summary> /// <param name="node"></param> /// <param name="registerForUndo"></param> void RemoveNode(IViewerNode node, bool registerForUndo); /// <summary> /// Routes the edge. The edge will not be not attached to the graph after the routing /// </summary> /// <returns></returns> IViewerEdge RouteEdge(Edge drawingEdge); /// <summary> /// gets the viewer graph /// </summary> IViewerGraph ViewerGraph { get; } /// <summary> /// arrowhead length for newly created edges /// </summary> double ArrowheadLength { get; } /// <summary> /// creates the port visual if it does not exist, and sets the port location /// </summary> /// <param name="portLocation"></param> void SetSourcePortForEdgeRouting(Point portLocation); /// <summary> /// creates the port visual if it does not exist, and sets the port location /// </summary> /// <param name="portLocation"></param> void SetTargetPortForEdgeRouting(Point portLocation); /// <summary> /// removes the port /// </summary> void RemoveSourcePortEdgeRouting(); /// <summary> /// removes the port /// </summary> void RemoveTargetPortEdgeRouting(); /// <summary> /// /// </summary> /// <param name="edgeGeometry"></param> void DrawRubberEdge(EdgeGeometry edgeGeometry); /// <summary> /// stops drawing the rubber edge /// </summary> void StopDrawingRubberEdge(); /// <summary> /// the transformation from the graph surface to the client viewport /// </summary> PlaneTransformation Transform { get; set; } } }
using UnityEngine; using System.Collections.Generic; using System.Collections; /*! \brief Represent a Fick's law 'reaction'. \details Manages Fick's law 'reactions'. This class manages a Fick's first law 'reaction', corresponding to the diffusion of small molecules across the cell membrane or between two different media. In this simulation, we model the rate of passive transport by diffusion across membranes. This rate depends on the concentration gradient between the two media and the (semi-)permeability of the membrane that separates them. Diffusion moves materials from an area of higher concentration to the lower according to Fick's first law. A diffusion reaction, based on Fick's first law model, estimates the speed of diffusion of a molecule according to this formula : dn/dt = (C1 - C2) * P * A - dn/dt: speed of diffusion - C1-C2: difference of concentration between both media - P: permeability coefficient - An exchange surface \reference http://books.google.fr/books?id=fXZW1REM0YEC&pg=PA636&lpg=PA636&dq=vitesse+de+diffusion+loi+de+fick&source=bl&ots=3eKv2NYYtx&sig=ciSW-RNAr0RTieE2oZfdBa73nT8&hl=en&sa=X&ei=bTufUcw4sI7sBqykgOAL&sqi=2&ved=0CD0Q6AEwAQ#v=onepage&q=vitesse%20de%20diffusion%20loi%20de%20fick&f=false */ public class FickReaction : Reaction { private float _surface; //!< Contact surface size bwtween the two mediums private float _P; //!< Permeability coefficient private Medium _medium1; //!< The first Medium private Medium _medium2; //!< The second Medium //! Default constructor. public FickReaction () { _surface = 0; _P = 0; _medium1 = null; _medium2 = null; } public FickReaction (FickReaction r) : base (r) { _surface = r._surface; _P = r._P; _medium1 = r._medium1; _medium2 = r._medium2; } public void setSurface (float surface) { _surface = surface; } public float getSurface () { return _surface; } public void setPermCoef (float P) { _P = P; } public float getPermCoef () { return _P; } public void setMedium1 (Medium medium) { _medium1 = medium; } public Medium getMedium1 () { return _medium1; } public void setMedium2 (Medium medium) { _medium2 = medium; } public Medium getMedium2 () { return _medium2; } /* ! \brief Checks that two reactions have the same FickReaction field values. \param reaction The reaction that will be compared to 'this'. */ protected override bool PartialEquals (Reaction reaction) { FickReaction fick = reaction as FickReaction; return (fick != null) && base.PartialEquals (reaction) && (_surface == fick._surface) && (_P == fick._P) && _medium1.Equals (fick._medium1) && _medium2.Equals (fick._medium2); //TODO check Medium equality } public override bool hasValidData () { return base.hasValidData () && 0 != _surface && 0 != _P && null != _medium1 && null != _medium2; } public static Reaction buildFickReactionFromProps (FickProperties props, LinkedList<Medium> mediums) { FickReaction reaction = new FickReaction (); Medium med1 = ReactionEngine.getMediumFromId (props.MediumId1, mediums); Medium med2 = ReactionEngine.getMediumFromId (props.MediumId2, mediums); if (med1 == null || med2 == null) { // Debug.Log("Fick failed to build FickReaction from FickProperties beacause one or all the medium id don't exist"); return null; } reaction.setSurface (props.surface); reaction.setPermCoef (props.P); reaction.setMedium1 (med1); reaction.setMedium2 (med2); reaction.setEnergyCost (props.energyCost); return reaction; } //! Return all the FickReactions possible from a Medium list. /*! \param mediums The list of mediums. \details This function return all the possible combinaisons of FickReaction in Medium list. Example : - Medium1 + Medium2 + Medium3 = FickReaction(1, 2) + FickReaction(1, 3) + FickReaction(2, 3) */ public static LinkedList<FickReaction> getFickReactionsFromMediumList (LinkedList<Medium> mediums) { FickReaction newReaction; LinkedListNode<Medium> node; LinkedListNode<Medium> start = mediums.First; LinkedList<FickReaction> fickReactions = new LinkedList<FickReaction> (); while (start != null) { node = start.Next; while (node != null) { newReaction = new FickReaction (); newReaction.setMedium1 (start.Value); newReaction.setMedium2 (node.Value); fickReactions.AddLast (newReaction); node = node.Next; } start = start.Next; } return fickReactions; } //! Processing a reaction. /*! \param molecules A list of molecules (not usefull here) A diffusion reaction based on fick model is calculated by using this formula : dn/dt = c1 - c2 * P * A Where: - dn is the difference of concentration that will be applied - c1 and c2 the concentration the molecules in the 2 Mediums - P is the permeability coefficient - A is the contact surface size between the two Mediums */ public override void react (Dictionary<string, Molecule> molecules) { var molMed1 = _medium1.getMolecules (); var molMed2 = _medium2.getMolecules (); Molecule mol2; float c1; float c2; float result; if (_P == 0f || _surface == 0f) return; foreach (Molecule mol1 in molMed1.Values) { c1 = mol1.getConcentration (); mol2 = ReactionEngine.getMoleculeFromName (mol1.getName (), molMed2); if (mol2 != null && mol2.getFickFactor () > 0f) { c2 = mol2.getConcentration (); result = (c2 - c1) * _P * _surface * mol2.getFickFactor () * _reactionSpeed * ReactionEngine.reactionSpeed * Time.deltaTime; if (enableSequential) { mol2.addConcentration (-result); mol1.addConcentration (result); } else { mol2.subNewConcentration (result); mol1.addNewConcentration (result); } } } } public override string ToString () { return "[FickReaction m1=" + _medium1.getName () + " m2=" + _medium2.getName () + "]"; } }
namespace Epi.Windows.Enter.Dialogs { partial class FindRecords { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Clean up any resources being used. /// </summary> private void DELETE_ME_PLEASE_Dispose(bool disposing) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FindRecords)); this.BottomToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.TopToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.RightToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.LeftToolStripPanel = new System.Windows.Forms.ToolStripPanel(); this.ContentPanel = new System.Windows.Forms.ToolStripContentPanel(); this.splitContainer1 = new System.Windows.Forms.SplitContainer(); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this.lbxSearchFields = new System.Windows.Forms.ListBox(); this.toolStrip2 = new System.Windows.Forms.ToolStrip(); this.toolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.toolStripButton5 = new System.Windows.Forms.ToolStripButton(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.toolStripBackButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripResetButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripSearchButton = new System.Windows.Forms.ToolStripButton(); this.menuStrip2 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitFindRecordToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.resetToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.goBackToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.searchToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.commandReferenceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutEpiInfoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolTip1 = new System.Windows.Forms.ToolTip(this.components); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit(); this.splitContainer1.Panel1.SuspendLayout(); this.splitContainer1.SuspendLayout(); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); this.toolStrip2.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.menuStrip2.SuspendLayout(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); this.baseImageList.Images.SetKeyName(76, ""); this.baseImageList.Images.SetKeyName(77, ""); this.baseImageList.Images.SetKeyName(78, ""); this.baseImageList.Images.SetKeyName(79, ""); // // BottomToolStripPanel // this.BottomToolStripPanel.Location = new System.Drawing.Point(0, 0); this.BottomToolStripPanel.Name = "BottomToolStripPanel"; this.BottomToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.BottomToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.BottomToolStripPanel.Size = new System.Drawing.Size(0, 0); // // TopToolStripPanel // this.TopToolStripPanel.Location = new System.Drawing.Point(0, 0); this.TopToolStripPanel.Name = "TopToolStripPanel"; this.TopToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.TopToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.TopToolStripPanel.Size = new System.Drawing.Size(0, 0); // // RightToolStripPanel // this.RightToolStripPanel.Location = new System.Drawing.Point(0, 0); this.RightToolStripPanel.Name = "RightToolStripPanel"; this.RightToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.RightToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.RightToolStripPanel.Size = new System.Drawing.Size(0, 0); // // LeftToolStripPanel // this.LeftToolStripPanel.Location = new System.Drawing.Point(0, 0); this.LeftToolStripPanel.Name = "LeftToolStripPanel"; this.LeftToolStripPanel.Orientation = System.Windows.Forms.Orientation.Horizontal; this.LeftToolStripPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0); this.LeftToolStripPanel.Size = new System.Drawing.Size(0, 0); // // ContentPanel // this.ContentPanel.Size = new System.Drawing.Size(200, 100); // // splitContainer1 // this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer1.Location = new System.Drawing.Point(0, 49); this.splitContainer1.Name = "splitContainer1"; // // splitContainer1.Panel1 // this.splitContainer1.Panel1.Controls.Add(this.toolStripContainer1); this.splitContainer1.Size = new System.Drawing.Size(1030, 600); this.splitContainer1.SplitterDistance = 243; this.splitContainer1.TabIndex = 42; // // toolStripContainer1 // this.toolStripContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.toolStripContainer1.BottomToolStripPanelVisible = false; // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.Controls.Add(this.lbxSearchFields); this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(243, 575); this.toolStripContainer1.Location = new System.Drawing.Point(0, 0); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.Size = new System.Drawing.Size(243, 600); this.toolStripContainer1.TabIndex = 0; this.toolStripContainer1.Text = "Search Fields For ..."; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip2); // // lbxSearchFields // this.lbxSearchFields.Dock = System.Windows.Forms.DockStyle.Fill; this.lbxSearchFields.FormattingEnabled = true; this.lbxSearchFields.Location = new System.Drawing.Point(0, 0); this.lbxSearchFields.Name = "lbxSearchFields"; this.lbxSearchFields.SelectionMode = System.Windows.Forms.SelectionMode.MultiSimple; this.lbxSearchFields.Size = new System.Drawing.Size(243, 575); this.lbxSearchFields.Sorted = true; this.lbxSearchFields.TabIndex = 0; this.lbxSearchFields.SelectedIndexChanged += new System.EventHandler(this.lbxSearchFields_SelectedIndexChanged); this.lbxSearchFields.MouseDown += new System.Windows.Forms.MouseEventHandler(this.lbxSearchFields_MouseDown); // // toolStrip2 // this.toolStrip2.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripLabel1, this.toolStripButton5}); this.toolStrip2.Location = new System.Drawing.Point(0, 0); this.toolStrip2.Name = "toolStrip2"; this.toolStrip2.Size = new System.Drawing.Size(243, 25); this.toolStrip2.Stretch = true; this.toolStrip2.TabIndex = 0; // // toolStripLabel1 // this.toolStripLabel1.AutoSize = false; this.toolStripLabel1.Name = "toolStripLabel1"; this.toolStripLabel1.Size = new System.Drawing.Size(154, 22); this.toolStripLabel1.Text = "Select/Unselect Search Fields"; // // toolStripButton5 // this.toolStripButton5.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.toolStripButton5.AutoToolTip = false; this.toolStripButton5.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.None; this.toolStripButton5.Enabled = false; this.toolStripButton5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton5.Image"))); this.toolStripButton5.ImageTransparentColor = System.Drawing.Color.Magenta; this.toolStripButton5.Name = "toolStripButton5"; this.toolStripButton5.Size = new System.Drawing.Size(23, 22); this.toolStripButton5.Text = "toolStripDownButton"; // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripBackButton, this.toolStripSeparator1, this.toolStripResetButton, this.toolStripSeparator2, this.toolStripSearchButton}); this.toolStrip1.Location = new System.Drawing.Point(0, 24); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(1030, 25); this.toolStrip1.TabIndex = 41; this.toolStrip1.Text = "toolStrip1"; this.toolStrip1.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStrip1_ItemClicked); // // toolStripBackButton // this.toolStripBackButton.Image = ((System.Drawing.Image)(resources.GetObject("toolStripBackButton.Image"))); this.toolStripBackButton.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.toolStripBackButton.Name = "toolStripBackButton"; this.toolStripBackButton.Size = new System.Drawing.Size(52, 22); this.toolStripBackButton.Text = "&Back"; this.toolStripBackButton.ToolTipText = "Go Back"; this.toolStripBackButton.Click += new System.EventHandler(this.exitFindRecordToolStripMenuItem_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // toolStripResetButton // this.toolStripResetButton.Image = ((System.Drawing.Image)(resources.GetObject("toolStripResetButton.Image"))); this.toolStripResetButton.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.toolStripResetButton.Name = "toolStripResetButton"; this.toolStripResetButton.Size = new System.Drawing.Size(55, 22); this.toolStripResetButton.Text = "&Reset"; this.toolStripResetButton.Click += new System.EventHandler(this.resetToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); // // toolStripSearchButton // this.toolStripSearchButton.Image = ((System.Drawing.Image)(resources.GetObject("toolStripSearchButton.Image"))); this.toolStripSearchButton.ImageTransparentColor = System.Drawing.Color.FromArgb(((int)(((byte)(128)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.toolStripSearchButton.Name = "toolStripSearchButton"; this.toolStripSearchButton.Size = new System.Drawing.Size(62, 22); this.toolStripSearchButton.Text = "Search"; this.toolStripSearchButton.Click += new System.EventHandler(this.searchToolStripMenuItem_Click); // // menuStrip2 // this.menuStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.toolsToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip2.Location = new System.Drawing.Point(0, 0); this.menuStrip2.Name = "menuStrip2"; this.menuStrip2.Size = new System.Drawing.Size(1030, 24); this.menuStrip2.TabIndex = 40; this.menuStrip2.Text = "menuStrip2"; this.menuStrip2.ItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.menuStrip2_ItemClicked); // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.exitFindRecordToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "&File"; // // exitFindRecordToolStripMenuItem // this.exitFindRecordToolStripMenuItem.Name = "exitFindRecordToolStripMenuItem"; this.exitFindRecordToolStripMenuItem.Size = new System.Drawing.Size(163, 22); this.exitFindRecordToolStripMenuItem.Text = "E&xit Find Records"; this.exitFindRecordToolStripMenuItem.Click += new System.EventHandler(this.exitFindRecordToolStripMenuItem_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.resetToolStripMenuItem, this.goBackToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20); this.editToolStripMenuItem.Text = "&Edit"; // // resetToolStripMenuItem // this.resetToolStripMenuItem.Name = "resetToolStripMenuItem"; this.resetToolStripMenuItem.Size = new System.Drawing.Size(117, 22); this.resetToolStripMenuItem.Text = "&Reset"; this.resetToolStripMenuItem.Click += new System.EventHandler(this.resetToolStripMenuItem_Click); // // goBackToolStripMenuItem // this.goBackToolStripMenuItem.Name = "goBackToolStripMenuItem"; this.goBackToolStripMenuItem.Size = new System.Drawing.Size(117, 22); this.goBackToolStripMenuItem.Text = "Go &Back"; this.goBackToolStripMenuItem.Click += new System.EventHandler(this.exitFindRecordToolStripMenuItem_Click); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.searchToolStripMenuItem}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(47, 20); this.toolsToolStripMenuItem.Text = "&Tools"; // // searchToolStripMenuItem // this.searchToolStripMenuItem.Enabled = false; this.searchToolStripMenuItem.Name = "searchToolStripMenuItem"; this.searchToolStripMenuItem.Size = new System.Drawing.Size(109, 22); this.searchToolStripMenuItem.Text = "Search"; this.searchToolStripMenuItem.Click += new System.EventHandler(this.searchToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.contentsToolStripMenuItem, this.commandReferenceToolStripMenuItem, this.aboutEpiInfoToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.helpToolStripMenuItem.Text = "&Help"; // // contentsToolStripMenuItem // this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem"; this.contentsToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.contentsToolStripMenuItem.Text = "Contents"; this.contentsToolStripMenuItem.Click += new System.EventHandler(this.contentsToolStripMenuItem_Click); // // commandReferenceToolStripMenuItem // this.commandReferenceToolStripMenuItem.Name = "commandReferenceToolStripMenuItem"; this.commandReferenceToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.commandReferenceToolStripMenuItem.Text = "Command &Reference"; this.commandReferenceToolStripMenuItem.Click += new System.EventHandler(this.commandReferenceToolStripMenuItem_Click); // // aboutEpiInfoToolStripMenuItem // this.aboutEpiInfoToolStripMenuItem.Name = "aboutEpiInfoToolStripMenuItem"; this.aboutEpiInfoToolStripMenuItem.Size = new System.Drawing.Size(186, 22); this.aboutEpiInfoToolStripMenuItem.Text = "&About Epi Info"; this.aboutEpiInfoToolStripMenuItem.Click += new System.EventHandler(this.aboutEpiInfoToolStripMenuItem_Click); // // toolTip1 // this.toolTip1.AutomaticDelay = 250; this.toolTip1.ShowAlways = true; this.toolTip1.ToolTipIcon = System.Windows.Forms.ToolTipIcon.Info; this.toolTip1.ToolTipTitle = "Find Record"; // // FindRecords // this.BackColor = System.Drawing.SystemColors.Control; this.ClientSize = new System.Drawing.Size(1030, 649); this.Controls.Add(this.splitContainer1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.menuStrip2); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MinimizeBox = false; this.Name = "FindRecords"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Find Records"; this.Load += new System.EventHandler(this.FindRecords_Load); this.splitContainer1.Panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit(); this.splitContainer1.ResumeLayout(false); this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); this.toolStrip2.ResumeLayout(false); this.toolStrip2.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.menuStrip2.ResumeLayout(false); this.menuStrip2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion //Designer Generated Code private System.Windows.Forms.ToolStripPanel BottomToolStripPanel; private System.Windows.Forms.ToolStripPanel TopToolStripPanel; private System.Windows.Forms.ToolStripPanel RightToolStripPanel; private System.Windows.Forms.ToolStripPanel LeftToolStripPanel; private System.Windows.Forms.ToolStripContentPanel ContentPanel; private System.Windows.Forms.SplitContainer splitContainer1; private System.Windows.Forms.ToolStripContainer toolStripContainer1; private System.Windows.Forms.ListBox lbxSearchFields; private System.Windows.Forms.ToolStrip toolStrip2; private System.Windows.Forms.ToolStripLabel toolStripLabel1; private System.Windows.Forms.ToolStripButton toolStripButton5; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton toolStripBackButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton toolStripResetButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.ToolStripButton toolStripSearchButton; private System.Windows.Forms.MenuStrip menuStrip2; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitFindRecordToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem resetToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem goBackToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem commandReferenceToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutEpiInfoToolStripMenuItem; private System.Windows.Forms.ToolTip toolTip1; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace GuidanceService.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Threading; using NLog.Common; using NLog.Internal.NetworkSenders; using NLog.Layouts; /// <summary> /// Sends log messages over the network. /// </summary> /// <seealso href="http://nlog-project.org/wiki/Network_target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Network/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Network/Simple/Example.cs" /> /// <p> /// To print the results, use any application that's able to receive messages over /// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is /// a simple but very powerful command-line tool that can be used for that. This image /// demonstrates the NetCat tool receiving log messages from Network target. /// </p> /// <img src="examples/targets/Screenshots/Network/Output.gif" /> /// <p> /// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol /// or you'll get TCP timeouts and your application will be very slow. /// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target /// so that your application threads will not be blocked by the timing-out connection attempts. /// </p> /// <p> /// There are two specialized versions of the Network target: <a href="target.Chainsaw.html">Chainsaw</a> /// and <a href="target.NLogViewer.html">NLogViewer</a> which write to instances of Chainsaw log4j viewer /// or NLogViewer application respectively. /// </p> /// </example> [Target("Network")] public class NetworkTarget : TargetWithLayout { private Dictionary<string, NetworkSender> currentSenderCache = new Dictionary<string, NetworkSender>(); private List<NetworkSender> openNetworkSenders = new List<NetworkSender>(); /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public NetworkTarget() { this.SenderFactory = NetworkSenderFactory.Default; this.Encoding = Encoding.UTF8; this.OnOverflow = NetworkTargetOverflowAction.Split; this.KeepConnection = true; this.MaxMessageSize = 65000; this.ConnectionCacheSize = 5; } /// <summary> /// Gets or sets the network address. /// </summary> /// <remarks> /// The network address can be: /// <ul> /// <li>tcp://host:port - TCP (auto select IPv4/IPv6) (not supported on Windows Phone 7.0)</li> /// <li>tcp4://host:port - force TCP/IPv4 (not supported on Windows Phone 7.0)</li> /// <li>tcp6://host:port - force TCP/IPv6 (not supported on Windows Phone 7.0)</li> /// <li>udp://host:port - UDP (auto select IPv4/IPv6, not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>udp4://host:port - force UDP/IPv4 (not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>udp6://host:port - force UDP/IPv6 (not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>http://host:port/pageName - HTTP using POST verb</li> /// <li>https://host:port/pageName - HTTPS using POST verb</li> /// </ul> /// For SOAP-based webservice support over HTTP use WebService target. /// </remarks> /// <docgen category='Connection Options' order='10' /> public Layout Address { get; set; } /// <summary> /// Gets or sets a value indicating whether to keep connection open whenever possible. /// </summary> /// <docgen category='Connection Options' order='10' /> [DefaultValue(true)] public bool KeepConnection { get; set; } /// <summary> /// Gets or sets a value indicating whether to append newline at the end of log message. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(false)] public bool NewLine { get; set; } /// <summary> /// Gets or sets the maximum message size in bytes. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(65000)] public int MaxMessageSize { get; set; } /// <summary> /// Gets or sets the size of the connection cache (number of connections which are kept alive). /// </summary> /// <docgen category="Connection Options" order="10"/> [DefaultValue(5)] public int ConnectionCacheSize { get; set; } /// <summary> /// Gets or sets the action that should be taken if the message is larger than /// maxMessageSize. /// </summary> /// <docgen category='Layout Options' order='10' /> public NetworkTargetOverflowAction OnOverflow { get; set; } /// <summary> /// Gets or sets the encoding to be used. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue("utf-8")] public Encoding Encoding { get; set; } internal INetworkSenderFactory SenderFactory { get; set; } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { int remainingCount = 0; AsyncContinuation continuation = ex => { // ignore exception if (Interlocked.Decrement(ref remainingCount) == 0) { asyncContinuation(null); } }; lock (this.openNetworkSenders) { remainingCount = this.openNetworkSenders.Count; if (remainingCount == 0) { // nothing to flush asyncContinuation(null); } else { // otherwise call FlushAsync() on all senders // and invoke continuation at the very end foreach (var openSender in this.openNetworkSenders) { openSender.FlushAsync(continuation); } } } } /// <summary> /// Closes the target. /// </summary> protected override void CloseTarget() { base.CloseTarget(); lock (this.openNetworkSenders) { foreach (var openSender in this.openNetworkSenders) { openSender.Close(ex => { }); } this.openNetworkSenders.Clear(); } } /// <summary> /// Sends the /// rendered logging event over the network optionally concatenating it with a newline character. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { string address = this.Address.Render(logEvent.LogEvent); byte[] bytes = this.GetBytesToWrite(logEvent.LogEvent); if (this.KeepConnection) { NetworkSender sender = this.GetCachedNetworkSender(address); this.ChunkedSend( sender, bytes, ex => { if (ex != null) { InternalLogger.Error("Error when sending {0}", ex); this.ReleaseCachedConnection(sender); } logEvent.Continuation(ex); }); } else { var sender = this.SenderFactory.Create(address); sender.Initialize(); lock (this.openNetworkSenders) { this.openNetworkSenders.Add(sender); this.ChunkedSend( sender, bytes, ex => { lock (this.openNetworkSenders) { this.openNetworkSenders.Remove(sender); } if (ex != null) { InternalLogger.Error("Error when sending {0}", ex); } sender.Close(ex2 => { }); logEvent.Continuation(ex); }); } } } /// <summary> /// Gets the bytes to be written. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns>Byte array.</returns> protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent) { string text; if (this.NewLine) { text = this.Layout.Render(logEvent) + "\r\n"; } else { text = this.Layout.Render(logEvent); } return this.Encoding.GetBytes(text); } private NetworkSender GetCachedNetworkSender(string address) { lock (this.currentSenderCache) { NetworkSender sender; // already have address if (this.currentSenderCache.TryGetValue(address, out sender)) { return sender; } if (this.currentSenderCache.Count >= this.ConnectionCacheSize) { // make room in the cache by closing the least recently used connection int minAccessTime = int.MaxValue; NetworkSender leastRecentlyUsed = null; foreach (var kvp in this.currentSenderCache) { if (kvp.Value.LastSendTime < minAccessTime) { minAccessTime = kvp.Value.LastSendTime; leastRecentlyUsed = kvp.Value; } } if (leastRecentlyUsed != null) { this.ReleaseCachedConnection(leastRecentlyUsed); } } sender = this.SenderFactory.Create(address); sender.Initialize(); lock (this.openNetworkSenders) { this.openNetworkSenders.Add(sender); } this.currentSenderCache.Add(address, sender); return sender; } } private void ReleaseCachedConnection(NetworkSender sender) { lock (this.currentSenderCache) { lock (this.openNetworkSenders) { if (this.openNetworkSenders.Remove(sender)) { // only remove it once sender.Close(ex => { }); } } NetworkSender sender2; // make sure the current sender for this address is the one we want to remove if (this.currentSenderCache.TryGetValue(sender.Address, out sender2)) { if (ReferenceEquals(sender, sender2)) { this.currentSenderCache.Remove(sender.Address); } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using property names in message.")] private void ChunkedSend(NetworkSender sender, byte[] buffer, AsyncContinuation continuation) { int tosend = buffer.Length; int pos = 0; AsyncContinuation sendNextChunk = null; sendNextChunk = ex => { if (ex != null) { continuation(ex); return; } if (tosend <= 0) { continuation(null); return; } int chunksize = tosend; if (chunksize > this.MaxMessageSize) { if (this.OnOverflow == NetworkTargetOverflowAction.Discard) { continuation(null); return; } if (this.OnOverflow == NetworkTargetOverflowAction.Error) { continuation(new OverflowException("Attempted to send a message larger than MaxMessageSize (" + this.MaxMessageSize + "). Actual size was: " + buffer.Length + ". Adjust OnOverflow and MaxMessageSize parameters accordingly.")); return; } chunksize = this.MaxMessageSize; } int pos0 = pos; tosend -= chunksize; pos += chunksize; sender.Send(buffer, pos0, chunksize, sendNextChunk); }; sendNextChunk(null); } } }
// // TranscoderService.cs // // Author: // Aaron Bockover <[email protected]> // Gabriel Burt <[email protected]> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Mono.Addins; using Hyena; using Hyena.Jobs; using Banshee.Base; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.MediaProfiles; namespace Banshee.MediaEngine { public class TranscoderService : IRegisterOnDemandService { public delegate void TrackTranscodedHandler (TrackInfo track, SafeUri uri); public delegate void TranscodeCancelledHandler (); public delegate void TranscodeErrorHandler (TrackInfo track); private struct TranscodeContext { public TrackInfo Track; public SafeUri OutUri; public ProfileConfiguration Config; public TrackTranscodedHandler Handler; public TranscodeCancelledHandler CancelledHandler; public TranscodeErrorHandler ErrorHandler; public TranscodeContext (TrackInfo track, SafeUri out_uri, ProfileConfiguration config, TrackTranscodedHandler handler, TranscodeCancelledHandler cancelledHandler, TranscodeErrorHandler errorHandler) { Track = track; OutUri = out_uri; Config = config; Handler = handler; CancelledHandler = cancelledHandler; ErrorHandler = errorHandler; } } private static bool transcoder_extension_queried = false; private static TypeExtensionNode transcoder_extension_node = null; private static TypeExtensionNode TranscoderExtensionNode { get { if (!transcoder_extension_queried) { transcoder_extension_queried = true; foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes ( "/Banshee/MediaEngine/Transcoder")) { transcoder_extension_node = node; break; } } return transcoder_extension_node; } } public static bool Supported { get { return TranscoderExtensionNode != null; } } private ITranscoder transcoder; private BatchUserJob user_job; private Queue<TranscodeContext> queue; private TranscodeContext current_context; public TranscoderService () { queue = new Queue <TranscodeContext> (); try { Banshee.IO.Directory.Delete (cache_dir, true); } catch {} Banshee.IO.Directory.Create (cache_dir); } private static string cache_dir = Paths.Combine (Paths.ApplicationCache, "transcoder"); public static SafeUri GetTempUriFor (string extension) { return new SafeUri (Paths.GetTempFileName (cache_dir, extension)); } private ITranscoder Transcoder { get { if (transcoder == null) { if (TranscoderExtensionNode != null) { transcoder = (ITranscoder) TranscoderExtensionNode.CreateInstance (); transcoder.TrackFinished += OnTrackFinished; transcoder.Progress += OnProgress; transcoder.Error += OnError; } else { throw new ApplicationException ("No Transcoder extension is installed"); } } return transcoder; } } private BatchUserJob UserJob { get { if (user_job == null) { user_job = new BatchUserJob (Catalog.GetString("Converting {0} of {1}"), Catalog.GetString("Initializing"), "encode"); user_job.SetResources (Resource.Cpu); user_job.PriorityHints = PriorityHints.SpeedSensitive; user_job.CancelMessage = Catalog.GetString ("Files are currently being converted to another format. Would you like to stop this?"); user_job.CanCancel = true; user_job.DelayShow = true; user_job.CancelRequested += OnCancelRequested; user_job.Finished += OnFinished; user_job.Register (); } return user_job; } } private void Reset () { lock (queue) { if (user_job != null) { user_job.CancelRequested -= OnCancelRequested; user_job.Finished -= OnFinished; user_job.Finish (); user_job = null; } if (transcoder != null) { transcoder.Finish (); transcoder = null; } foreach (TranscodeContext context in queue) { context.CancelledHandler (); } if (transcoding) { current_context.CancelledHandler (); transcoding = false; } queue.Clear (); } } public void Enqueue (TrackInfo track, ProfileConfiguration config, TrackTranscodedHandler handler, TranscodeCancelledHandler cancelledHandler, TranscodeErrorHandler errorHandler) { Enqueue (track, GetTempUriFor (config.Profile.OutputFileExtension), config, handler, cancelledHandler, errorHandler); } public void Enqueue (TrackInfo track, SafeUri out_uri, ProfileConfiguration config, TrackTranscodedHandler handler, TranscodeCancelledHandler cancelledHandler, TranscodeErrorHandler errorHandler) { bool start = false; lock (queue) { start = (queue.Count == 0 && !transcoding); queue.Enqueue (new TranscodeContext (track, out_uri, config, handler, cancelledHandler, errorHandler)); UserJob.Total++; } if (start) ProcessQueue (); } private bool transcoding = false; private void ProcessQueue () { TranscodeContext context; lock (queue) { if (queue.Count == 0) { Reset (); return; } context = queue.Dequeue (); transcoding = true; } current_context = context; UserJob.Status = String.Format("{0} - {1}", context.Track.ArtistName, context.Track.TrackTitle); Transcoder.TranscodeTrack (context.Track, context.OutUri, context.Config); } #region Transcoder Event Handlers private void OnTrackFinished (object o, TranscoderTrackFinishedArgs args) { transcoding = false; if (user_job == null || transcoder == null) { return; } UserJob.Completed++; args.Track.MimeType = current_context.Config.Profile.MimeTypes[0]; current_context.Handler (args.Track, current_context.OutUri); ProcessQueue (); } private void OnProgress (object o, TranscoderProgressArgs args) { if (user_job == null) { return; } UserJob.DetailedProgress = args.Fraction; } private void OnError (object o, TranscoderErrorArgs args) { transcoding = false; if (user_job == null || transcoder == null) { return; } UserJob.Completed++; current_context.ErrorHandler (current_context.Track); Hyena.Log.Error ("Cannot Convert File", args.Message); ProcessQueue (); } #endregion #region User Job Event Handlers private void OnCancelRequested (object o, EventArgs args) { Reset (); } private void OnFinished (object o, EventArgs args) { Reset (); } #endregion string IService.ServiceName { get { return "TranscoderService"; } } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Runtime.InteropServices; namespace Picodex.Render.Unity { /// <summary> /// Represents a 3x3 matrix containing 3D rotation and scale. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Matrix3 : IEquatable<Matrix3> { #region Fields /// <summary> /// First row of the matrix. /// </summary> public Vector3 Row0; /// <summary> /// Second row of the matrix. /// </summary> public Vector3 Row1; /// <summary> /// Third row of the matrix. /// </summary> public Vector3 Row2; /// <summary> /// The identity matrix. /// </summary> public static readonly Matrix3 Identity = new Matrix3(Vector3.UnitX, Vector3.UnitY, Vector3.UnitZ); /// <summary> /// The zero matrix. /// </summary> public static readonly Matrix3 Zero = new Matrix3(Vector3.Zero, Vector3.Zero, Vector3.Zero); #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="row0">Top row of the matrix</param> /// <param name="row1">Second row of the matrix</param> /// <param name="row2">Bottom row of the matrix</param> public Matrix3(Vector3 row0, Vector3 row1, Vector3 row2) { Row0 = row0; Row1 = row1; Row2 = row2; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="m00">First item of the first row of the matrix.</param> /// <param name="m01">Second item of the first row of the matrix.</param> /// <param name="m02">Third item of the first row of the matrix.</param> /// <param name="m10">First item of the second row of the matrix.</param> /// <param name="m11">Second item of the second row of the matrix.</param> /// <param name="m12">Third item of the second row of the matrix.</param> /// <param name="m20">First item of the third row of the matrix.</param> /// <param name="m21">Second item of the third row of the matrix.</param> /// <param name="m22">Third item of the third row of the matrix.</param> public Matrix3( float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) { Row0 = new Vector3(m00, m01, m02); Row1 = new Vector3(m10, m11, m12); Row2 = new Vector3(m20, m21, m22); } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="matrix">A Matrix4x4 to take the upper-left 3x3 from.</param> public Matrix3(Matrix4x4 matrix) { Row0 = matrix.Row0.Xyz; Row1 = matrix.Row1.Xyz; Row2 = matrix.Row2.Xyz; } #endregion #region Public Members #region Properties /// <summary> /// Gets the determinant of this matrix. /// </summary> public float Determinant { get { float m11 = Row0.X, m12 = Row0.Y, m13 = Row0.Z, m21 = Row1.X, m22 = Row1.Y, m23 = Row1.Z, m31 = Row2.X, m32 = Row2.Y, m33 = Row2.Z; return m11 * m22 * m33 + m12 * m23 * m31 + m13 * m21 * m32 - m13 * m22 * m31 - m11 * m23 * m32 - m12 * m21 * m33; } } /// <summary> /// Gets the first column of this matrix. /// </summary> public Vector3 Column0 { get { return new Vector3(Row0.X, Row1.X, Row2.X); } } /// <summary> /// Gets the second column of this matrix. /// </summary> public Vector3 Column1 { get { return new Vector3(Row0.Y, Row1.Y, Row2.Y); } } /// <summary> /// Gets the third column of this matrix. /// </summary> public Vector3 Column2 { get { return new Vector3(Row0.Z, Row1.Z, Row2.Z); } } /// <summary> /// Gets or sets the value at row 1, column 1 of this instance. /// </summary> public float M11 { get { return Row0.X; } set { Row0.X = value; } } /// <summary> /// Gets or sets the value at row 1, column 2 of this instance. /// </summary> public float M12 { get { return Row0.Y; } set { Row0.Y = value; } } /// <summary> /// Gets or sets the value at row 1, column 3 of this instance. /// </summary> public float M13 { get { return Row0.Z; } set { Row0.Z = value; } } /// <summary> /// Gets or sets the value at row 2, column 1 of this instance. /// </summary> public float M21 { get { return Row1.X; } set { Row1.X = value; } } /// <summary> /// Gets or sets the value at row 2, column 2 of this instance. /// </summary> public float M22 { get { return Row1.Y; } set { Row1.Y = value; } } /// <summary> /// Gets or sets the value at row 2, column 3 of this instance. /// </summary> public float M23 { get { return Row1.Z; } set { Row1.Z = value; } } /// <summary> /// Gets or sets the value at row 3, column 1 of this instance. /// </summary> public float M31 { get { return Row2.X; } set { Row2.X = value; } } /// <summary> /// Gets or sets the value at row 3, column 2 of this instance. /// </summary> public float M32 { get { return Row2.Y; } set { Row2.Y = value; } } /// <summary> /// Gets or sets the value at row 3, column 3 of this instance. /// </summary> public float M33 { get { return Row2.Z; } set { Row2.Z = value; } } /// <summary> /// Gets or sets the values along the main diagonal of the matrix. /// </summary> public Vector3 Diagonal { get { return new Vector3(Row0.X, Row1.Y, Row2.Z); } set { Row0.X = value.X; Row1.Y = value.Y; Row2.Z = value.Z; } } /// <summary> /// Gets the trace of the matrix, the sum of the values along the diagonal. /// </summary> public float Trace { get { return Row0.X + Row1.Y + Row2.Z; } } #endregion #region Indexers /// <summary> /// Gets or sets the value at a specified row and column. /// </summary> public float this[int rowIndex, int columnIndex] { get { if (rowIndex == 0) return Row0[columnIndex]; else if (rowIndex == 1) return Row1[columnIndex]; else if (rowIndex == 2) return Row2[columnIndex]; throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } set { if (rowIndex == 0) Row0[columnIndex] = value; else if (rowIndex == 1) Row1[columnIndex] = value; else if (rowIndex == 2) Row2[columnIndex] = value; else throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } } #endregion #region Instance #region public void Invert() /// <summary> /// Converts this instance into its inverse. /// </summary> public void Invert() { this = Matrix3.Invert(this); } #endregion #region public void Transpose() /// <summary> /// Converts this instance into its transpose. /// </summary> public void Transpose() { this = Matrix3.Transpose(this); } #endregion /// <summary> /// Returns a normalised copy of this instance. /// </summary> public Matrix3 Normalized() { Matrix3 m = this; m.Normalize(); return m; } /// <summary> /// Divides each element in the Matrix by the <see cref="Determinant"/>. /// </summary> public void Normalize() { var determinant = this.Determinant; Row0 /= determinant; Row1 /= determinant; Row2 /= determinant; } /// <summary> /// Returns an inverted copy of this instance. /// </summary> public Matrix3 Inverted() { Matrix3 m = this; if (m.Determinant != 0) m.Invert(); return m; } /// <summary> /// Returns a copy of this Matrix3 without scale. /// </summary> public Matrix3 ClearScale() { Matrix3 m = this; m.Row0 = m.Row0.Normalized(); m.Row1 = m.Row1.Normalized(); m.Row2 = m.Row2.Normalized(); return m; } /// <summary> /// Returns a copy of this Matrix3 without rotation. /// </summary> public Matrix3 ClearRotation() { Matrix3 m = this; m.Row0 = new Vector3(m.Row0.Length, 0, 0); m.Row1 = new Vector3(0, m.Row1.Length, 0); m.Row2 = new Vector3(0, 0, m.Row2.Length); return m; } /// <summary> /// Returns the scale component of this instance. /// </summary> public Vector3 ExtractScale() { return new Vector3(Row0.Length, Row1.Length, Row2.Length); } /// <summary> /// Returns the rotation component of this instance. Quite slow. /// </summary> /// <param name="row_normalise">Whether the method should row-normalise (i.e. remove scale from) the Matrix. Pass false if you know it's already normalised.</param> public Quaternion ExtractRotation() { return ExtractRotation(true); } public Quaternion ExtractRotation(bool row_normalise ) { var row0 = Row0; var row1 = Row1; var row2 = Row2; if (row_normalise) { row0 = row0.Normalized(); row1 = row1.Normalized(); row2 = row2.Normalized(); } // code below adapted from Blender Quaternion q = new Quaternion(); double trace = 0.25 * (row0[0] + row1[1] + row2[2] + 1.0); if (trace > 0) { double sq = Math.Sqrt(trace); q.W = (float)sq; sq = 1.0 / (4.0 * sq); q.X = (float)((row1[2] - row2[1]) * sq); q.Y = (float)((row2[0] - row0[2]) * sq); q.Z = (float)((row0[1] - row1[0]) * sq); } else if (row0[0] > row1[1] && row0[0] > row2[2]) { double sq = 2.0 * Math.Sqrt(1.0 + row0[0] - row1[1] - row2[2]); q.X = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row2[1] - row1[2]) * sq); q.Y = (float)((row1[0] + row0[1]) * sq); q.Z = (float)((row2[0] + row0[2]) * sq); } else if (row1[1] > row2[2]) { double sq = 2.0 * Math.Sqrt(1.0 + row1[1] - row0[0] - row2[2]); q.Y = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row2[0] - row0[2]) * sq); q.X = (float)((row1[0] + row0[1]) * sq); q.Z = (float)((row2[1] + row1[2]) * sq); } else { double sq = 2.0 * Math.Sqrt(1.0 + row2[2] - row0[0] - row1[1]); q.Z = (float)(0.25 * sq); sq = 1.0 / sq; q.W = (float)((row1[0] - row0[1]) * sq); q.X = (float)((row2[0] + row0[2]) * sq); q.Y = (float)((row2[1] + row1[2]) * sq); } q.Normalize(); return q; } #endregion #region Static #region CreateFromAxisAngle /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <param name="result">A matrix instance.</param> public static void CreateFromAxisAngle(Vector3 axis, float angle, out Matrix3 result) { //normalize and create a local copy of the vector. axis.Normalize(); float axisX = axis.X, axisY = axis.Y, axisZ = axis.Z; //calculate angles float cos = (float)System.Math.Cos(-angle); float sin = (float)System.Math.Sin(-angle); float t = 1.0f - cos; //do the conversion math once float tXX = t * axisX * axisX, tXY = t * axisX * axisY, tXZ = t * axisX * axisZ, tYY = t * axisY * axisY, tYZ = t * axisY * axisZ, tZZ = t * axisZ * axisZ; float sinX = sin * axisX, sinY = sin * axisY, sinZ = sin * axisZ; result.Row0.X = tXX + cos; result.Row0.Y = tXY - sinZ; result.Row0.Z = tXZ + sinY; result.Row1.X = tXY + sinZ; result.Row1.Y = tYY + cos; result.Row1.Z = tYZ - sinX; result.Row2.X = tXZ - sinY; result.Row2.Y = tYZ + sinX; result.Row2.Z = tZZ + cos; } /// <summary> /// Build a rotation matrix from the specified axis/angle rotation. /// </summary> /// <param name="axis">The axis to rotate about.</param> /// <param name="angle">Angle in radians to rotate counter-clockwise (looking in the direction of the given axis).</param> /// <returns>A matrix instance.</returns> public static Matrix3 CreateFromAxisAngle(Vector3 axis, float angle) { Matrix3 result; CreateFromAxisAngle(axis, angle, out result); return result; } #endregion #region CreateFromQuaternion /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <param name="result">Matrix result.</param> public static void CreateFromQuaternion(ref Quaternion q, out Matrix3 result) { Vector3 axis; float angle; q.ToAxisAngle(out axis, out angle); CreateFromAxisAngle(axis, angle, out result); } /// <summary> /// Build a rotation matrix from the specified quaternion. /// </summary> /// <param name="q">Quaternion to translate.</param> /// <returns>A matrix instance.</returns> public static Matrix3 CreateFromQuaternion(Quaternion q) { Matrix3 result; CreateFromQuaternion(ref q, out result); return result; } #endregion #region CreateRotation[XYZ] /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationX(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row1.Y = cos; result.Row1.Z = sin; result.Row2.Y = -sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the x-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationX(float angle) { Matrix3 result; CreateRotationX(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationY(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Z = -sin; result.Row2.X = sin; result.Row2.Z = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the y-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationY(float angle) { Matrix3 result; CreateRotationY(angle, out result); return result; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix3 instance.</param> public static void CreateRotationZ(float angle, out Matrix3 result) { float cos = (float)System.Math.Cos(angle); float sin = (float)System.Math.Sin(angle); result = Identity; result.Row0.X = cos; result.Row0.Y = sin; result.Row1.X = -sin; result.Row1.Y = cos; } /// <summary> /// Builds a rotation matrix for a rotation around the z-axis. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix3 instance.</returns> public static Matrix3 CreateRotationZ(float angle) { Matrix3 result; CreateRotationZ(angle, out result); return result; } #endregion #region CreateScale /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(float scale) { Matrix3 result; CreateScale(scale, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(Vector3 scale) { Matrix3 result; CreateScale(ref scale, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <returns>A scale matrix.</returns> public static Matrix3 CreateScale(float x, float y, float z) { Matrix3 result; CreateScale(x, y, z, out result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(float scale, out Matrix3 result) { result = Identity; result.Row0.X = scale; result.Row1.Y = scale; result.Row2.Z = scale; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(ref Vector3 scale, out Matrix3 result) { result = Identity; result.Row0.X = scale.X; result.Row1.Y = scale.Y; result.Row2.Z = scale.Z; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="z">Scale factor for the z axis.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(float x, float y, float z, out Matrix3 result) { result = Identity; result.Row0.X = x; result.Row1.Y = y; result.Row2.Z = z; } #endregion #region Multiply Functions /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication</returns> public static Matrix3 Mult(Matrix3 left, Matrix3 right) { Matrix3 result; Mult(ref left, ref right, out result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication</param> public static void Mult(ref Matrix3 left, ref Matrix3 right, out Matrix3 result) { float lM11 = left.Row0.X, lM12 = left.Row0.Y, lM13 = left.Row0.Z, lM21 = left.Row1.X, lM22 = left.Row1.Y, lM23 = left.Row1.Z, lM31 = left.Row2.X, lM32 = left.Row2.Y, lM33 = left.Row2.Z, rM11 = right.Row0.X, rM12 = right.Row0.Y, rM13 = right.Row0.Z, rM21 = right.Row1.X, rM22 = right.Row1.Y, rM23 = right.Row1.Z, rM31 = right.Row2.X, rM32 = right.Row2.Y, rM33 = right.Row2.Z; result.Row0.X = ((lM11 * rM11) + (lM12 * rM21)) + (lM13 * rM31); result.Row0.Y = ((lM11 * rM12) + (lM12 * rM22)) + (lM13 * rM32); result.Row0.Z = ((lM11 * rM13) + (lM12 * rM23)) + (lM13 * rM33); result.Row1.X = ((lM21 * rM11) + (lM22 * rM21)) + (lM23 * rM31); result.Row1.Y = ((lM21 * rM12) + (lM22 * rM22)) + (lM23 * rM32); result.Row1.Z = ((lM21 * rM13) + (lM22 * rM23)) + (lM23 * rM33); result.Row2.X = ((lM31 * rM11) + (lM32 * rM21)) + (lM33 * rM31); result.Row2.Y = ((lM31 * rM12) + (lM32 * rM22)) + (lM33 * rM32); result.Row2.Z = ((lM31 * rM13) + (lM32 * rM23)) + (lM33 * rM33); } #endregion #region Invert Functions /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular</param> /// <exception cref="InvalidOperationException">Thrown if the Matrix3 is singular.</exception> public static void Invert(ref Matrix3 mat, out Matrix3 result) { int[] colIdx = { 0, 0, 0 }; int[] rowIdx = { 0, 0, 0 }; int[] pivotIdx = { -1, -1, -1 }; float[,] inverse = {{mat.Row0.X, mat.Row0.Y, mat.Row0.Z}, {mat.Row1.X, mat.Row1.Y, mat.Row1.Z}, {mat.Row2.X, mat.Row2.Y, mat.Row2.Z}}; int icol = 0; int irow = 0; for (int i = 0; i < 3; i++) { float maxPivot = 0.0f; for (int j = 0; j < 3; j++) { if (pivotIdx[j] != 0) { for (int k = 0; k < 3; ++k) { if (pivotIdx[k] == -1) { float absVal = System.Math.Abs(inverse[j, k]); if (absVal > maxPivot) { maxPivot = absVal; irow = j; icol = k; } } else if (pivotIdx[k] > 0) { result = mat; return; } } } } ++(pivotIdx[icol]); if (irow != icol) { for (int k = 0; k < 3; ++k) { float f = inverse[irow, k]; inverse[irow, k] = inverse[icol, k]; inverse[icol, k] = f; } } rowIdx[i] = irow; colIdx[i] = icol; float pivot = inverse[icol, icol]; if (pivot == 0.0f) { throw new InvalidOperationException("Matrix is singular and cannot be inverted."); } float oneOverPivot = 1.0f / pivot; inverse[icol, icol] = 1.0f; for (int k = 0; k < 3; ++k) inverse[icol, k] *= oneOverPivot; for (int j = 0; j < 3; ++j) { if (icol != j) { float f = inverse[j, icol]; inverse[j, icol] = 0.0f; for (int k = 0; k < 3; ++k) inverse[j, k] -= inverse[icol, k] * f; } } } for (int j = 2; j >= 0; --j) { int ir = rowIdx[j]; int ic = colIdx[j]; for (int k = 0; k < 3; ++k) { float f = inverse[k, ir]; inverse[k, ir] = inverse[k, ic]; inverse[k, ic] = f; } } result.Row0.X = inverse[0, 0]; result.Row0.Y = inverse[0, 1]; result.Row0.Z = inverse[0, 2]; result.Row1.X = inverse[1, 0]; result.Row1.Y = inverse[1, 1]; result.Row1.Z = inverse[1, 2]; result.Row2.X = inverse[2, 0]; result.Row2.Y = inverse[2, 1]; result.Row2.Z = inverse[2, 2]; } /// <summary> /// Calculate the inverse of the given matrix /// </summary> /// <param name="mat">The matrix to invert</param> /// <returns>The inverse of the given matrix if it has one, or the input if it is singular</returns> /// <exception cref="InvalidOperationException">Thrown if the Matrix4 is singular.</exception> public static Matrix3 Invert(Matrix3 mat) { Matrix3 result; Invert(ref mat, out result); return result; } #endregion #region Transpose /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <returns>The transpose of the given matrix</returns> public static Matrix3 Transpose(Matrix3 mat) { return new Matrix3(mat.Column0, mat.Column1, mat.Column2); } /// <summary> /// Calculate the transpose of the given matrix /// </summary> /// <param name="mat">The matrix to transpose</param> /// <param name="result">The result of the calculation</param> public static void Transpose(ref Matrix3 mat, out Matrix3 result) { result.Row0.X = mat.Row0.X; result.Row0.Y = mat.Row1.X; result.Row0.Z = mat.Row2.X; result.Row1.X = mat.Row0.Y; result.Row1.Y = mat.Row1.Y; result.Row1.Z = mat.Row2.Y; result.Row2.X = mat.Row0.Z; result.Row2.Y = mat.Row1.Z; result.Row2.Z = mat.Row2.Z; } #endregion #endregion #region Operators /// <summary> /// Matrix multiplication /// </summary> /// <param name="left">left-hand operand</param> /// <param name="right">right-hand operand</param> /// <returns>A new Matrix3d which holds the result of the multiplication</returns> public static Matrix3 operator *(Matrix3 left, Matrix3 right) { return Matrix3.Mult(left, right); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Matrix3 left, Matrix3 right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> public static bool operator !=(Matrix3 left, Matrix3 right) { return !left.Equals(right); } #endregion #region Overrides #region public override string ToString() /// <summary> /// Returns a System.String that represents the current Matrix3d. /// </summary> /// <returns>The string representation of the matrix.</returns> public override string ToString() { return String.Format("{0}\n{1}\n{2}", Row0, Row1, Row2); } #endregion #region public override int GetHashCode() /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return Row0.GetHashCode() ^ Row1.GetHashCode() ^ Row2.GetHashCode(); } #endregion #region public override bool Equals(object obj) /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Matrix3)) return false; return this.Equals((Matrix3)obj); } #endregion #endregion #endregion #region IEquatable<Matrix3> Members /// <summary>Indicates whether the current matrix is equal to another matrix.</summary> /// <param name="other">A matrix to compare with this matrix.</param> /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns> public bool Equals(Matrix3 other) { return Row0 == other.Row0 && Row1 == other.Row1 && Row2 == other.Row2; } #endregion } }
namespace Tao.Platform.Windows { using System; using System.Runtime.InteropServices; #pragma warning disable 0649 partial class Wgl { internal static partial class Delegates { [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr CreateContext(IntPtr hDc); internal static CreateContext wglCreateContext; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean DeleteContext(IntPtr oldContext); internal static DeleteContext wglDeleteContext; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetCurrentContext(); internal static GetCurrentContext wglGetCurrentContext; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean MakeCurrent(IntPtr hDc, IntPtr newContext); internal static MakeCurrent wglMakeCurrent; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean CopyContext(IntPtr hglrcSrc, IntPtr hglrcDst, UInt32 mask); internal static CopyContext wglCopyContext; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int ChoosePixelFormat(IntPtr hDc, Gdi.PIXELFORMATDESCRIPTOR* pPfd); internal unsafe static ChoosePixelFormat wglChoosePixelFormat; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int DescribePixelFormat(IntPtr hdc, int ipfd, UInt32 cjpfd, Gdi.PIXELFORMATDESCRIPTOR* ppfd); internal unsafe static DescribePixelFormat wglDescribePixelFormat; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetCurrentDC(); internal static GetCurrentDC wglGetCurrentDC; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetDefaultProcAddress(String lpszProc); internal static GetDefaultProcAddress wglGetDefaultProcAddress; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetProcAddress(String lpszProc); internal static GetProcAddress wglGetProcAddress; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int GetPixelFormat(IntPtr hdc); internal static GetPixelFormat wglGetPixelFormat; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean SetPixelFormat(IntPtr hdc, int ipfd, Gdi.PIXELFORMATDESCRIPTOR* ppfd); internal unsafe static SetPixelFormat wglSetPixelFormat; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean SwapBuffers(IntPtr hdc); internal static SwapBuffers wglSwapBuffers; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean ShareLists(IntPtr hrcSrvShare, IntPtr hrcSrvSource); internal static ShareLists wglShareLists; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr CreateLayerContext(IntPtr hDc, int level); internal static CreateLayerContext wglCreateLayerContext; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean DescribeLayerPlane(IntPtr hDc, int pixelFormat, int layerPlane, UInt32 nBytes, Gdi.LAYERPLANEDESCRIPTOR* plpd); internal unsafe static DescribeLayerPlane wglDescribeLayerPlane; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int SetLayerPaletteEntries(IntPtr hdc, int iLayerPlane, int iStart, int cEntries, Int32* pcr); internal unsafe static SetLayerPaletteEntries wglSetLayerPaletteEntries; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate int GetLayerPaletteEntries(IntPtr hdc, int iLayerPlane, int iStart, int cEntries, Int32* pcr); internal unsafe static GetLayerPaletteEntries wglGetLayerPaletteEntries; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean RealizeLayerPalette(IntPtr hdc, int iLayerPlane, Boolean bRealize); internal static RealizeLayerPalette wglRealizeLayerPalette; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean SwapLayerBuffers(IntPtr hdc, UInt32 fuFlags); internal static SwapLayerBuffers wglSwapLayerBuffers; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean UseFontBitmapsA(IntPtr hDC, Int32 first, Int32 count, Int32 listBase); internal static UseFontBitmapsA wglUseFontBitmapsA; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean UseFontBitmapsW(IntPtr hDC, Int32 first, Int32 count, Int32 listBase); internal static UseFontBitmapsW wglUseFontBitmapsW; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean UseFontOutlinesA(IntPtr hDC, Int32 first, Int32 count, Int32 listBase, float thickness, float deviation, Int32 fontMode, Gdi.GLYPHMETRICSFLOAT* glyphMetrics); internal unsafe static UseFontOutlinesA wglUseFontOutlinesA; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean UseFontOutlinesW(IntPtr hDC, Int32 first, Int32 count, Int32 listBase, float thickness, float deviation, Int32 fontMode, Gdi.GLYPHMETRICSFLOAT* glyphMetrics); internal unsafe static UseFontOutlinesW wglUseFontOutlinesW; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr CreateBufferRegionARB(IntPtr hDC, int iLayerPlane, UInt32 uType); internal static CreateBufferRegionARB wglCreateBufferRegionARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate void DeleteBufferRegionARB(IntPtr hRegion); internal static DeleteBufferRegionARB wglDeleteBufferRegionARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean SaveBufferRegionARB(IntPtr hRegion, int x, int y, int width, int height); internal static SaveBufferRegionARB wglSaveBufferRegionARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean RestoreBufferRegionARB(IntPtr hRegion, int x, int y, int width, int height, int xSrc, int ySrc); internal static RestoreBufferRegionARB wglRestoreBufferRegionARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetExtensionsStringARB(IntPtr hdc); internal static GetExtensionsStringARB wglGetExtensionsStringARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetPixelFormatAttribivARB(IntPtr hdc, int iPixelFormat, int iLayerPlane, UInt32 nAttributes, int* piAttributes, [Out] int* piValues); internal unsafe static GetPixelFormatAttribivARB wglGetPixelFormatAttribivARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetPixelFormatAttribfvARB(IntPtr hdc, int iPixelFormat, int iLayerPlane, UInt32 nAttributes, int* piAttributes, [Out] Single* pfValues); internal unsafe static GetPixelFormatAttribfvARB wglGetPixelFormatAttribfvARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean ChoosePixelFormatARB(IntPtr hdc, int* piAttribIList, Single* pfAttribFList, UInt32 nMaxFormats, [Out] int* piFormats, [Out] UInt32* nNumFormats); internal unsafe static ChoosePixelFormatARB wglChoosePixelFormatARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean MakeContextCurrentARB(IntPtr hDrawDC, IntPtr hReadDC, IntPtr hglrc); internal static MakeContextCurrentARB wglMakeContextCurrentARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetCurrentReadDCARB(); internal static GetCurrentReadDCARB wglGetCurrentReadDCARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreatePbufferARB(IntPtr hDC, int iPixelFormat, int iWidth, int iHeight, int* piAttribList); internal unsafe static CreatePbufferARB wglCreatePbufferARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetPbufferDCARB(IntPtr hPbuffer); internal static GetPbufferDCARB wglGetPbufferDCARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleasePbufferDCARB(IntPtr hPbuffer, IntPtr hDC); internal static ReleasePbufferDCARB wglReleasePbufferDCARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean DestroyPbufferARB(IntPtr hPbuffer); internal static DestroyPbufferARB wglDestroyPbufferARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean QueryPbufferARB(IntPtr hPbuffer, int iAttribute, [Out] int* piValue); internal unsafe static QueryPbufferARB wglQueryPbufferARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean BindTexImageARB(IntPtr hPbuffer, int iBuffer); internal static BindTexImageARB wglBindTexImageARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean ReleaseTexImageARB(IntPtr hPbuffer, int iBuffer); internal static ReleaseTexImageARB wglReleaseTexImageARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean SetPbufferAttribARB(IntPtr hPbuffer, int* piAttribList); internal unsafe static SetPbufferAttribARB wglSetPbufferAttribARB; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate bool CreateDisplayColorTableEXT(UInt16 id); internal static CreateDisplayColorTableEXT wglCreateDisplayColorTableEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate bool LoadDisplayColorTableEXT(UInt16* table, UInt32 length); internal unsafe static LoadDisplayColorTableEXT wglLoadDisplayColorTableEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate bool BindDisplayColorTableEXT(UInt16 id); internal static BindDisplayColorTableEXT wglBindDisplayColorTableEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate void DestroyDisplayColorTableEXT(UInt16 id); internal static DestroyDisplayColorTableEXT wglDestroyDisplayColorTableEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetExtensionsStringEXT(); internal static GetExtensionsStringEXT wglGetExtensionsStringEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean MakeContextCurrentEXT(IntPtr hDrawDC, IntPtr hReadDC, IntPtr hglrc); internal static MakeContextCurrentEXT wglMakeContextCurrentEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetCurrentReadDCEXT(); internal static GetCurrentReadDCEXT wglGetCurrentReadDCEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreatePbufferEXT(IntPtr hDC, int iPixelFormat, int iWidth, int iHeight, int* piAttribList); internal unsafe static CreatePbufferEXT wglCreatePbufferEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate IntPtr GetPbufferDCEXT(IntPtr hPbuffer); internal static GetPbufferDCEXT wglGetPbufferDCEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int ReleasePbufferDCEXT(IntPtr hPbuffer, IntPtr hDC); internal static ReleasePbufferDCEXT wglReleasePbufferDCEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean DestroyPbufferEXT(IntPtr hPbuffer); internal static DestroyPbufferEXT wglDestroyPbufferEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean QueryPbufferEXT(IntPtr hPbuffer, int iAttribute, [Out] int* piValue); internal unsafe static QueryPbufferEXT wglQueryPbufferEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetPixelFormatAttribivEXT(IntPtr hdc, int iPixelFormat, int iLayerPlane, UInt32 nAttributes, [Out] int* piAttributes, [Out] int* piValues); internal unsafe static GetPixelFormatAttribivEXT wglGetPixelFormatAttribivEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetPixelFormatAttribfvEXT(IntPtr hdc, int iPixelFormat, int iLayerPlane, UInt32 nAttributes, [Out] int* piAttributes, [Out] Single* pfValues); internal unsafe static GetPixelFormatAttribfvEXT wglGetPixelFormatAttribfvEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean ChoosePixelFormatEXT(IntPtr hdc, int* piAttribIList, Single* pfAttribFList, UInt32 nMaxFormats, [Out] int* piFormats, [Out] UInt32* nNumFormats); internal unsafe static ChoosePixelFormatEXT wglChoosePixelFormatEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean SwapIntervalEXT(int interval); internal static SwapIntervalEXT wglSwapIntervalEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate int GetSwapIntervalEXT(); internal static GetSwapIntervalEXT wglGetSwapIntervalEXT; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr AllocateMemoryNV(Int32 size, Single readfreq, Single writefreq, Single priority); internal unsafe static AllocateMemoryNV wglAllocateMemoryNV; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate void FreeMemoryNV([Out] IntPtr* pointer); internal unsafe static FreeMemoryNV wglFreeMemoryNV; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetSyncValuesOML(IntPtr hdc, [Out] Int64* ust, [Out] Int64* msc, [Out] Int64* sbc); internal unsafe static GetSyncValuesOML wglGetSyncValuesOML; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetMscRateOML(IntPtr hdc, [Out] Int32* numerator, [Out] Int32* denominator); internal unsafe static GetMscRateOML wglGetMscRateOML; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Int64 SwapBuffersMscOML(IntPtr hdc, Int64 target_msc, Int64 divisor, Int64 remainder); internal static SwapBuffersMscOML wglSwapBuffersMscOML; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Int64 SwapLayerBuffersMscOML(IntPtr hdc, int fuPlanes, Int64 target_msc, Int64 divisor, Int64 remainder); internal static SwapLayerBuffersMscOML wglSwapLayerBuffersMscOML; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean WaitForMscOML(IntPtr hdc, Int64 target_msc, Int64 divisor, Int64 remainder, [Out] Int64* ust, [Out] Int64* msc, [Out] Int64* sbc); internal unsafe static WaitForMscOML wglWaitForMscOML; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean WaitForSbcOML(IntPtr hdc, Int64 target_sbc, [Out] Int64* ust, [Out] Int64* msc, [Out] Int64* sbc); internal unsafe static WaitForSbcOML wglWaitForSbcOML; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetDigitalVideoParametersI3D(IntPtr hDC, int iAttribute, [Out] int* piValue); internal unsafe static GetDigitalVideoParametersI3D wglGetDigitalVideoParametersI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean SetDigitalVideoParametersI3D(IntPtr hDC, int iAttribute, int* piValue); internal unsafe static SetDigitalVideoParametersI3D wglSetDigitalVideoParametersI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetGammaTableParametersI3D(IntPtr hDC, int iAttribute, [Out] int* piValue); internal unsafe static GetGammaTableParametersI3D wglGetGammaTableParametersI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean SetGammaTableParametersI3D(IntPtr hDC, int iAttribute, int* piValue); internal unsafe static SetGammaTableParametersI3D wglSetGammaTableParametersI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetGammaTableI3D(IntPtr hDC, int iEntries, [Out] UInt16* puRed, [Out] UInt16* puGreen, [Out] UInt16* puBlue); internal unsafe static GetGammaTableI3D wglGetGammaTableI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean SetGammaTableI3D(IntPtr hDC, int iEntries, UInt16* puRed, UInt16* puGreen, UInt16* puBlue); internal unsafe static SetGammaTableI3D wglSetGammaTableI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean EnableGenlockI3D(IntPtr hDC); internal static EnableGenlockI3D wglEnableGenlockI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean DisableGenlockI3D(IntPtr hDC); internal static DisableGenlockI3D wglDisableGenlockI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean IsEnabledGenlockI3D(IntPtr hDC, [Out] Boolean* pFlag); internal unsafe static IsEnabledGenlockI3D wglIsEnabledGenlockI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean GenlockSourceI3D(IntPtr hDC, UInt32 uSource); internal static GenlockSourceI3D wglGenlockSourceI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetGenlockSourceI3D(IntPtr hDC, [Out] UInt32* uSource); internal unsafe static GetGenlockSourceI3D wglGetGenlockSourceI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean GenlockSourceEdgeI3D(IntPtr hDC, UInt32 uEdge); internal static GenlockSourceEdgeI3D wglGenlockSourceEdgeI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetGenlockSourceEdgeI3D(IntPtr hDC, [Out] UInt32* uEdge); internal unsafe static GetGenlockSourceEdgeI3D wglGetGenlockSourceEdgeI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean GenlockSampleRateI3D(IntPtr hDC, UInt32 uRate); internal static GenlockSampleRateI3D wglGenlockSampleRateI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetGenlockSampleRateI3D(IntPtr hDC, [Out] UInt32* uRate); internal unsafe static GetGenlockSampleRateI3D wglGetGenlockSampleRateI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean GenlockSourceDelayI3D(IntPtr hDC, UInt32 uDelay); internal static GenlockSourceDelayI3D wglGenlockSourceDelayI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetGenlockSourceDelayI3D(IntPtr hDC, [Out] UInt32* uDelay); internal unsafe static GetGenlockSourceDelayI3D wglGetGenlockSourceDelayI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean QueryGenlockMaxSourceDelayI3D(IntPtr hDC, [Out] UInt32* uMaxLineDelay, [Out] UInt32* uMaxPixelDelay); internal unsafe static QueryGenlockMaxSourceDelayI3D wglQueryGenlockMaxSourceDelayI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate IntPtr CreateImageBufferI3D(IntPtr hDC, Int32 dwSize, UInt32 uFlags); internal unsafe static CreateImageBufferI3D wglCreateImageBufferI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean DestroyImageBufferI3D(IntPtr hDC, IntPtr pAddress); internal static DestroyImageBufferI3D wglDestroyImageBufferI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean AssociateImageBufferEventsI3D(IntPtr hDC, IntPtr* pEvent, IntPtr pAddress, Int32* pSize, UInt32 count); internal unsafe static AssociateImageBufferEventsI3D wglAssociateImageBufferEventsI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean ReleaseImageBufferEventsI3D(IntPtr hDC, IntPtr pAddress, UInt32 count); internal static ReleaseImageBufferEventsI3D wglReleaseImageBufferEventsI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean EnableFrameLockI3D(); internal static EnableFrameLockI3D wglEnableFrameLockI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean DisableFrameLockI3D(); internal static DisableFrameLockI3D wglDisableFrameLockI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean IsEnabledFrameLockI3D([Out] Boolean* pFlag); internal unsafe static IsEnabledFrameLockI3D wglIsEnabledFrameLockI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean QueryFrameLockMasterI3D([Out] Boolean* pFlag); internal unsafe static QueryFrameLockMasterI3D wglQueryFrameLockMasterI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean GetFrameUsageI3D([Out] float* pUsage); internal unsafe static GetFrameUsageI3D wglGetFrameUsageI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean BeginFrameTrackingI3D(); internal static BeginFrameTrackingI3D wglBeginFrameTrackingI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal delegate Boolean EndFrameTrackingI3D(); internal static EndFrameTrackingI3D wglEndFrameTrackingI3D; [System.Security.SuppressUnmanagedCodeSecurity()] internal unsafe delegate Boolean QueryFrameTrackingI3D([Out] Int32* pFrameCount, [Out] Int32* pMissedFrames, [Out] float* pLastMissedUsage); internal unsafe static QueryFrameTrackingI3D wglQueryFrameTrackingI3D; } } #pragma warning restore 0649 }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.VisualStudio; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.Project { internal static class NativeMethods { // IIDS public static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}"); public const int CLSCTX_INPROC_SERVER = 0x1; public const int S_FALSE = 0x00000001, S_OK = 0x00000000, IDOK = 1, IDCANCEL = 2, IDABORT = 3, IDRETRY = 4, IDIGNORE = 5, IDYES = 6, IDNO = 7, IDCLOSE = 8, IDHELP = 9, IDTRYAGAIN = 10, IDCONTINUE = 11, OLECMDERR_E_NOTSUPPORTED = unchecked((int)0x80040100), OLECMDERR_E_UNKNOWNGROUP = unchecked((int)0x80040104), UNDO_E_CLIENTABORT = unchecked((int)0x80044001), E_OUTOFMEMORY = unchecked((int)0x8007000E), E_INVALIDARG = unchecked((int)0x80070057), E_FAIL = unchecked((int)0x80004005), E_NOINTERFACE = unchecked((int)0x80004002), E_POINTER = unchecked((int)0x80004003), E_NOTIMPL = unchecked((int)0x80004001), E_UNEXPECTED = unchecked((int)0x8000FFFF), E_HANDLE = unchecked((int)0x80070006), E_ABORT = unchecked((int)0x80004004), E_ACCESSDENIED = unchecked((int)0x80070005), E_PENDING = unchecked((int)0x8000000A); public const int OLECLOSE_SAVEIFDIRTY = 0, OLECLOSE_NOSAVE = 1, OLECLOSE_PROMPTSAVE = 2; public const int OLEIVERB_PRIMARY = 0, OLEIVERB_SHOW = -1, OLEIVERB_OPEN = -2, OLEIVERB_HIDE = -3, OLEIVERB_UIACTIVATE = -4, OLEIVERB_INPLACEACTIVATE = -5, OLEIVERB_DISCARDUNDOSTATE = -6, OLEIVERB_PROPERTIES = -7; public const int OFN_READONLY = unchecked((int)0x00000001), OFN_OVERWRITEPROMPT = unchecked((int)0x00000002), OFN_HIDEREADONLY = unchecked((int)0x00000004), OFN_NOCHANGEDIR = unchecked((int)0x00000008), OFN_SHOWHELP = unchecked((int)0x00000010), OFN_ENABLEHOOK = unchecked((int)0x00000020), OFN_ENABLETEMPLATE = unchecked((int)0x00000040), OFN_ENABLETEMPLATEHANDLE = unchecked((int)0x00000080), OFN_NOVALIDATE = unchecked((int)0x00000100), OFN_ALLOWMULTISELECT = unchecked((int)0x00000200), OFN_EXTENSIONDIFFERENT = unchecked((int)0x00000400), OFN_PATHMUSTEXIST = unchecked((int)0x00000800), OFN_FILEMUSTEXIST = unchecked((int)0x00001000), OFN_CREATEPROMPT = unchecked((int)0x00002000), OFN_SHAREAWARE = unchecked((int)0x00004000), OFN_NOREADONLYRETURN = unchecked((int)0x00008000), OFN_NOTESTFILECREATE = unchecked((int)0x00010000), OFN_NONETWORKBUTTON = unchecked((int)0x00020000), OFN_NOLONGNAMES = unchecked((int)0x00040000), OFN_EXPLORER = unchecked((int)0x00080000), OFN_NODEREFERENCELINKS = unchecked((int)0x00100000), OFN_LONGNAMES = unchecked((int)0x00200000), OFN_ENABLEINCLUDENOTIFY = unchecked((int)0x00400000), OFN_ENABLESIZING = unchecked((int)0x00800000), OFN_USESHELLITEM = unchecked((int)0x01000000), OFN_DONTADDTORECENT = unchecked((int)0x02000000), OFN_FORCESHOWHIDDEN = unchecked((int)0x10000000); // for READONLYSTATUS public const int ROSTATUS_NotReadOnly = 0x0, ROSTATUS_ReadOnly = 0x1, ROSTATUS_Unknown = unchecked((int)0xFFFFFFFF); public const int IEI_DoNotLoadDocData = 0x10000000; public const int CB_SETDROPPEDWIDTH = 0x0160, GWL_STYLE = (-16), GWL_EXSTYLE = (-20), DWL_MSGRESULT = 0, SW_SHOWNORMAL = 1, HTMENU = 5, WS_POPUP = unchecked((int)0x80000000), WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_MDICHILD = 0x00000040, WS_EX_TOOLWINDOW = 0x00000080, WS_EX_CLIENTEDGE = 0x00000200, WS_EX_CONTEXTHELP = 0x00000400, WS_EX_RIGHT = 0x00001000, WS_EX_LEFT = 0x00000000, WS_EX_RTLREADING = 0x00002000, WS_EX_LEFTSCROLLBAR = 0x00004000, WS_EX_CONTROLPARENT = 0x00010000, WS_EX_STATICEDGE = 0x00020000, WS_EX_APPWINDOW = 0x00040000, WS_EX_LAYERED = 0x00080000, WS_EX_TOPMOST = 0x00000008, WS_EX_NOPARENTNOTIFY = 0x00000004, LVM_SETEXTENDEDLISTVIEWSTYLE = (0x1000 + 54), LVS_EX_LABELTIP = 0x00004000, // winuser.h WH_JOURNALPLAYBACK = 1, WH_GETMESSAGE = 3, WH_MOUSE = 7, WSF_VISIBLE = 0x0001, WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DELETEITEM = 0x002D, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, WA_INACTIVE = 0, WA_ACTIVE = 1, WA_CLICKACTIVE = 2, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, WM_QUERYOPEN = 0x0013, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, WM_WININICHANGE = 0x001A, WM_SETTINGCHANGE = 0x001A, WM_DEVMODECHANGE = 0x001B, WM_ACTIVATEAPP = 0x001C, WM_FONTCHANGE = 0x001D, WM_TIMECHANGE = 0x001E, WM_CANCELMODE = 0x001F, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_CHILDACTIVATE = 0x0022, WM_QUEUESYNC = 0x0023, WM_GETMINMAXINFO = 0x0024, WM_PAINTICON = 0x0026, WM_ICONERASEBKGND = 0x0027, WM_NEXTDLGCTL = 0x0028, WM_SPOOLERSTATUS = 0x002A, WM_DRAWITEM = 0x002B, WM_MEASUREITEM = 0x002C, WM_VKEYTOITEM = 0x002E, WM_CHARTOITEM = 0x002F, WM_SETFONT = 0x0030, WM_GETFONT = 0x0031, WM_SETHOTKEY = 0x0032, WM_GETHOTKEY = 0x0033, WM_QUERYDRAGICON = 0x0037, WM_COMPAREITEM = 0x0039, WM_GETOBJECT = 0x003D, WM_COMPACTING = 0x0041, WM_COMMNOTIFY = 0x0044, WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_POWER = 0x0048, WM_COPYDATA = 0x004A, WM_CANCELJOURNAL = 0x004B, WM_NOTIFY = 0x004E, WM_INPUTLANGCHANGEREQUEST = 0x0050, WM_INPUTLANGCHANGE = 0x0051, WM_TCARD = 0x0052, WM_HELP = 0x0053, WM_USERCHANGED = 0x0054, WM_NOTIFYFORMAT = 0x0055, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, WM_NCXBUTTONDOWN = 0x00AB, WM_NCXBUTTONUP = 0x00AC, WM_NCXBUTTONDBLCLK = 0x00AD, WM_KEYFIRST = 0x0100, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_CTLCOLOR = 0x0019, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_KEYLAST = 0x0108, WM_IME_STARTCOMPOSITION = 0x010D, WM_IME_ENDCOMPOSITION = 0x010E, WM_IME_COMPOSITION = 0x010F, WM_IME_KEYLAST = 0x010F, WM_INITDIALOG = 0x0110, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_CHANGEUISTATE = 0x0127, WM_UPDATEUISTATE = 0x0128, WM_QUERYUISTATE = 0x0129, WM_CTLCOLORMSGBOX = 0x0132, WM_CTLCOLOREDIT = 0x0133, WM_CTLCOLORLISTBOX = 0x0134, WM_CTLCOLORBTN = 0x0135, WM_CTLCOLORDLG = 0x0136, WM_CTLCOLORSCROLLBAR = 0x0137, WM_CTLCOLORSTATIC = 0x0138, WM_MOUSEFIRST = 0x0200, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_XBUTTONDOWN = 0x020B, WM_XBUTTONUP = 0x020C, WM_XBUTTONDBLCLK = 0x020D, WM_MOUSEWHEEL = 0x020A, WM_MOUSELAST = 0x020A, WM_PARENTNOTIFY = 0x0210, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_POWERBROADCAST = 0x0218, WM_DEVICECHANGE = 0x0219, WM_IME_SETCONTEXT = 0x0281, WM_IME_NOTIFY = 0x0282, WM_IME_CONTROL = 0x0283, WM_IME_COMPOSITIONFULL = 0x0284, WM_IME_SELECT = 0x0285, WM_IME_CHAR = 0x0286, WM_IME_KEYDOWN = 0x0290, WM_IME_KEYUP = 0x0291, WM_MDICREATE = 0x0220, WM_MDIDESTROY = 0x0221, WM_MDIACTIVATE = 0x0222, WM_MDIRESTORE = 0x0223, WM_MDINEXT = 0x0224, WM_MDIMAXIMIZE = 0x0225, WM_MDITILE = 0x0226, WM_MDICASCADE = 0x0227, WM_MDIICONARRANGE = 0x0228, WM_MDIGETACTIVE = 0x0229, WM_MDISETMENU = 0x0230, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, WM_DROPFILES = 0x0233, WM_MDIREFRESHMENU = 0x0234, WM_MOUSEHOVER = 0x02A1, WM_MOUSELEAVE = 0x02A3, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_RENDERFORMAT = 0x0305, WM_RENDERALLFORMATS = 0x0306, WM_DESTROYCLIPBOARD = 0x0307, WM_DRAWCLIPBOARD = 0x0308, WM_PAINTCLIPBOARD = 0x0309, WM_VSCROLLCLIPBOARD = 0x030A, WM_SIZECLIPBOARD = 0x030B, WM_ASKCBFORMATNAME = 0x030C, WM_CHANGECBCHAIN = 0x030D, WM_HSCROLLCLIPBOARD = 0x030E, WM_QUERYNEWPALETTE = 0x030F, WM_PALETTEISCHANGING = 0x0310, WM_PALETTECHANGED = 0x0311, WM_HOTKEY = 0x0312, WM_PRINT = 0x0317, WM_PRINTCLIENT = 0x0318, WM_HANDHELDFIRST = 0x0358, WM_HANDHELDLAST = 0x035F, WM_AFXFIRST = 0x0360, WM_AFXLAST = 0x037F, WM_PENWINFIRST = 0x0380, WM_PENWINLAST = 0x038F, WM_APP = unchecked((int)0x8000), WM_USER = 0x0400, WM_REFLECT = WM_USER + 0x1C00, WS_OVERLAPPED = 0x00000000, WPF_SETMINPOSITION = 0x0001, WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1), WHEEL_DELTA = 120, DWLP_MSGRESULT = 0, PSNRET_NOERROR = 0, PSNRET_INVALID = 1, PSNRET_INVALID_NOCHANGEPAGE = 2; public const int PSN_APPLY = ((0 - 200) - 2), PSN_KILLACTIVE = ((0 - 200) - 1), PSN_RESET = ((0 - 200) - 3), PSN_SETACTIVE = ((0 - 200) - 0); public const int GMEM_MOVEABLE = 0x0002, GMEM_ZEROINIT = 0x0040, GMEM_DDESHARE = 0x2000; public const int SWP_NOACTIVATE = 0x0010, SWP_NOZORDER = 0x0004, SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_FRAMECHANGED = 0x0020; public const int TVM_SETINSERTMARK = (0x1100 + 26), TVM_GETEDITCONTROL = (0x1100 + 15); public const int FILE_ATTRIBUTE_READONLY = 0x00000001; public const int PSP_DEFAULT = 0x00000000, PSP_DLGINDIRECT = 0x00000001, PSP_USEHICON = 0x00000002, PSP_USEICONID = 0x00000004, PSP_USETITLE = 0x00000008, PSP_RTLREADING = 0x00000010, PSP_HASHELP = 0x00000020, PSP_USEREFPARENT = 0x00000040, PSP_USECALLBACK = 0x00000080, PSP_PREMATURE = 0x00000400, PSP_HIDEHEADER = 0x00000800, PSP_USEHEADERTITLE = 0x00001000, PSP_USEHEADERSUBTITLE = 0x00002000; public const int PSH_DEFAULT = 0x00000000, PSH_PROPTITLE = 0x00000001, PSH_USEHICON = 0x00000002, PSH_USEICONID = 0x00000004, PSH_PROPSHEETPAGE = 0x00000008, PSH_WIZARDHASFINISH = 0x00000010, PSH_WIZARD = 0x00000020, PSH_USEPSTARTPAGE = 0x00000040, PSH_NOAPPLYNOW = 0x00000080, PSH_USECALLBACK = 0x00000100, PSH_HASHELP = 0x00000200, PSH_MODELESS = 0x00000400, PSH_RTLREADING = 0x00000800, PSH_WIZARDCONTEXTHELP = 0x00001000, PSH_WATERMARK = 0x00008000, PSH_USEHBMWATERMARK = 0x00010000, // user pass in a hbmWatermark instead of pszbmWatermark PSH_USEHPLWATERMARK = 0x00020000, // PSH_STRETCHWATERMARK = 0x00040000, // stretchwatermark also applies for the header PSH_HEADER = 0x00080000, PSH_USEHBMHEADER = 0x00100000, PSH_USEPAGELANG = 0x00200000, // use frame dialog template matched to page PSH_WIZARD_LITE = 0x00400000, PSH_NOCONTEXTHELP = 0x02000000; public const int PSBTN_BACK = 0, PSBTN_NEXT = 1, PSBTN_FINISH = 2, PSBTN_OK = 3, PSBTN_APPLYNOW = 4, PSBTN_CANCEL = 5, PSBTN_HELP = 6, PSBTN_MAX = 6; public const int TRANSPARENT = 1, OPAQUE = 2, FW_BOLD = 700; [StructLayout(LayoutKind.Sequential)] public struct NMHDR { public IntPtr hwndFrom; public int idFrom; public int code; } /// <devdoc> /// Helper class for setting the text parameters to OLECMDTEXT structures. /// </devdoc> public static class OLECMDTEXT { /// <summary> /// Flags for the OLE command text /// </summary> public enum OLECMDTEXTF { /// <summary>No flag</summary> OLECMDTEXTF_NONE = 0, /// <summary>The name of the command is required.</summary> OLECMDTEXTF_NAME = 1, /// <summary>A description of the status is required.</summary> OLECMDTEXTF_STATUS = 2 } } /// <devdoc> /// OLECMDF enums for IOleCommandTarget /// </devdoc> public enum tagOLECMDF { OLECMDF_SUPPORTED = 1, OLECMDF_ENABLED = 2, OLECMDF_LATCHED = 4, OLECMDF_NINCHED = 8, OLECMDF_INVISIBLE = 16 } /// <devdoc> /// This method takes a file URL and converts it to an absolute path. The trick here is that /// if there is a '#' in the path, everything after this is treated as a fragment. So /// we need to append the fragment to the end of the path. /// </devdoc> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static string GetAbsolutePath(string fileName) { System.Diagnostics.Debug.Assert(fileName != null && fileName.Length > 0, "Cannot get absolute path, fileName is not valid"); Uri uri = new Uri(fileName); return uri.LocalPath + uri.Fragment; } /// <devdoc> /// Please use this "approved" method to compare file names. /// </devdoc> public static bool IsSamePath(string file1, string file2) { if(file1 == null || file1.Length == 0) { return (file2 == null || file2.Length == 0); } Uri uri1 = null; Uri uri2 = null; try { if(!Uri.TryCreate(file1, UriKind.Absolute, out uri1) || !Uri.TryCreate(file2, UriKind.Absolute, out uri2)) { return false; } if(uri1 != null && uri1.IsFile && uri2 != null && uri2.IsFile) { return 0 == String.Compare(uri1.LocalPath, uri2.LocalPath, StringComparison.OrdinalIgnoreCase); } return file1 == file2; } catch(UriFormatException e) { Trace.WriteLine("Exception " + e.Message); } return false; } [ComImport(), Guid("9BDA66AE-CA28-4e22-AA27-8A7218A0E3FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IEventHandler { // converts the underlying codefunction into an event handler for the given event // if the given event is NULL, then the function will handle no events [PreserveSig] int AddHandler(string bstrEventName); [PreserveSig] int RemoveHandler(string bstrEventName); IVsEnumBSTR GetHandledEvents(); bool HandlesEvent(string bstrEventName); } [ComImport(), Guid("A55CCBCC-7031-432d-B30A-A68DE7BDAD75"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IParameterKind { void SetParameterPassingMode(PARAMETER_PASSING_MODE ParamPassingMode); void SetParameterArrayDimensions(int uDimensions); int GetParameterArrayCount(); int GetParameterArrayDimensions(int uIndex); int GetParameterPassingMode(); } public enum PARAMETER_PASSING_MODE { cmParameterTypeIn = 1, cmParameterTypeOut = 2, cmParameterTypeInOut = 3 } [ ComImport, ComVisible(true), Guid("3E596484-D2E4-461a-A876-254C4F097EBB"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown) ] public interface IMethodXML { // Generate XML describing the contents of this function's body. void GetXML(ref string pbstrXML); // Parse the incoming XML with respect to the CodeModel XML schema and // use the result to regenerate the body of the function. /// <include file='doc\NativeMethods.uex' path='docs/doc[@for="IMethodXML.SetXML"]/*' /> [PreserveSig] int SetXML(string pszXML); // This is really a textpoint [PreserveSig] int GetBodyPoint([MarshalAs(UnmanagedType.Interface)]out object bodyPoint); } [ComImport(), Guid("EA1A87AD-7BC5-4349-B3BE-CADC301F17A3"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] public interface IVBFileCodeModelEvents { [PreserveSig] int StartEdit(); [PreserveSig] int EndEdit(); } ///-------------------------------------------------------------------------- /// ICodeClassBase: ///-------------------------------------------------------------------------- [GuidAttribute("23BBD58A-7C59-449b-A93C-43E59EFC080C")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [ComImport()] public interface ICodeClassBase { [PreserveSig()] int GetBaseName(out string pBaseName); } public const ushort CF_HDROP = 15; // winuser.h public const uint MK_CONTROL = 0x0008; //winuser.h public const uint MK_SHIFT = 0x0004; public const int MAX_PATH = 260; // windef.h /// <summary> /// Specifies options for a bitmap image associated with a task item. /// </summary> public enum VSTASKBITMAP { BMP_COMPILE = -1, BMP_SQUIGGLE = -2, BMP_COMMENT = -3, BMP_SHORTCUT = -4, BMP_USER = -5 }; public const int ILD_NORMAL = 0x0000, ILD_TRANSPARENT = 0x0001, ILD_MASK = 0x0010, ILD_ROP = 0x0040; /// <summary> /// Defines the values that are not supported by the System.Environment.SpecialFolder enumeration /// </summary> [ComVisible(true)] public enum ExtendedSpecialFolder { /// <summary> /// Identical to CSIDL_COMMON_STARTUP /// </summary> CommonStartup = 0x0018, /// <summary> /// Identical to CSIDL_WINDOWS /// </summary> Windows = 0x0024, } // APIS /// <summary> /// Changes the parent window of the specified child window. /// </summary> /// <param name="hWnd">Handle to the child window.</param> /// <param name="hWndParent">Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.</param> /// <returns>A handle to the previous parent window indicates success. NULL indicates failure.</returns> [DllImport("User32", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent); [DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)] public static extern bool DestroyIcon(IntPtr handle); [DllImport("user32.dll", EntryPoint = "IsDialogMessageA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)] public static extern bool IsDialogMessageA(IntPtr hDlg, ref MSG msg); /// <summary> /// Indicates whether the file type is binary or not /// </summary> /// <param name="lpApplicationName">Full path to the file to check</param> /// <param name="lpBinaryType">If file isbianry the bitness of the app is indicated by lpBinaryType value.</param> /// <returns>True if the file is binary false otherwise</returns> [DllImport("kernel32.dll")] public static extern bool GetBinaryType([MarshalAs(UnmanagedType.LPWStr)]string lpApplicationName, out uint lpBinaryType); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text.Unicode; namespace System.Text { public readonly ref partial struct Utf8Span { public static bool operator ==(Utf8Span left, Utf8Span right) => Equals(left, right); public static bool operator !=(Utf8Span left, Utf8Span right) => !Equals(left, right); public int CompareTo(Utf8Span other) { // TODO_UTF8STRING: This is ordinal, but String.CompareTo uses CurrentCulture. // Is this acceptable? return Utf8StringComparer.Ordinal.Compare(this, other); } public int CompareTo(Utf8Span other, StringComparison comparison) { // TODO_UTF8STRING: We can avoid the virtual dispatch by moving the switch into this method. return Utf8StringComparer.FromComparison(comparison).Compare(this, other); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains /// <paramref name="value"/>. An ordinal comparison is used. /// </summary> public bool Contains(char value) { return Rune.TryCreate(value, out Rune rune) && Contains(rune); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains /// <paramref name="value"/>. The specified comparison is used. /// </summary> public bool Contains(char value, StringComparison comparison) { return Rune.TryCreate(value, out Rune rune) && Contains(rune, comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains /// the specified <see cref="Rune"/>. An ordinal comparison is used. /// </summary> public bool Contains(Rune value) { // TODO_UTF8STRING: This should be split into two methods: // One which operates on a single-byte (ASCII) search value, // the other which operates on a multi-byte (non-ASCII) search value. Span<byte> runeBytes = stackalloc byte[Utf8Utility.MaxBytesPerScalar]; int runeBytesWritten = value.EncodeToUtf8(runeBytes); return (this.Bytes.IndexOf(runeBytes.Slice(0, runeBytesWritten)) >= 0); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains /// the specified <see cref="Rune"/>. The specified comparison is used. /// </summary> public bool Contains(Rune value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().Contains(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains <paramref name="value"/>. /// An ordinal comparison is used. /// </summary> public bool Contains(Utf8Span value) { return (this.Bytes.IndexOf(value.Bytes) >= 0); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance contains <paramref name="value"/>. /// The specified comparison is used. /// </summary> public bool Contains(Utf8Span value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().Contains(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with /// <paramref name="value"/>. An ordinal comparison is used. /// </summary> public bool EndsWith(char value) { return Rune.TryCreate(value, out Rune rune) && EndsWith(rune); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with /// <paramref name="value"/>. The specified comparison is used. /// </summary> public bool EndsWith(char value, StringComparison comparison) { return Rune.TryCreate(value, out Rune rune) && EndsWith(rune, comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with /// the specified <see cref="Rune"/>. An ordinal comparison is used. /// </summary> public bool EndsWith(Rune value) { // TODO_UTF8STRING: This should be split into two methods: // One which operates on a single-byte (ASCII) search value, // the other which operates on a multi-byte (non-ASCII) search value. Span<byte> runeBytes = stackalloc byte[Utf8Utility.MaxBytesPerScalar]; int runeBytesWritten = value.EncodeToUtf8(runeBytes); return this.Bytes.EndsWith(runeBytes.Slice(0, runeBytesWritten)); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with /// the specified <see cref="Rune"/>. The specified comparison is used. /// </summary> public bool EndsWith(Rune value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().EndsWith(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with <paramref name="value"/>. /// An ordinal comparison is used. /// </summary> public bool EndsWith(Utf8Span value) { return this.Bytes.EndsWith(value.Bytes); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance ends with <paramref name="value"/>. /// The specified comparison is used. /// </summary> public bool EndsWith(Utf8Span value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().EndsWith(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with /// <paramref name="value"/>. An ordinal comparison is used. /// </summary> public bool StartsWith(char value) { return Rune.TryCreate(value, out Rune rune) && StartsWith(rune); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with /// <paramref name="value"/>. The specified comparison is used. /// </summary> public bool StartsWith(char value, StringComparison comparison) { return Rune.TryCreate(value, out Rune rune) && StartsWith(rune, comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with /// the specified <see cref="Rune"/>. An ordinal comparison is used. /// </summary> public bool StartsWith(Rune value) { // TODO_UTF8STRING: This should be split into two methods: // One which operates on a single-byte (ASCII) search value, // the other which operates on a multi-byte (non-ASCII) search value. Span<byte> runeBytes = stackalloc byte[Utf8Utility.MaxBytesPerScalar]; int runeBytesWritten = value.EncodeToUtf8(runeBytes); return this.Bytes.StartsWith(runeBytes.Slice(0, runeBytesWritten)); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with /// the specified <see cref="Rune"/>. The specified comparison is used. /// </summary> public bool StartsWith(Rune value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().StartsWith(value.ToString(), comparison); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with <paramref name="value"/>. /// An ordinal comparison is used. /// </summary> public bool StartsWith(Utf8Span value) { return this.Bytes.StartsWith(value.Bytes); } /// <summary> /// Returns a value stating whether the current <see cref="Utf8Span"/> instance begins with <paramref name="value"/>. /// The specified comparison is used. /// </summary> public bool StartsWith(Utf8Span value, StringComparison comparison) { // TODO_UTF8STRING: Optimize me to avoid allocations. return this.ToString().StartsWith(value.ToString(), comparison); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using Xunit; namespace System.Reflection.Tests { public class GetTypeReflectionTests { [Fact] public void GetType1() { Assembly a = typeof(GetTypeReflectionTests).GetTypeInfo().Assembly; String assemblyName = a.FullName; PerformTests(null, "NON-EXISTENT-TYPE"); PerformTests(typeof(MyClass1)); PerformTests(typeof(MyClass1), "System.Reflection.Tests.mYclAss1"); PerformTests(null, "System.Reflection.Tests.MyNameSPACe1.MyNAMEspace99.MyClASs3+inNer"); PerformTests(null, "System.Reflection.Tests.MyNameSPACe1.MyNAMEspace2.MyClASs399+inNer"); PerformTests(null, "System.Reflection.Tests.MyNameSPACe1.MyNAMEspace2.MyClASs3+inNer99"); PerformTests(typeof(MyNamespace1.MyNamespace2.MyClass2)); PerformTests(typeof(MyNamespace1.MyNamespace2.MyClass2)); PerformTests(typeof(MyNamespace1.MyNamespace2.MyClass3.iNner)); PerformTests(typeof(MyNamespace1.MyNamespace2.MyClass3.iNner), "System.Reflection.Tests.MyNameSPACe1.MyNAMEspace2.MyClASs3+inNer"); PerformTests(typeof(MyNamespace1.MyNaMespace3.Foo)); PerformTests(typeof(MyNamespace1.MyNaMespace3.Foo), "System.Reflection.Tests.mynamespace1.mynamespace3.foo"); PerformTests(typeof(MyNamespace1.MyNaMespace3.Foo), "System.Reflection.Tests.MYNAMESPACE1.MYNAMESPACE3.FOO"); { Type g = typeof(MyNamespace1.MynAmespace3.Goo<int>); String fullName = g.FullName; PerformTests(g, fullName); PerformTests(g, fullName.ToUpper()); PerformTests(g, fullName.ToLower()); } } [Fact] public void GetTypeFromCoreAssembly() { Type typeInt32 = typeof(Int32); Type t; t = Type.GetType("System.Int32", throwOnError: true); Assert.Equal(t, typeInt32); t = Type.GetType("system.int32", throwOnError: true, ignoreCase: true); Assert.Equal(t, typeInt32); } [Fact] public void GetTypeEmptyString() { Assembly a = typeof(GetTypeReflectionTests).GetTypeInfo().Assembly; Module m = a.ManifestModule; String typeName = ""; String aqn = ", " + typeof(GetTypeReflectionTests).GetTypeInfo().Assembly.FullName; Assert.Null(Type.GetType(typeName)); Assert.Null(Type.GetType(aqn)); Assert.Null(Type.GetType(typeName, throwOnError: false)); Assert.Null(Type.GetType(aqn, throwOnError: false)); Assert.Throws<TypeLoadException>(() => Type.GetType(typeName, throwOnError: true)); Assert.Throws<ArgumentException>(() => Type.GetType(aqn, throwOnError: true)); Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(Type.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(Type.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); Assert.Throws<TypeLoadException>(() => Type.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => Type.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => Type.GetType(aqn, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => a.GetType(typeName)); Assert.Null(a.GetType(aqn)); Assert.Throws<ArgumentException>(() => a.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Throws<ArgumentException>(() => a.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<ArgumentException>(() => a.GetType(typeName, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => a.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => a.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => a.GetType(aqn, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => m.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Throws<ArgumentException>(() => m.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(m.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(m.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<ArgumentException>(() => m.GetType(typeName, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => m.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => m.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => m.GetType(aqn, throwOnError: true, ignoreCase: true)); } private static void PerformTests(Type expectedResult, String typeName = null) { if (typeName == null) typeName = expectedResult.FullName; Assembly a = typeof(GetTypeReflectionTests).GetTypeInfo().Assembly; Module m = a.ManifestModule; String aqn = typeName + ", " + a.FullName; if (expectedResult == null) { Assert.Null(Type.GetType(typeName)); Assert.Null(Type.GetType(aqn)); Assert.Null(Type.GetType(typeName, throwOnError: false)); Assert.Null(Type.GetType(aqn, throwOnError: false)); Assert.Throws<TypeLoadException>(() => Type.GetType(typeName, throwOnError: true)); Assert.Throws<TypeLoadException>(() => Type.GetType(aqn, throwOnError: true)); Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(Type.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(Type.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); Assert.Throws<TypeLoadException>(() => Type.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => Type.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<TypeLoadException>(() => Type.GetType(aqn, throwOnError: true, ignoreCase: true)); Assert.Null(a.GetType(typeName)); Assert.Null(a.GetType(aqn)); Assert.Null(a.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Null(a.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => a.GetType(typeName, throwOnError: true, ignoreCase: false)); Assert.Throws<TypeLoadException>(() => a.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => a.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => a.GetType(aqn, throwOnError: true, ignoreCase: true)); Assert.Null(m.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Null(m.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(m.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(m.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => m.GetType(typeName, throwOnError: true, ignoreCase: false)); Assert.Throws<TypeLoadException>(() => m.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => m.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => m.GetType(aqn, throwOnError: true, ignoreCase: true)); } else if (expectedResult.FullName == typeName) { // Case-sensitive match. Assert.Equal(expectedResult, Type.GetType(typeName)); Assert.Equal(expectedResult, Type.GetType(aqn)); Assert.Equal(expectedResult, Type.GetType(typeName, throwOnError: false)); Assert.Equal(expectedResult, Type.GetType(aqn, throwOnError: false)); Assert.Equal(expectedResult, Type.GetType(typeName, throwOnError: true)); Assert.Equal(expectedResult, Type.GetType(aqn, throwOnError: true)); Assert.Equal(expectedResult, Type.GetType(typeName, throwOnError: false, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, Type.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Equal(expectedResult, Type.GetType(aqn, throwOnError: false, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, Type.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Equal(expectedResult, Type.GetType(typeName, throwOnError: true, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, Type.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Equal(expectedResult, Type.GetType(aqn, throwOnError: true, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, Type.GetType(aqn, throwOnError: true, ignoreCase: true)); Assert.Equal(expectedResult, a.GetType(typeName)); Assert.Null(a.GetType(aqn)); Assert.Equal(expectedResult, a.GetType(typeName, throwOnError: false, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, a.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Equal(expectedResult, a.GetType(typeName, throwOnError: true, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, a.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => a.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => a.GetType(aqn, throwOnError: true, ignoreCase: true)); Assert.Equal(expectedResult, m.GetType(typeName, throwOnError: false, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, m.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(m.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(m.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Equal(expectedResult, m.GetType(typeName, throwOnError: true, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, m.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => m.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => m.GetType(aqn, throwOnError: true, ignoreCase: true)); } else if (expectedResult.FullName.Equals(typeName, StringComparison.OrdinalIgnoreCase)) { // Case-insensitive match. Assert.Null(Type.GetType(typeName)); Assert.Null(Type.GetType(aqn)); Assert.Null(Type.GetType(typeName, throwOnError: false)); Assert.Null(Type.GetType(aqn, throwOnError: false)); Assert.Throws<TypeLoadException>(() => Type.GetType(typeName, throwOnError: true)); Assert.Throws<TypeLoadException>(() => Type.GetType(aqn, throwOnError: true)); Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, Type.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(Type.GetType(aqn, throwOnError: false, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, Type.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, Type.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => Type.GetType(aqn, throwOnError: true, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, Type.GetType(aqn, throwOnError: true, ignoreCase: true)); Assert.Null(a.GetType(typeName)); Assert.Null(a.GetType(aqn)); Assert.Null(a.GetType(typeName, throwOnError: false, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, a.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(a.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => a.GetType(typeName, throwOnError: true, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, a.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => a.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => a.GetType(aqn, throwOnError: true, ignoreCase: true)); Assert.Null(m.GetType(typeName, throwOnError: false, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, m.GetType(typeName, throwOnError: false, ignoreCase: true)); Assert.Null(m.GetType(aqn, throwOnError: false, ignoreCase: false)); Assert.Null(m.GetType(aqn, throwOnError: false, ignoreCase: true)); Assert.Throws<TypeLoadException>(() => m.GetType(typeName, throwOnError: true, ignoreCase: false)); AssertCaseInsensitiveMatch(expectedResult, m.GetType(typeName, throwOnError: true, ignoreCase: true)); Assert.Throws<ArgumentException>(() => m.GetType(aqn, throwOnError: true, ignoreCase: false)); Assert.Throws<ArgumentException>(() => m.GetType(aqn, throwOnError: true, ignoreCase: true)); } else { throw new InvalidOperationException("TEST ERROR."); } } private static void AssertCaseInsensitiveMatch(Type expectedResult, Type actualResult) { // When called with "ignoreCase: true", GetType() may have a choice of matching items. The one that is chosen // is an implementation detail (and on the CLR, *very* implementation-dependent as it's influenced by the internal // layout of private hash tables.) As a result, we do not expect the same result across desktop and Project N // and so the best we can do is compare the names. Assert.True(expectedResult.AssemblyQualifiedName.Equals(actualResult.AssemblyQualifiedName, StringComparison.OrdinalIgnoreCase)); } } namespace MyNamespace1 { namespace MyNamespace2 { public class MyClass2 { } public class MyClass3 { public class Inner { } public class inner { } public class iNner { } public class inNer { } } public class MyClass4 { } public class mYClass4 { } public class Myclass4 { } public class myCLass4 { } public class myClAss4 { } } namespace MyNamespace3 { public class Foo { } } namespace MynAmespace3 { public class Foo { } public class Goo<T> { } public class gOo<T> { } public class goO<T> { } } namespace MyNaMespace3 { public class Foo { } } namespace MyNamEspace3 { public class Foo { } } } public class MyClass1 { } }
using System; using System.Collections.Generic; using Sce.PlayStation.Core; using Sce.PlayStation.Core.Environment; using Sce.PlayStation.Core.Graphics; using Sce.PlayStation.Core.Input; namespace ShaderSample { public class AppMain { private static GraphicsContext graphics; //private static ShaderProgram shaderTile; //private static ShaderProgram shaderDanmaku; private static ShaderProgram shaderStar; //private static ShaderProgram shaderNoise; //from sample2.1 static float[] vertices=new float[12]; static float[] texcoords; static float[] colors = { 1.0f, 1.0f, 1.0f, 1.0f, // 0 top left. 1.0f, 1.0f, 1.0f, 1.0f, // 1 bottom left. 1.0f, 1.0f, 1.0f, 1.0f, // 2 top right. 1.0f, 1.0f, 1.0f, 1.0f, // 3 bottom right. }; const int indexSize = 4; static ushort[] indices; static VertexBuffer vertexBuffer; static Matrix4 screenMatrix; //end static DateTime StartTime; public static void Main (string[] args) { Initialize (); while (true) { SystemEvents.CheckEvents (); Update (); Render (); } } public static void Initialize () { // Set up the graphics system graphics = new GraphicsContext (); //shaderTile= new ShaderProgram( "/Application/shaders/TileBritish.cgx" ); //shaderDanmaku=new ShaderProgram("/Application/shaders/DanmakuRepeatLimited.cgx"); shaderStar=new ShaderProgram("/Application/shaders/StarIntegerWaveTwinkle.cgx"); //shaderNoise=new ShaderProgram("/Application/shaders/NoiseColor.cgx"); texcoords = new float[]{ 0.0f, 0.0f, // 0 top left. 0.0f, 544.0f, // 1 bottom left. 960.0f, 0.0f, // 2 top right. 960.0f, 544.0f, // 3 bottom right. }; //sample vertices[0]=0.0f; // x0 vertices[1]=0.0f; // y0 vertices[2]=0.0f; // z0 vertices[3]=0.0f; // x1 vertices[4]=graphics.Screen.Height; // y1 vertices[5]=0.0f; // z1 vertices[6]=graphics.Screen.Width; // x2 vertices[7]=0.0f; // y2 vertices[8]=0.0f; // z2 vertices[9]=graphics.Screen.Width; // x3 vertices[10]=graphics.Screen.Height; // y3 vertices[11]=0.0f; // z3 indices = new ushort[indexSize]; indices[0] = 0; indices[1] = 1; indices[2] = 2; indices[3] = 3; // vertex pos, texture, color vertexBuffer = new VertexBuffer(4, indexSize, VertexFormat.Float3, VertexFormat.Float2, VertexFormat.Float4); vertexBuffer.SetVertices(0, vertices); vertexBuffer.SetVertices(1, texcoords); vertexBuffer.SetVertices(2, colors); vertexBuffer.SetIndices(indices); graphics.SetVertexBuffer(0, vertexBuffer); screenMatrix = new Matrix4( 2.0f/graphics.Screen.Width, 0.0f, 0.0f, 0.0f, 0.0f, -2.0f/graphics.Screen.Height, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -1.0f, 1.0f, 0.0f, 1.0f ); //end StartTime=DateTime.Now; } public static void Update () { // Query gamepad for current state var gamePadData = GamePad.GetData (0); } public static void Render () { // Clear the screen graphics.SetClearColor (0.0f, 0.0f, 0.0f, 0.0f); graphics.Clear (); /* graphics.SetShaderProgram(shaderTile); shaderTile.SetUniformValue(shaderTile.FindUniform("WorldViewProj"),ref screenMatrix); Vector2 tileSize=new Vector2(10.0f,10.0f); shaderTile.SetUniformValue(shaderTile.FindUniform("TileSize"),ref tileSize); Vector2 jointSize=new Vector2(1f,1f); shaderTile.SetUniformValue(shaderTile.FindUniform("JointSize"),ref jointSize); Vector4 tileColor=new Vector4(156.0f/255.0f,75.0f/255.0f,54.0f/255.0f,1.0f); shaderTile.SetUniformValue(shaderTile.FindUniform("TileColor"),ref tileColor); Vector4 jointColor=new Vector4(0.0f,0.0f,0.0f,1.0f); shaderTile.SetUniformValue(shaderTile.FindUniform("JointColor"),ref jointColor); */ //shaderTile.SetUniformValue(0,ref screenMatrix); /* graphics.SetShaderProgram(shaderDanmaku); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("WorldViewProj"),ref screenMatrix); float EllapsedTime=(float)((DateTime.Now-StartTime).TotalSeconds); //if(EllapsedTime<0.3f){EllapsedTime*=4.0f;}else{EllapsedTime+=0.9f;} //if(EllapsedTime>10.0f & EllapsedTime<20.0f){EllapsedTime=20.0f-EllapsedTime;} //if(EllapsedTime>5.0f){EllapsedTime=5.0f;} //EllapsedTime/=5.0f; shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("EllapsedTime"),EllapsedTime); Vector2 ExplosionPoint=new Vector2(480.0f,272.0f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("ExplosionPoint"),ref ExplosionPoint); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("BulletSize"),10.0f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("BulletSpeed"),150.0f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("BulletRotationSpeed"),0.8f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("BulletCount"),15); Vector4 bgColor=new Vector4(0.0f,0.0f,0.0f,1.0f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("BackGroundColor"),ref bgColor); Vector4 bulletColor=new Vector4(0.0f,0.0f,0.9f,1.0f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("BulletColor"),ref bulletColor); Vector4 bulletColorCenter=new Vector4(0.5f,0.5f,1.0f,1.0f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("BulletColorCenter"),ref bulletColorCenter); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("RepeatTime"),0.1f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("RepeatCountLimit"),-1); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("RepeatRotationDifference"),1.0f); Vector2 bulletRotationLimit=new Vector2(1.57f,3.4f); shaderDanmaku.SetUniformValue(shaderDanmaku.FindUniform("BulletRotationLimit"),ref bulletRotationLimit); */ graphics.SetShaderProgram(shaderStar); shaderStar.SetUniformValue(shaderStar.FindUniform("WorldViewProj"),ref screenMatrix); Vector4 StarBgColor=new Vector4(0.0f,0.0f,0.0f,1.0f); shaderStar.SetUniformValue(shaderStar.FindUniform("BgColor"),ref StarBgColor); Vector4 StarStarColor=new Vector4(1.0f,1.0f,0.0f,1.0f); shaderStar.SetUniformValue(shaderStar.FindUniform("StarColor"),ref StarStarColor); float StarEllapsedTime=(float)((DateTime.Now-StartTime).TotalSeconds); shaderStar.SetUniformValue(shaderStar.FindUniform("OffsetX"),(int)(StarEllapsedTime*300.0f)); shaderStar.SetUniformValue(shaderStar.FindUniform("OffsetY"),(int)(StarEllapsedTime*000.0f)); shaderStar.SetUniformValue(shaderStar.FindUniform("Possibility"),0.002f); Vector2 WaveCoord=new Vector2(300.0f,272.0f); shaderStar.SetUniformValue(shaderStar.FindUniform("WaveCoord"),ref WaveCoord); shaderStar.SetUniformValue(shaderStar.FindUniform("WaveTime"),StarEllapsedTime-2.0f); shaderStar.SetUniformValue(shaderStar.FindUniform("WaveSpeed"),200.0f); shaderStar.SetUniformValue(shaderStar.FindUniform("WaveScale"),50.0f); shaderStar.SetUniformValue(shaderStar.FindUniform("WaveFrequency"),2.0f); shaderStar.SetUniformValue(shaderStar.FindUniform("WaveLastTime"),5.0f); shaderStar.SetUniformValue(shaderStar.FindUniform("TwinkleTime"),StarEllapsedTime); shaderStar.SetUniformValue(shaderStar.FindUniform("Seed"),2); /* graphics.SetShaderProgram(shaderNoise); shaderNoise.SetUniformValue(shaderNoise.FindUniform("WorldViewProj"),ref screenMatrix); float NoiseEllapsedTime=(float)((DateTime.Now-StartTime).TotalSeconds); shaderNoise.SetUniformValue(shaderNoise.FindUniform("Time"),(int)(NoiseEllapsedTime*60)); */ graphics.DrawArrays(DrawMode.TriangleStrip, 0, indexSize); // Present the screen graphics.SwapBuffers (); } } }
//--------------------------------------------------------------------- // <copyright file="ODataAsynchronousResponseMessage.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- namespace Microsoft.OData.Core { #region Namespaces using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; #if ODATALIB_ASYNC using System.Threading.Tasks; #endif #endregion Namespaces /// <summary> /// Representing the message of a non-batch async response. /// </summary> public sealed class ODataAsynchronousResponseMessage : #if ODATALIB_ASYNC IODataResponseMessageAsync #else IODataResponseMessage #endif { /// <summary>True if we are wrting the response; false if we are reading it.</summary> private readonly bool writing; /// <summary>The stream of the response message.</summary> private readonly Stream stream; /// <summary>The action to write envelope for the inner message before returning the stream.</summary> private readonly Action<ODataAsynchronousResponseMessage> writeEnvelope; /// <summary>Prevent the envelope for the inner message from being written more than one time.</summary> private bool envelopeWritten; /// <summary>The result status code of the response message.</summary> private int statusCode; /// <summary>The set of headers of the response message.</summary> private IDictionary<string, string> headers; /// <summary> /// Constructor. /// </summary> /// <param name="stream">The stream underlying the response message.</param> /// <param name="statusCode">The status code to use for the async response message.</param> /// <param name="headers">The headers to use for the async response message.</param> /// <param name="writeEnvelope">The action to write envelope for the inner message before returning the stream.</param> /// <param name="writing">true if the response message is being written; false when it is read.</param> private ODataAsynchronousResponseMessage( Stream stream, int statusCode, IDictionary<string, string> headers, Action<ODataAsynchronousResponseMessage> writeEnvelope, bool writing) { Debug.Assert(stream != null, "stream != null"); this.stream = stream; this.statusCode = statusCode; this.headers = headers; this.writeEnvelope = writeEnvelope; this.writing = writing; } /// <summary>Gets or sets the result status code of the response message.</summary> /// <returns>The result status code of the response message.</returns> public int StatusCode { get { return this.statusCode; } set { this.VerifyCanSetHeaderAndStatusCode(); this.statusCode = value; } } /// <summary>Gets an enumerable over all the headers for this message.</summary> /// <returns>An enumerable over all the headers for this message.</returns> public IEnumerable<KeyValuePair<string, string>> Headers { get { return this.headers; } } /// <summary>Returns a value of an HTTP header of this operation.</summary> /// <returns>The value of the HTTP header, or null if no such header was present on the message.</returns> /// <param name="headerName">The name of the header to get.</param> public string GetHeader(string headerName) { if (this.headers != null) { string headerValue; if (this.headers.TryGetValue(headerName, out headerValue)) { return headerValue; } } return null; } /// <summary>Sets the value of an HTTP header of this operation.</summary> /// <param name="headerName">The name of the header to set.</param> /// <param name="headerValue">The value of the HTTP header or null if the header should be removed.</param> public void SetHeader(string headerName, string headerValue) { this.VerifyCanSetHeaderAndStatusCode(); if (headerValue == null) { if (this.headers != null) { this.headers.Remove(headerName); } } else { if (this.headers == null) { this.headers = new Dictionary<string, string>(StringComparer.Ordinal); } this.headers[headerName] = headerValue; } } /// <summary>Gets the stream backing for this message.</summary> /// <returns>The stream backing for this message.</returns> public Stream GetStream() { // If writing response, the envelope for the inner message should be written once and only once before returning the stream. if (this.writing && !this.envelopeWritten) { if (this.writeEnvelope != null) { this.writeEnvelope(this); } this.envelopeWritten = true; } return this.stream; } #if ODATALIB_ASYNC /// <summary>Asynchronously get the stream backing for this message.</summary> /// <returns>The stream backing for this message.</returns> public Task<Stream> GetStreamAsync() { return Task<Stream>.Factory.StartNew(this.GetStream); } #endif /// <summary> /// Creates an async response message that can be used to write the response content to. /// </summary> /// <param name="outputStream">The output stream underlying the response message.</param> /// <param name="writeEnvelope">The action to write envelope for the inner message before returning the stream.</param> /// <returns>An <see cref="ODataAsynchronousResponseMessage"/> that can be used to write the response content.</returns> internal static ODataAsynchronousResponseMessage CreateMessageForWriting(Stream outputStream, Action<ODataAsynchronousResponseMessage> writeEnvelope) { return new ODataAsynchronousResponseMessage(outputStream, /*statusCode*/0, /*headers*/null, writeEnvelope, /*writing*/true); } /// <summary> /// Creates an async response message that can be used to read the response content from. /// </summary> /// <param name="stream">The input stream underlying the response message.</param> /// <param name="statusCode">The status code to use for the async response message.</param> /// <param name="headers">The headers to use for the async response message.</param> /// <returns>An <see cref="ODataAsynchronousResponseMessage"/> that can be used to read the response content.</returns> internal static ODataAsynchronousResponseMessage CreateMessageForReading(Stream stream, int statusCode, IDictionary<string, string> headers) { return new ODataAsynchronousResponseMessage(stream, statusCode, headers, /*writeEnvelope*/null, /*writing*/false); } /// <summary> /// Verifies that setting a header or the status code is allowed /// </summary> /// <remarks> /// We allow modifying the headers and the status code only if we are writing the message. /// </remarks> private void VerifyCanSetHeaderAndStatusCode() { if (!this.writing) { throw new ODataException(Strings.ODataAsyncResponseMessage_MustNotModifyMessage); } } } }
using UnityEngine; using System.Collections; public class Shooting : MonoBehaviour { // Transforms to manipulate objects. public Transform sphere; // Sphere. private Transform clone; // Clone of sphere. public Transform targetSphere; // Target spheres. public Transform wallLeft; // Left wall of level. public Transform wallRight; // Right wall of level. public Transform wallTop; // Top wall of level. public Transform wallDown; // Down wall of level. public Transform capsule; public Transform cameraMain; public Transform cameraWide; public float movespeed = 1; // Move speed of gun. public int shotPowerStart = 10; // How much power the shot starts with. public int shotPower = 10; // Force used to shoot Sphere. public int shotPowerPlus = 1; // How fast shot power increaces. public int shotPowerLimit = 100; // Max shot power. public int frames = 0; // Count for each Update() frame ran. private Vector3 gunRotation; // Gun rotation towards mouse. public int spheres = 0; // Count for Sphere clones. public int maxSpheres = 5; public int targetSpheres = 0; public float targetOrigin = 0; public int scrollLimit = 2; public int scrolled = 0; // Interface public string GUIPower; // Displays shot power. public string GUITime; // //Displays frames played so far. // Mouse Position Ray ray; RaycastHit hit; // Graphical User Interface void OnGUI() { // Box displaying shot power at top left of screen. GUI.Box(new Rect(0,0,100,50), GUIPower); //Box displaying total frames and time at top right of screen. GUI.Box(new Rect (Screen.width - 100,0,100,50), GUITime); } string hitChecker = "Nothing"; void Update () { // Set ray to mouse position. if(cameraMain.camera.enabled == true) ray = Camera.main.ScreenPointToRay(Input.mousePosition); else ray = cameraWide.camera.ScreenPointToRay(Input.mousePosition); // Hitting target. if(targetOrigin != 0 && targetSphere) { if(hitChecker == "Nothing") if(targetSphere.transform.position.x == targetOrigin) { Debug.Log("Not hit"); hitChecker = "Not Hit"; } if(hitChecker == "Nothing" || hitChecker == "Not Hit") if(targetSphere.transform.position.x != targetOrigin) { Debug.Log("Hit"); Destroy(targetSphere.gameObject,2f); hitChecker = "Hit"; } } // Controls // Movement for gun. // Press W to go up. if(Input.GetKey("w")) rigidbody.MovePosition(new Vector3(rigidbody.position.x ,rigidbody.position.y+movespeed/5 ,rigidbody.position.z)); // Press A to go Left. if(Input.GetKey("a")) rigidbody.MovePosition(new Vector3(rigidbody.position.x-movespeed/5 ,rigidbody.position.y ,rigidbody.position.z)); // Press S to go Down. if(Input.GetKey("s")) rigidbody.MovePosition(new Vector3(rigidbody.position.x ,rigidbody.position.y-movespeed/5 ,rigidbody.position.z)); // Press D to go Right. if(Input.GetKey("d")) rigidbody.MovePosition(new Vector3(rigidbody.position.x+movespeed/5 ,rigidbody.position.y ,rigidbody.position.z)); // Limit Spheres created. if(spheres < maxSpheres){ // Increase shot power. // Check if left mouse button if pressed. if(Input.GetKey(KeyCode.Mouse0)){ // Check if shot power is under limit. if(shotPower<shotPowerLimit) // Increase shot power. shotPower += shotPowerPlus; // Display shot power GUIPower = "Power: " + shotPower; } // Launch Sphere clone. // Check if left mouse button is released. if(Input.GetKeyUp(KeyCode.Mouse0)){ // Set Clone instance of a Sphere and position at gun. clone = Instantiate(sphere ,transform.position ,transform.rotation) as Transform; // Push clone by shot power towards mouse location. clone.rigidbody.AddRelativeForce(0 ,0 ,shotPower*20); // Reset shot power. shotPower = shotPowerStart; } } float scrollWheel = Input.GetAxis("Mouse ScrollWheel"); if(scrolled < scrollLimit){ // Mouse scroll forwards. if(scrollWheel > 0){ // Move camera forward. cameraMain.Translate(Vector3.forward*5); scrolled++; } } if(scrolled > ~scrollLimit){ // ~ means reverse. // Mouse scroll backwards. if(scrollWheel < 0){ // Move camera back. cameraMain.Translate(Vector3.back*5); scrolled--; } } // Change timescale of game. // Press Q to increase timescale. if(Input.GetKeyDown(KeyCode.Q)) Time.timeScale++; // Press E to decrease timescale. if(Input.GetKeyDown(KeyCode.E)) Time.timeScale--; // Press R to reset timescale. if(Input.GetKeyDown(KeyCode.R)) Time.timeScale = 1; // Restricting movement. // Restrict movement of gun. if(transform.position.x > wallRight.position.x){ rigidbody.MovePosition(new Vector3(wallLeft.position.x ,rigidbody.position.y ,rigidbody.position.z)); } if(transform.position.x < wallLeft.position.x){ rigidbody.MovePosition(new Vector3(wallRight.position.x ,rigidbody.position.y ,rigidbody.position.z)); } if(transform.position.y < wallDown .position.y){ rigidbody.MovePosition(new Vector3(rigidbody.position.x ,wallTop.position.y ,rigidbody.position.z)); } if(transform.position.y > wallTop.position.y){ rigidbody.MovePosition(new Vector3(rigidbody.position.x ,wallDown.position.y ,rigidbody.position.z)); } string clonePosition = ""; // Restricting clone of Sphere movement. if(clone){ if(clone.position.x > wallRight.position.x || clone.position.x < wallLeft.position.x || clone.position.y < wallDown .position.y || clone.position.y > wallTop.position.y){ clonePosition = "Outside"; } else if(clone.position.x < wallRight.position.x || clone.position.x > wallLeft.position.x || clone.position.y > wallDown .position.y || clone.position.y < wallTop.position.y){ clonePosition = "Inside"; } } if(clonePosition == "Outside"){ // When clone is created and is outside the walls, destroy clone. Destroy(clone.gameObject); } if(clonePosition == "Inside"){ // When clone is created and inside the walls, destroy clone in 10 seconds. Destroy(clone.gameObject, 5f); } // Change cameras // Press C to invert to other camera. if(Input.GetKeyDown(KeyCode.C)) { cameraMain.camera.enabled = !cameraMain.camera.enabled; cameraWide.camera.enabled = !cameraWide.camera.enabled; } // Every frame maintinance. // Check if raycast has been set, then draw line on Scene Screen. if (Physics.Raycast(ray, out hit, 100)) Debug.DrawLine(transform.position, hit.point); // Draw line from gun to mouse location. capsule.rigidbody.MovePosition(hit.point); // Set casule at mouse position. Vector3 cameraPosition = new Vector3(transform.position.x-cameraMain.transform.position.x ,transform.position.y-cameraMain.transform.position.y ,0); cameraMain.Translate(cameraPosition); // Position camera above Gun. // Rotation of gun towards mouse position. gunRotation = new Vector3(hit.point.x,hit.point.y,0); transform.LookAt(gunRotation); if(targetSphere)targetOrigin = targetSphere.transform.position.x; capsule.Rotate(new Vector3(0,0,10)); spheres = GameObject.FindGameObjectsWithTag("Respawn").Length; // Number of spheres in game. targetSpheres = GameObject.FindGameObjectsWithTag("Finish").Length; // Number of target spheres in game. GUIPower = "Power: " + shotPower + "\n Spheres: " + spheres + "\n Targets: " + targetSpheres; // Display shot power, spheres and target spheres. GUITime = "Time: " + (int)Time.time + "\n TimeScale: " + Time.timeScale + "\n Frames: " + frames; // //Display frames run. frames++; // Add to frames run. // Game Over. if(GameObject.FindGameObjectsWithTag("Finish").Length == 0){ Debug.Log("Game Over."); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using SampleMetadata; using Xunit; namespace System.Reflection.Tests { public static partial class PropertyTests { [Fact] public static void TestProperties_GetterSetter() { Type t = typeof(DerivedFromPropertyHolder1<>).Project(); Type bt = t.BaseType; { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.ReadOnlyProp)); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.ReadOnlyProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); Assert.True(p.CanRead); Assert.False(p.CanWrite); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.ReadOnlyProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); Assert.Null(p.SetMethod); Assert.Null(p.GetSetMethod(nonPublic: true)); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(int).Project(), p.PropertyType); } { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.ReadWriteProp)); Type theT = t.GetGenericTypeParameters()[0]; Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.ReadWriteProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.ReadWriteProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); MethodInfo setter = p.SetMethod; Assert.Equal("set_" + nameof(PropertyHolder1<int>.ReadWriteProp), setter.Name); Assert.Equal(bt, setter.DeclaringType); Assert.Equal(t, setter.ReflectedType); MethodInfo[] accessors = p.GetAccessors(nonPublic: false); Assert.Equal<MethodInfo>(new MethodInfo[] { getter, setter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(theT, p.PropertyType); } { PropertyInfo p = bt.GetProperty(nameof(DerivedFromPropertyHolder1<int>.PublicPrivateProp)); Type theT = t.GetGenericTypeDefinition().GetGenericTypeParameters()[0]; Assert.True(p.CanRead); Assert.True(p.CanWrite); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.PublicPrivateProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(bt, p.ReflectedType); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.PublicPrivateProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(bt, getter.ReflectedType); MethodInfo setter = p.SetMethod; Assert.Equal("set_" + nameof(PropertyHolder1<int>.PublicPrivateProp), setter.Name); Assert.Equal(bt, setter.DeclaringType); Assert.Equal(bt, setter.ReflectedType); Assert.Equal(setter, p.GetSetMethod(nonPublic: true)); Assert.Null(p.GetSetMethod(nonPublic: false)); MethodInfo[] accessors = p.GetAccessors(nonPublic: true); Assert.Equal<MethodInfo>(new MethodInfo[] { getter, setter }, accessors); accessors = p.GetAccessors(nonPublic: false); Assert.Equal<MethodInfo>(new MethodInfo[] { getter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(GenericClass1<>).Project().MakeGenericType(theT), p.PropertyType); } { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.PublicPrivateProp)); Type theT = t.GetGenericTypeDefinition().GetGenericTypeParameters()[0]; Assert.True(p.CanRead); Assert.False(p.CanWrite); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.PublicPrivateProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.PublicPrivateProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); Assert.Null(p.GetSetMethod(nonPublic: true)); Assert.Null(p.GetSetMethod(nonPublic: false)); MethodInfo[] accessors = p.GetAccessors(nonPublic: true); Assert.Equal<MethodInfo>(new MethodInfo[] { getter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(GenericClass1<>).Project().MakeGenericType(theT), p.PropertyType); } { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.PublicInternalProp)); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.PublicInternalProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); Assert.True(p.CanRead); Assert.True(p.CanWrite); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.PublicInternalProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); MethodInfo setter = p.SetMethod; Assert.Equal("set_" + nameof(PropertyHolder1<int>.PublicInternalProp), setter.Name); Assert.Equal(bt, setter.DeclaringType); Assert.Equal(t, setter.ReflectedType); Assert.Equal(setter, p.GetSetMethod(nonPublic: true)); Assert.Null(p.GetSetMethod(nonPublic: false)); MethodInfo[] accessors = p.GetAccessors(nonPublic: true); Assert.Equal<MethodInfo>(new MethodInfo[] { getter, setter }, accessors); accessors = p.GetAccessors(nonPublic: false); Assert.Equal<MethodInfo>(new MethodInfo[] { getter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(int).Project(), p.PropertyType); } { PropertyInfo p = t.GetProperty(nameof(DerivedFromPropertyHolder1<int>.PublicProtectedProp)); Assert.Equal(nameof(DerivedFromPropertyHolder1<int>.PublicProtectedProp), p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); Assert.True(p.CanRead); Assert.True(p.CanWrite); MethodInfo getter = p.GetMethod; Assert.Equal("get_" + nameof(PropertyHolder1<int>.PublicProtectedProp), getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); MethodInfo setter = p.SetMethod; Assert.Equal("set_" + nameof(PropertyHolder1<int>.PublicProtectedProp), setter.Name); Assert.Equal(bt, setter.DeclaringType); Assert.Equal(t, setter.ReflectedType); Assert.Equal(setter, p.GetSetMethod(nonPublic: true)); Assert.Null(p.GetSetMethod(nonPublic: false)); MethodInfo[] accessors = p.GetAccessors(nonPublic: true); Assert.Equal<MethodInfo>(new MethodInfo[] { getter, setter }, accessors); accessors = p.GetAccessors(nonPublic: false); Assert.Equal<MethodInfo>(new MethodInfo[] { getter }, accessors); Assert.Equal(0, p.GetIndexParameters().Length); Assert.Equal(typeof(int).Project(), p.PropertyType); } { PropertyInfo p = t.GetProperty("Item"); Type theT = t.GetGenericTypeDefinition().GetGenericTypeParameters()[0]; Assert.Equal("Item", p.Name); Assert.Equal(bt, p.DeclaringType); Assert.Equal(t, p.ReflectedType); MethodInfo getter = p.GetMethod; Assert.Equal("get_Item", getter.Name); Assert.Equal(bt, getter.DeclaringType); Assert.Equal(t, getter.ReflectedType); ParameterInfo[] pis = p.GetIndexParameters(); Assert.Equal(2, pis.Length); for (int i = 0; i < pis.Length; i++) { ParameterInfo pi = pis[i]; Assert.Equal(i, pi.Position); Assert.Equal(p, pi.Member); } Assert.Equal("i", pis[0].Name); Assert.Equal(typeof(int).Project(), pis[0].ParameterType); Assert.Equal("t", pis[1].Name); Assert.Equal(theT, pis[1].ParameterType); } } [Fact] public static unsafe void TestCustomModifiers1() { using (MetadataLoadContext lc = new MetadataLoadContext(new CoreMetadataAssemblyResolver(), "mscorlib")) { Assembly a = lc.LoadFromByteArray(TestData.s_CustomModifiersImage); Type t = a.GetType("N", throwOnError: true); Type reqA = a.GetType("ReqA", throwOnError: true); Type reqB = a.GetType("ReqB", throwOnError: true); Type reqC = a.GetType("ReqC", throwOnError: true); Type optA = a.GetType("OptA", throwOnError: true); Type optB = a.GetType("OptB", throwOnError: true); Type optC = a.GetType("OptC", throwOnError: true); PropertyInfo p = t.GetProperty("MyProperty"); Type[] req = p.GetRequiredCustomModifiers(); Type[] opt = p.GetOptionalCustomModifiers(); Assert.Equal<Type>(new Type[] { reqA, reqB, reqC }, req); Assert.Equal<Type>(new Type[] { optA, optB, optC }, opt); TestUtils.AssertNewObjectReturnedEachTime(() => p.GetRequiredCustomModifiers()); TestUtils.AssertNewObjectReturnedEachTime(() => p.GetOptionalCustomModifiers()); } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System.IO; using DiscUtils; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vdi; using Xunit; namespace LibraryTests.Partitions { public class GuidPartitionTableTest { [Fact] public void Initialize() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 3 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); Assert.Equal(0, table.Count); } } [Fact] public void CreateSmallWholeDisk() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 3 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.Create(WellKnownPartitionType.WindowsFat, true); // Make sure the partition fills from first to last usable. Assert.Equal(table.FirstUsableSector, table[idx].FirstSector); Assert.Equal(table.LastUsableSector, table[idx].LastSector); } } [Fact] public void CreateMediumWholeDisk() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 2 * 1024L * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.Create(WellKnownPartitionType.WindowsFat, true); Assert.Equal(2, table.Partitions.Count); Assert.Equal(GuidPartitionTypes.MicrosoftReserved, table[0].GuidType); Assert.Equal(32 * 1024 * 1024, table[0].SectorCount * 512); // Make sure the partition fills from first to last usable, allowing for MicrosoftReserved sector. Assert.Equal(table[0].LastSector + 1, table[idx].FirstSector); Assert.Equal(table.LastUsableSector, table[idx].LastSector); } } [Fact] public void CreateLargeWholeDisk() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 200 * 1024L * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.Create(WellKnownPartitionType.WindowsFat, true); Assert.Equal(2, table.Partitions.Count); Assert.Equal(GuidPartitionTypes.MicrosoftReserved, table[0].GuidType); Assert.Equal(128 * 1024 * 1024, table[0].SectorCount * 512); // Make sure the partition fills from first to last usable, allowing for MicrosoftReserved sector. Assert.Equal(table[0].LastSector + 1, table[idx].FirstSector); Assert.Equal(table.LastUsableSector, table[idx].LastSector); } } [Fact] public void CreateAlignedWholeDisk() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 200 * 1024L * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.CreateAligned(WellKnownPartitionType.WindowsFat, true, 1024 * 1024); Assert.Equal(2, table.Partitions.Count); Assert.Equal(GuidPartitionTypes.MicrosoftReserved, table[0].GuidType); Assert.Equal(128 * 1024 * 1024, table[0].SectorCount * 512); // Make sure the partition is aligned Assert.Equal(0, table[idx].FirstSector % 2048); Assert.Equal(0, (table[idx].LastSector + 1) % 2048); // Ensure partition fills most of the disk Assert.True((table[idx].SectorCount * 512) > disk.Capacity * 0.9); } } [Fact] public void CreateBySize() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 3 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); int idx = table.Create(2 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); // Make sure the partition is within 10% of the size requested. Assert.True((2 * 1024 * 2) * 0.9 < table[idx].SectorCount); Assert.Equal(table.FirstUsableSector, table[idx].FirstSector); } } [Fact] public void CreateBySizeInGap() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 300 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); table.Create(10 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); table.Create((20 * 1024 * 1024) / 512, ((30 * 1024 * 1024) / 512) - 1, GuidPartitionTypes.WindowsBasicData, 0, "Data Partition"); table.Create((60 * 1024 * 1024) / 512, ((70 * 1024 * 1024) / 512) - 1, GuidPartitionTypes.WindowsBasicData, 0, "Data Partition"); int idx = table.Create(20 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); Assert.Equal(((30 * 1024 * 1024) / 512), table[idx].FirstSector); Assert.Equal(((50 * 1024 * 1024) / 512) - 1, table[idx].LastSector); } } [Fact] public void CreateBySizeInGapAligned() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 300 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); table.Create(10 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); // Note: end is unaligned table.Create((20 * 1024 * 1024) / 512, ((30 * 1024 * 1024) / 512) - 5, GuidPartitionTypes.WindowsBasicData, 0, "Data Partition"); table.Create((60 * 1024 * 1024) / 512, ((70 * 1024 * 1024) / 512) - 1, GuidPartitionTypes.WindowsBasicData, 0, "Data Partition"); int idx = table.CreateAligned(20 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false, 64 * 1024); Assert.Equal(((30 * 1024 * 1024) / 512), table[idx].FirstSector); Assert.Equal(((50 * 1024 * 1024) / 512) - 1, table[idx].LastSector); } } [Fact] public void Delete() { MemoryStream ms = new MemoryStream(); using (Disk disk = Disk.InitializeDynamic(ms, Ownership.Dispose, 10 * 1024 * 1024)) { GuidPartitionTable table = GuidPartitionTable.Initialize(disk); Assert.Equal(0, table.Create(1 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); Assert.Equal(1, table.Create(2 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); Assert.Equal(2, table.Create(3 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); long[] sectorCount = new long[] { table[0].SectorCount, table[1].SectorCount, table[2].SectorCount }; table.Delete(1); Assert.Equal(2, table.Count); Assert.Equal(sectorCount[2], table[1].SectorCount); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Numerics.Tests { public class DivideTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void RunDivideTwoLargeBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - Two Large BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [Fact] public static void RunDivideTwoSmallBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - Two Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [Fact] public static void RunDivideOneLargeOneSmallBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); } } [Fact] public static void RunDivideOneLargeOneZeroBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One large BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = new byte[] { 0 }; VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); Assert.Throws<DivideByZeroException>(() => { VerifyDivideString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivide"); }); } } [Fact] public static void RunDivideOneSmallOneZeroBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Divide Method - One small BigIntegers and zero for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = new byte[] { 0 }; VerifyDivideString(Print(tempByteArray1) + Print(tempByteArray2) + "bDivide"); Assert.Throws<DivideByZeroException>(() => { VerifyDivideString(Print(tempByteArray2) + Print(tempByteArray1) + "bDivide"); }); } } [Fact] public static void RunDivideOneOverOne() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: X/1 = X VerifyIdentityString(BigInteger.One + " " + Int32.MaxValue + " bDivide", Int32.MaxValue.ToString()); VerifyIdentityString(BigInteger.One + " " + Int64.MaxValue + " bDivide", Int64.MaxValue.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(BigInteger.One + " " + randBigInt + "bDivide", randBigInt.Substring(0, randBigInt.Length - 1)); } } [Fact] public static void RunDivideZeroOverBI() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Axiom: 0/X = 0 VerifyIdentityString(Int32.MaxValue + " " + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); VerifyIdentityString(Int64.MaxValue + " " + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); for (int i = 0; i < s_samples; i++) { String randBigInt = Print(GetRandomByteArray(s_random)); VerifyIdentityString(randBigInt + BigInteger.Zero + " bDivide", BigInteger.Zero.ToString()); } } [Fact] public static void RunDivideBoundary() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyDivideString(Math.Pow(2, 32) + " 2 bDivide"); // 32 bit boundary n1=0 n2=1 VerifyDivideString(Math.Pow(2, 33) + " 2 bDivide"); } [Fact] public static void RunOverflow() { // these values lead to an "overflow", if dividing digit by digit // we need to ensure that this case is being handled accordingly... var x = new BigInteger(new byte[] { 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); var y = new BigInteger(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); var z = new BigInteger(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0 }); Assert.Equal(z, BigInteger.Divide(x, y)); } private static void VerifyDivideString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetNonZeroRandomByteArray(random, size); } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using static System.Math; using Qwack.Math; using Qwack.Transport.BasicTypes; namespace Qwack.Math.Interpolation { public class LinearInterpolatorFlatExtrap : IInterpolator1D, IIntegrableInterpolator { public Interpolator1DType Type => Interpolator1DType.LinearFlatExtrap; private readonly double[] _x; private readonly double[] _y; private double[] _slope; private double _minX; private double _maxX; public double MinX => _minX; public double MaxX => _maxX; public double[] Xs => _x; public double[] Ys => _y; public LinearInterpolatorFlatExtrap(double[] x, double[] y) { _x = x; _y = y; _minX = _x[0]; _maxX = _x[x.Length - 1]; CalculateSlope(); } public LinearInterpolatorFlatExtrap() { } private LinearInterpolatorFlatExtrap(double[] x, double[] y, double[] slope) { _x = x; _y = y; _slope = slope; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private int FindFloorPoint(double t) { var index = Array.BinarySearch(_x, t); if (index < 0) { index = ~index - 1; } return Min(Max(index, 0), _x.Length - 2); } private void CalculateSlope() { _slope = new double[_x.Length - 1]; for (var i = 0; i < _slope.Length; i++) { _slope[i] = (_y[i + 1] - _y[i]) / (_x[i + 1] - _x[i]); } } public IInterpolator1D Bump(int pillar, double delta, bool updateInPlace = false) { var newY = _y[pillar] + delta; return UpdateY(pillar, newY, updateInPlace); } public double FirstDerivative(double t) { if (t < _minX || t > _maxX) { return 0; } else { var k = FindFloorPoint(t); return _slope[k]; } } public double Interpolate(double t) { if (t < _minX) { return _y[0]; } else if (t > _maxX) { return _y[_y.Length - 1]; } else { var k = FindFloorPoint(t); return _y[k] + (t - _x[k]) * _slope[k]; } } public double SecondDerivative(double x) { if (!_x.Contains(x)) return 0; var k = FindFloorPoint(x); if (k == 0) return 0.5 * _slope[0]; if(k==_x.Length) return 0.5 * _slope[_slope.Length]; return (_slope[k] + _slope[k - 1]) / 2.0; } public double DefiniteIntegral(double a, double b) { if (b < a) throw new Exception("b must be strictly greater than a"); if (b == a) return 0; var iSum = 0.0; if(a<_minX) //flat extrap on the left { iSum += (_minX - a) * _minX; a = _minX; } if (b > _maxX) //flat extrap on the right { iSum += (b - _maxX) * _maxX; b = _maxX; } var ka = FindFloorPoint(a); var kb = FindFloorPoint(b); double vA, vU; while(kb>ka) { var u = _x[ka + 1]; //upper bound of segment vA = Interpolate(a); vU = Interpolate(u); iSum += 0.5 * (vU + vA) * (u - a); a = u; ka++; } vA = Interpolate(a); vU = Interpolate(b); iSum += 0.5 * (vU + vA) * (b - a); return iSum; } public IInterpolator1D UpdateY(int pillar, double newValue, bool updateInPlace = false) { if (updateInPlace) { _y[pillar] = newValue; if (pillar < _slope.Length) { _slope[pillar] = (_y[pillar + 1] - _y[pillar]) / (_x[pillar + 1] - _x[pillar]); } if (pillar > 0) { pillar -= 1; _slope[pillar] = (_y[pillar + 1] - _y[pillar]) / (_x[pillar + 1] - _x[pillar]); } _minX = _x[0]; _maxX = _x[_x.Length - 1]; return this; } else { var newY = new double[_y.Length]; Buffer.BlockCopy(_y, 0, newY, 0, _y.Length * 8); var newSlope = new double[_slope.Length]; Buffer.BlockCopy(_slope, 0, newSlope, 0, _slope.Length * 8); var returnValue = new LinearInterpolatorFlatExtrap(_x, newY, newSlope).Bump(pillar, newValue - _y[pillar], true); return returnValue; } } public double[] Sensitivity(double t) { var o = new double[_y.Length]; if (t <= _minX) { o[0] = 1; } else if (t >= _maxX) { o[o.Length - 1] = 1; } else { var k = FindFloorPoint(t); var prop = (t - _x[k]) / (_x[k + 1] - _x[k]); o[k + 1] = prop; o[k] = (1.0 - prop); } return o; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System; using System.Xml; using System.Diagnostics; using System.Text; /// <summary> /// This enum specifies what format should be used when converting string to XsdDateTime /// </summary> [Flags] internal enum XsdDateTimeFlags { DateTime = 0x01, Time = 0x02, Date = 0x04, GYearMonth = 0x08, GYear = 0x10, GMonthDay = 0x20, GDay = 0x40, GMonth = 0x80, #if !SILVERLIGHT // XDR is not supported in Silverlight XdrDateTimeNoTz = 0x100, XdrDateTime = 0x200, XdrTimeNoTz = 0x400, //XDRTime with tz is the same as xsd:time #endif AllXsd = 0xFF //All still does not include the XDR formats } /// <summary> /// This structure extends System.DateTime to support timeInTicks zone and Gregorian types components of an Xsd Duration. It is used internally to support Xsd durations without loss /// of fidelity. XsdDuration structures are immutable once they've been created. /// </summary> internal struct XsdDateTime { // DateTime is being used as an internal representation only // Casting XsdDateTime to DateTime might return a different value private DateTime _dt; // Additional information that DateTime is not preserving // Information is stored in the following format: // Bits Info // 31-24 DateTimeTypeCode // 23-16 XsdDateTimeKind // 15-8 Zone Hours // 7-0 Zone Minutes private uint _extra; // Subset of XML Schema types XsdDateTime represents private enum DateTimeTypeCode { DateTime, Time, Date, GYearMonth, GYear, GMonthDay, GDay, GMonth, #if !SILVERLIGHT // XDR is not supported in Silverlight XdrDateTime, #endif } // Internal representation of DateTimeKind private enum XsdDateTimeKind { Unspecified, Zulu, LocalWestOfZulu, // GMT-1..14, N..Y LocalEastOfZulu // GMT+1..14, A..M } // Masks and shifts used for packing and unpacking extra private const uint TypeMask = 0xFF000000; private const uint KindMask = 0x00FF0000; private const uint ZoneHourMask = 0x0000FF00; private const uint ZoneMinuteMask = 0x000000FF; private const int TypeShift = 24; private const int KindShift = 16; private const int ZoneHourShift = 8; // Maximum number of fraction digits; private const short maxFractionDigits = 7; private static readonly int s_lzyyyy = "yyyy".Length; private static readonly int s_lzyyyy_ = "yyyy-".Length; private static readonly int s_lzyyyy_MM = "yyyy-MM".Length; private static readonly int s_lzyyyy_MM_ = "yyyy-MM-".Length; private static readonly int s_lzyyyy_MM_dd = "yyyy-MM-dd".Length; private static readonly int s_lzyyyy_MM_ddT = "yyyy-MM-ddT".Length; private static readonly int s_lzHH = "HH".Length; private static readonly int s_lzHH_ = "HH:".Length; private static readonly int s_lzHH_mm = "HH:mm".Length; private static readonly int s_lzHH_mm_ = "HH:mm:".Length; private static readonly int s_lzHH_mm_ss = "HH:mm:ss".Length; private static readonly int s_Lz_ = "-".Length; private static readonly int s_lz_zz = "-zz".Length; private static readonly int s_lz_zz_ = "-zz:".Length; private static readonly int s_lz_zz_zz = "-zz:zz".Length; private static readonly int s_Lz__ = "--".Length; private static readonly int s_lz__mm = "--MM".Length; private static readonly int s_lz__mm_ = "--MM-".Length; private static readonly int s_lz__mm__ = "--MM--".Length; private static readonly int s_lz__mm_dd = "--MM-dd".Length; private static readonly int s_Lz___ = "---".Length; private static readonly int s_lz___dd = "---dd".Length; #if !SILVERLIGHT /// <summary> /// Constructs an XsdDateTime from a string trying all possible formats. /// </summary> public XsdDateTime(string text) : this(text, XsdDateTimeFlags.AllXsd) { } #endif /// <summary> /// Constructs an XsdDateTime from a string using specific format. /// </summary> public XsdDateTime(string text, XsdDateTimeFlags kinds) : this() { Parser parser = new Parser(); if (!parser.Parse(text, kinds)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, text, kinds)); } InitiateXsdDateTime(parser); } #if !SILVERLIGHT private XsdDateTime(Parser parser) : this() { InitiateXsdDateTime(parser); } #endif private void InitiateXsdDateTime(Parser parser) { _dt = new DateTime(parser.year, parser.month, parser.day, parser.hour, parser.minute, parser.second); if (parser.fraction != 0) { _dt = _dt.AddTicks(parser.fraction); } _extra = (uint)(((int)parser.typeCode << TypeShift) | ((int)parser.kind << KindShift) | (parser.zoneHour << ZoneHourShift) | parser.zoneMinute); } #if !SILVERLIGHT internal static bool TryParse(string text, XsdDateTimeFlags kinds, out XsdDateTime result) { Parser parser = new Parser(); if (!parser.Parse(text, kinds)) { result = new XsdDateTime(); return false; } result = new XsdDateTime(parser); return true; } #endif /// <summary> /// Constructs an XsdDateTime from a DateTime. /// </summary> public XsdDateTime(DateTime dateTime, XsdDateTimeFlags kinds) { Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set."); _dt = dateTime; DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1); int zoneHour = 0; int zoneMinute = 0; XsdDateTimeKind kind; switch (dateTime.Kind) { case DateTimeKind.Unspecified: kind = XsdDateTimeKind.Unspecified; break; case DateTimeKind.Utc: kind = XsdDateTimeKind.Zulu; break; default: { Debug.Assert(dateTime.Kind == DateTimeKind.Local, "Unknown DateTimeKind: " + dateTime.Kind); TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(dateTime); if (utcOffset.Ticks < 0) { kind = XsdDateTimeKind.LocalWestOfZulu; zoneHour = -utcOffset.Hours; zoneMinute = -utcOffset.Minutes; } else { kind = XsdDateTimeKind.LocalEastOfZulu; zoneHour = utcOffset.Hours; zoneMinute = utcOffset.Minutes; } break; } } _extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneHour << ZoneHourShift) | zoneMinute); } // Constructs an XsdDateTime from a DateTimeOffset public XsdDateTime(DateTimeOffset dateTimeOffset) : this(dateTimeOffset, XsdDateTimeFlags.DateTime) { } public XsdDateTime(DateTimeOffset dateTimeOffset, XsdDateTimeFlags kinds) { Debug.Assert(Bits.ExactlyOne((uint)kinds), "Only one DateTime type code can be set."); _dt = dateTimeOffset.DateTime; TimeSpan zoneOffset = dateTimeOffset.Offset; DateTimeTypeCode code = (DateTimeTypeCode)(Bits.LeastPosition((uint)kinds) - 1); XsdDateTimeKind kind; if (zoneOffset.TotalMinutes < 0) { zoneOffset = zoneOffset.Negate(); kind = XsdDateTimeKind.LocalWestOfZulu; } else if (zoneOffset.TotalMinutes > 0) { kind = XsdDateTimeKind.LocalEastOfZulu; } else { kind = XsdDateTimeKind.Zulu; } _extra = (uint)(((int)code << TypeShift) | ((int)kind << KindShift) | (zoneOffset.Hours << ZoneHourShift) | zoneOffset.Minutes); } /// <summary> /// Returns auxiliary enumeration of XSD date type /// </summary> private DateTimeTypeCode InternalTypeCode { get { return (DateTimeTypeCode)((_extra & TypeMask) >> TypeShift); } } /// <summary> /// Returns geographical "position" of the value /// </summary> private XsdDateTimeKind InternalKind { get { return (XsdDateTimeKind)((_extra & KindMask) >> KindShift); } } #if !SILVERLIGHT /// <summary> /// Returns XmlTypeCode of the value being stored /// </summary> public XmlTypeCode TypeCode { get { return s_typeCodes[(int)InternalTypeCode]; } } /// <summary> /// Returns whether object represent local, UTC or unspecified time /// </summary> public DateTimeKind Kind { get { switch (InternalKind) { case XsdDateTimeKind.Unspecified: return DateTimeKind.Unspecified; case XsdDateTimeKind.Zulu: return DateTimeKind.Utc; default: // XsdDateTimeKind.LocalEastOfZulu: // XsdDateTimeKind.LocalWestOfZulu: return DateTimeKind.Local; } } } #endif /// <summary> /// Returns the year part of XsdDateTime /// The returned value is integer between 1 and 9999 /// </summary> public int Year { get { return _dt.Year; } } /// <summary> /// Returns the month part of XsdDateTime /// The returned value is integer between 1 and 12 /// </summary> public int Month { get { return _dt.Month; } } /// <summary> /// Returns the day of the month part of XsdDateTime /// The returned value is integer between 1 and 31 /// </summary> public int Day { get { return _dt.Day; } } /// <summary> /// Returns the hour part of XsdDateTime /// The returned value is integer between 0 and 23 /// </summary> public int Hour { get { return _dt.Hour; } } /// <summary> /// Returns the minute part of XsdDateTime /// The returned value is integer between 0 and 60 /// </summary> public int Minute { get { return _dt.Minute; } } /// <summary> /// Returns the second part of XsdDateTime /// The returned value is integer between 0 and 60 /// </summary> public int Second { get { return _dt.Second; } } /// <summary> /// Returns number of ticks in the fraction of the second /// The returned value is integer between 0 and 9999999 /// </summary> public int Fraction { get { return (int)(_dt.Ticks - new DateTime(_dt.Year, _dt.Month, _dt.Day, _dt.Hour, _dt.Minute, _dt.Second).Ticks); } } /// <summary> /// Returns the hour part of the time zone /// The returned value is integer between -13 and 13 /// </summary> public int ZoneHour { get { uint result = (_extra & ZoneHourMask) >> ZoneHourShift; return (int)result; } } /// <summary> /// Returns the minute part of the time zone /// The returned value is integer between 0 and 60 /// </summary> public int ZoneMinute { get { uint result = (_extra & ZoneMinuteMask); return (int)result; } } #if !SILVERLIGHT public DateTime ToZulu() { switch (InternalKind) { case XsdDateTimeKind.Zulu: // set it to UTC return new DateTime(_dt.Ticks, DateTimeKind.Utc); case XsdDateTimeKind.LocalEastOfZulu: // Adjust to UTC and then convert to local in the current time zone return new DateTime(_dt.Subtract(new TimeSpan(ZoneHour, ZoneMinute, 0)).Ticks, DateTimeKind.Utc); case XsdDateTimeKind.LocalWestOfZulu: // Adjust to UTC and then convert to local in the current time zone return new DateTime(_dt.Add(new TimeSpan(ZoneHour, ZoneMinute, 0)).Ticks, DateTimeKind.Utc); default: return _dt; } } #endif /// <summary> /// Cast to DateTime /// The following table describes the behaviors of getting the default value /// when a certain year/month/day values are missing. /// /// An "X" means that the value exists. And "--" means that value is missing. /// /// Year Month Day => ResultYear ResultMonth ResultDay Note /// /// X X X Parsed year Parsed month Parsed day /// X X -- Parsed Year Parsed month First day If we have year and month, assume the first day of that month. /// X -- X Parsed year First month Parsed day If the month is missing, assume first month of that year. /// X -- -- Parsed year First month First day If we have only the year, assume the first day of that year. /// /// -- X X CurrentYear Parsed month Parsed day If the year is missing, assume the current year. /// -- X -- CurrentYear Parsed month First day If we have only a month value, assume the current year and current day. /// -- -- X CurrentYear First month Parsed day If we have only a day value, assume current year and first month. /// -- -- -- CurrentYear Current month Current day So this means that if the date string only contains time, you will get current date. /// </summary> public static implicit operator DateTime(XsdDateTime xdt) { DateTime result; switch (xdt.InternalTypeCode) { case DateTimeTypeCode.GMonth: case DateTimeTypeCode.GDay: result = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day); break; case DateTimeTypeCode.Time: //back to DateTime.Now DateTime currentDateTime = DateTime.Now; TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day); result = xdt._dt.Add(addDiff); break; default: result = xdt._dt; break; } long ticks; switch (xdt.InternalKind) { case XsdDateTimeKind.Zulu: // set it to UTC result = new DateTime(result.Ticks, DateTimeKind.Utc); break; case XsdDateTimeKind.LocalEastOfZulu: // Adjust to UTC and then convert to local in the current time zone ticks = result.Ticks - new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks; if (ticks < DateTime.MinValue.Ticks) { // Underflow. Return the DateTime as local time directly ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks; if (ticks < DateTime.MinValue.Ticks) ticks = DateTime.MinValue.Ticks; return new DateTime(ticks, DateTimeKind.Local); } result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime(); break; case XsdDateTimeKind.LocalWestOfZulu: // Adjust to UTC and then convert to local in the current time zone ticks = result.Ticks + new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0).Ticks; if (ticks > DateTime.MaxValue.Ticks) { // Overflow. Return the DateTime as local time directly ticks += TimeZoneInfo.Local.GetUtcOffset(result).Ticks; if (ticks > DateTime.MaxValue.Ticks) ticks = DateTime.MaxValue.Ticks; return new DateTime(ticks, DateTimeKind.Local); } result = new DateTime(ticks, DateTimeKind.Utc).ToLocalTime(); break; default: break; } return result; } public static implicit operator DateTimeOffset(XsdDateTime xdt) { DateTime dt; switch (xdt.InternalTypeCode) { case DateTimeTypeCode.GMonth: case DateTimeTypeCode.GDay: dt = new DateTime(DateTime.Now.Year, xdt.Month, xdt.Day); break; case DateTimeTypeCode.Time: //back to DateTime.Now DateTime currentDateTime = DateTime.Now; TimeSpan addDiff = new DateTime(currentDateTime.Year, currentDateTime.Month, currentDateTime.Day) - new DateTime(xdt.Year, xdt.Month, xdt.Day); dt = xdt._dt.Add(addDiff); break; default: dt = xdt._dt; break; } DateTimeOffset result; switch (xdt.InternalKind) { case XsdDateTimeKind.LocalEastOfZulu: result = new DateTimeOffset(dt, new TimeSpan(xdt.ZoneHour, xdt.ZoneMinute, 0)); break; case XsdDateTimeKind.LocalWestOfZulu: result = new DateTimeOffset(dt, new TimeSpan(-xdt.ZoneHour, -xdt.ZoneMinute, 0)); break; case XsdDateTimeKind.Zulu: result = new DateTimeOffset(dt, new TimeSpan(0)); break; case XsdDateTimeKind.Unspecified: default: result = new DateTimeOffset(dt, TimeZoneInfo.Local.GetUtcOffset(dt)); break; } return result; } #if !SILVERLIGHT /// <summary> /// Compares two DateTime values, returning an integer that indicates /// their relationship. /// </summary> public static int Compare(XsdDateTime left, XsdDateTime right) { if (left._extra == right._extra) { return DateTime.Compare(left._dt, right._dt); } else { // Xsd types should be the same for it to be comparable if (left.InternalTypeCode != right.InternalTypeCode) { throw new ArgumentException(SR.Format(SR.Sch_XsdDateTimeCompare, left.TypeCode, right.TypeCode)); } // Convert both to UTC return DateTime.Compare(left.GetZuluDateTime(), right.GetZuluDateTime()); } } // Compares this DateTime to a given object. This method provides an // implementation of the IComparable interface. The object // argument must be another DateTime, or otherwise an exception // occurs. Null is considered less than any instance. // // Returns a value less than zero if this object /// <include file='doc\DateTime.uex' path='docs/doc[@for="DateTime.CompareTo"]/*' /> public int CompareTo(Object value) { if (value == null) return 1; return Compare(this, (XsdDateTime)value); } #endif /// <summary> /// Serialization to a string /// </summary> public override string ToString() { StringBuilder sb = new StringBuilder(64); char[] text; switch (InternalTypeCode) { case DateTimeTypeCode.DateTime: PrintDate(sb); sb.Append('T'); PrintTime(sb); break; case DateTimeTypeCode.Time: PrintTime(sb); break; case DateTimeTypeCode.Date: PrintDate(sb); break; case DateTimeTypeCode.GYearMonth: text = new char[s_lzyyyy_MM]; IntToCharArray(text, 0, Year, 4); text[s_lzyyyy] = '-'; ShortToCharArray(text, s_lzyyyy_, Month); sb.Append(text); break; case DateTimeTypeCode.GYear: text = new char[s_lzyyyy]; IntToCharArray(text, 0, Year, 4); sb.Append(text); break; case DateTimeTypeCode.GMonthDay: text = new char[s_lz__mm_dd]; text[0] = '-'; text[s_Lz_] = '-'; ShortToCharArray(text, s_Lz__, Month); text[s_lz__mm] = '-'; ShortToCharArray(text, s_lz__mm_, Day); sb.Append(text); break; case DateTimeTypeCode.GDay: text = new char[s_lz___dd]; text[0] = '-'; text[s_Lz_] = '-'; text[s_Lz__] = '-'; ShortToCharArray(text, s_Lz___, Day); sb.Append(text); break; case DateTimeTypeCode.GMonth: text = new char[s_lz__mm__]; text[0] = '-'; text[s_Lz_] = '-'; ShortToCharArray(text, s_Lz__, Month); text[s_lz__mm] = '-'; text[s_lz__mm_] = '-'; sb.Append(text); break; } PrintZone(sb); return sb.ToString(); } // Serialize year, month and day private void PrintDate(StringBuilder sb) { char[] text = new char[s_lzyyyy_MM_dd]; IntToCharArray(text, 0, Year, 4); text[s_lzyyyy] = '-'; ShortToCharArray(text, s_lzyyyy_, Month); text[s_lzyyyy_MM] = '-'; ShortToCharArray(text, s_lzyyyy_MM_, Day); sb.Append(text); } // Serialize hour, minute, second and fraction private void PrintTime(StringBuilder sb) { char[] text = new char[s_lzHH_mm_ss]; ShortToCharArray(text, 0, Hour); text[s_lzHH] = ':'; ShortToCharArray(text, s_lzHH_, Minute); text[s_lzHH_mm] = ':'; ShortToCharArray(text, s_lzHH_mm_, Second); sb.Append(text); int fraction = Fraction; if (fraction != 0) { int fractionDigits = maxFractionDigits; while (fraction % 10 == 0) { fractionDigits--; fraction /= 10; } text = new char[fractionDigits + 1]; text[0] = '.'; IntToCharArray(text, 1, fraction, fractionDigits); sb.Append(text); } } // Serialize time zone private void PrintZone(StringBuilder sb) { char[] text; switch (InternalKind) { case XsdDateTimeKind.Zulu: sb.Append('Z'); break; case XsdDateTimeKind.LocalWestOfZulu: text = new char[s_lz_zz_zz]; text[0] = '-'; ShortToCharArray(text, s_Lz_, ZoneHour); text[s_lz_zz] = ':'; ShortToCharArray(text, s_lz_zz_, ZoneMinute); sb.Append(text); break; case XsdDateTimeKind.LocalEastOfZulu: text = new char[s_lz_zz_zz]; text[0] = '+'; ShortToCharArray(text, s_Lz_, ZoneHour); text[s_lz_zz] = ':'; ShortToCharArray(text, s_lz_zz_, ZoneMinute); sb.Append(text); break; default: // do nothing break; } } // Serialize integer into character array starting with index [start]. // Number of digits is set by [digits] private void IntToCharArray(char[] text, int start, int value, int digits) { while (digits-- != 0) { text[start + digits] = (char)(value % 10 + '0'); value /= 10; } } // Serialize two digit integer into character array starting with index [start]. private void ShortToCharArray(char[] text, int start, int value) { text[start] = (char)(value / 10 + '0'); text[start + 1] = (char)(value % 10 + '0'); } #if !SILVERLIGHT // Auxiliary for compare. // Returns UTC DateTime private DateTime GetZuluDateTime() { switch (InternalKind) { case XsdDateTimeKind.Zulu: return _dt; case XsdDateTimeKind.LocalEastOfZulu: return _dt.Subtract(new TimeSpan(ZoneHour, ZoneMinute, 0)); case XsdDateTimeKind.LocalWestOfZulu: return _dt.Add(new TimeSpan(ZoneHour, ZoneMinute, 0)); default: return _dt.ToUniversalTime(); } } #endif private static readonly XmlTypeCode[] s_typeCodes = { XmlTypeCode.DateTime, XmlTypeCode.Time, XmlTypeCode.Date, XmlTypeCode.GYearMonth, XmlTypeCode.GYear, XmlTypeCode.GMonthDay, XmlTypeCode.GDay, XmlTypeCode.GMonth }; // Parsing string according to XML schema spec private struct Parser { private const int leapYear = 1904; private const int firstMonth = 1; private const int firstDay = 1; public DateTimeTypeCode typeCode; public int year; public int month; public int day; public int hour; public int minute; public int second; public int fraction; public XsdDateTimeKind kind; public int zoneHour; public int zoneMinute; private string _text; private int _length; public bool Parse(string text, XsdDateTimeFlags kinds) { _text = text; _length = text.Length; // Skip leading whitespace int start = 0; while (start < _length && char.IsWhiteSpace(text[start])) { start++; } // Choose format starting from the most common and trying not to reparse the same thing too many times #if !SILVERLIGHT // XDR is not supported in Silverlight if (Test(kinds, XsdDateTimeFlags.DateTime | XsdDateTimeFlags.Date | XsdDateTimeFlags.XdrDateTime | XsdDateTimeFlags.XdrDateTimeNoTz)) { #else if (Test(kinds, XsdDateTimeFlags.DateTime | XsdDateTimeFlags.Date)) { #endif if (ParseDate(start)) { if (Test(kinds, XsdDateTimeFlags.DateTime)) { if (ParseChar(start + s_lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + s_lzyyyy_MM_ddT)) { typeCode = DateTimeTypeCode.DateTime; return true; } } if (Test(kinds, XsdDateTimeFlags.Date)) { if (ParseZoneAndWhitespace(start + s_lzyyyy_MM_dd)) { typeCode = DateTimeTypeCode.Date; return true; } } #if !SILVERLIGHT // XDR is not supported in Silverlight if (Test(kinds, XsdDateTimeFlags.XdrDateTime)) { if (ParseZoneAndWhitespace(start + s_lzyyyy_MM_dd) || (ParseChar(start + s_lzyyyy_MM_dd, 'T') && ParseTimeAndZoneAndWhitespace(start + s_lzyyyy_MM_ddT))) { typeCode = DateTimeTypeCode.XdrDateTime; return true; } } if (Test(kinds, XsdDateTimeFlags.XdrDateTimeNoTz)) { if (ParseChar(start + s_lzyyyy_MM_dd, 'T')) { if (ParseTimeAndWhitespace(start + s_lzyyyy_MM_ddT)) { typeCode = DateTimeTypeCode.XdrDateTime; return true; } } else { typeCode = DateTimeTypeCode.XdrDateTime; return true; } } #endif } } if (Test(kinds, XsdDateTimeFlags.Time)) { if (ParseTimeAndZoneAndWhitespace(start)) { //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time year = leapYear; month = firstMonth; day = firstDay; typeCode = DateTimeTypeCode.Time; return true; } } #if !SILVERLIGHT // XDR is not supported in Silverlight if (Test(kinds, XsdDateTimeFlags.XdrTimeNoTz)) { if (ParseTimeAndWhitespace(start)) { //Equivalent to NoCurrentDateDefault on DateTimeStyles while parsing xs:time year = leapYear; month = firstMonth; day = firstDay; typeCode = DateTimeTypeCode.Time; return true; } } #endif if (Test(kinds, XsdDateTimeFlags.GYearMonth | XsdDateTimeFlags.GYear)) { if (Parse4Dig(start, ref year) && 1 <= year) { if (Test(kinds, XsdDateTimeFlags.GYearMonth)) { if ( ParseChar(start + s_lzyyyy, '-') && Parse2Dig(start + s_lzyyyy_, ref month) && 1 <= month && month <= 12 && ParseZoneAndWhitespace(start + s_lzyyyy_MM) ) { day = firstDay; typeCode = DateTimeTypeCode.GYearMonth; return true; } } if (Test(kinds, XsdDateTimeFlags.GYear)) { if (ParseZoneAndWhitespace(start + s_lzyyyy)) { month = firstMonth; day = firstDay; typeCode = DateTimeTypeCode.GYear; return true; } } } } if (Test(kinds, XsdDateTimeFlags.GMonthDay | XsdDateTimeFlags.GMonth)) { if ( ParseChar(start, '-') && ParseChar(start + s_Lz_, '-') && Parse2Dig(start + s_Lz__, ref month) && 1 <= month && month <= 12 ) { if (Test(kinds, XsdDateTimeFlags.GMonthDay) && ParseChar(start + s_lz__mm, '-')) { if ( Parse2Dig(start + s_lz__mm_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, month) && ParseZoneAndWhitespace(start + s_lz__mm_dd) ) { year = leapYear; typeCode = DateTimeTypeCode.GMonthDay; return true; } } if (Test(kinds, XsdDateTimeFlags.GMonth)) { if (ParseZoneAndWhitespace(start + s_lz__mm) || (ParseChar(start + s_lz__mm, '-') && ParseChar(start + s_lz__mm_, '-') && ParseZoneAndWhitespace(start + s_lz__mm__))) { year = leapYear; day = firstDay; typeCode = DateTimeTypeCode.GMonth; return true; } } } } if (Test(kinds, XsdDateTimeFlags.GDay)) { if ( ParseChar(start, '-') && ParseChar(start + s_Lz_, '-') && ParseChar(start + s_Lz__, '-') && Parse2Dig(start + s_Lz___, ref day) && 1 <= day && day <= DateTime.DaysInMonth(leapYear, firstMonth) && ParseZoneAndWhitespace(start + s_lz___dd) ) { year = leapYear; month = firstMonth; typeCode = DateTimeTypeCode.GDay; return true; } } return false; } private bool ParseDate(int start) { return Parse4Dig(start, ref year) && 1 <= year && ParseChar(start + s_lzyyyy, '-') && Parse2Dig(start + s_lzyyyy_, ref month) && 1 <= month && month <= 12 && ParseChar(start + s_lzyyyy_MM, '-') && Parse2Dig(start + s_lzyyyy_MM_, ref day) && 1 <= day && day <= DateTime.DaysInMonth(year, month); } private bool ParseTimeAndZoneAndWhitespace(int start) { if (ParseTime(ref start)) { if (ParseZoneAndWhitespace(start)) { return true; } } return false; } #if !SILVERLIGHT // XDR is not supported in Silverlight private bool ParseTimeAndWhitespace(int start) { if (ParseTime(ref start)) { while (start < _length) {//&& char.IsWhiteSpace(text[start])) { start++; } return start == _length; } return false; } #endif private static int[] s_power10 = new int[maxFractionDigits] { -1, 10, 100, 1000, 10000, 100000, 1000000 }; private bool ParseTime(ref int start) { if ( Parse2Dig(start, ref hour) && hour < 24 && ParseChar(start + s_lzHH, ':') && Parse2Dig(start + s_lzHH_, ref minute) && minute < 60 && ParseChar(start + s_lzHH_mm, ':') && Parse2Dig(start + s_lzHH_mm_, ref second) && second < 60 ) { start += s_lzHH_mm_ss; if (ParseChar(start, '.')) { // Parse factional part of seconds // We allow any number of digits, but keep only first 7 this.fraction = 0; int fractionDigits = 0; int round = 0; while (++start < _length) { int d = _text[start] - '0'; if (9u < unchecked((uint)d)) { // d < 0 || 9 < d break; } if (fractionDigits < maxFractionDigits) { this.fraction = (this.fraction * 10) + d; } else if (fractionDigits == maxFractionDigits) { if (5 < d) { round = 1; } else if (d == 5) { round = -1; } } else if (round < 0 && d != 0) { round = 1; } fractionDigits++; } if (fractionDigits < maxFractionDigits) { if (fractionDigits == 0) { return false; // cannot end with . } fraction *= s_power10[maxFractionDigits - fractionDigits]; } else { if (round < 0) { round = fraction & 1; } fraction += round; } } return true; } // cleanup - conflict with gYear hour = 0; return false; } private bool ParseZoneAndWhitespace(int start) { if (start < _length) { char ch = _text[start]; if (ch == 'Z' || ch == 'z') { kind = XsdDateTimeKind.Zulu; start++; } else if (start + 5 < _length) { if ( Parse2Dig(start + s_Lz_, ref zoneHour) && zoneHour <= 99 && ParseChar(start + s_lz_zz, ':') && Parse2Dig(start + s_lz_zz_, ref zoneMinute) && zoneMinute <= 99 ) { if (ch == '-') { kind = XsdDateTimeKind.LocalWestOfZulu; start += s_lz_zz_zz; } else if (ch == '+') { kind = XsdDateTimeKind.LocalEastOfZulu; start += s_lz_zz_zz; } } } } while (start < _length && char.IsWhiteSpace(_text[start])) { start++; } return start == _length; } private bool Parse4Dig(int start, ref int num) { if (start + 3 < _length) { int d4 = _text[start] - '0'; int d3 = _text[start + 1] - '0'; int d2 = _text[start + 2] - '0'; int d1 = _text[start + 3] - '0'; if (0 <= d4 && d4 < 10 && 0 <= d3 && d3 < 10 && 0 <= d2 && d2 < 10 && 0 <= d1 && d1 < 10 ) { num = ((d4 * 10 + d3) * 10 + d2) * 10 + d1; return true; } } return false; } private bool Parse2Dig(int start, ref int num) { if (start + 1 < _length) { int d2 = _text[start] - '0'; int d1 = _text[start + 1] - '0'; if (0 <= d2 && d2 < 10 && 0 <= d1 && d1 < 10 ) { num = d2 * 10 + d1; return true; } } return false; } private bool ParseChar(int start, char ch) { return start < _length && _text[start] == ch; } private static bool Test(XsdDateTimeFlags left, XsdDateTimeFlags right) { return (left & right) != 0; } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using Microsoft.PythonTools.Analysis; using Microsoft.VisualStudioTools; using Microsoft.Win32; namespace Microsoft.PythonTools.Interpreter { [Export(typeof(IPythonInterpreterFactoryProvider))] [PartCreationPolicy(CreationPolicy.Shared)] class CPythonInterpreterFactoryProvider : IPythonInterpreterFactoryProvider { private readonly List<IPythonInterpreterFactory> _interpreters; const string PythonPath = "Software\\Python"; const string PythonCorePath = "Software\\Python\\PythonCore"; public CPythonInterpreterFactoryProvider() { _interpreters = new List<IPythonInterpreterFactory>(); DiscoverInterpreterFactories(); StartWatching(RegistryHive.CurrentUser, RegistryView.Default); StartWatching(RegistryHive.LocalMachine, RegistryView.Registry32); if (Environment.Is64BitOperatingSystem) { StartWatching(RegistryHive.LocalMachine, RegistryView.Registry64); } } private void StartWatching(RegistryHive hive, RegistryView view, int retries = 5) { var tag = RegistryWatcher.Instance.TryAdd( hive, view, PythonCorePath, Registry_PythonCorePath_Changed, recursive: true, notifyValueChange: true, notifyKeyChange: true ) ?? RegistryWatcher.Instance.TryAdd( hive, view, PythonPath, Registry_PythonPath_Changed, recursive: false, notifyValueChange: false, notifyKeyChange: true ) ?? RegistryWatcher.Instance.TryAdd( hive, view, "Software", Registry_Software_Changed, recursive: false, notifyValueChange: false, notifyKeyChange: true ); if (tag == null && retries > 0) { Trace.TraceWarning("Failed to watch registry. Retrying {0} more times", retries); Thread.Sleep(100); StartWatching(hive, view, retries - 1); } else if (tag == null) { Trace.TraceError("Failed to watch registry"); } } #region Registry Watching private static bool Exists(RegistryChangedEventArgs e) { using (var root = RegistryKey.OpenBaseKey(e.Hive, e.View)) using (var key = root.OpenSubKey(e.Key)) { return key != null; } } private void Registry_PythonCorePath_Changed(object sender, RegistryChangedEventArgs e) { if (!Exists(e)) { // PythonCore key no longer exists, so go back to watching // Python. e.CancelWatcher = true; StartWatching(e.Hive, e.View); } else { DiscoverInterpreterFactories(); } } private void Registry_PythonPath_Changed(object sender, RegistryChangedEventArgs e) { if (Exists(e)) { if (RegistryWatcher.Instance.TryAdd( e.Hive, e.View, PythonCorePath, Registry_PythonCorePath_Changed, recursive: true, notifyValueChange: true, notifyKeyChange: true ) != null) { // PythonCore key now exists, so start watching it, // discover any interpreters, and cancel this watcher. e.CancelWatcher = true; DiscoverInterpreterFactories(); } } else { // Python key no longer exists, so go back to watching // Software. e.CancelWatcher = true; StartWatching(e.Hive, e.View); } } private void Registry_Software_Changed(object sender, RegistryChangedEventArgs e) { Registry_PythonPath_Changed(sender, e); if (e.CancelWatcher) { // PythonCore key also exists and is now being watched, so just // return. return; } if (RegistryWatcher.Instance.TryAdd( e.Hive, e.View, PythonPath, Registry_PythonPath_Changed, recursive: false, notifyValueChange: false, notifyKeyChange: true ) != null) { // Python exists, but not PythonCore, so watch Python until // PythonCore is created. e.CancelWatcher = true; } } #endregion private static bool TryParsePythonVersion(string spec, out Version version, out ProcessorArchitecture? arch) { version = null; arch = null; if (string.IsNullOrEmpty(spec) || spec.Length < 3) { return false; } var m = Regex.Match(spec, @"^(?<ver>[23]\.[0-9]+)(?<suffix>.*)$"); if (!m.Success) { return false; } if (!Version.TryParse(m.Groups["ver"].Value, out version)) { return false; } if (m.Groups["suffix"].Value == "-32") { arch = ProcessorArchitecture.X86; } return true; } private bool RegisterInterpreters(HashSet<string> registeredPaths, RegistryKey python, ProcessorArchitecture? arch) { bool anyAdded = false; string[] subKeyNames = null; for (int retries = 5; subKeyNames == null && retries > 0; --retries) { try { subKeyNames = python.GetSubKeyNames(); } catch (IOException) { // Registry changed while enumerating subkeys. Give it a // short period to settle down and try again. // We are almost certainly being called from a background // thread, so sleeping here is fine. Thread.Sleep(100); } } if (subKeyNames == null) { return false; } foreach (var key in subKeyNames) { Version version; ProcessorArchitecture? arch2; if (TryParsePythonVersion(key, out version, out arch2)) { if (version.Major == 2 && version.Minor <= 4) { // 2.4 and below not supported. continue; } var installPath = python.OpenSubKey(key + "\\InstallPath"); if (installPath != null) { var basePathObj = installPath.GetValue(""); if (basePathObj == null) { // http://pytools.codeplex.com/discussions/301384 // messed up install, we don't know where it lives, we can't use it. continue; } string basePath = basePathObj.ToString(); if (!CommonUtils.IsValidPath(basePath)) { // Invalid path in registry continue; } if (!registeredPaths.Add(basePath)) { // registered in both HCKU and HKLM continue; } var actualArch = arch ?? arch2; if (!actualArch.HasValue) { actualArch = NativeMethods.GetBinaryType(Path.Combine(basePath, CPythonInterpreterFactoryConstants.ConsoleExecutable)); } var id = CPythonInterpreterFactoryConstants.Guid32; var description = CPythonInterpreterFactoryConstants.Description32; if (actualArch == ProcessorArchitecture.Amd64) { id = CPythonInterpreterFactoryConstants.Guid64; description = CPythonInterpreterFactoryConstants.Description64; } if (!_interpreters.Any(f => f.Id == id && f.Configuration.Version == version)) { IPythonInterpreterFactory fact; try { fact = InterpreterFactoryCreator.CreateInterpreterFactory( new InterpreterFactoryCreationOptions { LanguageVersion = version, Id = id, Description = string.Format("{0} {1}", description, version), InterpreterPath = Path.Combine(basePath, CPythonInterpreterFactoryConstants.ConsoleExecutable), WindowInterpreterPath = Path.Combine(basePath, CPythonInterpreterFactoryConstants.WindowsExecutable), LibraryPath = Path.Combine(basePath, CPythonInterpreterFactoryConstants.LibrarySubPath), PathEnvironmentVariableName = CPythonInterpreterFactoryConstants.PathEnvironmentVariableName, Architecture = actualArch ?? ProcessorArchitecture.None, WatchLibraryForNewModules = true } ); } catch (ArgumentException) { continue; } _interpreters.Add(fact); anyAdded = true; } } } } return anyAdded; } private void DiscoverInterpreterFactories() { bool anyAdded = false; HashSet<string> registeredPaths = new HashSet<string>(); var arch = Environment.Is64BitOperatingSystem ? null : (ProcessorArchitecture?)ProcessorArchitecture.X86; using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default)) using (var python = baseKey.OpenSubKey(PythonCorePath)) { if (python != null) { anyAdded |= RegisterInterpreters(registeredPaths, python, arch); } } using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) using (var python = baseKey.OpenSubKey(PythonCorePath)) { if (python != null) { anyAdded |= RegisterInterpreters(registeredPaths, python, ProcessorArchitecture.X86); } } if (Environment.Is64BitOperatingSystem) { using (var baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) using (var python64 = baseKey.OpenSubKey(PythonCorePath)) { if (python64 != null) { anyAdded |= RegisterInterpreters(registeredPaths, python64, ProcessorArchitecture.Amd64); } } } if (anyAdded) { OnInterpreterFactoriesChanged(); } } #region IPythonInterpreterProvider Members public IEnumerable<IPythonInterpreterFactory> GetInterpreterFactories() { return _interpreters; } public event EventHandler InterpreterFactoriesChanged; private void OnInterpreterFactoriesChanged() { var evt = InterpreterFactoriesChanged; if (evt != null) { evt(this, EventArgs.Empty); } } #endregion } }
using System.Net; using System.Net.Sockets; using System.Timers; using KNXLib.Exceptions; using KNXLib.Log; using System; namespace KNXLib { /// <summary> /// Class that controls a Tunneling KNX connection, a tunneling connection is UDP based and has state. /// This class will connect to the remote gateway provided and create an endpoint for the remote gateway /// to connect back /// </summary> public class KnxConnectionTunneling : KnxConnection { private static readonly string ClassName = typeof(KnxConnectionTunneling).ToString(); private readonly IPEndPoint _localEndpoint; private readonly Timer _stateRequestTimer; private const int stateRequestTimerInterval = 60000; private UdpClient _udpClient; private byte _sequenceNumber; /// <summary> /// Initializes a new KNX tunneling connection with provided values. Make sure the local system allows /// UDP messages to the localIpAddress and localPort provided /// </summary> /// <param name="remoteIpAddress">Remote gateway IP address</param> /// <param name="remotePort">Remote gateway port</param> /// <param name="localIpAddress">Local IP address to bind to</param> /// <param name="localPort">Local port to bind to</param> public KnxConnectionTunneling(string remoteIpAddress, int remotePort, string localIpAddress, int localPort) : base(remoteIpAddress, remotePort) { _localEndpoint = new IPEndPoint(IPAddress.Parse(localIpAddress), localPort); ChannelId = 0x00; SequenceNumberLock = new object(); _stateRequestTimer = new Timer(stateRequestTimerInterval) { AutoReset = true }; // same time as ETS with group monitor open _stateRequestTimer.Elapsed += StateRequest; } internal byte ChannelId { get; set; } internal object SequenceNumberLock { get; set; } internal byte GenerateSequenceNumber() { return _sequenceNumber++; } internal void RevertSingleSequenceNumber() { _sequenceNumber--; } internal void ResetSequenceNumber() { _sequenceNumber = 0x00; } /// <summary> /// Start the connection /// </summary> public override void Connect() { Logger.Info(ClassName, "KNXLib connecting..."); try { if (_udpClient != null) { try { _udpClient.Close(); if (_udpClient.Client != null) _udpClient.Client.Dispose(); } catch (Exception e) { Logger.Error(ClassName, e); } } _udpClient = new UdpClient(_localEndpoint) { Client = { DontFragment = true, SendBufferSize = 0, ReceiveTimeout = stateRequestTimerInterval * 2 } }; } catch (SocketException ex) { throw new ConnectionErrorException(ConnectionConfiguration, ex); } if (KnxReceiver == null || KnxSender == null) { KnxReceiver = new KnxReceiverTunneling(this, _udpClient, _localEndpoint); KnxSender = new KnxSenderTunneling(this, _udpClient, RemoteEndpoint); } else { ((KnxReceiverTunneling) KnxReceiver).SetClient(_udpClient); ((KnxSenderTunneling) KnxSender).SetClient(_udpClient); } KnxReceiver.Start(); try { ConnectRequest(); } catch (Exception e) { Logger.Error(ClassName, e); } } /// <summary> /// Stop the connection /// </summary> public override void Disconnect() { try { TerminateStateRequest(); DisconnectRequest(); KnxReceiver.Stop(); _udpClient.Close(); } catch (Exception e) { Logger.Error(ClassName, e); } base.Disconnected(); } internal override void Connected() { base.Connected(); InitializeStateRequest(); } internal override void Disconnected() { base.Disconnected(); TerminateStateRequest(); } private void InitializeStateRequest() { _stateRequestTimer.Enabled = true; } private void TerminateStateRequest() { if (_stateRequestTimer == null) return; _stateRequestTimer.Enabled = false; } // TODO: I wonder if we can extract all these types of requests private void ConnectRequest() { // HEADER var datagram = new byte[26]; datagram[00] = 0x06; datagram[01] = 0x10; datagram[02] = 0x02; datagram[03] = 0x05; datagram[04] = 0x00; datagram[05] = 0x1A; datagram[06] = 0x08; datagram[07] = 0x01; datagram[08] = _localEndpoint.Address.GetAddressBytes()[0]; datagram[09] = _localEndpoint.Address.GetAddressBytes()[1]; datagram[10] = _localEndpoint.Address.GetAddressBytes()[2]; datagram[11] = _localEndpoint.Address.GetAddressBytes()[3]; datagram[12] = (byte) (_localEndpoint.Port >> 8); datagram[13] = (byte) _localEndpoint.Port; datagram[14] = 0x08; datagram[15] = 0x01; datagram[16] = _localEndpoint.Address.GetAddressBytes()[0]; datagram[17] = _localEndpoint.Address.GetAddressBytes()[1]; datagram[18] = _localEndpoint.Address.GetAddressBytes()[2]; datagram[19] = _localEndpoint.Address.GetAddressBytes()[3]; datagram[20] = (byte) (_localEndpoint.Port >> 8); datagram[21] = (byte) _localEndpoint.Port; datagram[22] = 0x04; datagram[23] = 0x04; datagram[24] = 0x02; datagram[25] = 0x00; ((KnxSenderTunneling) KnxSender).SendDataSingle(datagram); } private void StateRequest(object sender, ElapsedEventArgs ev) { // HEADER var datagram = new byte[16]; datagram[00] = 0x06; datagram[01] = 0x10; datagram[02] = 0x02; datagram[03] = 0x07; datagram[04] = 0x00; datagram[05] = 0x10; datagram[06] = ChannelId; datagram[07] = 0x00; datagram[08] = 0x08; datagram[09] = 0x01; datagram[10] = _localEndpoint.Address.GetAddressBytes()[0]; datagram[11] = _localEndpoint.Address.GetAddressBytes()[1]; datagram[12] = _localEndpoint.Address.GetAddressBytes()[2]; datagram[13] = _localEndpoint.Address.GetAddressBytes()[3]; datagram[14] = (byte) (_localEndpoint.Port >> 8); datagram[15] = (byte) _localEndpoint.Port; try { KnxSender.SendData(datagram); } catch (Exception e) { Logger.Error(ClassName, e); } } internal void DisconnectRequest() { // HEADER var datagram = new byte[16]; datagram[00] = 0x06; datagram[01] = 0x10; datagram[02] = 0x02; datagram[03] = 0x09; datagram[04] = 0x00; datagram[05] = 0x10; datagram[06] = ChannelId; datagram[07] = 0x00; datagram[08] = 0x08; datagram[09] = 0x01; datagram[10] = _localEndpoint.Address.GetAddressBytes()[0]; datagram[11] = _localEndpoint.Address.GetAddressBytes()[1]; datagram[12] = _localEndpoint.Address.GetAddressBytes()[2]; datagram[13] = _localEndpoint.Address.GetAddressBytes()[3]; datagram[14] = (byte) (_localEndpoint.Port >> 8); datagram[15] = (byte) _localEndpoint.Port; KnxSender.SendData(datagram); } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using NLog.Config; #if !NETSTANDARD namespace NLog.UnitTests.LayoutRenderers { using System; using Microsoft.Win32; using Xunit; public class RegistryTests : NLogTestBase, IDisposable { private const string TestKey = @"Software\NLogTest"; public RegistryTests() { var key = Registry.CurrentUser.CreateSubKey(TestKey); key.SetValue("Foo", "FooValue"); key.SetValue(null, "UnnamedValue"); #if !NET3_5 //different keys because in 32bit the 64bits uses the 32 RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).CreateSubKey("Software\\NLogTest").SetValue("view32", "reg32"); RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).CreateSubKey("Software\\NLogTest").SetValue("view64", "reg64"); #endif } public void Dispose() { #if !NET3_5 //different keys because in 32bit the 64bits uses the 32 try { RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32).DeleteSubKey("Software\\NLogTest"); } catch (Exception) { } try { RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64).DeleteSubKey("Software\\NLogTest"); } catch (Exception) { } #endif try { Registry.CurrentUser.DeleteSubKey(TestKey); } catch (Exception) { } } [Fact] public void RegistryNamedValueTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=Foo}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "FooValue"); } #if !NET3_5 [Fact] public void RegistryNamedValueTest_hive32() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view32:view=Registry32}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "reg32"); } [Fact] public void RegistryNamedValueTest_hive64() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=view64:view=Registry64}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "reg64"); } #endif [Fact] public void RegistryNamedValueTest_forward_slash() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest:value=Foo}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "FooValue"); } [Fact] public void RegistryUnnamedValueTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "UnnamedValue"); } [Fact] public void RegistryUnnamedValueTest_forward_slash() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NLogTest}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "UnnamedValue"); } [Fact] public void RegistryKeyNotFoundTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NoSuchKey:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "xyz"); } [Fact] public void RegistryKeyNotFoundTest_forward_slash() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU/Software/NoSuchKey:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "xyz"); } [Fact] public void RegistryValueNotFoundTest() { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${registry:key=HKCU\\Software\\NLogTest:value=NoSuchValue:defaultValue=xyz}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); LogManager.GetLogger("d").Debug("zzz"); AssertDebugLastMessage("debug", "xyz"); } [Fact] public void RegistryDefaultValueTest() { using (new NoThrowNLogExceptions()) { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=logdefaultvalue}", "logdefaultvalue"); } } [Fact] public void RegistryDefaultValueTest_with_colon() { using (new NoThrowNLogExceptions()) { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\:temp}", "C:temp"); } } [Fact] public void RegistryDefaultValueTest_with_slash() { using (new NoThrowNLogExceptions()) { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C/temp}", "C/temp"); } } [Fact] public void RegistryDefaultValueTest_with_foward_slash() { using (new NoThrowNLogExceptions()) { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\\\temp}", "C\\temp"); } } [Fact] public void RegistryDefaultValueTest_with_foward_slash2() { //example: 0003: NLog.UnitTests using (new NoThrowNLogExceptions()) { AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT:defaultValue=C\\temp:requireEscapingSlashesInDefaultValue=false}", "C\\temp"); } } [Fact] public void Registry_nosubky() { using (new NoThrowNLogExceptions()) { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:key=HKEY_CURRENT_CONFIG}", ""); } } [Fact] public void RegistryDefaultValueNull() { using (new NoThrowNLogExceptions()) { //example: 0003: NLog.UnitTests AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=HKLM/NOT_EXISTENT}", ""); } } [Fact] public void RegistryTestWrongKey_no_ex() { using (new NoThrowNLogExceptions()) { AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", ""); } } [Fact] public void RegistryTestWrongKey_ex() { LogManager.ThrowExceptions = true; Assert.Throws<ArgumentException>( () => { AssertLayoutRendererOutput("${registry:value=NOT_EXISTENT:key=garabageHKLM/NOT_EXISTENT:defaultValue=empty}", ""); }); } } } #endif
using System; using System.Diagnostics; using System.Runtime.InteropServices; using Pgno = System.UInt32; using i64 = System.Int64; using u32 = System.UInt32; using BITVEC_TELEM = System.Byte; namespace Community.CsharpSqlite { public partial class Sqlite3 { /* ** 2008 February 16 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file implements an object that represents a fixed-length ** bitmap. Bits are numbered starting with 1. ** ** A bitmap is used to record which pages of a database file have been ** journalled during a transaction, or which pages have the "dont-write" ** property. Usually only a few pages are meet either condition. ** So the bitmap is usually sparse and has low cardinality. ** But sometimes (for example when during a DROP of a large table) most ** or all of the pages in a database can get journalled. In those cases, ** the bitmap becomes dense with high cardinality. The algorithm needs ** to handle both cases well. ** ** The size of the bitmap is fixed when the object is created. ** ** All bits are clear when the bitmap is created. Individual bits ** may be set or cleared one at a time. ** ** Test operations are about 100 times more common that set operations. ** Clear operations are exceedingly rare. There are usually between ** 5 and 500 set operations per Bitvec object, though the number of sets can ** sometimes grow into tens of thousands or larger. The size of the ** Bitvec object is the number of pages in the database file at the ** start of a transaction, and is thus usually less than a few thousand, ** but can be as large as 2 billion for a really big database. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" /* Size of the Bitvec structure in bytes. */ static int BITVEC_SZ = 512; /* Round the union size down to the nearest pointer boundary, since that's how ** it will be aligned within the Bitvec struct. */ //#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*)) static int BITVEC_USIZE = ( ( ( BITVEC_SZ - ( 3 * sizeof( u32 ) ) ) / 4 ) * 4 ); /* Type of the array "element" for the bitmap representation. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. ** Setting this to the "natural word" size of your CPU may improve ** performance. */ //#define BITVEC_TELEM u8 //using BITVEC_TELEM = System.Byte; /* Size, in bits, of the bitmap element. */ //#define BITVEC_SZELEM 8 const int BITVEC_SZELEM = 8; /* Number of elements in a bitmap array. */ //#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM)) static int BITVEC_NELEM = (int)( BITVEC_USIZE / sizeof( BITVEC_TELEM ) ); /* Number of bits in the bitmap array. */ //#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM) static int BITVEC_NBIT = ( BITVEC_NELEM * BITVEC_SZELEM ); /* Number of u32 values in hash table. */ //#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32)) static u32 BITVEC_NINT = (u32)( BITVEC_USIZE / sizeof( u32 ) ); /* Maximum number of entries in hash table before ** sub-dividing and re-hashing. */ //#define BITVEC_MXHASH (BITVEC_NINT/2) static int BITVEC_MXHASH = (int)( BITVEC_NINT / 2 ); /* Hashing function for the aHash representation. ** Empirical testing showed that the *37 multiplier ** (an arbitrary prime)in the hash function provided ** no fewer collisions than the no-op *1. */ //#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT) static u32 BITVEC_HASH( u32 X ) { return (u32)( ( ( X ) * 1 ) % BITVEC_NINT ); } static int BITVEC_NPTR = (int)( BITVEC_USIZE / 4 );//sizeof(Bitvec *)); /* ** A bitmap is an instance of the following structure. ** ** This bitmap records the existence of zero or more bits ** with values between 1 and iSize, inclusive. ** ** There are three possible representations of the bitmap. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight ** bitmap. The least significant bit is bit 1. ** ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is ** a hash table that will hold up to BITVEC_MXHASH distinct values. ** ** Otherwise, the value i is redirected into one of BITVEC_NPTR ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap ** handles up to iDivisor separate values of i. apSub[0] holds ** values between 1 and iDivisor. apSub[1] holds values between ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized ** to hold deal with values between 1 and iDivisor. */ public class _u { public BITVEC_TELEM[] aBitmap = new byte[BITVEC_NELEM]; /* Bitmap representation */ public u32[] aHash = new u32[BITVEC_NINT]; /* Hash table representation */ public Bitvec[] apSub = new Bitvec[BITVEC_NPTR]; /* Recursive representation */ } public class Bitvec { public u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */ public u32 nSet; /* Number of bits that are set - only valid for aHash ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512, ** this would be 125. */ public u32 iDivisor; /* Number of bits handled by each apSub[] entry. */ /* Should >=0 for apSub element. */ /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */ /* For a BITVEC_SZ of 512, this would be 34,359,739. */ public _u u = new _u(); public static implicit operator bool( Bitvec b ) { return ( b != null ); } }; /* ** Create a new bitmap object able to handle bits between 0 and iSize, ** inclusive. Return a pointer to the new object. Return NULL if ** malloc fails. */ static Bitvec sqlite3BitvecCreate( u32 iSize ) { Bitvec p; //Debug.Assert( sizeof(p)==BITVEC_SZ ); p = new Bitvec();//sqlite3MallocZero( sizeof(p) ); if ( p != null ) { p.iSize = iSize; } return p; } /* ** Check to see if the i-th bit is set. Return true or false. ** If p is NULL (if the bitmap has not been created) or if ** i is out of range, then return false. */ static int sqlite3BitvecTest( Bitvec p, u32 i ) { if ( p == null || i == 0 ) return 0; if ( i > p.iSize ) return 0; i--; while ( p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; p = p.u.apSub[bin]; if ( null == p ) { return 0; } } if ( p.iSize <= BITVEC_NBIT ) { return ( ( p.u.aBitmap[i / BITVEC_SZELEM] & ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ) != 0 ) ? 1 : 0; } else { u32 h = BITVEC_HASH( i++ ); while ( p.u.aHash[h] != 0 ) { if ( p.u.aHash[h] == i ) return 1; h = ( h + 1 ) % BITVEC_NINT; } return 0; } } /* ** Set the i-th bit. Return 0 on success and an error code if ** anything goes wrong. ** ** This routine might cause sub-bitmaps to be allocated. Failing ** to get the memory needed to hold the sub-bitmap is the only ** that can go wrong with an insert, assuming p and i are valid. ** ** The calling function must ensure that p is a valid Bitvec object ** and that the value for "i" is within range of the Bitvec object. ** Otherwise the behavior is undefined. */ static int sqlite3BitvecSet( Bitvec p, u32 i ) { u32 h; if ( p == null ) return SQLITE_OK; Debug.Assert( i > 0 ); Debug.Assert( i <= p.iSize ); i--; while ( ( p.iSize > BITVEC_NBIT ) && p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; if ( p.u.apSub[bin] == null ) { p.u.apSub[bin] = sqlite3BitvecCreate( p.iDivisor ); if ( p.u.apSub[bin] == null ) return SQLITE_NOMEM; } p = p.u.apSub[bin]; } if ( p.iSize <= BITVEC_NBIT ) { p.u.aBitmap[i / BITVEC_SZELEM] |= (byte)( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ); return SQLITE_OK; } h = BITVEC_HASH( i++ ); /* if there wasn't a hash collision, and this doesn't */ /* completely fill the hash, then just add it without */ /* worring about sub-dividing and re-hashing. */ if ( 0 == p.u.aHash[h] ) { if ( p.nSet < ( BITVEC_NINT - 1 ) ) { goto bitvec_set_end; } else { goto bitvec_set_rehash; } } /* there was a collision, check to see if it's already */ /* in hash, if not, try to find a spot for it */ do { if ( p.u.aHash[h] == i ) return SQLITE_OK; h++; if ( h >= BITVEC_NINT ) h = 0; } while ( p.u.aHash[h] != 0 ); /* we didn't find it in the hash. h points to the first */ /* available free spot. check to see if this is going to */ /* make our hash too "full". */ bitvec_set_rehash: if ( p.nSet >= BITVEC_MXHASH ) { u32 j; int rc; u32[] aiValues = new u32[BITVEC_NINT];// = sqlite3StackAllocRaw(0, sizeof(p->u.aHash)); if ( aiValues == null ) { return SQLITE_NOMEM; } else { Buffer.BlockCopy( p.u.aHash, 0, aiValues, 0, aiValues.Length * ( sizeof( u32 ) ) );// memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); p.u.apSub = new Bitvec[BITVEC_NPTR];//memset(p->u.apSub, 0, sizeof(p->u.apSub)); p.iDivisor = (u32)( ( p.iSize + BITVEC_NPTR - 1 ) / BITVEC_NPTR ); rc = sqlite3BitvecSet( p, i ); for ( j = 0; j < BITVEC_NINT; j++ ) { if ( aiValues[j] != 0 ) rc |= sqlite3BitvecSet( p, aiValues[j] ); } //sqlite3StackFree( null, aiValues ); return rc; } } bitvec_set_end: p.nSet++; p.u.aHash[h] = i; return SQLITE_OK; } /* ** Clear the i-th bit. ** ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage ** that BitvecClear can use to rebuilt its hash table. */ static void sqlite3BitvecClear( Bitvec p, u32 i, u32[] pBuf ) { if ( p == null ) return; Debug.Assert( i > 0 ); i--; while ( p.iDivisor != 0 ) { u32 bin = i / p.iDivisor; i = i % p.iDivisor; p = p.u.apSub[bin]; if ( null == p ) { return; } } if ( p.iSize <= BITVEC_NBIT ) { p.u.aBitmap[i / BITVEC_SZELEM] &= (byte)~( ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ); } else { u32 j; u32[] aiValues = pBuf; Array.Copy( p.u.aHash, aiValues, p.u.aHash.Length );//memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash)); p.u.aHash = new u32[aiValues.Length];// memset(p->u.aHash, 0, sizeof(p->u.aHash)); p.nSet = 0; for ( j = 0; j < BITVEC_NINT; j++ ) { if ( aiValues[j] != 0 && aiValues[j] != ( i + 1 ) ) { u32 h = BITVEC_HASH( aiValues[j] - 1 ); p.nSet++; while ( p.u.aHash[h] != 0 ) { h++; if ( h >= BITVEC_NINT ) h = 0; } p.u.aHash[h] = aiValues[j]; } } } } /* ** Destroy a bitmap object. Reclaim all memory used. */ static void sqlite3BitvecDestroy( ref Bitvec p ) { if ( p == null ) return; if ( p.iDivisor != 0 ) { u32 i; for ( i = 0; i < BITVEC_NPTR; i++ ) { sqlite3BitvecDestroy( ref p.u.apSub[i] ); } } //sqlite3_free( ref p ); } /* ** Return the value of the iSize parameter specified when Bitvec *p ** was created. */ static u32 sqlite3BitvecSize( Bitvec p ) { return p.iSize; } #if !SQLITE_OMIT_BUILTIN_TEST /* ** Let V[] be an array of unsigned characters sufficient to hold ** up to N bits. Let I be an integer between 0 and N. 0<=I<N. ** Then the following macros can be used to set, clear, or test ** individual bits within V. */ //#define SETBIT(V,I) V[I>>3] |= (1<<(I&7)) static void SETBIT( byte[] V, int I ) { V[I >> 3] |= (byte)( 1 << ( I & 7 ) ); } //#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7)) static void CLEARBIT( byte[] V, int I ) { V[I >> 3] &= (byte)~( 1 << ( I & 7 ) ); } //#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0 static int TESTBIT( byte[] V, int I ) { return ( V[I >> 3] & ( 1 << ( I & 7 ) ) ) != 0 ? 1 : 0; } /* ** This routine runs an extensive test of the Bitvec code. ** ** The input is an array of integers that acts as a program ** to test the Bitvec. The integers are opcodes followed ** by 0, 1, or 3 operands, depending on the opcode. Another ** opcode follows immediately after the last operand. ** ** There are 6 opcodes numbered from 0 through 5. 0 is the ** "halt" opcode and causes the test to end. ** ** 0 Halt and return the number of errors ** 1 N S X Set N bits beginning with S and incrementing by X ** 2 N S X Clear N bits beginning with S and incrementing by X ** 3 N Set N randomly chosen bits ** 4 N Clear N randomly chosen bits ** 5 N S X Set N bits from S increment X in array only, not in bitvec ** ** The opcodes 1 through 4 perform set and clear operations are performed ** on both a Bitvec object and on a linear array of bits obtained from malloc. ** Opcode 5 works on the linear array only, not on the Bitvec. ** Opcode 5 is used to deliberately induce a fault in order to ** confirm that error detection works. ** ** At the conclusion of the test the linear array is compared ** against the Bitvec object. If there are any differences, ** an error is returned. If they are the same, zero is returned. ** ** If a memory allocation error occurs, return -1. */ static int sqlite3BitvecBuiltinTest( u32 sz, int[] aOp ) { Bitvec pBitvec = null; byte[] pV = null; int rc = -1; int i, nx, pc, op; u32[] pTmpSpace; /* Allocate the Bitvec to be tested and a linear array of ** bits to act as the reference */ pBitvec = sqlite3BitvecCreate( sz ); pV = sqlite3_malloc( (int)( sz + 7 ) / 8 + 1 ); pTmpSpace = new u32[BITVEC_SZ];// sqlite3_malloc( BITVEC_SZ ); if ( pBitvec == null || pV == null || pTmpSpace == null ) goto bitvec_end; Array.Clear( pV, 0, (int)( sz + 7 ) / 8 + 1 );// memset( pV, 0, ( sz + 7 ) / 8 + 1 ); /* NULL pBitvec tests */ sqlite3BitvecSet( null, (u32)1 ); sqlite3BitvecClear( null, 1, pTmpSpace ); /* Run the program */ pc = 0; while ( ( op = aOp[pc] ) != 0 ) { switch ( op ) { case 1: case 2: case 5: { nx = 4; i = aOp[pc + 2] - 1; aOp[pc + 2] += aOp[pc + 3]; break; } case 3: case 4: default: { nx = 2; i64 i64Temp = 0; sqlite3_randomness( sizeof( i64 ), ref i64Temp ); i = (int)i64Temp; break; } } if ( ( --aOp[pc + 1] ) > 0 ) nx = 0; pc += nx; i = (int)( ( i & 0x7fffffff ) % sz ); if ( ( op & 1 ) != 0 ) { SETBIT( pV, ( i + 1 ) ); if ( op != 5 ) { if ( sqlite3BitvecSet( pBitvec, (u32)i + 1 ) != 0 ) goto bitvec_end; } } else { CLEARBIT( pV, ( i + 1 ) ); sqlite3BitvecClear( pBitvec, (u32)i + 1, pTmpSpace ); } } /* Test to make sure the linear array exactly matches the ** Bitvec object. Start with the assumption that they do ** match (rc==0). Change rc to non-zero if a discrepancy ** is found. */ rc = sqlite3BitvecTest( null, 0 ) + sqlite3BitvecTest( pBitvec, sz + 1 ) + sqlite3BitvecTest( pBitvec, 0 ) + (int)( sqlite3BitvecSize( pBitvec ) - sz ); for ( i = 1; i <= sz; i++ ) { if ( ( TESTBIT( pV, i ) ) != sqlite3BitvecTest( pBitvec, (u32)i ) ) { rc = i; break; } } /* Free allocated structure */ bitvec_end: //sqlite3_free( ref pTmpSpace ); //sqlite3_free( ref pV ); sqlite3BitvecDestroy( ref pBitvec ); return rc; } #endif //* SQLITE_OMIT_BUILTIN_TEST */ } }
// // Tests.cs // // Author: // Gabriel Burt <[email protected]> // // Copyright (C) 2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if ENABLE_TESTS using System; using System.Linq; using System.Threading; using NUnit.Framework; using Hyena; using Hyena.Tests; using Banshee.Collection.Database; using Banshee.Collection; using Banshee.ServiceStack; namespace Banshee.MediaEngine { [TestFixture] public class Tests : TestBase { PlayerEngineService service; Random rand = new Random (); [Test] public void TestMediaEngineService () { AssertTransition (null, () => service.Volume = 5, PlayerEvent.Volume); for (int i = 0; i < 3; i++) { WaitFor (PlayerState.Idle); // Assert the default, just-started-up idle state Assert.IsFalse (service.IsPlaying ()); Assert.AreEqual (null, service.CurrentTrack); Assert.AreEqual (null, service.CurrentSafeUri); LoadAndPlay ("A_boy.ogg"); Assert.AreEqual (0, service.CurrentTrack.PlayCount); for (int j = 0; j < 4; j++) { AssertTransition (() => service.Pause (), PlayerState.Paused); AssertTransition (() => service.Play (), PlayerState.Playing); Assert.IsTrue (service.IsPlaying ()); Thread.Sleep ((int) (rand.NextDouble () * 100)); } AssertTransition (() => service.Position = service.Length - 200, PlayerEvent.Seek); WaitFor (PlayerState.Idle, PlayerEvent.EndOfStream); Assert.AreEqual (1, service.CurrentTrack.PlayCount); service.Close (true); } play_when_idles = 0; Assert.AreEqual (PlayerState.Idle, service.CurrentState); service.Play (); Thread.Sleep (50); Assert.AreEqual (1, play_when_idles); Assert.AreEqual (PlayerState.Idle, service.CurrentState); LoadAndPlay ("A_boy.ogg"); AssertTransition (() => service.TrackInfoUpdated (), PlayerEvent.TrackInfoUpdated); LoadAndPlay ("A_girl.ogg"); AssertTransition (() => service.TrackInfoUpdated (), PlayerEvent.TrackInfoUpdated); AssertTransition (() => service.Dispose (), PlayerState.Paused, PlayerState.Idle); } private void LoadAndPlay (string filename) { track_intercepts = 0; var uri = new SafeUri (Paths.Combine (TestsDir, "data", filename)); var states = service.IsPlaying () ? new object [] { PlayerState.Paused, PlayerState.Idle, PlayerState.Loading } : new object [] { PlayerState.Loading }; //var states = service.IsPlaying () ? new object [] { PlayerState.Paused, PlayerState.Loading } : new object [] { PlayerState.Loading }; Log.DebugFormat ("LoadAndPlaying {0}", filename); if (rand.NextDouble () > .5) { AssertTransition (() => service.Open (new TrackInfo () { Uri = uri }), states); } else { AssertTransition (() => service.Open (uri), states); } Assert.AreEqual (1, track_intercepts); // Sleep just a bit to ensure we didn't change from Loading Thread.Sleep (30); Assert.AreEqual (PlayerState.Loading, service.CurrentState); // Assert conditions after Opening (but not actually playing) a track Assert.AreEqual (uri, service.CurrentSafeUri); Assert.IsTrue (service.CanPause); Assert.IsTrue (service.IsPlaying ()); Assert.IsTrue (service.Position == 0); Assert.IsTrue (service.IsPlaying (service.CurrentTrack)); AssertTransition (() => service.Play (), PlayerState.Loaded, PlayerEvent.StartOfStream, PlayerState.Playing); Assert.IsTrue (service.Length > 0); } private void WaitFor (PlayerState state) { WaitFor (null, state); } private void WaitFor (System.Action action, PlayerState state) { WaitFor (default_ignore, action, state); } private void WaitFor (System.Func<PlayerState?, PlayerEvent?, bool> ignore, System.Action action, PlayerState state) { if (service.CurrentState != state) { AssertTransition (ignore, action, state); } else if (action != null) { Assert.Fail (String.Format ("Already in state {0} before invoking action", state)); } } private void WaitFor (params object [] states) { WaitFor (default_ignore, states); } private void WaitFor (System.Func<PlayerState?, PlayerEvent?, bool> ignore, params object [] states) { AssertTransition (ignore, null, states); } private void AssertTransition (System.Action action, params object [] states) { // By default, ignore volume events b/c the system/stream volume stuff seems to raise them at random times AssertTransition (default_ignore, action, states); } public System.Func<PlayerState?, PlayerEvent?, bool> default_ignore = new System.Func<PlayerState?, PlayerEvent?, bool> ((s, e) => e != null && (e.Value == PlayerEvent.Volume || e.Value == PlayerEvent.RequestNextTrack) ); private void AssertTransition (System.Func<PlayerState?, PlayerEvent?, bool> ignore, System.Action action, params object [] states) { Log.DebugFormat ("AssertTransition: {0}", String.Join (", ", states.Select (s => s.ToString ()).ToArray ())); int result_count = 0; var reset_event = new ManualResetEvent (false); var handler = new PlayerEventHandler (a => { lock (states) { if (result_count < states.Length) { var sca = a as PlayerEventStateChangeArgs; var last_state = sca != null ? sca.Current : service.CurrentState; var last_event = a.Event; if (ignore != null && ignore (last_state, last_event)) { Log.DebugFormat (" > ignoring {0}/{1}", last_event, last_state); return; } if (sca == null) { Log.DebugFormat (" > {0}", a.Event); } else { Log.DebugFormat (" > {0}", last_state); } var evnt = (states[result_count] as PlayerEvent?) ?? PlayerEvent.StateChange; var state = states[result_count] as PlayerState?; result_count++; Assert.AreEqual (evnt, last_event); if (state != null) { Assert.AreEqual (state, last_state); } } } reset_event.Set (); }); service.ConnectEvent (handler); if (action != null) action (); while (result_count < states.Length) { reset_event.Reset (); if (!reset_event.WaitOne (3000)) { Assert.Fail (String.Format ("Waited 3s for state/event, didnt' happen")); break; } } service.DisconnectEvent (handler); } //[Test] //public void TestMediaEngines () //{ // * TrackInfoUpdated () // * CurrentTrack // * CurrentState // * LastState // * Volume // * CanSeek // * Position // * Length //} /*public void AssertEvent (string evnt) { var evnt_obj = service. }*/ /* TODO: test: public event EventHandler PlayWhenIdleRequest; public event TrackInterceptHandler TrackIntercept; public event Action<PlayerEngine> EngineBeforeInitialize; public event Action<PlayerEngine> EngineAfterInitialize; public PlayerEngineService () public void Dispose () public void Open (TrackInfo track) public void Open (SafeUri uri) public void SetNextTrack (TrackInfo track) public void SetNextTrack (SafeUri uri) public void OpenPlay (TrackInfo track) public void IncrementLastPlayed () public void IncrementLastPlayed (double completed) public void Close () public void Close (bool fullShutdown) public void Play () public void Pause () public void TogglePlaying () public void TrackInfoUpdated () public bool IsPlaying (TrackInfo track) public bool IsPlaying () public TrackInfo CurrentTrack { public SafeUri CurrentSafeUri { public PlayerState CurrentState { public PlayerState LastState { public ushort Volume { public uint Position { public byte Rating { public bool CanSeek { public bool CanPause { public bool SupportsEqualizer { public uint Length { public PlayerEngine ActiveEngine { public PlayerEngine DefaultEngine { public IEnumerable<PlayerEngine> Engines { public void ConnectEvent (PlayerEventHandler handler) public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask) public void ConnectEvent (PlayerEventHandler handler, bool connectAfter) public void ConnectEvent (PlayerEventHandler handler, PlayerEvent eventMask, bool connectAfter) public void DisconnectEvent (PlayerEventHandler handler) public void ModifyEvent (PlayerEvent eventMask, PlayerEventHandler handler) */ Thread main_thread; GLib.MainLoop main_loop; bool started; [TestFixtureSetUp] public void Setup () { GLib.GType.Init (); if (!GLib.Thread.Supported) { GLib.Thread.Init (); } ApplicationContext.Debugging = false; //Log.Debugging = true; Application.TimeoutHandler = RunTimeout; Application.IdleHandler = RunIdle; Application.IdleTimeoutRemoveHandler = IdleTimeoutRemove; Application.Initialize (); Mono.Addins.AddinManager.Initialize (BinDir); main_thread = new Thread (RunMainLoop); main_thread.Start (); while (!started) {} } [TestFixtureTearDown] public void Teardown () { GLib.Idle.Add (delegate { main_loop.Quit (); return false; }); main_thread.Join (); main_thread = null; } int play_when_idles = 0; int track_intercepts = 0; private void RunMainLoop () { ThreadAssist.InitializeMainThread (); ThreadAssist.ProxyToMainHandler = Banshee.ServiceStack.Application.Invoke; service = new PlayerEngineService (); service.PlayWhenIdleRequest += delegate { play_when_idles++; }; service.TrackIntercept += delegate { track_intercepts++; return false; }; // TODO call each test w/ permutations of Gapless enabled/disabled, RG enabled/disabled try { ServiceManager.RegisterService (service); } catch {} ((IInitializeService)service).Initialize (); ((IDelayedInitializeService)service).DelayedInitialize (); main_loop = new GLib.MainLoop (); started = true; main_loop.Run (); } protected uint RunTimeout (uint milliseconds, TimeoutHandler handler) { return GLib.Timeout.Add (milliseconds, delegate { return handler (); }); } protected uint RunIdle (IdleHandler handler) { return GLib.Idle.Add (delegate { return handler (); }); } protected bool IdleTimeoutRemove (uint id) { return GLib.Source.Remove (id); } } } #endif
using Kitware.VTK; using System; /// <summary> /// Class Containing Main Method /// </summary> public class StreamlinesWithLineWidgetClass { /// <summary> /// Entry Point /// </summary> /// <param name="argv"></param> public static void Main(String[] argv) { // This example demonstrates how to use the vtkLineWidget to seed // and manipulate streamlines. Two line widgets are created. One is // invoked by pressing 'W', the other by pressing 'L'. Both can exist // together. // Start by loading some data. pl3d = vtkMultiBlockPLOT3DReader.New(); pl3d.SetXYZFileName("../../../combxyz.bin"); pl3d.SetQFileName("../../../combq.bin"); pl3d.SetScalarFunctionNumber(100); pl3d.SetVectorFunctionNumber(202); pl3d.Update(); // The line widget is used seed the streamlines. lineWidget = vtkLineWidget.New(); seeds = vtkPolyData.New(); lineWidget.SetInput(pl3d.GetOutput()); lineWidget.SetAlignToYAxis(); lineWidget.PlaceWidget(); lineWidget.GetPolyData(seeds); lineWidget.ClampToBoundsOn(); rk4 = vtkRungeKutta4.New(); streamer = vtkStreamLine.New(); streamer.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0)); streamer.SetSource(seeds); streamer.SetMaximumPropagationTime(100); streamer.SetIntegrationStepLength(.2); streamer.SetStepLength(.001); streamer.SetNumberOfThreads(1); streamer.SetIntegrationDirectionToForward(); streamer.VorticityOn(); streamer.SetIntegrator(rk4); rf = vtkRibbonFilter.New(); rf.SetInputConnection(streamer.GetOutputPort()); rf.SetWidth(0.1); rf.SetWidthFactor(5); streamMapper = vtkPolyDataMapper.New(); streamMapper.SetInputConnection(rf.GetOutputPort()); streamMapper.SetScalarRange(pl3d.GetOutput().GetScalarRange()[0], pl3d.GetOutput().GetScalarRange()[1]); streamline = vtkActor.New(); streamline.SetMapper(streamMapper); streamline.VisibilityOff(); // The second line widget is used seed more streamlines. lineWidget2 = vtkLineWidget.New(); seeds2 = vtkPolyData.New(); lineWidget2.SetInput(pl3d.GetOutput()); lineWidget2.PlaceWidget(); lineWidget2.GetPolyData(seeds2); lineWidget2.SetKeyPressActivationValue((sbyte)108); streamer2 = vtkStreamLine.New(); streamer2.SetInputDaat((vtkDataSet)pl3d.GetOutput().GetBlock(0)); streamer2.SetSource(seeds2); streamer2.SetMaximumPropagationTime(100); streamer2.SetIntegrationStepLength(.2); streamer2.SetStepLength(.001); streamer2.SetNumberOfThreads(1); streamer2.SetIntegrationDirectionToForward(); streamer2.VorticityOn(); streamer2.SetIntegrator(rk4); rf2 = vtkRibbonFilter.New(); rf2.SetInputConnection(streamer2.GetOutputPort()); rf2.SetWidth(0.1); rf2.SetWidthFactor(5); streamMapper2 = vtkPolyDataMapper.New(); streamMapper2.SetInputConnection(rf2.GetOutputPort()); streamMapper2.SetScalarRange(pl3d.GetOutput().GetScalarRange()[0], pl3d.GetOutput().GetScalarRange()[1]); streamline2 = vtkActor.New(); streamline2.SetMapper(streamMapper2); streamline2.VisibilityOff(); outline = vtkStructuredGridOutlineFilter.New(); outline.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0)); outlineMapper = vtkPolyDataMapper.New(); outlineMapper.SetInputConnection(outline.GetOutputPort()); outlineActor = vtkActor.New(); outlineActor.SetMapper(outlineMapper); // Create the RenderWindow, Renderer and both Actors ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer(ren1); iren = vtkRenderWindowInteractor.New(); iren.SetRenderWindow(renWin); // Associate the line widget with the interactor lineWidget.SetInteractor(iren); lineWidget.StartInteractionEvt += new vtkObject.vtkObjectEventHandler(BeginInteraction); lineWidget.InteractionEvt += new vtkObject.vtkObjectEventHandler(GenerateStreamlines); lineWidget2.SetInteractor(iren); lineWidget2.StartInteractionEvt += new vtkObject.vtkObjectEventHandler(BeginInteraction2); lineWidget2.EndInteractionEvt += new vtkObject.vtkObjectEventHandler(GenerateStreamlines2); // Add the actors to the renderer, set the background and size ren1.AddActor(outlineActor); ren1.AddActor(streamline); ren1.AddActor(streamline2); ren1.SetBackground(1, 1, 1); renWin.SetSize(300, 300); ren1.SetBackground(0.1, 0.2, 0.4); cam1 = ren1.GetActiveCamera(); cam1.SetClippingRange(3.95297, 50); cam1.SetFocalPoint(9.71821, 0.458166, 29.3999); cam1.SetPosition(2.7439, -37.3196, 38.7167); cam1.SetViewUp(-0.16123, 0.264271, 0.950876); // render the image renWin.Render(); lineWidget2.On(); iren.Initialize(); iren.Start(); //Clean Up deleteAllVTKObjects(); } static vtkMultiBlockPLOT3DReader pl3d; static vtkLineWidget lineWidget; static vtkPolyData seeds; static vtkRungeKutta4 rk4; static vtkStreamLine streamer; static vtkRibbonFilter rf; static vtkPolyDataMapper streamMapper; static vtkActor streamline; static vtkLineWidget lineWidget2; static vtkPolyData seeds2; static vtkStreamLine streamer2; static vtkRibbonFilter rf2; static vtkPolyDataMapper streamMapper2; static vtkActor streamline2; static vtkStructuredGridOutlineFilter outline; static vtkPolyDataMapper outlineMapper; static vtkActor outlineActor; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkCamera cam1; /// <summary> /// Callback function for lineWidget.StartInteractionEvt /// </summary> public static void BeginInteraction(vtkObject sender, vtkObjectEventArgs e) { streamline.VisibilityOn(); } /// <summary> /// Callback function for lineWidget.InteractionEvt /// </summary> public static void GenerateStreamlines(vtkObject sender, vtkObjectEventArgs e) { lineWidget.GetPolyData(seeds); } /// <summary> /// Callback function for lineWidget2.StartInteractionEvt /// </summary> public static void BeginInteraction2(vtkObject sender, vtkObjectEventArgs e) { streamline2.VisibilityOn(); } /// <summary> /// Callback function for lineWidget2.InteractionEvt /// </summary> public static void GenerateStreamlines2(vtkObject sender, vtkObjectEventArgs e) { lineWidget2.GetPolyData(seeds2); renWin.Render(); } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if (pl3d != null) { pl3d.Dispose(); } if (lineWidget != null) { lineWidget.Dispose(); } if (seeds != null) { seeds.Dispose(); } if (rk4 != null) { rk4.Dispose(); } if (streamer != null) { streamer.Dispose(); } if (rf != null) { rf.Dispose(); } if (streamMapper != null) { streamMapper.Dispose(); } if (streamline != null) { streamline.Dispose(); } if (lineWidget2 != null) { lineWidget2.Dispose(); } if (seeds2 != null) { seeds2.Dispose(); } if (streamer2 != null) { streamer2.Dispose(); } if (rf2 != null) { rf2.Dispose(); } if (streamMapper2 != null) { streamMapper2.Dispose(); } if (streamline2 != null) { streamline2.Dispose(); } if (outline != null) { outline.Dispose(); } if (outlineMapper != null) { outlineMapper.Dispose(); } if (outlineActor != null) { outlineActor.Dispose(); } if (ren1 != null) { ren1.Dispose(); } if (renWin != null) { renWin.Dispose(); } if (iren != null) { iren.Dispose(); } if (cam1 != null) { cam1.Dispose(); } } } //--- end of script --//
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Diagnostics; using System.Globalization; namespace Microsoft.SqlServer.Server { // Utilities for manipulating smi-related metadata. // // Since this class is built on top of SMI, SMI should not have a dependency on this class // // These are all based off of knowing the clr type of the value // as an ExtendedClrTypeCode enum for rapid access. internal class MetaDataUtilsSmi { internal const SqlDbType InvalidSqlDbType = (SqlDbType)(-1); internal const long InvalidMaxLength = -2; // Standard type inference map to get SqlDbType when all you know is the value's type (typecode) // This map's index is off by one (add one to typecode locate correct entry) in order // to support ExtendedSqlDbType.Invalid // This array is meant to be accessed from InferSqlDbTypeFromTypeCode. private static readonly SqlDbType[] s_extendedTypeCodeToSqlDbTypeMap = { InvalidSqlDbType, // Invalid extended type code SqlDbType.Bit, // System.Boolean SqlDbType.TinyInt, // System.Byte SqlDbType.NVarChar, // System.Char SqlDbType.DateTime, // System.DateTime InvalidSqlDbType, // System.DBNull doesn't have an inferable SqlDbType SqlDbType.Decimal, // System.Decimal SqlDbType.Float, // System.Double InvalidSqlDbType, // null reference doesn't have an inferable SqlDbType SqlDbType.SmallInt, // System.Int16 SqlDbType.Int, // System.Int32 SqlDbType.BigInt, // System.Int64 InvalidSqlDbType, // System.SByte doesn't have an inferable SqlDbType SqlDbType.Real, // System.Single SqlDbType.NVarChar, // System.String InvalidSqlDbType, // System.UInt16 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.UInt32 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.UInt64 doesn't have an inferable SqlDbType InvalidSqlDbType, // System.Object doesn't have an inferable SqlDbType SqlDbType.VarBinary, // System.ByteArray SqlDbType.NVarChar, // System.CharArray SqlDbType.UniqueIdentifier, // System.Guid SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBinary SqlDbType.Bit, // System.Data.SqlTypes.SqlBoolean SqlDbType.TinyInt, // System.Data.SqlTypes.SqlByte SqlDbType.DateTime, // System.Data.SqlTypes.SqlDateTime SqlDbType.Float, // System.Data.SqlTypes.SqlDouble SqlDbType.UniqueIdentifier, // System.Data.SqlTypes.SqlGuid SqlDbType.SmallInt, // System.Data.SqlTypes.SqlInt16 SqlDbType.Int, // System.Data.SqlTypes.SqlInt32 SqlDbType.BigInt, // System.Data.SqlTypes.SqlInt64 SqlDbType.Money, // System.Data.SqlTypes.SqlMoney SqlDbType.Decimal, // System.Data.SqlTypes.SqlDecimal SqlDbType.Real, // System.Data.SqlTypes.SqlSingle SqlDbType.NVarChar, // System.Data.SqlTypes.SqlString SqlDbType.NVarChar, // System.Data.SqlTypes.SqlChars SqlDbType.VarBinary, // System.Data.SqlTypes.SqlBytes SqlDbType.Xml, // System.Data.SqlTypes.SqlXml SqlDbType.Structured, // System.Data.DataTable SqlDbType.Structured, // System.Collections.IEnumerable, used for TVPs it must return IDataRecord SqlDbType.Structured, // System.Collections.Generic.IEnumerable<Microsoft.SqlServer.Server.SqlDataRecord> SqlDbType.Time, // System.TimeSpan SqlDbType.DateTimeOffset, // System.DateTimeOffset }; // Dictionary to map from clr type object to ExtendedClrTypeCodeMap enum. // This dictionary should only be accessed from DetermineExtendedTypeCode and class ctor for setup. private static readonly Dictionary<Type, ExtendedClrTypeCode> s_typeToExtendedTypeCodeMap = CreateTypeToExtendedTypeCodeMap(); private static Dictionary<Type, ExtendedClrTypeCode> CreateTypeToExtendedTypeCodeMap() { int Count = 42; // Keep this initialization list in the same order as ExtendedClrTypeCode for ease in validating! var dictionary = new Dictionary<Type, ExtendedClrTypeCode>(Count) { { typeof(bool), ExtendedClrTypeCode.Boolean }, { typeof(byte), ExtendedClrTypeCode.Byte }, { typeof(char), ExtendedClrTypeCode.Char }, { typeof(DateTime), ExtendedClrTypeCode.DateTime }, { typeof(DBNull), ExtendedClrTypeCode.DBNull }, { typeof(decimal), ExtendedClrTypeCode.Decimal }, { typeof(double), ExtendedClrTypeCode.Double }, // lookup code will handle special-case null-ref, omitting the addition of ExtendedTypeCode.Empty { typeof(short), ExtendedClrTypeCode.Int16 }, { typeof(int), ExtendedClrTypeCode.Int32 }, { typeof(long), ExtendedClrTypeCode.Int64 }, { typeof(sbyte), ExtendedClrTypeCode.SByte }, { typeof(float), ExtendedClrTypeCode.Single }, { typeof(string), ExtendedClrTypeCode.String }, { typeof(ushort), ExtendedClrTypeCode.UInt16 }, { typeof(uint), ExtendedClrTypeCode.UInt32 }, { typeof(ulong), ExtendedClrTypeCode.UInt64 }, { typeof(object), ExtendedClrTypeCode.Object }, { typeof(byte[]), ExtendedClrTypeCode.ByteArray }, { typeof(char[]), ExtendedClrTypeCode.CharArray }, { typeof(Guid), ExtendedClrTypeCode.Guid }, { typeof(SqlBinary), ExtendedClrTypeCode.SqlBinary }, { typeof(SqlBoolean), ExtendedClrTypeCode.SqlBoolean }, { typeof(SqlByte), ExtendedClrTypeCode.SqlByte }, { typeof(SqlDateTime), ExtendedClrTypeCode.SqlDateTime }, { typeof(SqlDouble), ExtendedClrTypeCode.SqlDouble }, { typeof(SqlGuid), ExtendedClrTypeCode.SqlGuid }, { typeof(SqlInt16), ExtendedClrTypeCode.SqlInt16 }, { typeof(SqlInt32), ExtendedClrTypeCode.SqlInt32 }, { typeof(SqlInt64), ExtendedClrTypeCode.SqlInt64 }, { typeof(SqlMoney), ExtendedClrTypeCode.SqlMoney }, { typeof(SqlDecimal), ExtendedClrTypeCode.SqlDecimal }, { typeof(SqlSingle), ExtendedClrTypeCode.SqlSingle }, { typeof(SqlString), ExtendedClrTypeCode.SqlString }, { typeof(SqlChars), ExtendedClrTypeCode.SqlChars }, { typeof(SqlBytes), ExtendedClrTypeCode.SqlBytes }, { typeof(SqlXml), ExtendedClrTypeCode.SqlXml }, { typeof(DataTable), ExtendedClrTypeCode.DataTable }, { typeof(DbDataReader), ExtendedClrTypeCode.DbDataReader }, { typeof(IEnumerable<SqlDataRecord>), ExtendedClrTypeCode.IEnumerableOfSqlDataRecord }, { typeof(TimeSpan), ExtendedClrTypeCode.TimeSpan }, { typeof(DateTimeOffset), ExtendedClrTypeCode.DateTimeOffset }, }; return dictionary; } internal static bool IsCharOrXmlType(SqlDbType type) { return IsUnicodeType(type) || IsAnsiType(type) || type == SqlDbType.Xml; } internal static bool IsUnicodeType(SqlDbType type) { return type == SqlDbType.NChar || type == SqlDbType.NVarChar || type == SqlDbType.NText; } internal static bool IsAnsiType(SqlDbType type) { return type == SqlDbType.Char || type == SqlDbType.VarChar || type == SqlDbType.Text; } internal static bool IsBinaryType(SqlDbType type) { return type == SqlDbType.Binary || type == SqlDbType.VarBinary || type == SqlDbType.Image; } // Does this type use PLP format values? internal static bool IsPlpFormat(SmiMetaData metaData) { return metaData.MaxLength == SmiMetaData.UnlimitedMaxLengthIndicator || metaData.SqlDbType == SqlDbType.Image || metaData.SqlDbType == SqlDbType.NText || metaData.SqlDbType == SqlDbType.Text || metaData.SqlDbType == SqlDbType.Udt; } // If we know we're only going to use this object to assign to a specific SqlDbType back end object, // we can save some processing time by only checking for the few valid types that can be assigned to the dbType. // This assumes a switch statement over SqlDbType is faster than getting the ClrTypeCode and iterating over a // series of if statements, or using a hash table. // NOTE: the form of these checks is taking advantage of a feature of the JIT compiler that is supposed to // optimize checks of the form '(xxx.GetType() == typeof( YYY ))'. The JIT team claimed at one point that // this doesn't even instantiate a Type instance, thus was the fastest method for individual comparisons. // Given that there's a known SqlDbType, thus a minimal number of comparisons, it's likely this is faster // than the other approaches considered (both GetType().GetTypeCode() switch and hash table using Type keys // must instantiate a Type object. The typecode switch also degenerates into a large if-then-else for // all but the primitive clr types. internal static ExtendedClrTypeCode DetermineExtendedTypeCodeForUseWithSqlDbType( SqlDbType dbType, bool isMultiValued, object value, Type udtType) { ExtendedClrTypeCode extendedCode = ExtendedClrTypeCode.Invalid; // fast-track null, which is valid for all types if (null == value) { extendedCode = ExtendedClrTypeCode.Empty; } else if (DBNull.Value == value) { extendedCode = ExtendedClrTypeCode.DBNull; } else { switch (dbType) { case SqlDbType.BigInt: if (value.GetType() == typeof(long)) extendedCode = ExtendedClrTypeCode.Int64; else if (value.GetType() == typeof(SqlInt64)) extendedCode = ExtendedClrTypeCode.SqlInt64; break; case SqlDbType.Binary: case SqlDbType.VarBinary: case SqlDbType.Image: case SqlDbType.Timestamp: if (value.GetType() == typeof(byte[])) extendedCode = ExtendedClrTypeCode.ByteArray; else if (value.GetType() == typeof(SqlBinary)) extendedCode = ExtendedClrTypeCode.SqlBinary; else if (value.GetType() == typeof(SqlBytes)) extendedCode = ExtendedClrTypeCode.SqlBytes; else if (value.GetType() == typeof(StreamDataFeed)) extendedCode = ExtendedClrTypeCode.Stream; break; case SqlDbType.Bit: if (value.GetType() == typeof(bool)) extendedCode = ExtendedClrTypeCode.Boolean; else if (value.GetType() == typeof(SqlBoolean)) extendedCode = ExtendedClrTypeCode.SqlBoolean; break; case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NText: case SqlDbType.NVarChar: case SqlDbType.Text: case SqlDbType.VarChar: if (value.GetType() == typeof(string)) extendedCode = ExtendedClrTypeCode.String; if (value.GetType() == typeof(TextDataFeed)) extendedCode = ExtendedClrTypeCode.TextReader; else if (value.GetType() == typeof(SqlString)) extendedCode = ExtendedClrTypeCode.SqlString; else if (value.GetType() == typeof(char[])) extendedCode = ExtendedClrTypeCode.CharArray; else if (value.GetType() == typeof(SqlChars)) extendedCode = ExtendedClrTypeCode.SqlChars; else if (value.GetType() == typeof(char)) extendedCode = ExtendedClrTypeCode.Char; break; case SqlDbType.Date: case SqlDbType.DateTime2: case SqlDbType.DateTime: case SqlDbType.SmallDateTime: if (value.GetType() == typeof(DateTime)) extendedCode = ExtendedClrTypeCode.DateTime; else if (value.GetType() == typeof(SqlDateTime)) extendedCode = ExtendedClrTypeCode.SqlDateTime; break; case SqlDbType.Decimal: if (value.GetType() == typeof(decimal)) extendedCode = ExtendedClrTypeCode.Decimal; else if (value.GetType() == typeof(SqlDecimal)) extendedCode = ExtendedClrTypeCode.SqlDecimal; break; case SqlDbType.Real: if (value.GetType() == typeof(float)) extendedCode = ExtendedClrTypeCode.Single; else if (value.GetType() == typeof(SqlSingle)) extendedCode = ExtendedClrTypeCode.SqlSingle; break; case SqlDbType.Int: if (value.GetType() == typeof(int)) extendedCode = ExtendedClrTypeCode.Int32; else if (value.GetType() == typeof(SqlInt32)) extendedCode = ExtendedClrTypeCode.SqlInt32; break; case SqlDbType.Money: case SqlDbType.SmallMoney: if (value.GetType() == typeof(SqlMoney)) extendedCode = ExtendedClrTypeCode.SqlMoney; else if (value.GetType() == typeof(decimal)) extendedCode = ExtendedClrTypeCode.Decimal; break; case SqlDbType.Float: if (value.GetType() == typeof(SqlDouble)) extendedCode = ExtendedClrTypeCode.SqlDouble; else if (value.GetType() == typeof(double)) extendedCode = ExtendedClrTypeCode.Double; break; case SqlDbType.UniqueIdentifier: if (value.GetType() == typeof(SqlGuid)) extendedCode = ExtendedClrTypeCode.SqlGuid; else if (value.GetType() == typeof(Guid)) extendedCode = ExtendedClrTypeCode.Guid; break; case SqlDbType.SmallInt: if (value.GetType() == typeof(short)) extendedCode = ExtendedClrTypeCode.Int16; else if (value.GetType() == typeof(SqlInt16)) extendedCode = ExtendedClrTypeCode.SqlInt16; break; case SqlDbType.TinyInt: if (value.GetType() == typeof(byte)) extendedCode = ExtendedClrTypeCode.Byte; else if (value.GetType() == typeof(SqlByte)) extendedCode = ExtendedClrTypeCode.SqlByte; break; case SqlDbType.Variant: // SqlDbType doesn't help us here, call general-purpose function extendedCode = DetermineExtendedTypeCode(value); // Some types aren't allowed for Variants but are for the general-purpose function. // Match behavior of other types and return invalid in these cases. if (ExtendedClrTypeCode.SqlXml == extendedCode) { extendedCode = ExtendedClrTypeCode.Invalid; } break; case SqlDbType.Udt: // Validate UDT type if caller gave us a type to validate against if (null == udtType || value.GetType() == udtType) { extendedCode = ExtendedClrTypeCode.Object; } else { extendedCode = ExtendedClrTypeCode.Invalid; } break; case SqlDbType.Time: if (value.GetType() == typeof(TimeSpan)) extendedCode = ExtendedClrTypeCode.TimeSpan; break; case SqlDbType.DateTimeOffset: if (value.GetType() == typeof(DateTimeOffset)) extendedCode = ExtendedClrTypeCode.DateTimeOffset; break; case SqlDbType.Xml: if (value.GetType() == typeof(SqlXml)) extendedCode = ExtendedClrTypeCode.SqlXml; if (value.GetType() == typeof(XmlDataFeed)) extendedCode = ExtendedClrTypeCode.XmlReader; else if (value.GetType() == typeof(string)) extendedCode = ExtendedClrTypeCode.String; break; case SqlDbType.Structured: if (isMultiValued) { if (value is DataTable) { extendedCode = ExtendedClrTypeCode.DataTable; } else if (value is IEnumerable<SqlDataRecord>) { extendedCode = ExtendedClrTypeCode.IEnumerableOfSqlDataRecord; } else if (value is DbDataReader) { extendedCode = ExtendedClrTypeCode.DbDataReader; } } break; default: // Leave as invalid break; } } return extendedCode; } // Method to map from Type to ExtendedTypeCode internal static ExtendedClrTypeCode DetermineExtendedTypeCodeFromType(Type clrType) { ExtendedClrTypeCode resultCode; return s_typeToExtendedTypeCodeMap.TryGetValue(clrType, out resultCode) ? resultCode : ExtendedClrTypeCode.Invalid; } // Returns the ExtendedClrTypeCode that describes the given value internal static ExtendedClrTypeCode DetermineExtendedTypeCode(object value) { return value != null ? DetermineExtendedTypeCodeFromType(value.GetType()) : ExtendedClrTypeCode.Empty; } // returns a sqldbtype for the given type code internal static SqlDbType InferSqlDbTypeFromTypeCode(ExtendedClrTypeCode typeCode) { Debug.Assert(typeCode >= ExtendedClrTypeCode.Invalid && typeCode <= ExtendedClrTypeCode.Last, "Someone added a typecode without adding support here!"); return s_extendedTypeCodeToSqlDbTypeMap[(int)typeCode + 1]; } // Infer SqlDbType from Type in the general case. Katmai-only (or later) features that need to // infer types should use InferSqlDbTypeFromType_Katmai. internal static SqlDbType InferSqlDbTypeFromType(Type type) { ExtendedClrTypeCode typeCode = DetermineExtendedTypeCodeFromType(type); SqlDbType returnType; if (ExtendedClrTypeCode.Invalid == typeCode) { returnType = InvalidSqlDbType; // Return invalid type so caller can generate specific error } else { returnType = InferSqlDbTypeFromTypeCode(typeCode); } return returnType; } // Inference rules changed for Katmai-or-later-only cases. Only features that are guaranteed to be // running against Katmai and don't have backward compat issues should call this code path. // example: TVP's are a new Katmai feature (no back compat issues) so can infer DATETIME2 // when mapping System.DateTime from DateTable or DbDataReader. DATETIME2 is better because // of greater range that can handle all DateTime values. internal static SqlDbType InferSqlDbTypeFromType_Katmai(Type type) { SqlDbType returnType = InferSqlDbTypeFromType(type); if (SqlDbType.DateTime == returnType) { returnType = SqlDbType.DateTime2; } return returnType; } internal static SqlMetaData SmiExtendedMetaDataToSqlMetaData(SmiExtendedMetaData source) { if (SqlDbType.Xml == source.SqlDbType) { return new SqlMetaData(source.Name, source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, source.TypeSpecificNamePart1, source.TypeSpecificNamePart2, source.TypeSpecificNamePart3, true, source.Type); } return new SqlMetaData(source.Name, source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, null); } // Convert SqlMetaData instance to an SmiExtendedMetaData instance. internal static SmiExtendedMetaData SqlMetaDataToSmiExtendedMetaData(SqlMetaData source) { // now map everything across to the extended metadata object string typeSpecificNamePart1 = null; string typeSpecificNamePart2 = null; string typeSpecificNamePart3 = null; if (SqlDbType.Xml == source.SqlDbType) { typeSpecificNamePart1 = source.XmlSchemaCollectionDatabase; typeSpecificNamePart2 = source.XmlSchemaCollectionOwningSchema; typeSpecificNamePart3 = source.XmlSchemaCollectionName; } else if (SqlDbType.Udt == source.SqlDbType) { // Split the input name. UdtTypeName is specified as single 3 part name. // NOTE: ParseUdtTypeName throws if format is incorrect string typeName = source.ServerTypeName; if (null != typeName) { string[] names = SqlParameter.ParseTypeName(typeName, true /* isUdtTypeName */); if (1 == names.Length) { typeSpecificNamePart3 = names[0]; } else if (2 == names.Length) { typeSpecificNamePart2 = names[0]; typeSpecificNamePart3 = names[1]; } else if (3 == names.Length) { typeSpecificNamePart1 = names[0]; typeSpecificNamePart2 = names[1]; typeSpecificNamePart3 = names[2]; } else { throw ADP.ArgumentOutOfRange(nameof(typeName)); } if ((!string.IsNullOrEmpty(typeSpecificNamePart1) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart1.Length) || (!string.IsNullOrEmpty(typeSpecificNamePart2) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart2.Length) || (!string.IsNullOrEmpty(typeSpecificNamePart3) && TdsEnums.MAX_SERVERNAME < typeSpecificNamePart3.Length)) { throw ADP.ArgumentOutOfRange(nameof(typeName)); } } } return new SmiExtendedMetaData(source.SqlDbType, source.MaxLength, source.Precision, source.Scale, source.LocaleId, source.CompareOptions, null, source.Name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3); } // compare SmiMetaData to SqlMetaData and determine if they are compatible. internal static bool IsCompatible(SmiMetaData firstMd, SqlMetaData secondMd) { return firstMd.SqlDbType == secondMd.SqlDbType && firstMd.MaxLength == secondMd.MaxLength && firstMd.Precision == secondMd.Precision && firstMd.Scale == secondMd.Scale && firstMd.CompareOptions == secondMd.CompareOptions && firstMd.LocaleId == secondMd.LocaleId && firstMd.SqlDbType != SqlDbType.Structured && // SqlMetaData doesn't support Structured types !firstMd.IsMultiValued; // SqlMetaData doesn't have a "multivalued" option } // Extract metadata for a single DataColumn internal static SmiExtendedMetaData SmiMetaDataFromDataColumn(DataColumn column, DataTable parent) { SqlDbType dbType = InferSqlDbTypeFromType_Katmai(column.DataType); if (InvalidSqlDbType == dbType) { throw SQL.UnsupportedColumnTypeForSqlProvider(column.ColumnName, column.DataType.Name); } long maxLength = AdjustMaxLength(dbType, column.MaxLength); if (InvalidMaxLength == maxLength) { throw SQL.InvalidColumnMaxLength(column.ColumnName, maxLength); } byte precision; byte scale; if (column.DataType == typeof(SqlDecimal)) { // Must scan all values in column to determine best-fit precision & scale Debug.Assert(null != parent); scale = 0; byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision foreach (DataRow row in parent.Rows) { object obj = row[column]; if (!(obj is DBNull)) { SqlDecimal value = (SqlDecimal)obj; if (!value.IsNull) { byte tempNonFractPrec = checked((byte)(value.Precision - value.Scale)); if (tempNonFractPrec > nonFractionalPrecision) { nonFractionalPrecision = tempNonFractPrec; } if (value.Scale > scale) { scale = value.Scale; } } } } precision = checked((byte)(nonFractionalPrecision + scale)); if (SqlDecimal.MaxPrecision < precision) { throw SQL.InvalidTableDerivedPrecisionForTvp(column.ColumnName, precision); } else if (0 == precision) { precision = 1; } } else if (dbType == SqlDbType.DateTime2 || dbType == SqlDbType.DateTimeOffset || dbType == SqlDbType.Time) { // Time types care about scale, too. But have to infer maximums for these. precision = 0; scale = SmiMetaData.DefaultTime.Scale; } else if (dbType == SqlDbType.Decimal) { // Must scan all values in column to determine best-fit precision & scale Debug.Assert(null != parent); scale = 0; byte nonFractionalPrecision = 0; // finds largest non-Fractional portion of precision foreach (DataRow row in parent.Rows) { object obj = row[column]; if (!(obj is DBNull)) { SqlDecimal value = (SqlDecimal)(decimal)obj; byte tempNonFractPrec = checked((byte)(value.Precision - value.Scale)); if (tempNonFractPrec > nonFractionalPrecision) { nonFractionalPrecision = tempNonFractPrec; } if (value.Scale > scale) { scale = value.Scale; } } } precision = checked((byte)(nonFractionalPrecision + scale)); if (SqlDecimal.MaxPrecision < precision) { throw SQL.InvalidTableDerivedPrecisionForTvp(column.ColumnName, precision); } else if (0 == precision) { precision = 1; } } else { precision = 0; scale = 0; } // In Net Core, since DataColumn.Locale is not accessible because it is internal and in a separate assembly, // we try to get the Locale from the parent CultureInfo columnLocale = ((null != parent) ? parent.Locale : CultureInfo.CurrentCulture); return new SmiExtendedMetaData( dbType, maxLength, precision, scale, columnLocale.LCID, SmiMetaData.DefaultNVarChar.CompareOptions, null, false, // no support for multi-valued columns in a TVP yet null, // no support for structured columns yet null, // no support for structured columns yet column.ColumnName, null, null, null); } internal static long AdjustMaxLength(SqlDbType dbType, long maxLength) { if (SmiMetaData.UnlimitedMaxLengthIndicator != maxLength) { if (maxLength < 0) { maxLength = InvalidMaxLength; } switch (dbType) { case SqlDbType.Binary: if (maxLength > SmiMetaData.MaxBinaryLength) { maxLength = InvalidMaxLength; } break; case SqlDbType.Char: if (maxLength > SmiMetaData.MaxANSICharacters) { maxLength = InvalidMaxLength; } break; case SqlDbType.NChar: if (maxLength > SmiMetaData.MaxUnicodeCharacters) { maxLength = InvalidMaxLength; } break; case SqlDbType.NVarChar: // Promote to MAX type if it won't fit in a normal type if (SmiMetaData.MaxUnicodeCharacters < maxLength) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.VarBinary: // Promote to MAX type if it won't fit in a normal type if (SmiMetaData.MaxBinaryLength < maxLength) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; case SqlDbType.VarChar: // Promote to MAX type if it won't fit in a normal type if (SmiMetaData.MaxANSICharacters < maxLength) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } break; default: break; } } return maxLength; } // Map SmiMetaData from a schema table. // DEVNOTE: Since we're using SchemaTable, we can assume that we aren't directly using a SqlDataReader // so we don't support the Sql-specific stuff, like collation. internal static SmiExtendedMetaData SmiMetaDataFromSchemaTableRow(DataRow schemaRow) { string colName = ""; object temp = schemaRow[SchemaTableColumn.ColumnName]; if (DBNull.Value != temp) { colName = (string)temp; } // Determine correct SqlDbType. temp = schemaRow[SchemaTableColumn.DataType]; if (DBNull.Value == temp) { throw SQL.NullSchemaTableDataTypeNotSupported(colName); } Type colType = (Type)temp; SqlDbType colDbType = InferSqlDbTypeFromType_Katmai(colType); if (InvalidSqlDbType == colDbType) { // Unknown through standard mapping, use VarBinary for columns that are Object typed, otherwise error if (typeof(object) == colType) { colDbType = SqlDbType.VarBinary; } else { throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString()); } } // Determine metadata modifier values per type (maxlength, precision, scale, etc) long maxLength = 0; byte precision = 0; byte scale = 0; switch (colDbType) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Float: case SqlDbType.Image: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.NText: case SqlDbType.Real: case SqlDbType.UniqueIdentifier: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.Text: case SqlDbType.Timestamp: case SqlDbType.TinyInt: case SqlDbType.Variant: case SqlDbType.Xml: case SqlDbType.Date: // These types require no metadata modifies break; case SqlDbType.Binary: case SqlDbType.VarBinary: // These types need a binary max length temp = schemaRow[SchemaTableColumn.ColumnSize]; if (DBNull.Value == temp) { // source isn't specifying a size, so assume the worst if (SqlDbType.Binary == colDbType) { maxLength = SmiMetaData.MaxBinaryLength; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } } else { // We (should) have a valid maxlength, so use it. maxLength = Convert.ToInt64(temp, null); // Max length must be 0 to MaxBinaryLength or it can be UnlimitedMAX if type is varbinary. // If it's greater than MaxBinaryLength, just promote it to UnlimitedMAX, if possible. if (maxLength > SmiMetaData.MaxBinaryLength) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } if ((maxLength < 0 && (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator || SqlDbType.Binary == colDbType))) { throw SQL.InvalidColumnMaxLength(colName, maxLength); } } break; case SqlDbType.Char: case SqlDbType.VarChar: // These types need an ANSI max length temp = schemaRow[SchemaTableColumn.ColumnSize]; if (DBNull.Value == temp) { // source isn't specifying a size, so assume the worst if (SqlDbType.Char == colDbType) { maxLength = SmiMetaData.MaxANSICharacters; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } } else { // We (should) have a valid maxlength, so use it. maxLength = Convert.ToInt64(temp, null); // Max length must be 0 to MaxANSICharacters or it can be UnlimitedMAX if type is varbinary. // If it's greater than MaxANSICharacters, just promote it to UnlimitedMAX, if possible. if (maxLength > SmiMetaData.MaxANSICharacters) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } if ((maxLength < 0 && (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator || SqlDbType.Char == colDbType))) { throw SQL.InvalidColumnMaxLength(colName, maxLength); } } break; case SqlDbType.NChar: case SqlDbType.NVarChar: // These types need a unicode max length temp = schemaRow[SchemaTableColumn.ColumnSize]; if (DBNull.Value == temp) { // source isn't specifying a size, so assume the worst if (SqlDbType.NChar == colDbType) { maxLength = SmiMetaData.MaxUnicodeCharacters; } else { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } } else { // We (should) have a valid maxlength, so use it. maxLength = Convert.ToInt64(temp, null); // Max length must be 0 to MaxUnicodeCharacters or it can be UnlimitedMAX if type is varbinary. // If it's greater than MaxUnicodeCharacters, just promote it to UnlimitedMAX, if possible. if (maxLength > SmiMetaData.MaxUnicodeCharacters) { maxLength = SmiMetaData.UnlimitedMaxLengthIndicator; } if ((maxLength < 0 && (maxLength != SmiMetaData.UnlimitedMaxLengthIndicator || SqlDbType.NChar == colDbType))) { throw SQL.InvalidColumnMaxLength(colName, maxLength); } } break; case SqlDbType.Decimal: // Decimal requires precision and scale temp = schemaRow[SchemaTableColumn.NumericPrecision]; if (DBNull.Value == temp) { precision = SmiMetaData.DefaultDecimal.Precision; } else { precision = Convert.ToByte(temp, null); } temp = schemaRow[SchemaTableColumn.NumericScale]; if (DBNull.Value == temp) { scale = SmiMetaData.DefaultDecimal.Scale; } else { scale = Convert.ToByte(temp, null); } if (precision < SmiMetaData.MinPrecision || precision > SqlDecimal.MaxPrecision || scale < SmiMetaData.MinScale || scale > SqlDecimal.MaxScale || scale > precision) { throw SQL.InvalidColumnPrecScale(); } break; case SqlDbType.Time: case SqlDbType.DateTime2: case SqlDbType.DateTimeOffset: // requires scale temp = schemaRow[SchemaTableColumn.NumericScale]; if (DBNull.Value == temp) { scale = SmiMetaData.DefaultTime.Scale; } else { scale = Convert.ToByte(temp, null); } if (scale > SmiMetaData.MaxTimeScale) { throw SQL.InvalidColumnPrecScale(); } else if (scale < 0) { scale = SmiMetaData.DefaultTime.Scale; } break; case SqlDbType.Udt: case SqlDbType.Structured: default: // These types are not supported from SchemaTable throw SQL.UnsupportedColumnTypeForSqlProvider(colName, colType.ToString()); } return new SmiExtendedMetaData( colDbType, maxLength, precision, scale, System.Globalization.CultureInfo.CurrentCulture.LCID, SmiMetaData.GetDefaultForType(colDbType).CompareOptions, null, false, // no support for multi-valued columns in a TVP yet null, // no support for structured columns yet null, // no support for structured columns yet colName, null, null, null); } } }
// ------------------------------------------------------------------------ // ======================================================================== // THIS CODE AND INFORMATION ARE GENERATED BY AUTOMATIC CODE GENERATOR // ======================================================================== // Template: ViewModel.tt using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Input; using Controls=WPAppStudio.Controls; using Entities=WPAppStudio.Entities; using EntitiesBase=WPAppStudio.Entities.Base; using IServices=WPAppStudio.Services.Interfaces; using IViewModels=WPAppStudio.ViewModel.Interfaces; using Localization=WPAppStudio.Localization; using Repositories=WPAppStudio.Repositories; using Services=WPAppStudio.Services; using ViewModelsBase=WPAppStudio.ViewModel.Base; using WPAppStudio; using WPAppStudio.Shared; namespace WPAppStudio.ViewModel { /// <summary> /// Implementation of NewsFeed_Detail ViewModel. /// </summary> [CompilerGenerated] [GeneratedCode("Radarc", "4.0")] public partial class NewsFeed_DetailViewModel : ViewModelsBase.VMBase, IViewModels.INewsFeed_DetailViewModel, ViewModelsBase.INavigable { private readonly Repositories.NewsFeed_NewsFeed _newsFeed_NewsFeed; private readonly IServices.IDialogService _dialogService; private readonly IServices.INavigationService _navigationService; private readonly IServices.ISpeechService _speechService; private readonly IServices.IShareService _shareService; private readonly IServices.ILiveTileService _liveTileService; /// <summary> /// Initializes a new instance of the <see cref="NewsFeed_DetailViewModel" /> class. /// </summary> /// <param name="newsFeed_NewsFeed">The News Feed_ News Feed.</param> /// <param name="dialogService">The Dialog Service.</param> /// <param name="navigationService">The Navigation Service.</param> /// <param name="speechService">The Speech Service.</param> /// <param name="shareService">The Share Service.</param> /// <param name="liveTileService">The Live Tile Service.</param> public NewsFeed_DetailViewModel(Repositories.NewsFeed_NewsFeed newsFeed_NewsFeed, IServices.IDialogService dialogService, IServices.INavigationService navigationService, IServices.ISpeechService speechService, IServices.IShareService shareService, IServices.ILiveTileService liveTileService) { _newsFeed_NewsFeed = newsFeed_NewsFeed; _dialogService = dialogService; _navigationService = navigationService; _speechService = speechService; _shareService = shareService; _liveTileService = liveTileService; } private EntitiesBase.RssSearchResult _currentRssSearchResult; /// <summary> /// CurrentRssSearchResult property. /// </summary> public EntitiesBase.RssSearchResult CurrentRssSearchResult { get { return _currentRssSearchResult; } set { SetProperty(ref _currentRssSearchResult, value); } } private bool _hasNextpanoramaNewsFeed_Detail0; /// <summary> /// HasNextpanoramaNewsFeed_Detail0 property. /// </summary> public bool HasNextpanoramaNewsFeed_Detail0 { get { return _hasNextpanoramaNewsFeed_Detail0; } set { SetProperty(ref _hasNextpanoramaNewsFeed_Detail0, value); } } private bool _hasPreviouspanoramaNewsFeed_Detail0; /// <summary> /// HasPreviouspanoramaNewsFeed_Detail0 property. /// </summary> public bool HasPreviouspanoramaNewsFeed_Detail0 { get { return _hasPreviouspanoramaNewsFeed_Detail0; } set { SetProperty(ref _hasPreviouspanoramaNewsFeed_Detail0, value); } } /// <summary> /// Delegate method for the TextToSpeechNewsFeed_DetailStaticControlCommand command. /// </summary> public void TextToSpeechNewsFeed_DetailStaticControlCommandDelegate() { _speechService.TextToSpeech(CurrentRssSearchResult.Title + " " + CurrentRssSearchResult.Content); } private ICommand _textToSpeechNewsFeed_DetailStaticControlCommand; /// <summary> /// Gets the TextToSpeechNewsFeed_DetailStaticControlCommand command. /// </summary> public ICommand TextToSpeechNewsFeed_DetailStaticControlCommand { get { return _textToSpeechNewsFeed_DetailStaticControlCommand = _textToSpeechNewsFeed_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(TextToSpeechNewsFeed_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the ShareNewsFeed_DetailStaticControlCommand command. /// </summary> public void ShareNewsFeed_DetailStaticControlCommandDelegate() { _shareService.Share(CurrentRssSearchResult.Title, CurrentRssSearchResult.Content, CurrentRssSearchResult.FeedUrl, CurrentRssSearchResult.ImageUrl); } private ICommand _shareNewsFeed_DetailStaticControlCommand; /// <summary> /// Gets the ShareNewsFeed_DetailStaticControlCommand command. /// </summary> public ICommand ShareNewsFeed_DetailStaticControlCommand { get { return _shareNewsFeed_DetailStaticControlCommand = _shareNewsFeed_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(ShareNewsFeed_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the PinToStartNewsFeed_DetailStaticControlCommand command. /// </summary> public void PinToStartNewsFeed_DetailStaticControlCommandDelegate() { _liveTileService.PinToStart(typeof(IViewModels.INewsFeed_DetailViewModel), CreateTileInfoNewsFeed_DetailStaticControl()); } private ICommand _pinToStartNewsFeed_DetailStaticControlCommand; /// <summary> /// Gets the PinToStartNewsFeed_DetailStaticControlCommand command. /// </summary> public ICommand PinToStartNewsFeed_DetailStaticControlCommand { get { return _pinToStartNewsFeed_DetailStaticControlCommand = _pinToStartNewsFeed_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(PinToStartNewsFeed_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the GoToSourceNewsFeed_DetailStaticControlCommand command. /// </summary> public void GoToSourceNewsFeed_DetailStaticControlCommandDelegate() { _navigationService.NavigateTo(string.IsNullOrEmpty(CurrentRssSearchResult.FeedUrl) ? null : new Uri(CurrentRssSearchResult.FeedUrl)); } private ICommand _goToSourceNewsFeed_DetailStaticControlCommand; /// <summary> /// Gets the GoToSourceNewsFeed_DetailStaticControlCommand command. /// </summary> public ICommand GoToSourceNewsFeed_DetailStaticControlCommand { get { return _goToSourceNewsFeed_DetailStaticControlCommand = _goToSourceNewsFeed_DetailStaticControlCommand ?? new ViewModelsBase.DelegateCommand(GoToSourceNewsFeed_DetailStaticControlCommandDelegate); } } /// <summary> /// Delegate method for the NextpanoramaNewsFeed_Detail0 command. /// </summary> public async void NextpanoramaNewsFeed_Detail0Delegate() { LoadingCurrentRssSearchResult = true; var next = await _newsFeed_NewsFeed.Next(CurrentRssSearchResult); if(next != null) CurrentRssSearchResult = next; RefreshHasPrevNext(); } private bool _loadingCurrentRssSearchResult; public bool LoadingCurrentRssSearchResult { get { return _loadingCurrentRssSearchResult; } set { SetProperty(ref _loadingCurrentRssSearchResult, value); } } private ICommand _nextpanoramaNewsFeed_Detail0; /// <summary> /// Gets the NextpanoramaNewsFeed_Detail0 command. /// </summary> public ICommand NextpanoramaNewsFeed_Detail0 { get { return _nextpanoramaNewsFeed_Detail0 = _nextpanoramaNewsFeed_Detail0 ?? new ViewModelsBase.DelegateCommand(NextpanoramaNewsFeed_Detail0Delegate); } } /// <summary> /// Delegate method for the PreviouspanoramaNewsFeed_Detail0 command. /// </summary> public async void PreviouspanoramaNewsFeed_Detail0Delegate() { LoadingCurrentRssSearchResult = true; var prev = await _newsFeed_NewsFeed.Previous(CurrentRssSearchResult); if(prev != null) CurrentRssSearchResult = prev; RefreshHasPrevNext(); } private ICommand _previouspanoramaNewsFeed_Detail0; /// <summary> /// Gets the PreviouspanoramaNewsFeed_Detail0 command. /// </summary> public ICommand PreviouspanoramaNewsFeed_Detail0 { get { return _previouspanoramaNewsFeed_Detail0 = _previouspanoramaNewsFeed_Detail0 ?? new ViewModelsBase.DelegateCommand(PreviouspanoramaNewsFeed_Detail0Delegate); } } private async void RefreshHasPrevNext() { HasPreviouspanoramaNewsFeed_Detail0 = await _newsFeed_NewsFeed.HasPrevious(CurrentRssSearchResult); HasNextpanoramaNewsFeed_Detail0 = await _newsFeed_NewsFeed.HasNext(CurrentRssSearchResult); LoadingCurrentRssSearchResult = false; } public object NavigationContext { set { if (!(value is EntitiesBase.RssSearchResult)) { return; } CurrentRssSearchResult = value as EntitiesBase.RssSearchResult; RefreshHasPrevNext(); } } /// <summary> /// Initializes a <see cref="Services.TileInfo" /> object for the NewsFeed_DetailStaticControl control. /// </summary> /// <returns>A <see cref="Services.TileInfo" /> object.</returns> public Services.TileInfo CreateTileInfoNewsFeed_DetailStaticControl() { var tileInfo = new Services.TileInfo { CurrentId = CurrentRssSearchResult.Title, Title = CurrentRssSearchResult.Title, BackTitle = CurrentRssSearchResult.Title, BackContent = CurrentRssSearchResult.Content, Count = 0, BackgroundImagePath = CurrentRssSearchResult.ImageUrl, BackBackgroundImagePath = CurrentRssSearchResult.ImageUrl, LogoPath = "Logo-242457de-80da-42c9-9fbb-98b5451c622c.png" }; return tileInfo; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //------------------------------------------------------------------------------ using System.Data.ProviderBase; using System.Diagnostics; namespace System.Data.Common { internal sealed class DataRecordInternal : DbDataRecord { private SchemaInfo[] _schemaInfo; private object[] _values; private FieldNameLookup _fieldNameLookup; // copy all runtime data information internal DataRecordInternal(SchemaInfo[] schemaInfo, object[] values, FieldNameLookup fieldNameLookup) { Debug.Assert(null != schemaInfo, "invalid attempt to instantiate DataRecordInternal with null schema information"); Debug.Assert(null != values, "invalid attempt to instantiate DataRecordInternal with null value[]"); _schemaInfo = schemaInfo; _values = values; _fieldNameLookup = fieldNameLookup; } internal void SetSchemaInfo(SchemaInfo[] schemaInfo) { Debug.Assert(null == _schemaInfo, "invalid attempt to override DataRecordInternal schema information"); _schemaInfo = schemaInfo; } public override int FieldCount { get { return _schemaInfo.Length; } } public override int GetValues(object[] values) { if (null == values) { throw ADP.ArgumentNull("values"); } int copyLen = (values.Length < _schemaInfo.Length) ? values.Length : _schemaInfo.Length; for (int i = 0; i < copyLen; i++) { values[i] = _values[i]; } return copyLen; } public override string GetName(int i) { return _schemaInfo[i].name; } public override object GetValue(int i) { return _values[i]; } public override string GetDataTypeName(int i) { return _schemaInfo[i].typeName; } public override Type GetFieldType(int i) { return _schemaInfo[i].type; } public override int GetOrdinal(string name) { return _fieldNameLookup.GetOrdinal(name); } public override object this[int i] { get { return GetValue(i); } } public override object this[string name] { get { return GetValue(GetOrdinal(name)); } } public override bool GetBoolean(int i) { return ((bool)_values[i]); } public override byte GetByte(int i) { return ((byte)_values[i]); } public override long GetBytes(int i, long dataIndex, byte[] buffer, int bufferIndex, int length) { int cbytes = 0; int ndataIndex; byte[] data = (byte[])_values[i]; cbytes = data.Length; // since arrays can't handle 64 bit values and this interface doesn't // allow chunked access to data, a dataIndex outside the rang of Int32 // is invalid if (dataIndex > Int32.MaxValue) { throw ADP.InvalidSourceBufferIndex(cbytes, dataIndex, "dataIndex"); } ndataIndex = (int)dataIndex; // if no buffer is passed in, return the number of characters we have if (null == buffer) return cbytes; try { if (ndataIndex < cbytes) { // help the user out in the case where there's less data than requested if ((ndataIndex + length) > cbytes) cbytes = cbytes - ndataIndex; else cbytes = length; } // until arrays are 64 bit, we have to do these casts Array.Copy(data, ndataIndex, buffer, bufferIndex, (int)cbytes); } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { cbytes = data.Length; if (length < 0) throw ADP.InvalidDataLength(length); // if bad buffer index, throw if (bufferIndex < 0 || bufferIndex >= buffer.Length) throw ADP.InvalidDestinationBufferIndex(length, bufferIndex, "bufferIndex"); // if bad data index, throw if (dataIndex < 0 || dataIndex >= cbytes) throw ADP.InvalidSourceBufferIndex(length, dataIndex, "dataIndex"); // if there is not enough room in the buffer for data if (cbytes + bufferIndex > buffer.Length) throw ADP.InvalidBufferSizeOrIndex(cbytes, bufferIndex); } throw; } return cbytes; } public override char GetChar(int i) { return ((string)_values[i])[0]; } public override long GetChars(int i, long dataIndex, char[] buffer, int bufferIndex, int length) { var s = (string)_values[i]; int cchars = s.Length; // since arrays can't handle 64 bit values and this interface doesn't // allow chunked access to data, a dataIndex outside the rang of Int32 // is invalid if (dataIndex > Int32.MaxValue) { throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, "dataIndex"); } int ndataIndex = (int)dataIndex; // if no buffer is passed in, return the number of characters we have if (null == buffer) return cchars; try { if (ndataIndex < cchars) { // help the user out in the case where there's less data than requested if ((ndataIndex + length) > cchars) cchars = cchars - ndataIndex; else cchars = length; } s.CopyTo(ndataIndex, buffer, bufferIndex, cchars); } catch (Exception e) { if (ADP.IsCatchableExceptionType(e)) { cchars = s.Length; if (length < 0) throw ADP.InvalidDataLength(length); // if bad buffer index, throw if (bufferIndex < 0 || bufferIndex >= buffer.Length) throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, "bufferIndex"); // if bad data index, throw if (ndataIndex < 0 || ndataIndex >= cchars) throw ADP.InvalidSourceBufferIndex(cchars, dataIndex, "dataIndex"); // if there is not enough room in the buffer for data if (cchars + bufferIndex > buffer.Length) throw ADP.InvalidBufferSizeOrIndex(cchars, bufferIndex); } throw; } return cchars; } public override Guid GetGuid(int i) { return ((Guid)_values[i]); } public override Int16 GetInt16(int i) { return ((Int16)_values[i]); } public override Int32 GetInt32(int i) { return ((Int32)_values[i]); } public override Int64 GetInt64(int i) { return ((Int64)_values[i]); } public override float GetFloat(int i) { return ((float)_values[i]); } public override double GetDouble(int i) { return ((double)_values[i]); } public override string GetString(int i) { return ((string)_values[i]); } public override Decimal GetDecimal(int i) { return ((Decimal)_values[i]); } public override DateTime GetDateTime(int i) { return ((DateTime)_values[i]); } public override bool IsDBNull(int i) { object o = _values[i]; return (null == o || o is DBNull); } // // ICustomTypeDescriptor // } // this doesn't change per record, only alloc once internal struct SchemaInfo { public string name; public string typeName; public Type type; } }
using System; using Foundation; using AVFoundation; using CoreAnimation; using UIKit; using System.IO; using CoreAudioKit; using AudioToolbox; using CoreGraphics; namespace IQAudioRecorderController { internal class IQInternalAudioRecorderController : UIViewController { #region Fields private AVAudioRecorder m_audioRecorder; private SCSiriWaveformView mMusicFlowView; private String m_recordingFilePath; private Boolean m_isRecording; private CADisplayLink mmeterUpdateDisplayLink; private AVAudioPlayer m_audioPlayer; private Boolean m_wasPlaying; private UIView m_viewPlayerDuration; private UISlider m_playerSlider; private UILabel m_labelCurrentTime; private UILabel m_labelRemainingTime; private CADisplayLink mplayProgressDisplayLink; private String m_navigationTitle; private UIBarButtonItem m_cancelButton; private UIBarButtonItem m_doneButton; private UIBarButtonItem m_flexItem1; private UIBarButtonItem m_flexItem2; private UIBarButtonItem m_playButton; private UIBarButtonItem m_pauseButton; private UIBarButtonItem m_recordButton; private UIBarButtonItem m_trashButton; private String m_oldSessionCategory; private UIColor m_normalTintColor; private UIColor m_recordingTintColor; private UIColor m_playingTintColor; private Boolean m_ShouldShowRemainingTime; #endregion #region Properties /// <summary> /// Gets or sets a value indicating whether this /// <see cref="IQAudioRecorderController.IQInternalAudioRecorderController"/> should show remaining time. /// </summary> /// <value><c>true</c> if should show remaining time; otherwise, <c>false</c>.</value> private Boolean ShouldShowRemainingTime { get { return this.m_ShouldShowRemainingTime; } set { this.m_ShouldShowRemainingTime = value; } } /// <summary> /// Gets or sets a value indicating whether this instance cancel action. /// </summary> /// <value><c>true</c> if this instance cancel action; otherwise, <c>false</c>.</value> internal Action<IQAudioRecorderViewController> CancelControllerAction { get; set;} /// <summary> /// Gets or sets the recording complete action. /// </summary> /// <value>The recording complete action.</value> internal Action<IQAudioRecorderViewController, string> RecordingCompleteAction { get; set;} /// <summary> /// Gets/Sets the wave colour when nothing is happenening /// </summary> /// <value>The color of the normal tint.</value> public UIColor NormalTintColor { get { if (m_normalTintColor == null) m_normalTintColor = UIColor.White; return m_normalTintColor; } set { m_normalTintColor = value; } } /// <summary> /// Gets/Sets the wave colour during recording /// </summary> /// <value>The color of the recording tint.</value> public UIColor RecordingTintColor { get { if (m_recordingTintColor == null) m_recordingTintColor = UIColor.FromRGBA(0.0f/255.0f, 128.0f/255.0f,255.0f/255.0f, 1.0f); return m_recordingTintColor; } set { m_recordingTintColor = value; } } /// <summary> /// Gets/Sets the wave colour during recording /// </summary> /// <value>The color of the recording tint.</value> public UIColor PlayingTintColor { get { if (m_playingTintColor == null) m_playingTintColor = UIColor.FromRGBA(255.0f/255.0f, 64.0f/255.0f,64.0f/255.0f,1.0f); return m_playingTintColor; } set { m_playingTintColor = value; } } #endregion #region Methods /// <summary> /// Loads the view. /// </summary> public override void LoadView() { // var view = new UIView(UIScreen.MainScreen.Bounds); view.BackgroundColor = UIColor.DarkGray; mMusicFlowView = new SCSiriWaveformView(view.Bounds); mMusicFlowView.TranslatesAutoresizingMaskIntoConstraints = false; view.Add (mMusicFlowView); this.View = view; NSLayoutConstraint constraintRatio = NSLayoutConstraint.Create (mMusicFlowView, NSLayoutAttribute.Width, NSLayoutRelation.Equal, mMusicFlowView, NSLayoutAttribute.Height, 1.0f, 0.0f); NSLayoutConstraint constraintCenterX = NSLayoutConstraint.Create (mMusicFlowView,NSLayoutAttribute.CenterX ,NSLayoutRelation.Equal,view,NSLayoutAttribute.CenterX,1.0f,0.0f); NSLayoutConstraint constraintCenterY = NSLayoutConstraint.Create (mMusicFlowView,NSLayoutAttribute.CenterY,NSLayoutRelation.Equal,view,NSLayoutAttribute.CenterY,1.0f, 0.0f); NSLayoutConstraint constraintWidth = NSLayoutConstraint.Create (mMusicFlowView,NSLayoutAttribute.Width,NSLayoutRelation.Equal,view,NSLayoutAttribute.Width,1.0f,0.0f); mMusicFlowView.AddConstraint (constraintRatio); view.AddConstraints (new NSLayoutConstraint[]{constraintWidth, constraintCenterX, constraintCenterY}); } /// <summary> /// Views the did load. /// </summary> public override void ViewDidLoad() { base.ViewDidLoad (); // m_navigationTitle = @"Audio Recorder"; // this.View.TintColor = NormalTintColor; mMusicFlowView.BackgroundColor = this.View.BackgroundColor; mMusicFlowView.IdleAmplitude = 0; //Unique recording URL var fileName = NSProcessInfo.ProcessInfo.GloballyUniqueString; var documents = Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments); var tmp = Path.Combine (documents, "..", "tmp"); m_recordingFilePath = Path.Combine(tmp,String.Format("{0}.m4a",fileName)); { m_flexItem1 = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace,null,null); m_flexItem2 = new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace,null,null); var img = UIImage.FromBundle("audio_record"); m_recordButton = new UIBarButtonItem(img,UIBarButtonItemStyle.Plain,RecordingButtonAction); m_playButton = new UIBarButtonItem(UIBarButtonSystemItem.Play,PlayAction); m_pauseButton = new UIBarButtonItem(UIBarButtonSystemItem.Pause,PauseAction); m_trashButton = new UIBarButtonItem(UIBarButtonSystemItem.Trash,DeleteAction); this.SetToolbarItems (new UIBarButtonItem[]{ m_playButton, m_flexItem1, m_recordButton, m_flexItem2, m_trashButton}, false); m_playButton.Enabled = false; m_trashButton.Enabled = false; } // Define the recorder setting { var audioSettings = new AudioSettings () { Format = AudioFormatType.MPEG4AAC, SampleRate = 44100.0f, NumberChannels = 2, }; NSError err = null; m_audioRecorder = AVAudioRecorder.Create (NSUrl.FromFilename (m_recordingFilePath), audioSettings,out err); // Initiate and prepare the recorder m_audioRecorder.WeakDelegate = this; m_audioRecorder.MeteringEnabled = true; mMusicFlowView.PrimaryWaveLineWidth = 3.0f; mMusicFlowView.SecondaryWaveLineWidth = 1.0f; } //Navigation Bar Settings { this.NavigationItem.Title = @"Audio Recorder"; m_cancelButton = new UIBarButtonItem(UIBarButtonSystemItem.Cancel,CancelAction); this.NavigationItem.LeftBarButtonItem = m_cancelButton; m_doneButton = new UIBarButtonItem(UIBarButtonSystemItem.Done, DoneAction); } //Player Duration View { m_viewPlayerDuration = new UIView (); m_viewPlayerDuration.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; m_viewPlayerDuration.BackgroundColor = UIColor.Clear; m_labelCurrentTime = new UILabel (); m_labelCurrentTime.Text = NSStringExtensions.TimeStringForTimeInterval (0); m_labelCurrentTime.Font = UIFont.BoldSystemFontOfSize(14.0f); m_labelCurrentTime.TextColor = NormalTintColor; m_labelCurrentTime.TranslatesAutoresizingMaskIntoConstraints = false; m_playerSlider = new UISlider(new CGRect(0, 0, this.View.Bounds.Size.Width, 64)); m_playerSlider.MinimumTrackTintColor = PlayingTintColor; m_playerSlider.Value = 0; m_playerSlider.TouchDown += SliderStart; m_playerSlider.ValueChanged += SliderMoved; m_playerSlider.TouchUpInside += SliderEnd; m_playerSlider.TouchUpOutside += SliderEnd; m_playerSlider.TranslatesAutoresizingMaskIntoConstraints = false; m_labelRemainingTime = new UILabel(); m_labelCurrentTime.Text = NSStringExtensions.TimeStringForTimeInterval (0); m_labelRemainingTime.UserInteractionEnabled = true; m_labelRemainingTime.AddGestureRecognizer (new UITapGestureRecognizer(TapRecognizer)); m_labelRemainingTime.Font = m_labelCurrentTime.Font; m_labelRemainingTime.TextColor = m_labelCurrentTime.TextColor; m_labelRemainingTime.TranslatesAutoresizingMaskIntoConstraints = false; m_viewPlayerDuration.Add (m_labelCurrentTime); m_viewPlayerDuration.Add (m_playerSlider); m_viewPlayerDuration.Add (m_labelRemainingTime); NSLayoutConstraint constraintCurrentTimeLeading = NSLayoutConstraint.Create (m_labelCurrentTime,NSLayoutAttribute.Leading,NSLayoutRelation.Equal,m_viewPlayerDuration,NSLayoutAttribute.Leading,1.0f, 10.0f); NSLayoutConstraint constraintCurrentTimeTrailing = NSLayoutConstraint.Create (m_playerSlider,NSLayoutAttribute.Leading,NSLayoutRelation.Equal,m_labelCurrentTime,NSLayoutAttribute.Trailing,1.0f,10); NSLayoutConstraint constraintRemainingTimeLeading = NSLayoutConstraint.Create (m_labelRemainingTime,NSLayoutAttribute.Leading,NSLayoutRelation.Equal,m_playerSlider,NSLayoutAttribute.Trailing,1.0f, 10.0f); NSLayoutConstraint constraintRemainingTimeTrailing = NSLayoutConstraint.Create (m_viewPlayerDuration,NSLayoutAttribute.Trailing,NSLayoutRelation.Equal,m_labelRemainingTime,NSLayoutAttribute.Trailing,1.0f,10.0f); NSLayoutConstraint constraintCurrentTimeCenter = NSLayoutConstraint.Create (m_labelCurrentTime,NSLayoutAttribute.CenterY,NSLayoutRelation.Equal,m_viewPlayerDuration,NSLayoutAttribute.CenterY,1.0f,0.0f); NSLayoutConstraint constraintSliderCenter = NSLayoutConstraint.Create (m_playerSlider,NSLayoutAttribute.CenterY,NSLayoutRelation.Equal,m_viewPlayerDuration,NSLayoutAttribute.CenterY,1.0f,0.0f); NSLayoutConstraint constraintRemainingTimeCenter = NSLayoutConstraint.Create (m_labelRemainingTime,NSLayoutAttribute.CenterY,NSLayoutRelation.Equal,m_viewPlayerDuration,NSLayoutAttribute.CenterY,1.0f,0.0f); m_viewPlayerDuration.AddConstraints(new NSLayoutConstraint[]{constraintCurrentTimeLeading,constraintCurrentTimeTrailing,constraintRemainingTimeLeading,constraintRemainingTimeTrailing,constraintCurrentTimeCenter,constraintSliderCenter,constraintRemainingTimeCenter}); } } /// <summary> /// Views the will appear. /// </summary> /// <param name="animated">If set to <c>true</c> animated.</param> public override void ViewWillAppear(Boolean animated) { base.ViewWillAppear (animated); StartUpdatingMeter (); } /// <summary> /// Views the will disappear. /// </summary> /// <param name="animated">If set to <c>true</c> animated.</param> public override void ViewWillDisappear(Boolean animated) { base.ViewDidDisappear (animated); // if (m_audioPlayer != null) { m_audioPlayer.Delegate = null; m_audioPlayer.Stop (); m_audioPlayer = null; } if (m_audioRecorder != null) { m_audioRecorder.Delegate = null; m_audioRecorder.Stop (); m_audioRecorder = null; } StopUpdatingMeter (); } /// <summary> /// Updates the meters. /// </summary> private void UpdateMeters() { if (m_audioRecorder.Recording) { m_audioRecorder.UpdateMeters(); var normalizedValue = Math.Pow (10, m_audioRecorder.AveragePower(0) / 20); mMusicFlowView.WaveColor = RecordingTintColor; mMusicFlowView.UpdateWithLevel ((nfloat)normalizedValue); this.NavigationItem.Title = NSStringExtensions.TimeStringForTimeInterval (m_audioRecorder.currentTime); } else if (m_audioPlayer != null && m_audioPlayer.Playing) { m_audioPlayer.UpdateMeters(); var normalizedValue = Math.Pow (10, m_audioPlayer.AveragePower(0) / 20); mMusicFlowView.WaveColor = PlayingTintColor; mMusicFlowView.UpdateWithLevel ((nfloat)normalizedValue); } else { mMusicFlowView.WaveColor = NormalTintColor; mMusicFlowView.UpdateWithLevel (0); } } /// <summary> /// Starts the updating meter. /// </summary> private void StartUpdatingMeter() { if (mmeterUpdateDisplayLink != null) mmeterUpdateDisplayLink.Invalidate (); mmeterUpdateDisplayLink = CADisplayLink.Create (UpdateMeters); mmeterUpdateDisplayLink.AddToRunLoop (NSRunLoop.Current, NSRunLoopMode.Common); } /// <summary> /// Stops the updating meter. /// </summary> private void StopUpdatingMeter() { mmeterUpdateDisplayLink.Invalidate (); mmeterUpdateDisplayLink = null; } /// <summary> /// Updates the play progress. /// </summary> private void UpdatePlayProgress() { m_labelCurrentTime.Text = NSStringExtensions.TimeStringForTimeInterval(m_audioPlayer.CurrentTime); m_labelRemainingTime.Text = NSStringExtensions.TimeStringForTimeInterval((m_ShouldShowRemainingTime) ? (m_audioPlayer.Duration - m_audioPlayer.CurrentTime) : m_audioPlayer.Duration); m_playerSlider.SetValue ((float)m_audioPlayer.CurrentTime, true); } /// <summary> /// Sliders the start. /// </summary> /// <param name="item">Item.</param> /// <param name="args">Arguments.</param> private void SliderStart(object item, EventArgs args) { m_wasPlaying = m_audioPlayer.Playing; if (m_audioPlayer.Playing) { m_audioPlayer.Pause (); } } /// <summary> /// Sliders the moved. /// </summary> /// <param name="item">Item.</param> /// <param name="args">Arguments.</param> private void SliderMoved(object item, EventArgs args) { if (item is UISlider) { m_audioPlayer.CurrentTime = ((UISlider)item).Value; } } /// <summary> /// Sliders the end. /// </summary> /// <param name="item">Item.</param> /// <param name="args">Arguments.</param> private void SliderEnd(object item, EventArgs args) { if (m_wasPlaying) { m_audioPlayer.Play(); } } /// <summary> /// Taps the recognizer. /// </summary> /// <param name="gesture">Gesture.</param> private void TapRecognizer(UITapGestureRecognizer gesture) { if (gesture.State == UIGestureRecognizerState.Ended) { m_ShouldShowRemainingTime = !m_ShouldShowRemainingTime; } } private void CancelAction(object item, EventArgs args) { if (CancelControllerAction != null) { var controller = (IQAudioRecorderViewController)this.NavigationController; CancelControllerAction (controller); } this.DismissViewController (true, null); } private void DoneAction(object item, EventArgs args) { if (RecordingCompleteAction != null) { var controller = (IQAudioRecorderViewController)this.NavigationController; RecordingCompleteAction (controller, m_recordingFilePath); } this.DismissViewController (true, null); } private void RecordingButtonAction(object item, EventArgs args) { if (m_isRecording == false) { m_isRecording = true; //UI Update { this.ShowNavigationButton(false); m_recordButton.TintColor = RecordingTintColor; m_playButton.Enabled = false; m_trashButton.Enabled = false; } if (File.Exists(m_recordingFilePath)) File.Delete(m_recordingFilePath); m_oldSessionCategory = AVAudioSession.SharedInstance().Category; AVAudioSession.SharedInstance ().SetCategory (AVAudioSessionCategory.Record); m_audioRecorder.PrepareToRecord (); m_audioRecorder.Record (); } else { m_isRecording = false; //UI Update { this.ShowNavigationButton(true); m_recordButton.TintColor = NormalTintColor; m_playButton.Enabled = true; m_trashButton.Enabled = true; } m_audioRecorder.Stop(); AVAudioSession.SharedInstance ().SetCategory (new NSString(m_oldSessionCategory)); } } /// <summary> /// Plaies the action. /// </summary> /// <param name="item">Item.</param> /// <param name="args">Arguments.</param> private void PlayAction(object item, EventArgs args) { m_oldSessionCategory = AVAudioSession.SharedInstance().Category; AVAudioSession.SharedInstance ().SetCategory (AVAudioSessionCategory.Playback); // m_audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename(m_recordingFilePath)); m_audioPlayer.WeakDelegate = this; m_audioPlayer.MeteringEnabled = true; m_audioPlayer.PrepareToPlay(); m_audioPlayer.Play(); //UI Update { this.SetToolbarItems (new UIBarButtonItem[]{ m_pauseButton,m_flexItem1, m_recordButton,m_flexItem2, m_trashButton}, true); this.ShowNavigationButton (false); m_recordButton.Enabled = false; m_trashButton.Enabled = false; } //Start regular update { m_playerSlider.Value = (float)m_audioPlayer.CurrentTime; m_playerSlider.MaxValue = (float)m_audioPlayer.Duration; m_viewPlayerDuration.Frame = this.NavigationController.NavigationBar.Bounds; m_labelCurrentTime.Text = NSStringExtensions.TimeStringForTimeInterval (m_audioPlayer.CurrentTime); m_labelRemainingTime.Text = NSStringExtensions.TimeStringForTimeInterval((m_ShouldShowRemainingTime) ? (m_audioPlayer.Duration - m_audioPlayer.CurrentTime): m_audioPlayer.Duration); m_viewPlayerDuration.SetNeedsLayout(); m_viewPlayerDuration.LayoutIfNeeded(); this.NavigationItem.TitleView = m_viewPlayerDuration; if (mplayProgressDisplayLink != null) mplayProgressDisplayLink.Invalidate (); mplayProgressDisplayLink = CADisplayLink.Create (UpdatePlayProgress); mplayProgressDisplayLink.AddToRunLoop (NSRunLoop.Current, NSRunLoopMode.Common); } } /// <summary> /// Pauses the action. /// </summary> /// <param name="item">Item.</param> /// <param name="args">Arguments.</param> private void PauseAction(object item, EventArgs args) { // //UI Update { this.SetToolbarItems (new UIBarButtonItem[]{m_playButton,m_flexItem1, m_recordButton,m_flexItem2, m_trashButton }, true); this.ShowNavigationButton (true); m_recordButton.Enabled = true; m_trashButton.Enabled = true; } // { mplayProgressDisplayLink.Invalidate (); mplayProgressDisplayLink = null; this.NavigationItem.TitleView = null; } // m_audioPlayer.Delegate = null; m_audioPlayer.Stop(); m_audioPlayer = null; AVAudioSession.SharedInstance ().SetCategory(new NSString(m_oldSessionCategory)); } /// <summary> /// Deletes the action. /// </summary> /// <param name="item">Item.</param> /// <param name="args">Arguments.</param> private void DeleteAction(object item, EventArgs args) { UIActionSheet actionSheet = new UIActionSheet (String.Empty, null, "Cancel", "Delete Recording", null); actionSheet.Tag = 1; actionSheet.Clicked += delegate(object sender, UIButtonEventArgs e) { if (e.ButtonIndex == ((UIActionSheet)sender).DestructiveButtonIndex) { File.Delete(m_recordingFilePath); m_playButton.Enabled = false; m_trashButton.Enabled = false; this.NavigationItem.SetRightBarButtonItem(null,true); this.NavigationItem.Title = m_navigationTitle; } }; actionSheet.ShowInView (this.View); } /// <summary> /// Shows the navigation button. /// </summary> /// <param name="show">If set to <c>true</c> show.</param> private void ShowNavigationButton(Boolean show) { if (show) { this.NavigationItem.SetLeftBarButtonItem(m_cancelButton,true); this.NavigationItem.SetRightBarButtonItem(m_doneButton,true); } else { this.NavigationItem.SetLeftBarButtonItem(null,true); this.NavigationItem.SetRightBarButtonItem(null,true); } } [Export ("audioPlayerDidFinishPlaying:successfully:")] /// <summary> /// Audios the player did finish playing. /// </summary> /// <param name="player">Player.</param> /// <param name="flag">If set to <c>true</c> flag.</param> private void AudioPlayerDidFinishPlaying(AVAudioPlayer player, Boolean flag) { PauseAction (this, new EventArgs ()); } [Export ("audioRecorderDidFinishRecording:successfully:")] public void AudioRecorderDidFinishRecording(AVAudioRecorder recorder, Boolean flag) { } [Export ("audioRecorderEncodeErrorDidOccur:error:")] public void AudioRecorderEncodeErrorDidOccur(AVAudioRecorder recorder, NSError error) { } #endregion } }
#pragma warning disable SA1633 // File should have header - This is an imported file, // original header with license shall remain the same /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <[email protected]> * Rudi Pettazzi <[email protected]> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ using System; using System.Text; using UtfUnknown.Core.Probers.MultiByte; using UtfUnknown.Core.Probers.MultiByte.Chinese; using UtfUnknown.Core.Probers.MultiByte.Japanese; using UtfUnknown.Core.Probers.MultiByte.Korean; namespace UtfUnknown.Core.Probers; /// <summary> /// Multi-byte charsets probers /// </summary> internal class MBCSGroupProber : CharsetProber { private const int PROBERS_NUM = 8; private CharsetProber[] probers = new CharsetProber[PROBERS_NUM]; private bool[] isActive = new bool[PROBERS_NUM]; private int bestGuess; private int activeNum; public MBCSGroupProber() { this.probers[0] = new UTF8Prober(); this.probers[1] = new SJISProber(); this.probers[2] = new EUCJPProber(); this.probers[3] = new GB18030Prober(); this.probers[4] = new EUCKRProber(); this.probers[5] = new CP949Prober(); this.probers[6] = new Big5Prober(); this.probers[7] = new EUCTWProber(); this.Reset(); } public override string GetCharsetName() { if (this.bestGuess == -1) { this.GetConfidence(); if (this.bestGuess == -1) { this.bestGuess = 0; } } return this.probers[this.bestGuess] .GetCharsetName(); } public override void Reset() { this.activeNum = 0; for (var i = 0; i < this.probers.Length; i++) { if (this.probers[i] != null) { this.probers[i] .Reset(); this.isActive[i] = true; ++this.activeNum; } else { this.isActive[i] = false; } } this.bestGuess = -1; this.state = ProbingState.Detecting; } public override ProbingState HandleData( byte[] buf, int offset, int len) { // do filtering to reduce load to probers var highbyteBuf = new byte[len]; var hptr = 0; //assume previous is not ascii, it will do no harm except add some noise var keepNext = true; var max = offset + len; for (var i = offset; i < max; i++) { if ((buf[i] & 0x80) != 0) { highbyteBuf[hptr++] = buf[i]; keepNext = true; } else { //if previous is highbyte, keep this even it is a ASCII if (keepNext) { highbyteBuf[hptr++] = buf[i]; keepNext = false; } } } for (var i = 0; i < this.probers.Length; i++) { if (this.isActive[i]) { ProbingState st = this.probers[i] .HandleData( highbyteBuf, 0, hptr); if (st == ProbingState.FoundIt) { this.bestGuess = i; this.state = ProbingState.FoundIt; break; } else if (st == ProbingState.NotMe) { this.isActive[i] = false; this.activeNum--; if (this.activeNum <= 0) { this.state = ProbingState.NotMe; break; } } } } return this.state; } public override float GetConfidence(StringBuilder? status = null) { var bestConf = 0.0f; switch (this.state) { case ProbingState.FoundIt: return 0.99f; case ProbingState.NotMe: return 0.01f; default: if (status != null) { status.AppendLine($"Get confidence:"); } for (var i = 0; i < PROBERS_NUM; i++) { if (this.isActive[i]) { var cf = this.probers[i] .GetConfidence(); if (bestConf < cf) { bestConf = cf; this.bestGuess = i; if (status != null) { status.AppendLine( $"-- new match found: confidence {bestConf}, index {this.bestGuess}, charset {this.probers[i].GetCharsetName()}."); } } } } if (status != null) { status.AppendLine($"Get confidence done."); } break; } return bestConf; } public override string DumpStatus() { var status = new StringBuilder(); var cf = this.GetConfidence(status); status.AppendLine(" MBCS Group Prober --------begin status"); for (var i = 0; i < PROBERS_NUM; i++) { if (this.probers[i] != null) { if (!this.isActive[i]) { status.AppendLine( $" MBCS inactive: {this.probers[i].GetCharsetName()} (i.e. confidence is too low)."); } else { var cfp = this.probers[i] .GetConfidence(); status.AppendLine($" MBCS {cfp}: [{this.probers[i].GetCharsetName()}]"); status.AppendLine( this.probers[i] .DumpStatus()); } } } status.AppendLine( $" MBCS Group found best match [{this.probers[this.bestGuess].GetCharsetName()}] confidence {cf}."); return status.ToString(); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Buffers; using System.IO.Pipelines; using System.Runtime.CompilerServices; using System.Text.Encodings.Web; using System.Text.Unicode; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http; namespace PlatformBenchmarks { public partial class BenchmarkApplication : IHttpConnection { private State _state; public PipeReader Reader { get; set; } public PipeWriter Writer { get; set; } protected HtmlEncoder HtmlEncoder { get; } = CreateHtmlEncoder(); private HttpParser<ParsingAdapter> Parser { get; } = new HttpParser<ParsingAdapter>(); public async Task ExecuteAsync() { try { await ProcessRequestsAsync(); Reader.Complete(); } catch (Exception ex) { Reader.Complete(ex); } finally { Writer.Complete(); } } private static HtmlEncoder CreateHtmlEncoder() { var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana); settings.AllowCharacter('\u2014'); // allow EM DASH through return HtmlEncoder.Create(settings); } #if !DATABASE private async Task ProcessRequestsAsync() { while (true) { var readResult = await Reader.ReadAsync(default); var buffer = readResult.Buffer; var isCompleted = readResult.IsCompleted; if (buffer.IsEmpty && isCompleted) { return; } if (!HandleRequests(buffer, isCompleted)) { return; } await Writer.FlushAsync(default); } } private bool HandleRequests(in ReadOnlySequence<byte> buffer, bool isCompleted) { var reader = new SequenceReader<byte>(buffer); var writer = GetWriter(Writer, sizeHint: 160 * 16); // 160*16 is for Plaintext, for Json 160 would be enough while (true) { if (!ParseHttpRequest(ref reader, isCompleted)) { return false; } if (_state == State.Body) { ProcessRequest(ref writer); _state = State.StartLine; if (!reader.End) { // More input data to parse continue; } } // No more input or incomplete data, Advance the Reader Reader.AdvanceTo(reader.Position, buffer.End); break; } writer.Commit(); return true; } private bool ParseHttpRequest(ref SequenceReader<byte> reader, bool isCompleted) { var state = _state; if (state == State.StartLine) { if (Parser.ParseRequestLine(new ParsingAdapter(this), ref reader)) { state = State.Headers; } } if (state == State.Headers) { var success = Parser.ParseHeaders(new ParsingAdapter(this), ref reader); if (success) { state = State.Body; } } if (state != State.Body && isCompleted) { ThrowUnexpectedEndOfData(); } _state = state; return true; } #else private async Task ProcessRequestsAsync() { while (true) { var readResult = await Reader.ReadAsync(); var buffer = readResult.Buffer; var isCompleted = readResult.IsCompleted; if (buffer.IsEmpty && isCompleted) { return; } while (true) { if (!ParseHttpRequest(ref buffer, isCompleted)) { return; } if (_state == State.Body) { await ProcessRequestAsync(); _state = State.StartLine; if (!buffer.IsEmpty) { // More input data to parse continue; } } // No more input or incomplete data, Advance the Reader Reader.AdvanceTo(buffer.Start, buffer.End); break; } await Writer.FlushAsync(); } } private bool ParseHttpRequest(ref ReadOnlySequence<byte> buffer, bool isCompleted) { var reader = new SequenceReader<byte>(buffer); var state = _state; if (state == State.StartLine) { if (Parser.ParseRequestLine(new ParsingAdapter(this), ref reader)) { state = State.Headers; } } if (state == State.Headers) { var success = Parser.ParseHeaders(new ParsingAdapter(this), ref reader); if (success) { state = State.Body; } } if (state != State.Body && isCompleted) { ThrowUnexpectedEndOfData(); } _state = state; if (state == State.Body) { // Complete request read, consumed and examined are the same (length 0) buffer = buffer.Slice(reader.Position, 0); } else { // In-complete request read, consumed is current position and examined is the remaining. buffer = buffer.Slice(reader.Position); } return true; } #endif public void OnStaticIndexedHeader(int index) { } public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value) { } public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) { } public void OnHeadersComplete(bool endStream) { } private static void ThrowUnexpectedEndOfData() { throw new InvalidOperationException("Unexpected end of data!"); } private enum State { StartLine, Headers, Body } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static BufferWriter<WriterAdapter> GetWriter(PipeWriter pipeWriter, int sizeHint) => new BufferWriter<WriterAdapter>(new WriterAdapter(pipeWriter), sizeHint); private struct WriterAdapter : IBufferWriter<byte> { public PipeWriter Writer; public WriterAdapter(PipeWriter writer) => Writer = writer; public void Advance(int count) => Writer.Advance(count); public Memory<byte> GetMemory(int sizeHint = 0) => Writer.GetMemory(sizeHint); public Span<byte> GetSpan(int sizeHint = 0) => Writer.GetSpan(sizeHint); } private struct ParsingAdapter : IHttpRequestLineHandler, IHttpHeadersHandler { public BenchmarkApplication RequestHandler; public ParsingAdapter(BenchmarkApplication requestHandler) => RequestHandler = requestHandler; public void OnStaticIndexedHeader(int index) => RequestHandler.OnStaticIndexedHeader(index); public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value) => RequestHandler.OnStaticIndexedHeader(index, value); public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value) => RequestHandler.OnHeader(name, value); public void OnHeadersComplete(bool endStream) => RequestHandler.OnHeadersComplete(endStream); public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine) => RequestHandler.OnStartLine(versionAndMethod, targetPath, startLine); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation; using System.Net.Mail; using System.Text; namespace Microsoft.PowerShell.Commands { #region SendMailMessage /// <summary> /// Implementation for the Send-MailMessage command. /// </summary> [Obsolete("This cmdlet does not guarantee secure connections to SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do not use Send-MailMessage at this time. See https://aka.ms/SendMailMessage for more information.")] [Cmdlet(VerbsCommunications.Send, "MailMessage", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097115")] public sealed class SendMailMessage : PSCmdlet { #region Command Line Parameters /// <summary> /// Gets or sets the files names to be attached to the email. /// If the filename specified can not be found, then the relevant error /// message should be thrown. /// </summary> [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [Alias("PsPath")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Attachments { get; set; } /// <summary> /// Gets or sets the address collection that contains the /// blind carbon copy (BCC) recipients for the e-mail message. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Bcc { get; set; } /// <summary> /// Gets or sets the body (content) of the message. /// </summary> [Parameter(Position = 2, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string Body { get; set; } /// <summary> /// Gets or sets the value indicating whether the mail message body is in Html. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [Alias("BAH")] public SwitchParameter BodyAsHtml { get; set; } /// <summary> /// Gets or sets the encoding used for the content of the body and also the subject. /// This is set to ASCII to ensure there are no problems with any email server. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [Alias("BE")] [ValidateNotNullOrEmpty] [ArgumentEncodingCompletionsAttribute] [ArgumentToEncodingTransformationAttribute] public Encoding Encoding { get { return _encoding; } set { EncodingConversion.WarnIfObsolete(this, value); _encoding = value; } } private Encoding _encoding = Encoding.ASCII; /// <summary> /// Gets or sets the address collection that contains the /// carbon copy (CC) recipients for the e-mail message. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Cc")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Cc { get; set; } /// <summary> /// Gets or sets the delivery notifications options for the e-mail message. The various /// options available for this parameter are None, OnSuccess, OnFailure, Delay and Never. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [Alias("DNO")] [ValidateNotNullOrEmpty] public DeliveryNotificationOptions DeliveryNotificationOption { get; set; } /// <summary> /// Gets or sets the from address for this e-mail message. The default value for /// this parameter is the email address of the currently logged on user. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string From { get; set; } /// <summary> /// Gets or sets the name of the Host used to send the email. This host name will be assigned /// to the Powershell variable PSEmailServer, if this host can not reached an appropriate error. /// message will be displayed. /// </summary> [Parameter(Position = 3, ValueFromPipelineByPropertyName = true)] [Alias("ComputerName")] [ValidateNotNullOrEmpty] public string SmtpServer { get; set; } /// <summary> /// Gets or sets the priority of the email message. The valid values for this are Normal, High and Low. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public MailPriority Priority { get; set; } /// <summary> /// Gets or sets the Reply-To field for this e-mail message. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public string[] ReplyTo { get; set; } /// <summary> /// Gets or sets the subject of the email message. /// </summary> [Parameter(Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] [Alias("sub")] public string Subject { get; set; } /// <summary> /// Gets or sets the To address for this e-mail message. /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] To { get; set; } /// <summary> /// Gets or sets the credential for this e-mail message. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [Credential] [ValidateNotNullOrEmpty] public PSCredential Credential { get; set; } /// <summary> /// Gets or sets if Secured layer is required or not. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter UseSsl { get; set; } /// <summary> /// Gets or sets the Port to be used on the server. <see cref="SmtpServer"/> /// </summary> /// <remarks> /// Value must be greater than zero. /// </remarks> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateRange(0, int.MaxValue)] public int Port { get; set; } #endregion #region Private variables and methods // Instantiate a new instance of MailMessage private readonly MailMessage _mMailMessage = new(); private SmtpClient _mSmtpClient = null; /// <summary> /// Add the input addresses which are either string or hashtable to the MailMessage. /// It returns true if the from parameter has more than one value. /// </summary> /// <param name="address"></param> /// <param name="param"></param> private void AddAddressesToMailMessage(object address, string param) { string[] objEmailAddresses = address as string[]; foreach (string strEmailAddress in objEmailAddresses) { try { switch (param) { case "to": { _mMailMessage.To.Add(new MailAddress(strEmailAddress)); break; } case "cc": { _mMailMessage.CC.Add(new MailAddress(strEmailAddress)); break; } case "bcc": { _mMailMessage.Bcc.Add(new MailAddress(strEmailAddress)); break; } case "replyTo": { _mMailMessage.ReplyToList.Add(new MailAddress(strEmailAddress)); break; } } } catch (FormatException e) { ErrorRecord er = new(e, "FormatException", ErrorCategory.InvalidType, null); WriteError(er); continue; } } } #endregion #region Overrides /// <summary> /// BeginProcessing override. /// </summary> protected override void BeginProcessing() { try { // Set the sender address of the mail message _mMailMessage.From = new MailAddress(From); } catch (FormatException e) { ErrorRecord er = new(e, "FormatException", ErrorCategory.InvalidType, From); ThrowTerminatingError(er); } // Set the recipient address of the mail message AddAddressesToMailMessage(To, "to"); // Set the BCC address of the mail message if (Bcc != null) { AddAddressesToMailMessage(Bcc, "bcc"); } // Set the CC address of the mail message if (Cc != null) { AddAddressesToMailMessage(Cc, "cc"); } // Set the Reply-To address of the mail message if (ReplyTo != null) { AddAddressesToMailMessage(ReplyTo, "replyTo"); } // Set the delivery notification _mMailMessage.DeliveryNotificationOptions = DeliveryNotificationOption; // Set the subject of the mail message _mMailMessage.Subject = Subject; // Set the body of the mail message _mMailMessage.Body = Body; // Set the subject and body encoding _mMailMessage.SubjectEncoding = Encoding; _mMailMessage.BodyEncoding = Encoding; // Set the format of the mail message body as HTML _mMailMessage.IsBodyHtml = BodyAsHtml; // Set the priority of the mail message to normal _mMailMessage.Priority = Priority; // Get the PowerShell environment variable // globalEmailServer might be null if it is deleted by: PS> del variable:PSEmailServer PSVariable globalEmailServer = SessionState.Internal.GetVariable(SpecialVariables.PSEmailServer); if (SmtpServer == null && globalEmailServer != null) { SmtpServer = Convert.ToString(globalEmailServer.Value, CultureInfo.InvariantCulture); } if (string.IsNullOrEmpty(SmtpServer)) { ErrorRecord er = new(new InvalidOperationException(SendMailMessageStrings.HostNameValue), null, ErrorCategory.InvalidArgument, null); this.ThrowTerminatingError(er); } if (Port == 0) { _mSmtpClient = new SmtpClient(SmtpServer); } else { _mSmtpClient = new SmtpClient(SmtpServer, Port); } if (UseSsl) { _mSmtpClient.EnableSsl = true; } if (Credential != null) { _mSmtpClient.UseDefaultCredentials = false; _mSmtpClient.Credentials = Credential.GetNetworkCredential(); } else if (!UseSsl) { _mSmtpClient.UseDefaultCredentials = true; } } /// <summary> /// ProcessRecord override. /// </summary> protected override void ProcessRecord() { // Add the attachments if (Attachments != null) { string filepath = string.Empty; foreach (string attachFile in Attachments) { try { filepath = PathUtils.ResolveFilePath(attachFile, this); } catch (ItemNotFoundException e) { // NOTE: This will throw PathUtils.ReportFileOpenFailure(this, filepath, e); } Attachment mailAttachment = new(filepath); _mMailMessage.Attachments.Add(mailAttachment); } } } /// <summary> /// EndProcessing override. /// </summary> protected override void EndProcessing() { try { // Send the mail message _mSmtpClient.Send(_mMailMessage); } catch (SmtpFailedRecipientsException ex) { ErrorRecord er = new(ex, "SmtpFailedRecipientsException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } catch (SmtpException ex) { if (ex.InnerException != null) { ErrorRecord er = new(new SmtpException(ex.InnerException.Message), "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } else { ErrorRecord er = new(ex, "SmtpException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } } catch (InvalidOperationException ex) { ErrorRecord er = new(ex, "InvalidOperationException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } catch (System.Security.Authentication.AuthenticationException ex) { ErrorRecord er = new(ex, "AuthenticationException", ErrorCategory.InvalidOperation, _mSmtpClient); WriteError(er); } finally { _mSmtpClient.Dispose(); // If we don't dispose the attachments, the sender can't modify or use the files sent. _mMailMessage.Attachments.Dispose(); } } #endregion } #endregion }
namespace System.IO.BACnet; /// <summary> /// This is the standard BACNet PTP transport /// </summary> public class BacnetPtpProtocolTransport : BacnetTransportBase { public const int T_HEARTBEAT = 15000; public const int T_FRAME_ABORT = 2000; private bool _isConnected; private readonly bool _isServer; private readonly ManualResetEvent _maySend = new(false); private IBacnetSerialTransport _port; private bool _sequenceCounter; private Thread _thread; public string Password { get; set; } public BacnetPtpProtocolTransport(IBacnetSerialTransport transport, bool isServer) { _port = transport; _isServer = isServer; Type = BacnetAddressTypes.PTP; HeaderLength = PTP.PTP_HEADER_LENGTH; MaxBufferLength = 502; MaxAdpuLength = PTP.PTP_MAX_APDU; } public BacnetPtpProtocolTransport(string portName, int baudRate, bool isServer) : this(new BacnetSerialPortTransport(portName, baudRate), isServer) { } public override int Send(byte[] buffer, int offset, int dataLength, BacnetAddress address, bool waitForTransmission, int timeout) { var frameType = BacnetPtpFrameTypes.FRAME_TYPE_DATA0; if (_sequenceCounter) frameType = BacnetPtpFrameTypes.FRAME_TYPE_DATA1; _sequenceCounter = !_sequenceCounter; //add header var fullLength = PTP.Encode(buffer, offset - PTP.PTP_HEADER_LENGTH, frameType, dataLength); //wait for send allowed if (!_maySend.WaitOne(timeout)) return -BacnetMstpProtocolTransport.ETIMEDOUT; Log.Debug(frameType); //send SendWithXonXoff(buffer, offset - HeaderLength, fullLength); return dataLength; } public override BacnetAddress GetBroadcastAddress() { return new BacnetAddress(BacnetAddressTypes.PTP, 0xFFFF, new byte[0]); } public override void Start() { if (_port == null) return; _thread = new Thread(PTPThread) { Name = "PTP Read", IsBackground = true }; _thread.Start(); } public override void Dispose() { _port?.Close(); _port = null; } public override bool Equals(object obj) { if (obj is not BacnetPtpProtocolTransport) return false; var a = (BacnetPtpProtocolTransport)obj; return _port.Equals(a._port); } public override int GetHashCode() { return _port.GetHashCode(); } public override string ToString() { return _port.ToString(); } private void SendGreeting() { Log.Debug("Sending Greeting"); byte[] greeting = { PTP.PTP_GREETING_PREAMBLE1, PTP.PTP_GREETING_PREAMBLE2, 0x43, 0x6E, 0x65, 0x74, 0x0D }; // BACnet\n _port.Write(greeting, 0, greeting.Length); } private static bool IsGreeting(IList<byte> buffer, int offset, int maxOffset) { byte[] greeting = { PTP.PTP_GREETING_PREAMBLE1, PTP.PTP_GREETING_PREAMBLE2, 0x43, 0x6E, 0x65, 0x74, 0x0D }; // BACnet\n maxOffset = Math.Min(offset + greeting.Length, maxOffset); for (var i = offset; i < maxOffset; i++) if (buffer[i] != greeting[i - offset]) return false; return true; } private static void RemoveGreetingGarbage(byte[] buffer, ref int maxOffset) { while (maxOffset > 0) { while (maxOffset > 0 && buffer[0] != 0x42) { if (maxOffset > 1) Array.Copy(buffer, 1, buffer, 0, maxOffset - 1); maxOffset--; } if (maxOffset > 1 && buffer[1] != 0x41) buffer[0] = 0xFF; else if (maxOffset > 2 && buffer[2] != 0x43) buffer[0] = 0xFF; else if (maxOffset > 3 && buffer[3] != 0x6E) buffer[0] = 0xFF; else if (maxOffset > 4 && buffer[4] != 0x65) buffer[0] = 0xFF; else if (maxOffset > 5 && buffer[5] != 0x74) buffer[0] = 0xFF; else if (maxOffset > 6 && buffer[6] != 0x0D) buffer[0] = 0xFF; else break; } } private bool WaitForGreeting(int timeout) { if (_port == null) return false; var buffer = new byte[7]; var offset = 0; while (offset < 7) { var currentTimeout = offset == 0 ? timeout : T_FRAME_ABORT; var rx = _port.Read(buffer, offset, 7 - offset, currentTimeout); if (rx <= 0) return false; offset += rx; //remove garbage RemoveGreetingGarbage(buffer, ref offset); } return true; } private bool Reconnect() { _isConnected = false; _maySend.Reset(); if (_port == null) return false; try { _port.Close(); } catch { } try { _port.Open(); } catch { return false; } //connect procedure if (_isServer) { ////wait for greeting //if (!WaitForGreeting(-1)) //{ // Log.Debug("Garbage Greeting"); // return false; //} //if (StateLogging) // Log.Debug("Got Greeting"); ////request connection //SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_CONNECT_REQUEST); } else { //send greeting SendGreeting(); } _isConnected = true; return true; } private void RemoveGarbage(byte[] buffer, ref int length) { //scan for preambles for (var i = 0; i < length - 1; i++) { if ((buffer[i] != PTP.PTP_PREAMBLE1 || buffer[i + 1] != PTP.PTP_PREAMBLE2) && !IsGreeting(buffer, i, length)) continue; if (i <= 0) return; //move back Array.Copy(buffer, i, buffer, 0, length - i); length -= i; Log.Debug("Garbage"); return; } //one preamble? if (length > 0 && (buffer[length - 1] == PTP.PTP_PREAMBLE1 || buffer[length - 1] == PTP.PTP_GREETING_PREAMBLE1)) { buffer[0] = buffer[length - 1]; length = 1; Log.Debug("Garbage"); return; } //no preamble? if (length <= 0) return; length = 0; Log.Debug("Garbage"); } private static void RemoveXonOff(byte[] buffer, int offset, ref int maxOffset, ref bool complimentNext) { //X'10' (DLE) => X'10' X'90' //X'11' (XON) => X'10' X'91' //X'13' (XOFF) => X'10' X'93' for (var i = offset; i < maxOffset; i++) { if (complimentNext) { buffer[i] &= 0x7F; complimentNext = false; } else if (buffer[i] == 0x11 || buffer[i] == 0x13 || buffer[i] == 0x10) { if (buffer[i] == 0x10) complimentNext = true; if (maxOffset - i > 0) Array.Copy(buffer, i + 1, buffer, i, maxOffset - i); maxOffset--; i--; } } } private void SendWithXonXoff(byte[] buffer, int offset, int length) { var escape = new byte[1] { 0x10 }; var maxOffset = length + offset; //scan for (var i = offset; i < maxOffset; i++) { if (buffer[i] != 0x10 && buffer[i] != 0x11 && buffer[i] != 0x13) continue; _port.Write(buffer, offset, i - offset); _port.Write(escape, 0, 1); buffer[i] |= 0x80; offset = i; } //leftover _port.Write(buffer, offset, maxOffset - offset); } private void SendFrame(BacnetPtpFrameTypes frameType, byte[] buffer = null, int msgLength = 0) { if (_port == null) return; var fullLength = PTP.PTP_HEADER_LENGTH + msgLength + (msgLength > 0 ? 2 : 0); if (buffer == null) buffer = new byte[fullLength]; PTP.Encode(buffer, 0, frameType, msgLength); Log.Debug(frameType); //send SendWithXonXoff(buffer, 0, fullLength); } private void SendDisconnect(BacnetPtpDisconnectReasons bacnetPtpDisconnectReasons) { var buffer = new byte[PTP.PTP_HEADER_LENGTH + 1 + 2]; buffer[PTP.PTP_HEADER_LENGTH] = (byte)bacnetPtpDisconnectReasons; SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_DISCONNECT_REQUEST, buffer, 1); } private BacnetMstpProtocolTransport.GetMessageStatus ProcessRxStatus(byte[] buffer, ref int offset, int rx) { if (rx == -BacnetMstpProtocolTransport.ETIMEDOUT) { //drop message var status = offset == 0 ? BacnetMstpProtocolTransport.GetMessageStatus.Timeout : BacnetMstpProtocolTransport.GetMessageStatus.SubTimeout; buffer[0] = 0xFF; RemoveGarbage(buffer, ref offset); return status; } if (rx < 0) { //drop message buffer[0] = 0xFF; RemoveGarbage(buffer, ref offset); return BacnetMstpProtocolTransport.GetMessageStatus.ConnectionError; } if (rx != 0) return BacnetMstpProtocolTransport.GetMessageStatus.Good; //drop message buffer[0] = 0xFF; RemoveGarbage(buffer, ref offset); return BacnetMstpProtocolTransport.GetMessageStatus.ConnectionClose; } private BacnetMstpProtocolTransport.GetMessageStatus GetNextMessage(byte[] buffer, ref int offset, int timeoutMs, out BacnetPtpFrameTypes frameType, out int msgLength) { BacnetMstpProtocolTransport.GetMessageStatus status; var timeout = timeoutMs; frameType = BacnetPtpFrameTypes.FRAME_TYPE_HEARTBEAT_XOFF; msgLength = 0; var complimentNext = false; //fetch header while (offset < PTP.PTP_HEADER_LENGTH) { if (_port == null) return BacnetMstpProtocolTransport.GetMessageStatus.ConnectionClose; timeout = offset > 0 ? T_FRAME_ABORT : timeoutMs; //read var rx = _port.Read(buffer, offset, PTP.PTP_HEADER_LENGTH - offset, timeout); status = ProcessRxStatus(buffer, ref offset, rx); if (status != BacnetMstpProtocolTransport.GetMessageStatus.Good) return status; //remove XON/XOFF var newOffset = offset + rx; RemoveXonOff(buffer, offset, ref newOffset, ref complimentNext); offset = newOffset; //remove garbage RemoveGarbage(buffer, ref offset); } //greeting if (IsGreeting(buffer, 0, offset)) { //get last byte var rx = _port.Read(buffer, offset, 1, timeout); status = ProcessRxStatus(buffer, ref offset, rx); if (status != BacnetMstpProtocolTransport.GetMessageStatus.Good) return status; offset += 1; if (IsGreeting(buffer, 0, offset)) { frameType = BacnetPtpFrameTypes.FRAME_TYPE_GREETING; Log.Debug(frameType); return BacnetMstpProtocolTransport.GetMessageStatus.Good; } //drop message buffer[0] = 0xFF; RemoveGarbage(buffer, ref offset); return BacnetMstpProtocolTransport.GetMessageStatus.DecodeError; } //decode if (PTP.Decode(buffer, 0, offset, out frameType, out msgLength) < 0) { //drop message buffer[0] = 0xFF; RemoveGarbage(buffer, ref offset); return BacnetMstpProtocolTransport.GetMessageStatus.DecodeError; } //valid length? var fullMsgLength = msgLength + PTP.PTP_HEADER_LENGTH + (msgLength > 0 ? 2 : 0); if (msgLength > MaxBufferLength) { //drop message buffer[0] = 0xFF; RemoveGarbage(buffer, ref offset); return BacnetMstpProtocolTransport.GetMessageStatus.DecodeError; } //fetch data if (msgLength > 0) { timeout = T_FRAME_ABORT; //set sub timeout while (offset < fullMsgLength) { //read var rx = _port.Read(buffer, offset, fullMsgLength - offset, timeout); status = ProcessRxStatus(buffer, ref offset, rx); if (status != BacnetMstpProtocolTransport.GetMessageStatus.Good) return status; //remove XON/XOFF var newOffset = offset + rx; RemoveXonOff(buffer, offset, ref newOffset, ref complimentNext); offset = newOffset; } //verify data crc if (PTP.Decode(buffer, 0, offset, out frameType, out msgLength) < 0) { //drop message buffer[0] = 0xFF; RemoveGarbage(buffer, ref offset); return BacnetMstpProtocolTransport.GetMessageStatus.DecodeError; } } Log.Debug(frameType); //done return BacnetMstpProtocolTransport.GetMessageStatus.Good; } private void PTPThread() { var buffer = new byte[MaxBufferLength]; try { while (_port != null) { //connect if needed if (!_isConnected) { if (!Reconnect()) { Thread.Sleep(1000); continue; } } //read message var offset = 0; var status = GetNextMessage(buffer, ref offset, T_HEARTBEAT, out var frameType, out var msgLength); //action switch (status) { case BacnetMstpProtocolTransport.GetMessageStatus.ConnectionClose: case BacnetMstpProtocolTransport.GetMessageStatus.ConnectionError: Log.Warn("Connection disturbance"); Reconnect(); break; case BacnetMstpProtocolTransport.GetMessageStatus.DecodeError: Log.Warn("PTP decode error"); break; case BacnetMstpProtocolTransport.GetMessageStatus.SubTimeout: Log.Warn("PTP frame abort"); break; case BacnetMstpProtocolTransport.GetMessageStatus.Timeout: SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_HEARTBEAT_XON); //both server and client will send this break; case BacnetMstpProtocolTransport.GetMessageStatus.Good: //action switch (frameType) { case BacnetPtpFrameTypes.FRAME_TYPE_GREETING: //request connection SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_CONNECT_REQUEST); break; case BacnetPtpFrameTypes.FRAME_TYPE_HEARTBEAT_XON: _maySend.Set(); break; case BacnetPtpFrameTypes.FRAME_TYPE_HEARTBEAT_XOFF: _maySend.Reset(); break; case BacnetPtpFrameTypes.FRAME_TYPE_DATA0: //send confirm SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_DATA_ACK0_XON); //notify the sky! InvokeMessageRecieved(buffer, PTP.PTP_HEADER_LENGTH, msgLength, GetBroadcastAddress()); break; case BacnetPtpFrameTypes.FRAME_TYPE_DATA1: //send confirm SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_DATA_ACK1_XON); //notify the sky! InvokeMessageRecieved(buffer, PTP.PTP_HEADER_LENGTH, msgLength, GetBroadcastAddress()); break; case BacnetPtpFrameTypes.FRAME_TYPE_DATA_ACK0_XOFF: case BacnetPtpFrameTypes.FRAME_TYPE_DATA_ACK1_XOFF: //so, the other one got the message, eh? _maySend.Reset(); break; case BacnetPtpFrameTypes.FRAME_TYPE_DATA_ACK0_XON: case BacnetPtpFrameTypes.FRAME_TYPE_DATA_ACK1_XON: //so, the other one got the message, eh? _maySend.Set(); break; case BacnetPtpFrameTypes.FRAME_TYPE_DATA_NAK0_XOFF: case BacnetPtpFrameTypes.FRAME_TYPE_DATA_NAK1_XOFF: _maySend.Reset(); //denial, eh? break; case BacnetPtpFrameTypes.FRAME_TYPE_DATA_NAK0_XON: case BacnetPtpFrameTypes.FRAME_TYPE_DATA_NAK1_XON: _maySend.Set(); //denial, eh? break; case BacnetPtpFrameTypes.FRAME_TYPE_CONNECT_REQUEST: //also send a password perhaps? if (!string.IsNullOrEmpty(Password)) { var pass = Encoding.ASCII.GetBytes(Password); var tmpBuffer = new byte[PTP.PTP_HEADER_LENGTH + pass.Length + 2]; Array.Copy(pass, 0, tmpBuffer, PTP.PTP_HEADER_LENGTH, pass.Length); SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_CONNECT_RESPONSE, tmpBuffer, pass.Length); } else SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_CONNECT_RESPONSE); //we're ready SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_HEARTBEAT_XON); break; case BacnetPtpFrameTypes.FRAME_TYPE_CONNECT_RESPONSE: if (msgLength > 0 && !string.IsNullOrEmpty(Password)) { var password = Encoding.ASCII.GetString(buffer, PTP.PTP_HEADER_LENGTH, msgLength); if (password != Password) SendDisconnect(BacnetPtpDisconnectReasons.PTP_DISCONNECT_INVALID_PASSWORD); else SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_HEARTBEAT_XON); //we're ready } else { //we're ready SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_HEARTBEAT_XON); } break; case BacnetPtpFrameTypes.FRAME_TYPE_DISCONNECT_REQUEST: var reason = BacnetPtpDisconnectReasons.PTP_DISCONNECT_OTHER; if (msgLength > 0) reason = (BacnetPtpDisconnectReasons)buffer[PTP.PTP_HEADER_LENGTH]; SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_DISCONNECT_RESPONSE); Log.Debug($"Disconnect requested: {reason}"); Reconnect(); break; case BacnetPtpFrameTypes.FRAME_TYPE_DISCONNECT_RESPONSE: _maySend.Reset(); //hopefully we'll be closing down now break; case BacnetPtpFrameTypes.FRAME_TYPE_TEST_REQUEST: SendFrame(BacnetPtpFrameTypes.FRAME_TYPE_TEST_RESPONSE, buffer, msgLength); break; case BacnetPtpFrameTypes.FRAME_TYPE_TEST_RESPONSE: //good break; } break; } } Log.Debug("PTP thread is closing down"); } catch (Exception ex) { Log.Error($"Exception in PTP thread", ex); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Screens; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Replays; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.Replays; using osu.Game.Rulesets.Mania.Scoring; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Replays; using osu.Game.Rulesets.Scoring; using osu.Game.Scoring; using osu.Game.Screens.Play; using osu.Game.Tests.Visual; namespace osu.Game.Rulesets.Mania.Tests { public class TestSceneHoldNoteInput : RateAdjustedBeatmapTestScene { private const double time_before_head = 250; private const double time_head = 1500; private const double time_during_hold_1 = 2500; private const double time_tail = 4000; private const double time_after_tail = 5250; private List<JudgementResult> judgementResults; /// <summary> /// -----[ ]----- /// o o /// </summary> [Test] public void TestNoInput() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.LargeTickMiss); assertTailJudgement(HitResult.Miss); assertNoteJudgement(HitResult.IgnoreHit); } /// <summary> /// -----[ ]----- /// x o /// </summary> [Test] public void TestPressTooEarlyAndReleaseAfterTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head, ManiaAction.Key1), new ManiaReplayFrame(time_after_tail, ManiaAction.Key1), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.LargeTickMiss); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// x o /// </summary> [Test] public void TestPressTooEarlyAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head, ManiaAction.Key1), new ManiaReplayFrame(time_tail), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.LargeTickMiss); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// xo x o /// </summary> [Test] public void TestPressTooEarlyThenPressAtStartAndReleaseAfterTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head, ManiaAction.Key1), new ManiaReplayFrame(time_before_head + 10), new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.LargeTickHit); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// xo x o /// </summary> [Test] public void TestPressTooEarlyThenPressAtStartAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_before_head, ManiaAction.Key1), new ManiaReplayFrame(time_before_head + 10), new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.LargeTickHit); assertTailJudgement(HitResult.Perfect); } /// <summary> /// -----[ ]----- /// xo o /// </summary> [Test] public void TestPressAtStartAndBreak() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_head + 10), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.LargeTickMiss); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// xo x o /// </summary> [Test] public void TestPressAtStartThenBreakThenRepressAndReleaseAfterTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_head + 10), new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.LargeTickHit); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// xo x o o /// </summary> [Test] public void TestPressAtStartThenBreakThenRepressAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_head + 10), new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1), new ManiaReplayFrame(time_tail), }); assertHeadJudgement(HitResult.Perfect); assertTickJudgement(HitResult.LargeTickHit); assertTailJudgement(HitResult.Meh); } /// <summary> /// -----[ ]----- /// x o /// </summary> [Test] public void TestPressDuringNoteAndReleaseAfterTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1), new ManiaReplayFrame(time_after_tail), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.LargeTickHit); assertTailJudgement(HitResult.Miss); } /// <summary> /// -----[ ]----- /// x o o /// </summary> [Test] public void TestPressDuringNoteAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_during_hold_1, ManiaAction.Key1), new ManiaReplayFrame(time_tail), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.LargeTickHit); assertTailJudgement(HitResult.Meh); } /// <summary> /// -----[ ]----- /// xo o /// </summary> [Test] public void TestPressAndReleaseAtTail() { performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_tail, ManiaAction.Key1), new ManiaReplayFrame(time_tail + 10), }); assertHeadJudgement(HitResult.Miss); assertTickJudgement(HitResult.LargeTickMiss); assertTailJudgement(HitResult.Meh); } [Test] public void TestMissReleaseAndHitSecondRelease() { var windows = new ManiaHitWindows(); windows.SetDifficulty(10); var beatmap = new Beatmap<ManiaHitObject> { HitObjects = { new HoldNote { StartTime = 1000, Duration = 500, Column = 0, }, new HoldNote { StartTime = 1000 + 500 + windows.WindowFor(HitResult.Miss) + 10, Duration = 500, Column = 0, }, }, BeatmapInfo = { Difficulty = new BeatmapDifficulty { SliderTickRate = 4, OverallDifficulty = 10, }, Ruleset = new ManiaRuleset().RulesetInfo }, }; performTest(new List<ReplayFrame> { new ManiaReplayFrame(beatmap.HitObjects[1].StartTime, ManiaAction.Key1), new ManiaReplayFrame(beatmap.HitObjects[1].GetEndTime()), }, beatmap); AddAssert("first hold note missed", () => judgementResults.Where(j => beatmap.HitObjects[0].NestedHitObjects.Contains(j.HitObject)) .All(j => !j.Type.IsHit())); AddAssert("second hold note missed", () => judgementResults.Where(j => beatmap.HitObjects[1].NestedHitObjects.Contains(j.HitObject)) .All(j => j.Type.IsHit())); } [Test] public void TestHitTailBeforeLastTick() { const int tick_rate = 8; const double tick_spacing = TimingControlPoint.DEFAULT_BEAT_LENGTH / tick_rate; const double time_last_tick = time_head + tick_spacing * (int)((time_tail - time_head) / tick_spacing - 1); var beatmap = new Beatmap<ManiaHitObject> { HitObjects = { new HoldNote { StartTime = time_head, Duration = time_tail - time_head, Column = 0, } }, BeatmapInfo = { Difficulty = new BeatmapDifficulty { SliderTickRate = tick_rate }, Ruleset = new ManiaRuleset().RulesetInfo }, }; performTest(new List<ReplayFrame> { new ManiaReplayFrame(time_head, ManiaAction.Key1), new ManiaReplayFrame(time_last_tick - 5) }, beatmap); assertHeadJudgement(HitResult.Perfect); assertLastTickJudgement(HitResult.LargeTickMiss); assertTailJudgement(HitResult.Ok); } [Test] public void TestZeroLength() { var beatmap = new Beatmap<ManiaHitObject> { HitObjects = { new HoldNote { StartTime = 1000, Duration = 0, Column = 0, }, }, BeatmapInfo = { Ruleset = new ManiaRuleset().RulesetInfo }, }; performTest(new List<ReplayFrame> { new ManiaReplayFrame(beatmap.HitObjects[0].StartTime, ManiaAction.Key1), new ManiaReplayFrame(beatmap.HitObjects[0].GetEndTime() + 1), }, beatmap); AddAssert("hold note hit", () => judgementResults.Where(j => beatmap.HitObjects[0].NestedHitObjects.Contains(j.HitObject)) .All(j => j.Type.IsHit())); } private void assertHeadJudgement(HitResult result) => AddAssert($"head judged as {result}", () => judgementResults.First(j => j.HitObject is Note).Type == result); private void assertTailJudgement(HitResult result) => AddAssert($"tail judged as {result}", () => judgementResults.Single(j => j.HitObject is TailNote).Type == result); private void assertNoteJudgement(HitResult result) => AddAssert($"hold note judged as {result}", () => judgementResults.Single(j => j.HitObject is HoldNote).Type == result); private void assertTickJudgement(HitResult result) => AddAssert($"any tick judged as {result}", () => judgementResults.Where(j => j.HitObject is HoldNoteTick).Any(j => j.Type == result)); private void assertLastTickJudgement(HitResult result) => AddAssert($"last tick judged as {result}", () => judgementResults.Last(j => j.HitObject is HoldNoteTick).Type == result); private ScoreAccessibleReplayPlayer currentPlayer; private void performTest(List<ReplayFrame> frames, Beatmap<ManiaHitObject> beatmap = null) { if (beatmap == null) { beatmap = new Beatmap<ManiaHitObject> { HitObjects = { new HoldNote { StartTime = time_head, Duration = time_tail - time_head, Column = 0, } }, BeatmapInfo = { Difficulty = new BeatmapDifficulty { SliderTickRate = 4 }, Ruleset = new ManiaRuleset().RulesetInfo }, }; beatmap.ControlPointInfo.Add(0, new EffectControlPoint { ScrollSpeed = 0.1f }); } AddStep("load player", () => { Beatmap.Value = CreateWorkingBeatmap(beatmap); var p = new ScoreAccessibleReplayPlayer(new Score { Replay = new Replay { Frames = frames } }); p.OnLoadComplete += _ => { p.ScoreProcessor.NewJudgement += result => { if (currentPlayer == p) judgementResults.Add(result); }; }; LoadScreen(currentPlayer = p); judgementResults = new List<JudgementResult>(); }); AddUntilStep("Beatmap at 0", () => Beatmap.Value.Track.CurrentTime == 0); AddUntilStep("Wait until player is loaded", () => currentPlayer.IsCurrentScreen()); AddUntilStep("Wait for completion", () => currentPlayer.ScoreProcessor?.HasCompleted.Value == true); } private class ScoreAccessibleReplayPlayer : ReplayPlayer { public new ScoreProcessor ScoreProcessor => base.ScoreProcessor; public new GameplayClockContainer GameplayClockContainer => base.GameplayClockContainer; protected override bool PauseOnFocusLost => false; public ScoreAccessibleReplayPlayer(Score score) : base(score, new PlayerConfiguration { AllowPause = false, ShowResults = false, }) { } } } }
using System; using System.IO; using System.Diagnostics; namespace CocosSharp { public enum CCSceneResolutionPolicy { // The Viewport is not automatically calculated and it is up to the developer to take care of setting // the values correctly. Custom, // The entire application is visible in the specified area without trying to preserve the original aspect ratio. // Distortion can occur, and the application may appear stretched or compressed. ExactFit, // The entire application fills the specified area, without distortion but possibly with some cropping, // while maintaining the original aspect ratio of the application. NoBorder, // The entire application is visible in the specified area without distortion while maintaining the original // aspect ratio of the application. Borders can appear on two sides of the application. ShowAll, // The application takes the height of the design resolution size and modifies the width of the internal // canvas so that it fits the aspect ratio of the device // no distortion will occur however you must make sure your application works on different // aspect ratios FixedHeight, // The application takes the width of the design resolution size and modifies the height of the internal // canvas so that it fits the aspect ratio of the device // no distortion will occur however you must make sure your application works on different // aspect ratios FixedWidth } /// <summary> /// brief CCScene is a subclass of CCNode that is used only as an abstract concept. /// CCScene and CCNode are almost identical with the difference that CCScene has it's /// anchor point (by default) at the center of the screen. Scenes have state management /// where they can serialize their state and have it reconstructed upon resurrection. /// It is a good practice to use and CCScene as the parent of all your nodes. /// </summary> public class CCScene : CCNode { static readonly CCRect exactFitRatio = new CCRect(0, 0, 1, 1); CCViewport viewport; CCWindow window; internal event EventHandler SceneViewportChanged = delegate { }; CCSceneResolutionPolicy resolutionPolicy = CCSceneResolutionPolicy.ExactFit; #region Properties public CCSceneResolutionPolicy SceneResolutionPolicy { get { return resolutionPolicy; } set { if (value != resolutionPolicy) { resolutionPolicy = value; UpdateResolutionRatios(); Viewport.UpdateViewport(); } } } public virtual bool IsTransition { get { return false; } } #if USE_PHYSICS private CCPhysicsWorld _physicsWorld; public CCPhysicsWorld PhysicsWorld { get { return _physicsWorld; } set { _physicsWorld = value; } } #endif public CCRect VisibleBoundsScreenspace { get { return Viewport.ViewportInPixels; } } public override CCScene Scene { get { return this; } } public override CCWindow Window { get { return window; } set { if (window != value) { window = value; viewport.LandscapeScreenSizeInPixels = Window.LandscapeWindowSizeInPixels; } if (window != null) { InitializeLazySceneGraph(Children); } } } void InitializeLazySceneGraph(CCRawList<CCNode> children) { if (children == null) return; foreach (var child in children) { if (child != null) { child.AttachEvents(); child.AttachActions(); child.AttachSchedules(); InitializeLazySceneGraph(child.Children); } } } public override CCDirector Director { get; set; } public override CCCamera Camera { get { return null; } set { } } public override CCViewport Viewport { get { return viewport; } set { if (viewport != value) { // Stop listening to previous viewport's event if (viewport != null) viewport.OnViewportChanged -= OnViewportChanged; viewport = value; viewport.OnViewportChanged += OnViewportChanged; OnViewportChanged(this, null); } } } internal override CCEventDispatcher EventDispatcher { get { return Window != null ? Window.EventDispatcher : null; } } public override CCSize ContentSize { get { return CCSize.Zero; } set { } } public override CCAffineTransform AffineLocalTransform { get { return CCAffineTransform.Identity; } } #endregion Properties #region Constructors #if USE_PHYSICS public CCScene(CCWindow window, CCViewport viewport, CCDirector director = null, bool physics = false) #else public CCScene(CCWindow window, CCViewport viewport, CCDirector director = null) #endif { IgnoreAnchorPointForPosition = true; AnchorPoint = new CCPoint(0.5f, 0.5f); Viewport = viewport; Window = window; Director = (director == null) ? window.DefaultDirector : director; if (window != null && director != null) window.AddSceneDirector(director); #if USE_PHYSICS _physicsWorld = physics ? new CCPhysicsWorld(this) : null; #endif SceneResolutionPolicy = window.DesignResolutionPolicy; } #if USE_PHYSICS public CCScene(CCWindow window, CCDirector director, bool physics = false) : this(window, new CCViewport(new CCRect(0.0f, 0.0f, 1.0f, 1.0f)), director, physics) #else public CCScene(CCWindow window, CCDirector director) : this(window, new CCViewport(new CCRect(0.0f, 0.0f, 1.0f, 1.0f)), director) #endif { } #if USE_PHYSICS public CCScene(CCWindow window, bool physics = false) : this(window, window.DefaultDirector, physics) #else public CCScene(CCWindow window) : this(window, window.DefaultDirector) #endif { } #if USE_PHYSICS public CCScene(CCScene scene, bool physics = false) : this(scene.Window, scene.Viewport, scene.Director, physics) #else public CCScene(CCScene scene) : this(scene.Window, scene.Viewport, scene.Director) #endif { } #endregion Constructors #region Viewport handling void OnViewportChanged(object sender, EventArgs e) { CCViewport viewport = sender as CCViewport; if (viewport != null && viewport == Viewport) { UpdateResolutionRatios(); SceneViewportChanged(this, null); } } #endregion Viewport handling #region Resolution Policy void UpdateResolutionRatios() { if (Children != null && SceneResolutionPolicy != CCSceneResolutionPolicy.Custom) { var unionedBounds = CCRect.Zero; foreach (var child in Children) { if (child != null && child is CCLayer) { var layer = child as CCLayer; unionedBounds.Origin.X = Math.Min(unionedBounds.Origin.X, layer.VisibleBoundsWorldspace.Origin.X); unionedBounds.Origin.Y = Math.Min(unionedBounds.Origin.Y, layer.VisibleBoundsWorldspace.Origin.Y); unionedBounds.Size.Width = Math.Max(unionedBounds.MaxX, layer.VisibleBoundsWorldspace.MaxX) - unionedBounds.Origin.X; unionedBounds.Size.Height = Math.Max(unionedBounds.MaxY, layer.VisibleBoundsWorldspace.MaxY) - unionedBounds.Origin.Y; } } // Calculate viewport ratios if not set to custom //var resolutionPolicy = Scene.SceneResolutionPolicy; if (unionedBounds != CCRect.Zero) { // Calculate Landscape Ratio var viewportRect = CalculateResolutionRatio(unionedBounds, resolutionPolicy); Viewport.exactFitLandscapeRatio = viewportRect; // Calculate Portrait Ratio var portraitBounds = unionedBounds.InvertedSize; viewportRect = CalculateResolutionRatio(portraitBounds, resolutionPolicy); Viewport.exactFitPortraitRatio = viewportRect; // End Calculate viewport ratios } } } CCRect CalculateResolutionRatio(CCRect resolutionRect, CCSceneResolutionPolicy resolutionPolicy) { var width = resolutionRect.Size.Width; var height = resolutionRect.Size.Height; if (width == 0.0f || height == 0.0f) { return exactFitRatio; } var x = resolutionRect.Origin.X; var y = resolutionRect.Origin.Y; var designResolutionSize = resolutionRect.Size; var viewPortRect = CCRect.Zero; float resolutionScaleX, resolutionScaleY; // Not set anywhere right now. var frameZoomFactor = 1; var screenSize = Scene.Window.WindowSizeInPixels; resolutionScaleX = screenSize.Width / designResolutionSize.Width; resolutionScaleY = screenSize.Height / designResolutionSize.Height; if (resolutionPolicy == CCSceneResolutionPolicy.NoBorder) { resolutionScaleX = resolutionScaleY = Math.Max(resolutionScaleX, resolutionScaleY); } if (resolutionPolicy == CCSceneResolutionPolicy.ShowAll) { resolutionScaleX = resolutionScaleY = Math.Min(resolutionScaleX, resolutionScaleY); } if (resolutionPolicy == CCSceneResolutionPolicy.FixedHeight) { resolutionScaleX = resolutionScaleY; designResolutionSize.Width = (float)Math.Ceiling(screenSize.Width / resolutionScaleX); } if (resolutionPolicy == CCSceneResolutionPolicy.FixedWidth) { resolutionScaleY = resolutionScaleX; designResolutionSize.Height = (float)Math.Ceiling(screenSize.Height / resolutionScaleY); } // calculate the rect of viewport float viewPortW = designResolutionSize.Width * resolutionScaleX; float viewPortH = designResolutionSize.Height * resolutionScaleY; viewPortRect = new CCRect((screenSize.Width - viewPortW) / 2, (screenSize.Height - viewPortH) / 2, viewPortW, viewPortH); var viewportRatio = new CCRect( ((x * resolutionScaleX * frameZoomFactor + viewPortRect.Origin.X * frameZoomFactor) / screenSize.Width), ((y * resolutionScaleY * frameZoomFactor + viewPortRect.Origin.Y * frameZoomFactor) / screenSize.Height), ((width * resolutionScaleX * frameZoomFactor) / screenSize.Width), ((height * resolutionScaleY * frameZoomFactor) / screenSize.Height) ); return viewportRatio; } #endregion #if USE_PHYSICS public override void AddChild(CCNode child, int zOrder, int tag) { base.AddChild(child, zOrder, tag); AddChildToPhysicsWorld(child); } public override void Update(float dt) { base.Update(dt); if (_physicsWorld != null) _physicsWorld.Update(dt); } protected internal virtual void AddChildToPhysicsWorld(CCNode child) { if (_physicsWorld != null) { Action<CCNode> addToPhysicsWorldFunc = null; addToPhysicsWorldFunc = new Action<CCNode>(node => { if (node.PhysicsBody != null) { _physicsWorld.AddBody(node.PhysicsBody); } var children = node.Children; if (children != null) foreach (var n in children) { addToPhysicsWorldFunc(n); } }); addToPhysicsWorldFunc(child); } } #endif protected override void Draw() { CCDrawManager drawManager = Window.DrawManager; base.Draw(); drawManager.Viewport = Viewport.XnaViewport; //#if USE_PHYSICS // if (physicsWorld != null) // physicsWorld.DebugDraw(); //#endif } } }
/* ************************************************************************* ** Custom classes used by C# ************************************************************************* */ using System; using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; using i64 = System.Int64; using u32 = System.UInt32; using time_t = System.Int64; namespace System.Data.SQLite { using sqlite3_value = Sqlite3.Mem; internal partial class Sqlite3 { static int atoi(byte[] inStr) { return atoi(Encoding.UTF8.GetString(inStr, 0, inStr.Length)); } static int atoi(string inStr) { int i; for (i = 0; i < inStr.Length; i++) { if (!sqlite3Isdigit(inStr[i]) && inStr[i] != '-') break; } int result = 0; return (Int32.TryParse(inStr.Substring(0, i), out result) ? result : 0); } static void fprintf(TextWriter tw, string zFormat, params object[] ap) { tw.Write(sqlite3_mprintf(zFormat, ap)); } static void printf(string zFormat, params object[] ap) { Console.Out.Write(sqlite3_mprintf(zFormat, ap)); } //Byte Buffer Testing static int memcmp(byte[] bA, byte[] bB, int Limit) { if (bA.Length < Limit) return (bA.Length < bB.Length) ? -1 : +1; if (bB.Length < Limit) return +1; for (int i = 0; i < Limit; i++) { if (bA[i] != bB[i]) return (bA[i] < bB[i]) ? -1 : 1; } return 0; } //Byte Buffer & String Testing static int memcmp(string A, byte[] bB, int Limit) { if (A.Length < Limit) return (A.Length < bB.Length) ? -1 : +1; if (bB.Length < Limit) return +1; char[] cA = A.ToCharArray(); for (int i = 0; i < Limit; i++) { if (cA[i] != bB[i]) return (cA[i] < bB[i]) ? -1 : 1; } return 0; } //byte with Offset & String Testing static int memcmp(byte[] a, int Offset, byte[] b, int Limit) { if (a.Length < Offset + Limit) return (a.Length - Offset < b.Length) ? -1 : +1; if (b.Length < Limit) return +1; for (int i = 0; i < Limit; i++) { if (a[i + Offset] != b[i]) return (a[i + Offset] < b[i]) ? -1 : 1; } return 0; } //byte with Offset & String Testing static int memcmp(byte[] a, int Aoffset, byte[] b, int Boffset, int Limit) { if (a.Length < Aoffset + Limit) return (a.Length - Aoffset < b.Length - Boffset) ? -1 : +1; if (b.Length < Boffset + Limit) return +1; for (int i = 0; i < Limit; i++) { if (a[i + Aoffset] != b[i + Boffset]) return (a[i + Aoffset] < b[i + Boffset]) ? -1 : 1; } return 0; } static int memcmp(byte[] a, int Offset, string b, int Limit) { if (a.Length < Offset + Limit) return (a.Length - Offset < b.Length) ? -1 : +1; if (b.Length < Limit) return +1; for (int i = 0; i < Limit; i++) { if (a[i + Offset] != b[i]) return (a[i + Offset] < b[i]) ? -1 : 1; } return 0; } //String Testing static int memcmp(string A, string B, int Limit) { if (A.Length < Limit) return (A.Length < B.Length) ? -1 : +1; if (B.Length < Limit) return +1; int rc; if ((rc = String.Compare(A, 0, B, 0, Limit, StringComparison.Ordinal)) == 0) return 0; return rc < 0 ? -1 : +1; } // ---------------------------- // ** Builtin Functions // ---------------------------- static Regex oRegex = null; /* ** The regexp() function. two arguments are both strings ** Collating sequences are not used. */ static void regexpFunc( sqlite3_context context, int argc, sqlite3_value[] argv ) { string zTest; /* The input string A */ string zRegex; /* The regex string B */ Debug.Assert(argc == 2); UNUSED_PARAMETER(argc); zRegex = sqlite3_value_text(argv[0]); zTest = sqlite3_value_text(argv[1]); if (zTest == null || String.IsNullOrEmpty(zRegex)) { sqlite3_result_int(context, 0); return; } if (oRegex == null || oRegex.ToString() == zRegex) { oRegex = new Regex(zRegex, RegexOptions.IgnoreCase); } sqlite3_result_int(context, oRegex.IsMatch(zTest) ? 1 : 0); } // ---------------------------- // ** Convertion routines // ---------------------------- static Object lock_va_list = new Object(); static string vaFORMAT; static int vaNEXT; static void va_start(object[] ap, string zFormat) { vaFORMAT = zFormat; vaNEXT = 0; } static Boolean va_arg(object[] ap, Boolean sysType) { return Convert.ToBoolean(ap[vaNEXT++]); } static Byte[] va_arg(object[] ap, Byte[] sysType) { return (Byte[])ap[vaNEXT++]; } static Byte[][] va_arg(object[] ap, Byte[][] sysType) { if (ap[vaNEXT] == null) { { vaNEXT++; return null; } } else { return (Byte[][])ap[vaNEXT++]; } } static Char va_arg(object[] ap, Char sysType) { if (ap[vaNEXT] is Int32 && (int)ap[vaNEXT] == 0) { vaNEXT++; return (char)'0'; } else { if (ap[vaNEXT] is Int64) if ((i64)ap[vaNEXT] == 0) { vaNEXT++; return (char)'0'; } else return (char)((i64)ap[vaNEXT++]); else return (char)ap[vaNEXT++]; } } static Double va_arg(object[] ap, Double sysType) { return Convert.ToDouble(ap[vaNEXT++]); } static dxLog va_arg(object[] ap, dxLog sysType) { return (dxLog)ap[vaNEXT++]; } static Int64 va_arg(object[] ap, Int64 sysType) { if (ap[vaNEXT] is System.Int64) return Convert.ToInt64(ap[vaNEXT++]); else return (Int64)(ap[vaNEXT++].GetHashCode()); } static Int32 va_arg(object[] ap, Int32 sysType) { if (Convert.ToInt64(ap[vaNEXT]) > 0 && (Convert.ToUInt32(ap[vaNEXT]) > Int32.MaxValue)) return (Int32)(Convert.ToUInt32(ap[vaNEXT++]) - System.UInt32.MaxValue - 1); else return (Int32)Convert.ToInt32(ap[vaNEXT++]); } static Int32[] va_arg(object[] ap, Int32[] sysType) { if (ap[vaNEXT] == null) { { vaNEXT++; return null; } } else { return (Int32[])ap[vaNEXT++]; } } static MemPage va_arg(object[] ap, MemPage sysType) { return (MemPage)ap[vaNEXT++]; } static Object va_arg(object[] ap, Object sysType) { return (Object)ap[vaNEXT++]; } static sqlite3 va_arg(object[] ap, sqlite3 sysType) { return (sqlite3)ap[vaNEXT++]; } static sqlite3_mem_methods va_arg(object[] ap, sqlite3_mem_methods sysType) { return (sqlite3_mem_methods)ap[vaNEXT++]; } static sqlite3_mutex_methods va_arg(object[] ap, sqlite3_mutex_methods sysType) { return (sqlite3_mutex_methods)ap[vaNEXT++]; } static SrcList va_arg(object[] ap, SrcList sysType) { return (SrcList)ap[vaNEXT++]; } static String va_arg(object[] ap, String sysType) { if (ap.Length < vaNEXT - 1 || ap[vaNEXT] == null) { vaNEXT++; return "NULL"; } else { if (ap[vaNEXT] is Byte[]) if (Encoding.UTF8.GetString((byte[])ap[vaNEXT], 0, ((byte[])ap[vaNEXT]).Length) == "\0") { vaNEXT++; return ""; } else return Encoding.UTF8.GetString((byte[])ap[vaNEXT], 0, ((byte[])ap[vaNEXT++]).Length); else if (ap[vaNEXT] is Int32) { vaNEXT++; return null; } else if (ap[vaNEXT] is StringBuilder) return (String)ap[vaNEXT++].ToString(); else if (ap[vaNEXT] is Char) return ((Char)ap[vaNEXT++]).ToString(); else return (String)ap[vaNEXT++]; } } static Token va_arg(object[] ap, Token sysType) { return (Token)ap[vaNEXT++]; } static UInt32 va_arg(object[] ap, UInt32 sysType) { if (ap[vaNEXT].GetType().IsClass) { return (UInt32)ap[vaNEXT++].GetHashCode(); } else { return (UInt32)Convert.ToUInt32(ap[vaNEXT++]); } } static UInt64 va_arg(object[] ap, UInt64 sysType) { if (ap[vaNEXT].GetType().IsClass) { return (UInt64)ap[vaNEXT++].GetHashCode(); } else { return (UInt64)Convert.ToUInt64(ap[vaNEXT++]); } } static void_function va_arg(object[] ap, void_function sysType) { return (void_function)ap[vaNEXT++]; } static void va_end(ref string[] ap) { ap = null; vaNEXT = -1; vaFORMAT = ""; } static void va_end(ref object[] ap) { ap = null; vaNEXT = -1; vaFORMAT = ""; } public static tm localtime(time_t baseTime) { System.DateTime RefTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); RefTime = RefTime.AddSeconds(Convert.ToDouble(baseTime)).ToLocalTime(); tm tm = new tm(); tm.tm_sec = RefTime.Second; tm.tm_min = RefTime.Minute; tm.tm_hour = RefTime.Hour; tm.tm_mday = RefTime.Day; tm.tm_mon = RefTime.Month; tm.tm_year = RefTime.Year; tm.tm_wday = (int)RefTime.DayOfWeek; tm.tm_yday = RefTime.DayOfYear; tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0; return tm; } public static long ToUnixtime(System.DateTime date) { System.DateTime unixStartTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); System.TimeSpan timeSpan = date - unixStartTime; return Convert.ToInt64(timeSpan.TotalSeconds); } public static System.DateTime ToCSharpTime(long unixTime) { System.DateTime unixStartTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0); return unixStartTime.AddSeconds(Convert.ToDouble(unixTime)); } public class tm { public int tm_sec; /* seconds after the minute - [0,59] */ public int tm_min; /* minutes after the hour - [0,59] */ public int tm_hour; /* hours since midnight - [0,23] */ public int tm_mday; /* day of the month - [1,31] */ public int tm_mon; /* months since January - [0,11] */ public int tm_year; /* years since 1900 */ public int tm_wday; /* days since Sunday - [0,6] */ public int tm_yday; /* days since January 1 - [0,365] */ public int tm_isdst; /* daylight savings time flag */ }; public struct FILETIME { public u32 dwLowDateTime; public u32 dwHighDateTime; } // Example (C#) public static int GetbytesPerSector(StringBuilder diskPath) { return 4096; } static void SWAP<T>(ref T A, ref T B) { T t = A; A = B; B = t; } static void x_CountStep( sqlite3_context context, int argc, sqlite3_value[] argv ) { SumCtx p; int type; Debug.Assert(argc <= 1); Mem pMem = sqlite3_aggregate_context(context, 1);//sizeof(*p)); if (pMem._SumCtx == null) pMem._SumCtx = new SumCtx(); p = pMem._SumCtx; if (p.Context == null) p.Context = pMem; if (argc == 0 || SQLITE_NULL == sqlite3_value_type(argv[0])) { p.cnt++; p.iSum += 1; } else { type = sqlite3_value_numeric_type(argv[0]); if (p != null && type != SQLITE_NULL) { p.cnt++; if (type == SQLITE_INTEGER) { i64 v = sqlite3_value_int64(argv[0]); if (v == 40 || v == 41) { sqlite3_result_error(context, "value of " + v + " handed to x_count", -1); return; } else { p.iSum += v; if (!(p.approx | p.overflow != 0)) { i64 iNewSum = p.iSum + v; int s1 = (int)(p.iSum >> (sizeof(i64) * 8 - 1)); int s2 = (int)(v >> (sizeof(i64) * 8 - 1)); int s3 = (int)(iNewSum >> (sizeof(i64) * 8 - 1)); p.overflow = ((s1 & s2 & ~s3) | (~s1 & ~s2 & s3)) != 0 ? 1 : 0; p.iSum = iNewSum; } } } else { p.rSum += sqlite3_value_double(argv[0]); p.approx = true; } } } } static void x_CountFinalize(sqlite3_context context) { SumCtx p; Mem pMem = sqlite3_aggregate_context(context, 0); p = pMem._SumCtx; if (p != null && p.cnt > 0) { if (p.overflow != 0) { sqlite3_result_error(context, "integer overflow", -1); } else if (p.approx) { sqlite3_result_double(context, p.rSum); } else if (p.iSum == 42) { sqlite3_result_error(context, "x_count totals to 42", -1); } else { sqlite3_result_int64(context, p.iSum); } } } #if SQLITE_MUTEX_W32 //---------------------WIN32 Definitions static int GetCurrentThreadId() { return Thread.CurrentThread.ManagedThreadId; } static long InterlockedIncrement( long location ) { Interlocked.Increment( ref location ); return location; } static void EnterCriticalSection( Object mtx ) { //long mid = mtx.GetHashCode(); //int tid = Thread.CurrentThread.ManagedThreadId; //long ticks = cnt++; //Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) ); Monitor.Enter( mtx ); } static void InitializeCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Enter( mtx ); } static void DeleteCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) ); Monitor.Exit( mtx ); } static void LeaveCriticalSection( Object mtx ) { //Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks )); Monitor.Exit( mtx ); } #endif // Miscellaneous Windows Constants //#define ERROR_FILE_NOT_FOUND 2L //#define ERROR_HANDLE_DISK_FULL 39L //#define ERROR_NOT_SUPPORTED 50L //#define ERROR_DISK_FULL 112L const long ERROR_FILE_NOT_FOUND = 2L; const long ERROR_HANDLE_DISK_FULL = 39L; const long ERROR_NOT_SUPPORTED = 50L; const long ERROR_DISK_FULL = 112L; private class SQLite3UpperToLower { static int[] sqlite3UpperToLower = new int[] { #if SQLITE_ASCII 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103, 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121, 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107, 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125, 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161, 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179, 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197, 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215, 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233, 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251, 252,253,254,255 #endif }; public int this[int index] { get { if (index < sqlite3UpperToLower.Length) return sqlite3UpperToLower[index]; else return index; } } public int this[u32 index] { get { if (index < sqlite3UpperToLower.Length) return sqlite3UpperToLower[index]; else return (int)index; } } } static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower(); static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower; } }
using Orleans.Serialization.Buffers; using Orleans.Serialization.Codecs; using Orleans.Serialization.Session; using Orleans.Serialization.Utilities; using Microsoft.Extensions.DependencyInjection; using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.IO.Pipelines; using System.Linq; using System.Text; using Xunit; namespace Orleans.Serialization.TestKit { [Trait("Category", "BVT")] [ExcludeFromCodeCoverage] public abstract class FieldCodecTester<TValue, TCodec> where TCodec : class, IFieldCodec<TValue> { private readonly IServiceProvider _serviceProvider; private readonly SerializerSessionPool _sessionPool; protected FieldCodecTester() { var services = new ServiceCollection(); _ = services.AddSerializer(builder => builder.Configure(config => config.FieldCodecs.Add(typeof(TCodec)))); if (!typeof(TCodec).IsAbstract && !typeof(TCodec).IsInterface) { _ = services.AddSingleton<TCodec>(); } _ = services.AddSerializer(Configure); _serviceProvider = services.BuildServiceProvider(); _sessionPool = _serviceProvider.GetService<SerializerSessionPool>(); } protected IServiceProvider ServiceProvider => _serviceProvider; protected SerializerSessionPool SessionPool => _sessionPool; protected virtual int[] MaxSegmentSizes => new[] { 16 }; protected virtual void Configure(ISerializerBuilder builder) { } protected virtual TCodec CreateCodec() => _serviceProvider.GetRequiredService<TCodec>(); protected abstract TValue CreateValue(); protected abstract TValue[] TestValues { get; } protected virtual bool Equals(TValue left, TValue right) => EqualityComparer<TValue>.Default.Equals(left, right); protected virtual Action<Action<TValue>> ValueProvider { get; } [Fact] public void CorrectlyAdvancesReferenceCounterStream() { var stream = new MemoryStream(); using var writerSession = _sessionPool.GetSession(); using var readerSession = _sessionPool.GetSession(); var writer = Writer.Create(stream, writerSession); var writerCodec = CreateCodec(); // Write the field. This should involve marking at least one reference in the session. Assert.Equal(0, writer.Position); foreach (var value in TestValues) { var beforeReference = writer.Session.ReferencedObjects.CurrentReferenceId; writerCodec.WriteField(ref writer, 0, typeof(TValue), value); Assert.True(writer.Position > 0); writer.Commit(); var afterReference = writer.Session.ReferencedObjects.CurrentReferenceId; Assert.True(beforeReference < afterReference, $"Writing a field should result in at least one reference being marked in the session. Before: {beforeReference}, After: {afterReference}"); if (value is null) { Assert.True(beforeReference + 1 == afterReference, $"Writing a null field should result in exactly one reference being marked in the session. Before: {beforeReference}, After: {afterReference}"); } stream.Flush(); stream.Position = 0; var reader = Reader.Create(stream, readerSession); var previousPos = reader.Position; Assert.Equal(0, previousPos); var readerCodec = CreateCodec(); var readField = reader.ReadFieldHeader(); Assert.True(reader.Position > previousPos); previousPos = reader.Position; beforeReference = reader.Session.ReferencedObjects.CurrentReferenceId; var readValue = readerCodec.ReadValue(ref reader, readField); Assert.True(reader.Position > previousPos); afterReference = reader.Session.ReferencedObjects.CurrentReferenceId; Assert.True(beforeReference < afterReference, $"Reading a field should result in at least one reference being marked in the session. Before: {beforeReference}, After: {afterReference}"); if (readValue is null) { Assert.True(beforeReference + 1 == afterReference, $"Reading a null field should result in at exactly one reference being marked in the session. Before: {beforeReference}, After: {afterReference}"); } } } [Fact] public void CorrectlyAdvancesReferenceCounter() { var pipe = new Pipe(); using var writerSession = _sessionPool.GetSession(); var writer = Writer.Create(pipe.Writer, writerSession); var writerCodec = CreateCodec(); var beforeReference = writer.Session.ReferencedObjects.CurrentReferenceId; // Write the field. This should involve marking at least one reference in the session. Assert.Equal(0, writer.Position); writerCodec.WriteField(ref writer, 0, typeof(TValue), CreateValue()); Assert.True(writer.Position > 0); writer.Commit(); var afterReference = writer.Session.ReferencedObjects.CurrentReferenceId; Assert.True(beforeReference < afterReference, $"Writing a field should result in at least one reference being marked in the session. Before: {beforeReference}, After: {afterReference}"); _ = pipe.Writer.FlushAsync().AsTask().GetAwaiter().GetResult(); pipe.Writer.Complete(); _ = pipe.Reader.TryRead(out var readResult); using var readerSession = _sessionPool.GetSession(); var reader = Reader.Create(readResult.Buffer, readerSession); var previousPos = reader.Position; Assert.Equal(0, previousPos); var readerCodec = CreateCodec(); var readField = reader.ReadFieldHeader(); Assert.True(reader.Position > previousPos); previousPos = reader.Position; beforeReference = reader.Session.ReferencedObjects.CurrentReferenceId; _ = readerCodec.ReadValue(ref reader, readField); Assert.True(reader.Position > previousPos); pipe.Reader.AdvanceTo(readResult.Buffer.End); pipe.Reader.Complete(); afterReference = reader.Session.ReferencedObjects.CurrentReferenceId; Assert.True(beforeReference < afterReference, $"Reading a field should result in at least one reference being marked in the session. Before: {beforeReference}, After: {afterReference}"); } [Fact] public void CanRoundTripViaSerializer_StreamPooled() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var original in TestValues) { Test(original); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue original) { var buffer = new MemoryStream(); var writer = Writer.CreatePooled(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); buffer.Flush(); writer.Output.Dispose(); buffer.Position = 0; var reader = Reader.Create(buffer, _sessionPool.GetSession()); var deserialized = serializer.Deserialize(ref reader); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); } } [Fact] public void CanRoundTripViaSerializer_Span() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var original in TestValues) { Test(original); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue original) { var buffer = new byte[8096].AsSpan(); var writer = Writer.Create(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); var reader = Reader.Create(buffer, _sessionPool.GetSession()); var deserialized = serializer.Deserialize(ref reader); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); } } [Fact] public void CanRoundTripViaSerializer_Array() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var original in TestValues) { Test(original); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue original) { var buffer = new byte[8096]; var writer = Writer.Create(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); var reader = Reader.Create(buffer, _sessionPool.GetSession()); var deserialized = serializer.Deserialize(ref reader); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); } } [Fact] public void CanRoundTripViaSerializer_Memory() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var original in TestValues) { Test(original); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue original) { var buffer = (new byte[8096]).AsMemory(); var writer = Writer.Create(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); var reader = Reader.Create(buffer, _sessionPool.GetSession()); var deserialized = serializer.Deserialize(ref reader); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); } } [Fact] public void CanRoundTripViaSerializer_MemoryStream() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var original in TestValues) { Test(original); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue original) { var buffer = new MemoryStream(); using var writerSession = _sessionPool.GetSession(); var writer = Writer.Create(buffer, writerSession); serializer.Serialize(original, ref writer); writer.Commit(); buffer.Flush(); buffer.SetLength(buffer.Position); buffer.Position = 0; using var readerSession = _sessionPool.GetSession(); var reader = Reader.Create(buffer, readerSession); var deserialized = serializer.Deserialize(ref reader); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); Assert.Equal(writer.Position, reader.Position); Assert.Equal(writerSession.ReferencedObjects.CurrentReferenceId, readerSession.ReferencedObjects.CurrentReferenceId); } } [Fact] public void CanRoundTripViaSerializer_ReadByteByByte() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var original in TestValues) { Test(original); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue original) { var buffer = new TestMultiSegmentBufferWriter(maxAllocationSize: 1024); using var writerSession = _sessionPool.GetSession(); var writer = Writer.Create(buffer, writerSession); serializer.Serialize(original, ref writer); writer.Commit(); using var readerSession = _sessionPool.GetSession(); var reader = Reader.Create(buffer.GetReadOnlySequence(maxSegmentSize: 1), readerSession); var deserialized = serializer.Deserialize(ref reader); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); Assert.Equal(writer.Position, reader.Position); Assert.Equal(writerSession.ReferencedObjects.CurrentReferenceId, readerSession.ReferencedObjects.CurrentReferenceId); } } [Fact] public void ProducesValidBitStream() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var value in TestValues) { Test(value); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue value) { var array = serializer.SerializeToArray(value); var session = _sessionPool.GetSession(); var reader = Reader.Create(array, session); var formatted = new StringBuilder(); try { BitStreamFormatter.Format(ref reader, formatted); Assert.True(formatted.ToString() is string { Length: > 0 }); } catch (Exception exception) { Assert.True(false, $"Formatting failed with exception: {exception} and partial result: \"{formatted}\""); } } } [Fact] public void WritersProduceSameResults() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var original in TestValues) { Test(original); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue original) { byte[] expected; { var buffer = new TestMultiSegmentBufferWriter(1024); var writer = Writer.Create(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); expected = buffer.GetReadOnlySequence(0).ToArray(); } { var buffer = new MemoryStream(); var writer = Writer.Create(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); buffer.Flush(); buffer.SetLength(buffer.Position); buffer.Position = 0; var result = buffer.ToArray(); Assert.Equal(expected, result); } var bytes = new byte[10240]; { var buffer = bytes.AsMemory(); var writer = Writer.Create(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); var result = buffer.Slice(0, writer.Output.BytesWritten).ToArray(); Assert.Equal(expected, result); } bytes.AsSpan().Clear(); { var buffer = bytes.AsSpan(); var writer = Writer.Create(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); var result = buffer.Slice(0, writer.Output.BytesWritten).ToArray(); Assert.Equal(expected, result); } bytes.AsSpan().Clear(); { var buffer = bytes; var writer = Writer.Create(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); var result = buffer.AsSpan(0, writer.Output.BytesWritten).ToArray(); Assert.Equal(expected, result); } bytes.AsSpan().Clear(); { var buffer = new MemoryStream(bytes); var writer = Writer.CreatePooled(buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); buffer.Flush(); buffer.SetLength(buffer.Position); buffer.Position = 0; var result = buffer.ToArray(); writer.Output.Dispose(); Assert.Equal(expected, result); } bytes.AsSpan().Clear(); { var buffer = new MemoryStream(bytes); var writer = Writer.Create((Stream)buffer, _sessionPool.GetSession()); serializer.Serialize(original, ref writer); buffer.Flush(); buffer.SetLength(buffer.Position); buffer.Position = 0; var result = buffer.ToArray(); Assert.Equal(expected, result); } } } [Fact] public void CanRoundTripViaSerializer() { var serializer = _serviceProvider.GetRequiredService<Serializer<TValue>>(); foreach (var original in TestValues) { Test(original); } if (ValueProvider is { } valueProvider) { valueProvider(Test); } void Test(TValue original) { var buffer = new TestMultiSegmentBufferWriter(1024); using var writerSession = _sessionPool.GetSession(); var writer = Writer.Create(buffer, writerSession); serializer.Serialize(original, ref writer); using var readerSession = _sessionPool.GetSession(); var reader = Reader.Create(buffer.GetReadOnlySequence(0), readerSession); var deserialized = serializer.Deserialize(ref reader); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); Assert.Equal(writer.Position, reader.Position); Assert.Equal(writerSession.ReferencedObjects.CurrentReferenceId, readerSession.ReferencedObjects.CurrentReferenceId); } } [Fact] public void CanRoundTripViaObjectSerializer() { var serializer = _serviceProvider.GetRequiredService<Serializer<object>>(); var buffer = new byte[10240]; foreach (var original in TestValues) { buffer.AsSpan().Clear(); using var writerSession = _sessionPool.GetSession(); var writer = Writer.Create(buffer, writerSession); serializer.Serialize(original, ref writer); using var readerSession = _sessionPool.GetSession(); var reader = Reader.Create(buffer, readerSession); var deserializedObject = serializer.Deserialize(ref reader); if (original != null && !typeof(TValue).IsEnum) { var deserialized = Assert.IsAssignableFrom<TValue>(deserializedObject); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); } else if (typeof(TValue).IsEnum) { var deserialized = (TValue)deserializedObject; var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); } else { Assert.Null(deserializedObject); } Assert.Equal(writer.Position, reader.Position); Assert.Equal(writerSession.ReferencedObjects.CurrentReferenceId, readerSession.ReferencedObjects.CurrentReferenceId); } } [Fact] public void RoundTrippedValuesEqual() => TestRoundTrippedValue(CreateValue()); [Fact] public void CanRoundTripDefaultValueViaCodec() => TestRoundTrippedValue(default); [Fact] public void CanSkipValue() => CanBeSkipped(default); [Fact] public void CanSkipDefaultValue() => CanBeSkipped(default); [Fact] public void CorrectlyHandlesBuffers() { var testers = BufferTestHelper<TValue>.GetTestSerializers(_serviceProvider, MaxSegmentSizes); foreach (var tester in testers) { foreach (var maxSegmentSize in MaxSegmentSizes) { foreach (var value in TestValues) { var buffer = tester.Serialize(value); var sequence = buffer.GetReadOnlySequence(maxSegmentSize); tester.Deserialize(sequence, out var output); var bufferWriterType = tester.GetType().BaseType?.GenericTypeArguments[1]; var isEqual = Equals(value, output); Assert.True(isEqual, isEqual ? string.Empty : $"Deserialized value {output} must be equal to serialized value {value}. " + $"IBufferWriter<> type: {bufferWriterType}, Max Read Segment Size: {maxSegmentSize}. " + $"Buffer: 0x{string.Join(" ", sequence.ToArray().Select(b => $"{b:X2}"))}"); } } } } private void CanBeSkipped(TValue original) { var pipe = new Pipe(); using var writerSession = _sessionPool.GetSession(); var writer = Writer.Create(pipe.Writer, writerSession); var writerCodec = CreateCodec(); writerCodec.WriteField(ref writer, 0, typeof(TValue), original); var expectedLength = writer.Position; writer.Commit(); _ = pipe.Writer.FlushAsync().AsTask().GetAwaiter().GetResult(); pipe.Writer.Complete(); _ = pipe.Reader.TryRead(out var readResult); { using var readerSession = _sessionPool.GetSession(); var reader = Reader.Create(readResult.Buffer, readerSession); var readField = reader.ReadFieldHeader(); reader.SkipField(readField); Assert.Equal(expectedLength, reader.Position); Assert.Equal(writerSession.ReferencedObjects.CurrentReferenceId, readerSession.ReferencedObjects.CurrentReferenceId); } { var codec = new SkipFieldCodec(); using var readerSession = _sessionPool.GetSession(); var reader = Reader.Create(readResult.Buffer, readerSession); var readField = reader.ReadFieldHeader(); var shouldBeNull = codec.ReadValue(ref reader, readField); Assert.Null(shouldBeNull); Assert.Equal(expectedLength, reader.Position); Assert.Equal(writerSession.ReferencedObjects.CurrentReferenceId, readerSession.ReferencedObjects.CurrentReferenceId); } pipe.Reader.AdvanceTo(readResult.Buffer.End); pipe.Reader.Complete(); } private void TestRoundTrippedValue(TValue original) { var pipe = new Pipe(); using var writerSession = _sessionPool.GetSession(); var writer = Writer.Create(pipe.Writer, writerSession); var writerCodec = CreateCodec(); writerCodec.WriteField(ref writer, 0, typeof(TValue), original); writer.Commit(); _ = pipe.Writer.FlushAsync().AsTask().GetAwaiter().GetResult(); pipe.Writer.Complete(); _ = pipe.Reader.TryRead(out var readResult); using var readerSession = _sessionPool.GetSession(); var reader = Reader.Create(readResult.Buffer, readerSession); var readerCodec = CreateCodec(); var readField = reader.ReadFieldHeader(); var deserialized = readerCodec.ReadValue(ref reader, readField); pipe.Reader.AdvanceTo(readResult.Buffer.End); pipe.Reader.Complete(); var isEqual = Equals(original, deserialized); Assert.True( isEqual, isEqual ? string.Empty : $"Deserialized value \"{deserialized}\" must equal original value \"{original}\""); Assert.Equal(writerSession.ReferencedObjects.CurrentReferenceId, readerSession.ReferencedObjects.CurrentReferenceId); } } }
using System; using System.Collections; using System.Collections.Generic; using NDatabase.Api; using NDatabase.Btree; using NDatabase.Exceptions; using NDatabase.Meta; using NDatabase.Services; using NDatabase.Tool; using NDatabase.Tool.Wrappers; namespace NDatabase.Core.BTree { /// <summary> /// Class that persists the BTree and its node into the NDatabase ODB Database. /// </summary> internal sealed class LazyOdbBtreePersister : IBTreePersister, ICommitListener { /// <summary> /// The odb interface /// </summary> private readonly IStorageEngine _engine; /// <summary> /// The list is used to keep the order. /// </summary> /// <remarks> /// The list is used to keep the order. Deleted object will be replaced by null value, to keep the positions /// </remarks> private readonly IOdbList<OID> _modifiedObjectOidList; /// <summary> /// All modified nodes : the map is used to avoid duplication The key is the oid, the value is the position is the list /// </summary> private readonly OdbHashMap<object, int> _modifiedObjectOids; /// <summary> /// All loaded nodes /// </summary> private readonly IDictionary<OID, object> _oids; private int _nbPersist; /// <summary> /// The tree we are persisting /// </summary> private IBTree _tree; public LazyOdbBtreePersister(IStorageEngine engine) { _oids = new OdbHashMap<OID, object>(); _modifiedObjectOids = new OdbHashMap<object, int>(); _modifiedObjectOidList = new OdbList<OID>(500); _engine = engine; _engine.AddCommitListener(this); } #region IBTreePersister Members /// <summary> /// Loads a node from its id. /// </summary> /// <remarks> /// Loads a node from its id. Tries to get if from memory, if not present then loads it from odb storage /// </remarks> /// <param name="id"> The id of the nod </param> /// <returns> The node with the specific id </returns> public IBTreeNode LoadNodeById(object id) { var oid = (OID) id; // Check if node is in memory var node = (IBTreeNode) _oids[oid]; if (node != null) { return node; } // else load from odb try { if (OdbConfiguration.IsLoggingEnabled()) DLogger.Debug(string.Format("LazyOdbBtreePersister: Loading node with id {0}", oid)); if (oid == null) throw new OdbRuntimeException(BTreeError.InvalidIdForBtree.AddParameter("oid")); var pn = (IBTreeNode) _engine.GetObjectFromOid(oid); pn.SetId(oid); if (_tree != null) pn.SetBTree(_tree); // Keep the node in memory _oids.Add(oid, pn); return pn; } catch (Exception e) { throw new OdbRuntimeException(BTreeError.InternalError, e); } } /// <summary> /// saves the bree node Only puts the current node in an 'modified Node' map to be saved on commit /// </summary> public void SaveNode(IBTreeNode node) { OID oid; // Here we only save the node if it does not have id, // else we just save into the hashmap if (node.GetId() == StorageEngineConstant.NullObjectId) { try { // first get the oid. : -2:it could be any value oid = _engine.GetObjectWriter().GetIdManager().GetNextObjectId(-2); node.SetId(oid); oid = _engine.Store(oid, node); if (OdbConfiguration.IsLoggingEnabled()) DLogger.Debug(string.Format("LazyOdbBtreePersister: Saved node id {0}", oid)); // + " : " + // node.toString()); if (_tree != null && node.GetBTree() == null) node.SetBTree(_tree); _oids.Add(oid, node); return; } catch (Exception e) { throw new OdbRuntimeException(BTreeError.InternalError.AddParameter("While saving node"), e); } } oid = (OID) node.GetId(); _oids.Add(oid, node); AddModifiedOid(oid); } public void Close() { Persist(); _engine.Close(); } public IBTree LoadBTree(object id) { var oid = (OID) id; try { if (OdbConfiguration.IsLoggingEnabled()) DLogger.Debug(string.Format("LazyOdbBtreePersister: Loading btree with id {0}", oid)); if (oid == StorageEngineConstant.NullObjectId) throw new OdbRuntimeException( BTreeError.InvalidIdForBtree.AddParameter(StorageEngineConstant.NullObjectId)); _tree = (IBTree) _engine.GetObjectFromOid(oid); _tree.SetId(oid); _tree.SetPersister(this); var root = _tree.GetRoot(); root.SetBTree(_tree); return _tree; } catch (Exception e) { throw new OdbRuntimeException(BTreeError.InternalError, e); } } public void SaveBTree(IBTree treeToSave) { try { var oid = (OID) treeToSave.GetId(); if (oid == null) { // first get the oid. -2 : it could be any value oid = _engine.GetObjectWriter().GetIdManager().GetNextObjectId(-2); treeToSave.SetId(oid); oid = _engine.Store(oid, treeToSave); if (OdbConfiguration.IsLoggingEnabled()) DLogger.Debug(string.Format("LazyOdbBtreePersister: Saved btree {0} with id {1} and root {2}", treeToSave.GetId(), oid, treeToSave.GetRoot())); if (_tree == null) _tree = treeToSave; _oids.Add(oid, treeToSave); } else { _oids.Add(oid, treeToSave); AddModifiedOid(oid); } } catch (Exception e) { throw new OdbRuntimeException(BTreeError.InternalError, e); } } public void DeleteNode(IBTreeNode o) { var oid = _engine.Delete(o); _oids.Remove(oid); var position = _modifiedObjectOids.Remove2(oid); // Just replace the element by null, to not modify all the other positions _modifiedObjectOidList[position] = null; } public void SetBTree(IBTree tree) { _tree = tree; } public void Flush() { Persist(); ClearModified(); } #endregion #region ICommitListener Members public void AfterCommit() { } // nothing to do public void BeforeCommit() { Persist(); Clear(); } #endregion private void Clear() { _oids.Clear(); _modifiedObjectOids.Clear(); _modifiedObjectOidList.Clear(); } private void Persist() { _nbPersist++; if (OdbConfiguration.IsLoggingEnabled()) { var count = _modifiedObjectOids.Count.ToString(); DLogger.Debug(string.Concat("LazyOdbBtreePersister: ", "persist ", _nbPersist.ToString(), " : Saving " + count + " objects - ", GetHashCode().ToString())); } var nbCommited = 0; var i = 0; var size = _modifiedObjectOids.Count; IEnumerator iterator = _modifiedObjectOidList.GetEnumerator(); while (iterator.MoveNext()) { var oid = (OID) iterator.Current; if (oid == null) continue; nbCommited++; long t0; long t1; try { t0 = OdbTime.GetCurrentTimeInMs(); var @object = _oids[oid]; _engine.Store(@object); t1 = OdbTime.GetCurrentTimeInMs(); } catch (Exception e) { throw new OdbRuntimeException( BTreeError.InternalError.AddParameter("Error while storing object with oid " + oid), e); } if (OdbConfiguration.IsLoggingEnabled()) DLogger.Debug(string.Concat("LazyOdbBtreePersister: ", "Committing oid " + oid, " | ", i.ToString(), "/", size.ToString(), " | ", (t1 - t0).ToString(), " ms")); i++; } if (OdbConfiguration.IsLoggingEnabled()) DLogger.Debug(string.Concat("LazyOdbBtreePersister: ", nbCommited.ToString(), " commits / ", size.ToString())); } private void ClearModified() { _modifiedObjectOids.Clear(); _modifiedObjectOidList.Clear(); } private void AddModifiedOid(OID oid) { if (_modifiedObjectOids.ContainsKey(oid)) { // Object is already in the list return; } _modifiedObjectOidList.Add(oid); // Keep the position of the oid in the list as the value of the map. // Used for the delete. _modifiedObjectOids.Add(oid, _modifiedObjectOidList.Count - 1); } } }