context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32; using OpenLiveWriter.Interop.Com; using OpenLiveWriter.Interop.Windows; namespace OpenLiveWriter.CoreServices { /// <summary> /// Summary description for ShellHelper. /// </summary> public class ShellHelper { private ShellHelper() { } public static string GetAbsolutePath(string path) { if (Uri.IsWellFormedUriString(path, UriKind.Absolute)) return path; else return Path.GetFullPath((path)); } /// <summary> /// Sets the window's application id by its window handle. /// </summary> /// <param name="hwnd">The window handle.</param> /// <param name="appId">The application id.</param> public static void SetWindowAppId(IntPtr hwnd, string appId) { SetWindowProperty(hwnd, SystemProperties.System.AppUserModel.ID, appId); } internal static void SetWindowProperty(IntPtr hwnd, PropertyKey propkey, string value) { // Get the IPropertyStore for the given window handle IPropertyStore propStore = GetWindowPropertyStore(hwnd); // Set the value PropVariant pv = new PropVariant(); propStore.SetValue(ref propkey, ref pv); // Dispose the IPropertyStore and PropVariant Marshal.ReleaseComObject(propStore); pv.Clear(); } internal static IPropertyStore GetWindowPropertyStore(IntPtr hwnd) { IPropertyStore propStore; Guid guid = new Guid(Shell32.IPropertyStore); int rc = Shell32.SHGetPropertyStoreForWindow( hwnd, ref guid, out propStore); if (rc != 0) throw Marshal.GetExceptionForHR(rc); return propStore; } /// <summary> /// For a file extension (with leading period) and a verb (or null for default /// verb), returns the (full?) path to the executable file that is assigned to /// that extension/verb. Returns null if an error occurs. /// </summary> public static string GetExecutablePath(string extension, string verb) { int capacity = 270; attempt: // we may need to retry with a different (larger) value for "capacity" StringBuilder buffer = new StringBuilder(capacity); // the buffer that will hold the result int hresult = Shlwapi.AssocQueryString(ASSOCF.NOTRUNCATE, ASSOCSTR.EXECUTABLE, extension, verb, buffer, ref capacity); switch (hresult) { case HRESULT.S_OK: return buffer.ToString(); // success; return the path // failure; buffer was too small case HRESULT.E_POINTER: case HRESULT.S_FALSE: // the capacity variable now holds the number of chars necessary (AssocQueryString // assigns it). it should work if we try again. goto attempt; // failure. the default case will catch all, but I'm explicitly // calling out the two failure codes I know about in case we need // them someday. case HRESULT.E_INVALIDARG: case HRESULT.E_FAILED: default: return null; } } /// <summary> /// Gets the friendly type string for an extension. /// </summary> public static string GetTypeNameForExtension(string extension) { if (extension != null) extension = extension.Trim(); int capacity = 270; attempt: StringBuilder builder = new StringBuilder(capacity); int hresult = Shlwapi.AssocQueryString(ASSOCF.NOTRUNCATE, ASSOCSTR.FRIENDLYDOCNAME, extension, null, builder, ref capacity); switch (hresult) { case HRESULT.S_OK: return builder.ToString(); case HRESULT.E_POINTER: case HRESULT.S_FALSE: // the capacity variable now holds the number of chars necessary. try again goto attempt; case HRESULT.E_INVALIDARG: case HRESULT.E_FAILED: default: break; } if (extension == null || extension == string.Empty) return "Unknown"; else return extension.TrimStart('.').ToUpper(CultureInfo.InvariantCulture) + " File"; } public struct ExecuteFileResult { public ExecuteFileResult(bool newProcessCreated, int processId, string processName) : this(newProcessCreated, new int[] { processId }, new string[] { processName }) { } public ExecuteFileResult(bool newProcessCreated, int[] processIdList, string[] processNameList) { this.NewProcessCreated = newProcessCreated; this.ProcessIdList = processIdList; this.ProcessNameList = processNameList; } public bool NewProcessCreated; public int[] ProcessIdList; public string[] ProcessNameList; } /// <summary> /// Shell-executes a file with a specific verb, then returns either the exact /// process that was launched, or if nothing was launched (i.e. a process was /// reused), returns a set of processes that might be handling the file. /// </summary> public static ExecuteFileResult ExecuteFile(string filePath, string verb) { // Execute the document using the shell. ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.UseShellExecute = true; startInfo.FileName = filePath; startInfo.Verb = verb; using (Process p = Process.Start(startInfo)) { if (p != null) { string processName = ProcessHelper.GetProcessName(p.Handle); if (processName != null) return new ExecuteFileResult(true, p.Id, processName); } } // A process was reused. Need to find all the possible processes // that could've been reused and return them all. int[] processIds; string[] processNames; string command = GetExecutablePath(Path.GetExtension(filePath), verb); if (command == null) { // The extension/verb combination has no registered application. // We can't even guess at what process could be editing the file. processIds = new int[0]; processNames = new string[0]; } else { // A registered app was found. We assume that a process with the // same name is editing the file. string imageName = Path.GetFileName(command); processIds = ProcessHelper.GetProcessIdsByName(imageName); processNames = new string[processIds.Length]; for (int i = 0; i < processIds.Length; i++) processNames[i] = imageName; } return new ExecuteFileResult(false, processIds, processNames); } public static ExecuteFileResult ExecuteFileWithExecutable(string filePath, string executable) { ProcessStartInfo startInfo = new ProcessStartInfo(executable); startInfo.Arguments = "\"" + filePath + "\""; using (Process p = Process.Start(startInfo)) { if (p != null) return new ExecuteFileResult(true, p.Id, ProcessHelper.GetProcessName(p.Handle)); } string imageName = Path.GetFileName(executable); int[] processIds = ProcessHelper.GetProcessIdsByName(imageName); string[] processNames = new string[processIds.Length]; for (int i = 0; i < processIds.Length; i++) processNames[i] = imageName; return new ExecuteFileResult(false, processIds, processNames); } /// <summary> /// This should be used as the default URL launching method, instead of Process.Start. /// </summary> public static void LaunchUrl(string url) { try { Process.Start(url); } catch (Win32Exception w32e) { // Benign but common error due to Firefox and/or Windows stupidity // http://kb.mozillazine.org/Windows_error_opening_Internet_shortcut_or_local_HTML_file_-_Firefox // The unchecked cast is necessary to make the uint wrap around to the proper int error code. if (w32e.ErrorCode == unchecked((int)0x80004005)) return; throw; } } /// <summary> /// Parse a "shell" file list (space delimited list with filenames that contain spaces /// being contained in quotes /// </summary> /// <param name="fileList">shell file list</param> /// <returns>array of file paths in the file list</returns> public static string[] ParseShellFileList(string fileList) { // otherwise check for a "shell format" list fileList = fileList.Trim(); ArrayList fileListArray = new ArrayList(); int currentLoc = 0; // scan for file entries while (currentLoc < fileList.Length) { // file entry string file = null; // skip leading white-space while (currentLoc < fileList.Length && Char.IsWhiteSpace(fileList[currentLoc])) currentLoc++; // account for quoted entries if (fileList[currentLoc] == '"') { // find next quote int nextQuote = fileList.IndexOf('"', currentLoc + 1); if (nextQuote != -1) { file = fileList.Substring(currentLoc + 1, nextQuote - currentLoc - 1); currentLoc = nextQuote + 1; } else break; // no end quote! } // if we didn't have a quoted entry then find next space delimited entry if (file == null) { // skip leading white-space while (currentLoc < fileList.Length && Char.IsWhiteSpace(fileList[currentLoc])) currentLoc++; // if we aren't at the end then get the next entry if (currentLoc < fileList.Length) { // find the end of the entry int endEntry = currentLoc; while (endEntry < fileList.Length) if (!Char.IsWhiteSpace(fileList[endEntry])) endEntry++; else break; // get the value for the entry file = fileList.Substring(currentLoc, endEntry - currentLoc); currentLoc = endEntry; } else break; // at the end } // add the file to our list fileListArray.Add(file.Trim()); } // return the list return (string[])fileListArray.ToArray(typeof(string)); } /// <summary> /// Determine if there is a custom icon handler for the specified file extension /// </summary> /// <param name="fileExtension">file extension (including ".")</param> /// <returns>true if it has a custom icon handler, otherwise false</returns> public static bool HasCustomIconHandler(string fileExtension) { using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(fileExtension)) { if (key != null) { using (RegistryKey classKey = Registry.ClassesRoot.OpenSubKey( key.GetValue(null, String.Empty) + @"\ShellEx\IconHandler")) { if (classKey != null) return true; else return false; } } else return false; } } /// <summary> /// Get the small icon for the specified file /// </summary> /// <param name="filePath">path to file</param> /// <returns>IconHandle (or null if none found). IconHandle represents /// a Win32 HICON. It must be Disposed when the caller is finished with /// it to free the underlying resources used by the Icon. </returns> public static IconHandle GetSmallIconForFile(string filePath) { return GetIconForFile(filePath, SHGFI.SMALLICON); } /// <summary> /// Get the larege icon for the specified file /// </summary> /// <param name="filePath">path to file</param> /// <returns>IconHandle (or null if none found). IconHandle represents /// a Win32 HICON. It must be Disposed when the caller is finished with /// it to free the underlying resources used by the Icon. </returns> public static IconHandle GetLargeIconForFile(string filePath) { return GetIconForFile(filePath, SHGFI.LARGEICON); } /// <summary> /// Get the icon for the specified file /// </summary> /// <param name="filePath">path to file</param> /// <param name="iconType">icon type (small or large)</param> /// <returns>IconHandle (or null if none found). IconHandle represents /// a Win32 HICON. It must be Disposed when the caller is finished with /// it to free the underlying resources used by the Icon. </returns> private static IconHandle GetIconForFile(string filePath, uint iconType) { // allocate SHFILEINFO for holding results SHFILEINFO fileInfo = new SHFILEINFO(); // get icon info IntPtr result = Shell32.SHGetFileInfo(filePath, 0, ref fileInfo, (uint)Marshal.SizeOf(fileInfo), SHGFI.ICON | iconType); if (result == IntPtr.Zero) { Debug.Fail("Error getting icon for file: " + Marshal.GetLastWin32Error()); return null; } // return IconHandle return new IconHandle(fileInfo.hIcon); } /// <summary> /// Get the small icon for the specified file extension /// </summary> /// <param name="extension">file extension (including leading .)</param> /// <returns>IconHandle (or null if none found). IconHandle represents /// a Win32 HICON. It must be Disposed when the caller is finished with /// it to free the underlying resources used by the Icon. </returns> public static IconHandle GetSmallShortcutIconForExtension(string extension) { return GetIconForExtension(extension, SHGFI.SMALLICON | SHGFI.LINKOVERLAY); } /// <summary> /// Get the small icon for the specified file extension /// </summary /// <param name="extension">file extension (including leading .)</param> /// <returns>IconHandle (or null if none found). IconHandle represents /// a Win32 HICON. It must be Disposed when the caller is finished with /// it to free the underlying resources used by the Icon. </returns> public static IconHandle GetLargeShortcutIconForExtension(string extension) { return GetIconForExtension(extension, SHGFI.LARGEICON | SHGFI.LINKOVERLAY); } /// <summary> /// Get the small icon for the specified file extension /// </summary> /// <param name="extension">file extension (including leading .)</param> /// <returns>IconHandle (or null if none found). IconHandle represents /// a Win32 HICON. It must be Disposed when the caller is finished with /// it to free the underlying resources used by the Icon. </returns> public static IconHandle GetSmallIconForExtension(string extension) { return GetIconForExtension(extension, SHGFI.SMALLICON); } /// <summary> /// Get the large icon for the specified file extension /// </summary> /// <param name="extension">file extension (including leading .)</param> /// <returns>IconHandle (or null if none found). IconHandle represents /// a Win32 HICON. It must be Disposed when the caller is finished with /// it to free the underlying resources used by the Icon. </returns> public static IconHandle GetLargeIconForExtension(string extension) { return GetIconForExtension(extension, SHGFI.LARGEICON); } public static string[] PathExtensions { get { string pathext = Environment.GetEnvironmentVariable("PATHEXT"); if (pathext == null) pathext = ".COM;.EXE;.BAT;.CMD"; string[] pathexts = StringHelper.Split(pathext, ";"); for (int i = 0; i < pathexts.Length; i++) pathexts[i] = pathexts[i].ToLower(CultureInfo.CurrentCulture).Trim(); return pathexts; } } public static bool IsPathExtension(string extension) { return Array.IndexOf(PathExtensions, extension) >= 0; } /// <summary> /// Get the icon for the specified file extension /// </summary> /// <param name="extension">file extension (including leading .)</param> /// <param name="flags">icon type (small or large)</param> /// <returns>IconHandle (or null if none found). IconHandle represents /// a Win32 HICON. It must be Disposed when the caller is finished with /// it to free the underlying resources used by the Icon. </returns> private static IconHandle GetIconForExtension(string extension, uint flags) { // allocate SHFILEINFO for holding results SHFILEINFO fileInfo = new SHFILEINFO(); // get icon info for file extension IntPtr result = Shell32.SHGetFileInfo(extension, FILE_ATTRIBUTE.NORMAL, ref fileInfo, (uint)Marshal.SizeOf(fileInfo), SHGFI.ICON | flags | SHGFI.USEFILEATTRIBUTES); if (result == IntPtr.Zero) { Debug.Fail("Error getting icon for file: " + Marshal.GetLastWin32Error()); return null; } // return IconHandle return new IconHandle(fileInfo.hIcon); } /// <summary> /// Extension used for shortcuts /// </summary> public static string ShortcutExtension = ".lnk"; public static void ParseCommand(string command, out string executable, out string arguments) { if (command == null) throw new ArgumentNullException("command", "Command cannot be null"); if (command.Length == 0) throw new ArgumentOutOfRangeException("command", "Command cannot be the empty string"); command = command.TrimStart(); if (command[0] == '"') { int split = command.IndexOf('"', 1); if (split != -1) { executable = command.Substring(1, split - 1); arguments = string.Empty; if (command.Length > split + 2) arguments = command.Substring(split + 2); } else { executable = command; arguments = string.Empty; } } else { int split = command.IndexOf(' '); if (split != -1) { executable = command.Substring(0, split); arguments = string.Empty; if (command.Length > split + 1) arguments = command.Substring(split + 1); } else { executable = command; arguments = string.Empty; } } } } /// <summary> /// Class that encapsulates a Win32 Icon Handle. The class can be implicitly /// converted to a .NET Icon. The class must be disposed when the caller /// is finished with using the Icon (this frees the HANDLE via DestroyIcon /// </summary> public class IconHandle : IDisposable { /// <summary> /// Initialize from an HICON /// </summary> /// <param name="hIcon"></param> public IconHandle(IntPtr hIcon) { this.hIcon = hIcon; } /// <summary> /// Underlying HICON /// </summary> public IntPtr Handle { get { return hIcon; } } /// <summary> /// .NET Icon for HICON (tied to underlying HICON) /// </summary> public Icon Icon { get { if (icon == null) icon = System.Drawing.Icon.FromHandle(hIcon); return icon; } } /// <summary> /// Dispose by destroying underlying HICON (makes all .NET icons returned /// from the Icon property invalid) /// </summary> public void Dispose() { User32.DestroyIcon(hIcon); } /// <summary> /// Underlying HICON /// </summary> private IntPtr hIcon = IntPtr.Zero; /// <summary> /// .NET Icon for HICON /// </summary> private Icon icon = null; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.IoT.TimeSeriesInsights { /// <summary> /// Perform operations such as creating, listing, replacing and deleting Time Series instances. /// </summary> public class TimeSeriesInsightsInstances { private readonly TimeSeriesInstancesRestClient _instancesRestClient; private readonly ClientDiagnostics _clientDiagnostics; /// <summary> /// Initializes a new instance of TimeSeriesInsightsInstances. This constructor should only be used for mocking purposes. /// </summary> protected TimeSeriesInsightsInstances() { } internal TimeSeriesInsightsInstances(TimeSeriesInstancesRestClient instancesRestClient, ClientDiagnostics clientDiagnostics) { Argument.AssertNotNull(instancesRestClient, nameof(instancesRestClient)); Argument.AssertNotNull(clientDiagnostics, nameof(clientDiagnostics)); _instancesRestClient = instancesRestClient; _clientDiagnostics = clientDiagnostics; } /// <summary> /// Gets Time Series instances in pages asynchronously. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The pageable list <see cref="AsyncPageable{TimeSeriesInstance}"/> of Time Series instances belonging to the TSI environment and the http response.</returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsGetAllInstances"> /// // Get all instances for the Time Series Insights environment /// AsyncPageable&lt;TimeSeriesInstance&gt; tsiInstances = client.Instances.GetAsync(); /// await foreach (TimeSeriesInstance tsiInstance in tsiInstances) /// { /// Console.WriteLine($&quot;Retrieved Time Series Insights instance with Id &apos;{tsiInstance.TimeSeriesId}&apos; and name &apos;{tsiInstance.Name}&apos;.&quot;); /// } /// </code> /// </example> public virtual AsyncPageable<TimeSeriesInstance> GetAsync(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { async Task<Page<TimeSeriesInstance>> FirstPageFunc(int? pageSizeHint) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Response<GetInstancesPage> getInstancesResponse = await _instancesRestClient .ListAsync(null, null, cancellationToken) .ConfigureAwait(false); return Page.FromValues(getInstancesResponse.Value.Instances, getInstancesResponse.Value.ContinuationToken, getInstancesResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } async Task<Page<TimeSeriesInstance>> NextPageFunc(string nextLink, int? pageSizeHint) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Response<GetInstancesPage> getInstancesResponse = await _instancesRestClient .ListAsync(nextLink, null, cancellationToken) .ConfigureAwait(false); return Page.FromValues(getInstancesResponse.Value.Instances, getInstancesResponse.Value.ContinuationToken, getInstancesResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series instances synchronously in pages. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The pageable list <see cref="Pageable{TimeSeriesInstance}"/> of Time Series instances belonging to the TSI environment and the http response.</returns> /// <seealso cref="GetAsync(CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> public virtual Pageable<TimeSeriesInstance> Get(CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Page<TimeSeriesInstance> FirstPageFunc(int? pageSizeHint) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Response<GetInstancesPage> getInstancesResponse = _instancesRestClient.List(null, null, cancellationToken); return Page.FromValues(getInstancesResponse.Value.Instances, getInstancesResponse.Value.ContinuationToken, getInstancesResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } Page<TimeSeriesInstance> NextPageFunc(string nextLink, int? pageSizeHint) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Response<GetInstancesPage> getInstancesResponse = _instancesRestClient.List(nextLink, null, cancellationToken); return Page.FromValues(getInstancesResponse.Value.Instances, getInstancesResponse.Value.ContinuationToken, getInstancesResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series instances by instance names asynchronously. /// </summary> /// <param name="timeSeriesNames">List of names of the Time Series instance to return.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of instance or error objects corresponding by position to the array in the request. Instance object is set when operation is successful /// and error object is set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesNames"/> is empty. /// </exception> public virtual async Task<Response<InstancesOperationResult[]>> GetAsync( IEnumerable<string> timeSeriesNames, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesNames, nameof(timeSeriesNames)); var batchRequest = new InstancesBatchRequest { Get = new InstancesRequestBatchGetOrDelete() }; foreach (string timeSeriesName in timeSeriesNames) { batchRequest.Get.Names.Add(timeSeriesName); } Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series instances by instance names synchronously. /// </summary> /// <param name="timeSeriesNames">List of names of the Time Series instance to return.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of instance or error objects corresponding by position to the array in the request. Instance object is set when operation is successful /// and error object is set when operation is unsuccessful. /// </returns> /// <seealso cref="GetAsync(IEnumerable{string}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesNames"/> is empty. /// </exception> public virtual Response<InstancesOperationResult[]> Get( IEnumerable<string> timeSeriesNames, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesNames, nameof(timeSeriesNames)); var batchRequest = new InstancesBatchRequest { Get = new InstancesRequestBatchGetOrDelete() }; foreach (string timeSeriesName in timeSeriesNames) { batchRequest.Get.Names.Add(timeSeriesName); } Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series instances by Time Series Ids asynchronously. /// </summary> /// <param name="timeSeriesIds">List of Ids of the Time Series instances to return.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of instance or error objects corresponding by position to the array in the request. Instance object is set when operation is successful /// and error object is set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsGetnstancesById"> /// // Get Time Series Insights instances by Id /// // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`. /// var timeSeriesIds = new List&lt;TimeSeriesId&gt; /// { /// tsId, /// }; /// /// Response&lt;InstancesOperationResult[]&gt; getByIdsResult = await client.Instances.GetAsync(timeSeriesIds); /// /// // The response of calling the API contains a list of instance or error objects corresponding by position to the array in the request. /// // Instance object is set when operation is successful and error object is set when operation is unsuccessful. /// for (int i = 0; i &lt; getByIdsResult.Value.Length; i++) /// { /// InstancesOperationResult currentOperationResult = getByIdsResult.Value[i]; /// /// if (currentOperationResult.Instance != null) /// { /// Console.WriteLine($&quot;Retrieved Time Series Insights instance with Id &apos;{currentOperationResult.Instance.TimeSeriesId}&apos; and name &apos;{currentOperationResult.Instance.Name}&apos;.&quot;); /// } /// else if (currentOperationResult.Error != null) /// { /// Console.WriteLine($&quot;Failed to retrieve a Time Series Insights instance with Id &apos;{timeSeriesIds[i]}&apos;. Error message: &apos;{currentOperationResult.Error.Message}&apos;.&quot;); /// } /// } /// </code> /// </example> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesIds"/> is empty. /// </exception> public virtual async Task<Response<InstancesOperationResult[]>> GetAsync( IEnumerable<TimeSeriesId> timeSeriesIds, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesIds, nameof(timeSeriesIds)); var batchRequest = new InstancesBatchRequest { Get = new InstancesRequestBatchGetOrDelete() }; foreach (TimeSeriesId timeSeriesId in timeSeriesIds) { batchRequest.Get.TimeSeriesIds.Add(timeSeriesId); } Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Gets Time Series instances by Time Series Ids synchronously. /// </summary> /// <param name="timeSeriesIds">List of Ids of the Time Series instances to return.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of instance or error objects corresponding by position to the array in the request. Instance object is set when operation is successful /// and error object is set when operation is unsuccessful. /// </returns> /// <seealso cref="GetAsync(IEnumerable{TimeSeriesId}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesIds"/> is empty. /// </exception> public virtual Response<InstancesOperationResult[]> Get( IEnumerable<TimeSeriesId> timeSeriesIds, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Get)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesIds, nameof(timeSeriesIds)); var batchRequest = new InstancesBatchRequest { Get = new InstancesRequestBatchGetOrDelete() }; foreach (TimeSeriesId timeSeriesId in timeSeriesIds) { batchRequest.Get.TimeSeriesIds.Add(timeSeriesId); } Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Get.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates Time Series instances asynchronously. If a provided instance is already in use, then this will attempt to replace the existing /// instance with the provided Time Series Instance. /// </summary> /// <param name="timeSeriesInstances">The Time Series instances to be created or replaced.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the <paramref name="timeSeriesInstances"/> array in the request. /// A <seealso cref="TimeSeriesOperationError"/> object will be set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleCreateInstance"> /// // Create a Time Series Instance object with the default Time Series Insights type Id. /// // The default type Id can be obtained programmatically by using the ModelSettings client. /// // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`. /// var instance = new TimeSeriesInstance(tsId, defaultTypeId) /// { /// Name = &quot;instance1&quot;, /// }; /// /// var tsiInstancesToCreate = new List&lt;TimeSeriesInstance&gt; /// { /// instance, /// }; /// /// Response&lt;TimeSeriesOperationError[]&gt; createInstanceErrors = await client /// .Instances /// .CreateOrReplaceAsync(tsiInstancesToCreate); /// /// // The response of calling the API contains a list of error objects corresponding by position to the input parameter /// // array in the request. If the error object is set to null, this means the operation was a success. /// for (int i = 0; i &lt; createInstanceErrors.Value.Length; i++) /// { /// TimeSeriesId tsiId = tsiInstancesToCreate[i].TimeSeriesId; /// /// if (createInstanceErrors.Value[i] == null) /// { /// Console.WriteLine($&quot;Created Time Series Insights instance with Id &apos;{tsiId}&apos;.&quot;); /// } /// else /// { /// Console.WriteLine($&quot;Failed to create a Time Series Insights instance with Id &apos;{tsiId}&apos;, &quot; + /// $&quot;Error Message: &apos;{createInstanceErrors.Value[i].Message}, &quot; + /// $&quot;Error code: &apos;{createInstanceErrors.Value[i].Code}&apos;.&quot;); /// } /// } /// </code> /// </example> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesInstances"/> is empty. /// </exception> public virtual async Task<Response<TimeSeriesOperationError[]>> CreateOrReplaceAsync( IEnumerable<TimeSeriesInstance> timeSeriesInstances, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics .CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateOrReplace)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesInstances, nameof(timeSeriesInstances)); var batchRequest = new InstancesBatchRequest(); foreach (TimeSeriesInstance instance in timeSeriesInstances) { batchRequest.Put.Add(instance); } Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); // Extract the errors array from the response. If there was an error with creating or replacing one of the instances, // it will be placed at the same index location that corresponds to its place in the input array. IEnumerable<TimeSeriesOperationError> errorResults = executeBatchResponse.Value.Put.Select((result) => result.Error); return Response.FromValue(errorResults.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Creates Time Series instances synchronously. If a provided instance is already in use, then this will attempt to replace the existing /// instance with the provided Time Series Instance. /// </summary> /// <param name="timeSeriesInstances">The Time Series instances to be created or replaced.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the <paramref name="timeSeriesInstances"/> array in the request. /// A <seealso cref="TimeSeriesOperationError"/> object will be set when operation is unsuccessful. /// </returns> /// <seealso cref="CreateOrReplaceAsync(IEnumerable{TimeSeriesInstance}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesInstances"/> is empty. /// </exception> public virtual Response<TimeSeriesOperationError[]> CreateOrReplace( IEnumerable<TimeSeriesInstance> timeSeriesInstances, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(CreateOrReplace)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesInstances, nameof(timeSeriesInstances)); var batchRequest = new InstancesBatchRequest(); foreach (TimeSeriesInstance instance in timeSeriesInstances) { batchRequest.Put.Add(instance); } Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); // Extract the errors array from the response. If there was an error with creating or replacing one of the instances, // it will be placed at the same index location that corresponds to its place in the input array. IEnumerable<TimeSeriesOperationError> errorResults = executeBatchResponse.Value.Put.Select((result) => result.Error); return Response.FromValue(errorResults.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces Time Series instances asynchronously. /// </summary> /// <param name="timeSeriesInstances">The Time Series instances to replaced.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of objects corresponding by position to the <paramref name="timeSeriesInstances"/> array in the request. Instance object /// is set when operation is successful and error object is set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsReplaceInstance"> /// // Get Time Series Insights instances by Id /// // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`. /// var instanceIdsToGet = new List&lt;TimeSeriesId&gt; /// { /// tsId, /// }; /// /// Response&lt;InstancesOperationResult[]&gt; getInstancesByIdResult = await client.Instances.GetAsync(instanceIdsToGet); /// /// TimeSeriesInstance instanceResult = getInstancesByIdResult.Value[0].Instance; /// Console.WriteLine($&quot;Retrieved Time Series Insights instance with Id &apos;{instanceResult.TimeSeriesId}&apos; and name &apos;{instanceResult.Name}&apos;.&quot;); /// /// // Now let&apos;s replace the instance with an updated name /// instanceResult.Name = &quot;newInstanceName&quot;; /// /// var instancesToReplace = new List&lt;TimeSeriesInstance&gt; /// { /// instanceResult, /// }; /// /// Response&lt;InstancesOperationResult[]&gt; replaceInstancesResult = await client.Instances.ReplaceAsync(instancesToReplace); /// /// // The response of calling the API contains a list of error objects corresponding by position to the input parameter. /// // array in the request. If the error object is set to null, this means the operation was a success. /// for (int i = 0; i &lt; replaceInstancesResult.Value.Length; i++) /// { /// TimeSeriesId tsiId = instancesToReplace[i].TimeSeriesId; /// /// TimeSeriesOperationError currentError = replaceInstancesResult.Value[i].Error; /// /// if (currentError != null) /// { /// Console.WriteLine($&quot;Failed to replace Time Series Insights instance with Id &apos;{tsiId}&apos;,&quot; + /// $&quot; Error Message: &apos;{currentError.Message}&apos;, Error code: &apos;{currentError.Code}&apos;.&quot;); /// } /// else /// { /// Console.WriteLine($&quot;Replaced Time Series Insights instance with Id &apos;{tsiId}&apos;.&quot;); /// } /// } /// </code> /// </example> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesInstances"/> is empty. /// </exception> public virtual async Task<Response<InstancesOperationResult[]>> ReplaceAsync( IEnumerable<TimeSeriesInstance> timeSeriesInstances, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics .CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Replace)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesInstances, nameof(timeSeriesInstances)); var batchRequest = new InstancesBatchRequest(); foreach (TimeSeriesInstance instance in timeSeriesInstances) { batchRequest.Update.Add(instance); } Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Update.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Replaces Time Series instances synchronously. /// </summary> /// <param name="timeSeriesInstances">The Time Series instances to be replaced.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of objects corresponding by position to the <paramref name="timeSeriesInstances"/> array in the request. Instance object /// is set when operation is successful and error object is set when operation is unsuccessful. /// </returns> /// <seealso cref="ReplaceAsync(IEnumerable{TimeSeriesInstance}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesInstances"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesInstances"/> is empty. /// </exception> public virtual Response<InstancesOperationResult[]> Replace( IEnumerable<TimeSeriesInstance> timeSeriesInstances, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Replace)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesInstances, nameof(timeSeriesInstances)); var batchRequest = new InstancesBatchRequest(); foreach (TimeSeriesInstance instance in timeSeriesInstances) { batchRequest.Update.Add(instance); } Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Update.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes Time Series instances from the environment by instance names asynchronously. /// </summary> /// <param name="timeSeriesNames">List of names of the Time Series instance to delete.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the array in the request. Null means the instance has been deleted, or did not exist. /// Error object is set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <example> /// <code snippet="Snippet:TimeSeriesInsightsSampleDeleteInstanceById"> /// // tsId is created above using `TimeSeriesIdHelper.CreateTimeSeriesId`. /// var instancesToDelete = new List&lt;TimeSeriesId&gt; /// { /// tsId, /// }; /// /// Response&lt;TimeSeriesOperationError[]&gt; deleteInstanceErrors = await client /// .Instances /// .DeleteAsync(instancesToDelete); /// /// // The response of calling the API contains a list of error objects corresponding by position to the input parameter /// // array in the request. If the error object is set to null, this means the operation was a success. /// for (int i = 0; i &lt; deleteInstanceErrors.Value.Length; i++) /// { /// TimeSeriesId tsiId = instancesToDelete[i]; /// /// if (deleteInstanceErrors.Value[i] == null) /// { /// Console.WriteLine($&quot;Deleted Time Series Insights instance with Id &apos;{tsiId}&apos;.&quot;); /// } /// else /// { /// Console.WriteLine($&quot;Failed to delete a Time Series Insights instance with Id &apos;{tsiId}&apos;. Error Message: &apos;{deleteInstanceErrors.Value[i].Message}&apos;&quot;); /// } /// } /// </code> /// </example> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesNames"/> is empty. /// </exception> public virtual async Task<Response<TimeSeriesOperationError[]>> DeleteAsync( IEnumerable<string> timeSeriesNames, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Delete)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesNames, nameof(timeSeriesNames)); var batchRequest = new InstancesBatchRequest { Delete = new InstancesRequestBatchGetOrDelete() }; foreach (string timeSeriesName in timeSeriesNames) { batchRequest.Delete.Names.Add(timeSeriesName); } Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes Time Series instances from the environment by instance names synchronously. /// </summary> /// <param name="timeSeriesNames">List of names of the Time Series instance to delete.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the array in the request. Null means the instance has been deleted, or did not exist. /// Error object is set when operation is unsuccessful. /// </returns> /// <seealso cref="DeleteAsync(IEnumerable{string}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesNames"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesNames"/> is empty. /// </exception> public virtual Response<TimeSeriesOperationError[]> Delete( IEnumerable<string> timeSeriesNames, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Delete)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesNames, nameof(timeSeriesNames)); var batchRequest = new InstancesBatchRequest { Delete = new InstancesRequestBatchGetOrDelete() }; foreach (string timeSeriesName in timeSeriesNames) { batchRequest.Delete.Names.Add(timeSeriesName); } Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes Time Series instances from the environment by Time Series Ids asynchronously. /// </summary> /// <param name="timeSeriesIds">List of Ids of the Time Series instances to delete.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the array in the request. Null means the instance has been deleted, or did not exist. /// Error object is set when operation is unsuccessful. /// </returns> /// <remarks> /// For more samples, see <see href="https://github.com/Azure/azure-sdk-for-net/tree/master/sdk/timeseriesinsights/Azure.IoT.TimeSeriesInsights/samples">our repo samples</see>. /// </remarks> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesIds"/> is empty. /// </exception> public virtual async Task<Response<TimeSeriesOperationError[]>> DeleteAsync( IEnumerable<TimeSeriesId> timeSeriesIds, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Delete)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesIds, nameof(timeSeriesIds)); var batchRequest = new InstancesBatchRequest { Delete = new InstancesRequestBatchGetOrDelete() }; foreach (TimeSeriesId timeSeriesId in timeSeriesIds) { batchRequest.Delete.TimeSeriesIds.Add(timeSeriesId); } Response<InstancesBatchResponse> executeBatchResponse = await _instancesRestClient .ExecuteBatchAsync(batchRequest, null, cancellationToken) .ConfigureAwait(false); return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } /// <summary> /// Deletes Time Series instances from the environment by Time Series Ids synchronously. /// </summary> /// <param name="timeSeriesIds">List of Ids of the Time Series instances to delete.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// List of error objects corresponding by position to the array in the request. Null means the instance has been deleted, or did not exist. /// Error object is set when operation is unsuccessful. /// </returns> /// <seealso cref="DeleteAsync(IEnumerable{TimeSeriesId}, CancellationToken)"> /// See the asynchronous version of this method for examples. /// </seealso> /// <exception cref="ArgumentNullException"> /// The exception is thrown when <paramref name="timeSeriesIds"/> is <c>null</c>. /// </exception> /// <exception cref="ArgumentException"> /// The exception is thrown when <paramref name="timeSeriesIds"/> is empty. /// </exception> public virtual Response<TimeSeriesOperationError[]> Delete( IEnumerable<TimeSeriesId> timeSeriesIds, CancellationToken cancellationToken = default) { using DiagnosticScope scope = _clientDiagnostics.CreateScope($"{nameof(TimeSeriesInsightsClient)}.{nameof(Delete)}"); scope.Start(); try { Argument.AssertNotNullOrEmpty(timeSeriesIds, nameof(timeSeriesIds)); var batchRequest = new InstancesBatchRequest { Delete = new InstancesRequestBatchGetOrDelete() }; foreach (TimeSeriesId timeSeriesId in timeSeriesIds) { batchRequest.Delete.TimeSeriesIds.Add(timeSeriesId); } Response<InstancesBatchResponse> executeBatchResponse = _instancesRestClient .ExecuteBatch(batchRequest, null, cancellationToken); return Response.FromValue(executeBatchResponse.Value.Delete.ToArray(), executeBatchResponse.GetRawResponse()); } catch (Exception ex) { scope.Failed(ex); throw; } } } }
// 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.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct Int16 : IComparable, IConvertible, IFormattable, IComparable<short>, IEquatable<short>, ISpanFormattable { private readonly short m_value; // Do not rename (binary serialization) public const short MaxValue = (short)0x7FFF; public const short MinValue = unchecked((short)0x8000); // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type Int16, this method throws an ArgumentException. // public int CompareTo(object? value) { if (value == null) { return 1; } if (value is short) { return m_value - ((short)value).m_value; } throw new ArgumentException(SR.Arg_MustBeInt16); } public int CompareTo(short value) { return m_value - value; } public override bool Equals(object? obj) { if (!(obj is short)) { return false; } return m_value == ((short)obj).m_value; } [NonVersionable] public bool Equals(short obj) { return m_value == obj; } // Returns a HashCode for the Int16 public override int GetHashCode() { return m_value; } public override string ToString() { return Number.FormatInt32(m_value, null, null); } public string ToString(IFormatProvider? provider) { return Number.FormatInt32(m_value, null, provider); } public string ToString(string? format) { return ToString(format, null); } public string ToString(string? format, IFormatProvider? provider) { if (m_value < 0 && format != null && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x0000FFFF); return Number.FormatUInt32(temp, format, provider); } return Number.FormatInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) { if (m_value < 0 && format.Length > 0 && (format[0] == 'X' || format[0] == 'x')) { uint temp = (uint)(m_value & 0x0000FFFF); return Number.TryFormatUInt32(temp, format, provider, destination, out charsWritten); } return Number.TryFormatInt32(m_value, format, provider, destination, out charsWritten); } public static short Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static short Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo); } public static short Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static short Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider)); } public static short Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static short Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { Number.ParsingStatus status = Number.TryParseInt32(s, style, info, out int i); if (status != Number.ParsingStatus.OK) { Number.ThrowOverflowOrFormatException(status, TypeCode.Int16); } // For hex number styles AllowHexSpecifier << 6 == 0x8000 and cancels out MinValue so the check is effectively: (uint)i > ushort.MaxValue // For integer styles it's zero and the effective check is (uint)(i - MinValue) > ushort.MaxValue if ((uint)(i - MinValue - ((int)(style & NumberStyles.AllowHexSpecifier) << 6)) > ushort.MaxValue) { Number.ThrowOverflowException(TypeCode.Int16); } return (short)i; } public static bool TryParse(string? s, out short result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out short result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out short result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out short result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out short result) { // For hex number styles AllowHexSpecifier << 6 == 0x8000 and cancels out MinValue so the check is effectively: (uint)i > ushort.MaxValue // For integer styles it's zero and the effective check is (uint)(i - MinValue) > ushort.MaxValue if (Number.TryParseInt32(s, style, info, out int i) != Number.ParsingStatus.OK || (uint)(i - MinValue - ((int)(style & NumberStyles.AllowHexSpecifier) << 6)) > ushort.MaxValue) { result = 0; return false; } result = (short)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.Int16; } bool IConvertible.ToBoolean(IFormatProvider? provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider? provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider? provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider? provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider? provider) { return m_value; } ushort IConvertible.ToUInt16(IFormatProvider? provider) { return Convert.ToUInt16(m_value); } int IConvertible.ToInt32(IFormatProvider? provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider? provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider? provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider? provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Int16", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
using AutoMapper; using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Commands.Compute.Models; using Microsoft.Azure.Common.Authentication.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Common.Extensions.DSC; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Blob; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Management.Automation; using System.Text.RegularExpressions; using Newtonsoft.Json; namespace Microsoft.Azure.Commands.Compute.Extension.DSC { [Cmdlet( VerbsCommon.Set, ProfileNouns.VirtualMachineDscExtension, SupportsShouldProcess = true, DefaultParameterSetName = AzureBlobDscExtensionParamSet)] [OutputType(typeof(PSAzureOperationResponse))] public class SetAzureVMDscExtensionCommand : VirtualMachineExtensionBaseCmdlet { protected const string AzureBlobDscExtensionParamSet = "AzureBlobDscExtension"; [Parameter( Mandatory = true, Position = 2, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the resource group that contains the virtual machine.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter( Mandatory = true, Position = 3, ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the virtual machine where dsc extension handler would be installed.")] [ValidateNotNullOrEmpty] public string VMName { get; set; } [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the ARM resource that represents the extension. This is defaulted to 'Microsoft.Powershell.DSC'")] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// The name of the configuration archive that was previously uploaded by /// Publish-AzureRmVMDSCConfiguration. This parameter must specify only the name /// of the file, without any path. /// A null value or empty string indicate that the VM extension should install DSC, /// but not start any configuration /// </summary> [Alias("ConfigurationArchiveBlob")] [Parameter( Mandatory = true, Position = 5, ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The name of the configuration file that was previously uploaded by Publish-AzureRmVMDSCConfiguration")] [AllowEmptyString] [AllowNull] public string ArchiveBlobName { get; set; } /// <summary> /// The Azure Storage Account name used to upload the configuration script to the container specified by ArchiveContainerName. /// </summary> [Alias("StorageAccountName")] [Parameter( Mandatory = true, Position = 4, ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The Azure Storage Account name used to download the ArchiveBlobName")] [ValidateNotNullOrEmpty] public String ArchiveStorageAccountName { get; set; } [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The name of the resource group that contains the storage account containing the configuration archive. " + "This param is optional if storage account and virtual machine both exists in the same resource group name, " + "specified by ResourceGroupName param.")] [ValidateNotNullOrEmpty] public string ArchiveResourceGroupName { get; set; } /// <summary> /// The DNS endpoint suffix for all storage services, e.g. "core.windows.net". /// </summary> [Alias("StorageEndpointSuffix")] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "The Storage Endpoint Suffix.")] [ValidateNotNullOrEmpty] public string ArchiveStorageEndpointSuffix { get; set; } /// <summary> /// Name of the Azure Storage Container where the configuration script is located. /// </summary> [Alias("ContainerName")] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = AzureBlobDscExtensionParamSet, HelpMessage = "Name of the Azure Storage Container where the configuration archive is located")] [ValidateNotNullOrEmpty] public string ArchiveContainerName { get; set; } /// <summary> /// Name of the configuration that will be invoked by the DSC Extension. The value of this parameter should be the name of one of the configurations /// contained within the file specified by ArchiveBlobName. /// /// If omitted, this parameter will default to the name of the file given by the ArchiveBlobName parameter, excluding any extension, for example if /// ArchiveBlobName is "SalesWebSite.ps1", the default value for ConfigurationName will be "SalesWebSite". /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Name of the configuration that will be invoked by the DSC Extension")] [ValidateNotNullOrEmpty] public string ConfigurationName { get; set; } /// <summary> /// A hashtable specifying the arguments to the ConfigurationFunction. The keys /// correspond to the parameter names and the values to the parameter values. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable specifying the arguments to the ConfigurationFunction")] [ValidateNotNullOrEmpty] public Hashtable ConfigurationArgument { get; set; } /// <summary> /// Path to a .psd1 file that specifies the data for the Configuration. This /// file must contain a hashtable with the items described in /// http://technet.microsoft.com/en-us/library/dn249925.aspx. /// </summary> [Parameter( ValueFromPipelineByPropertyName = true, HelpMessage = "Path to a .psd1 file that specifies the data for the Configuration")] [ValidateNotNullOrEmpty] public string ConfigurationData { get; set; } /// <summary> /// The specific version of the DSC extension that Set-AzureRmVMDSCExtension will /// apply the settings to. /// </summary> [Alias("HandlerVersion")] [Parameter( Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "The version of the DSC extension that Set-AzureRmVMDSCExtension will apply the settings to. " + "Allowed format N.N")] [ValidateNotNullOrEmpty] public string Version { get; set; } /// <summary> /// By default Set-AzureRmVMDscExtension will not overwrite any existing blobs. Use -Force to overwrite them. /// </summary> [Parameter( HelpMessage = "Use this parameter to overwrite any existing blobs")] public SwitchParameter Force { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Location of the resource.")] [ValidateNotNullOrEmpty] public string Location { get; set; } /// <summary> /// We install the extension handler version specified by the version param. By default extension handler is not autoupdated. /// Use -AutoUpdate to enable auto update of extension handler to the latest version as and when it is available. /// </summary> [Parameter( HelpMessage = "Extension handler gets auto updated to the latest version if this switch is present.")] public SwitchParameter AutoUpdate { get; set; } /// <summary> /// Specifies the version of the Windows Management Framework (WMF) to install /// on the VM. /// /// The DSC Azure Extension depends on DSC features that are only available in /// the WMF updates. This parameter specifies which version of the update to /// install on the VM. The possible values are "4.0","latest" and "5.0PP". /// /// A value of "4.0" will install KB3000850 /// (http://support.microsoft.com/kb/3000850) on Windows 8.1 or Windows Server /// 2012 R2, or WMF 4.0 /// (http://www.microsoft.com/en-us/download/details.aspx?id=40855) on other /// versions of Windows if a newer version isnt already installed. /// /// A value of "5.0PP" will install the latest release of WMF 5.0PP /// (http://go.microsoft.com/fwlink/?LinkId=398175). /// /// A value of "latest" will install the latest WMF, currently WMF 5.0PP /// /// The default value is "latest" /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateSetAttribute(new[] { "4.0", "latest", "5.0PP" })] public string WmfVersion { get; set; } /// <summary> /// The Extension Data Collection state /// </summary> [Parameter(ValueFromPipelineByPropertyName = true, HelpMessage = "Enables or Disables Data Collection in the extension. It is enabled if it is not specified. " + "The value is persisted in the extension between calls.") ] [ValidateSet("Enable", "Disable")] [AllowNull] public string DataCollection { get; set; } //Private Variables private const string VersionRegexExpr = @"^(([0-9])\.)\d+$"; /// <summary> /// Credentials used to access Azure Storage /// </summary> private StorageCredentials _storageCredentials; public override void ExecuteCmdlet() { base.ExecuteCmdlet(); ValidateParameters(); CreateConfiguration(); } //Private Methods private void ValidateParameters() { if (string.IsNullOrEmpty(ArchiveBlobName)) { if (ConfigurationName != null || ConfigurationArgument != null || ConfigurationData != null) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoConfiguragionParameters); } if (ArchiveContainerName != null || ArchiveStorageEndpointSuffix != null) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscNullArchiveNoStorageParameters); } } else { if (string.Compare( Path.GetFileName(ArchiveBlobName), ArchiveBlobName, StringComparison.InvariantCultureIgnoreCase) != 0) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscConfigurationDataFileShouldNotIncludePath); } if (ConfigurationData != null) { ConfigurationData = GetUnresolvedProviderPathFromPSPath(ConfigurationData); if (!File.Exists(ConfigurationData)) { this.ThrowInvalidArgumentError( Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscCannotFindConfigurationDataFile, ConfigurationData); } if (string.Compare( Path.GetExtension(ConfigurationData), ".psd1", StringComparison.InvariantCultureIgnoreCase) != 0) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscInvalidConfigurationDataFile); } } if (ArchiveResourceGroupName == null) { ArchiveResourceGroupName = ResourceGroupName; } _storageCredentials = this.GetStorageCredentials(ArchiveResourceGroupName, ArchiveStorageAccountName); if (ConfigurationName == null) { ConfigurationName = Path.GetFileNameWithoutExtension(ArchiveBlobName); } if (ArchiveContainerName == null) { ArchiveContainerName = DscExtensionCmdletConstants.DefaultContainerName; } if (ArchiveStorageEndpointSuffix == null) { ArchiveStorageEndpointSuffix = DefaultProfile.Context.Environment.GetEndpoint(AzureEnvironment.Endpoint.StorageEndpointSuffix); } if (!(Regex.Match(Version, VersionRegexExpr).Success)) { this.ThrowInvalidArgumentError(Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscExtensionInvalidVersion); } } } private void CreateConfiguration() { var publicSettings = new DscExtensionPublicSettings(); var privateSettings = new DscExtensionPrivateSettings(); if (!string.IsNullOrEmpty(ArchiveBlobName)) { ConfigurationUris configurationUris = UploadConfigurationDataToBlob(); publicSettings.SasToken = configurationUris.SasToken; publicSettings.ModulesUrl = configurationUris.ModulesUrl; Hashtable privacySetting = new Hashtable(); privacySetting.Add("DataCollection", DataCollection); publicSettings.Privacy = privacySetting; publicSettings.ConfigurationFunction = string.Format( CultureInfo.InvariantCulture, "{0}\\{1}", Path.GetFileNameWithoutExtension(ArchiveBlobName), ConfigurationName); Tuple<DscExtensionPublicSettings.Property[], Hashtable> settings = DscExtensionSettingsSerializer.SeparatePrivateItems(ConfigurationArgument); publicSettings.Properties = settings.Item1; privateSettings.Items = settings.Item2; privateSettings.DataBlobUri = configurationUris.DataBlobUri; if (!string.IsNullOrEmpty(WmfVersion)) { publicSettings.WmfVersion = WmfVersion; } } if (string.IsNullOrEmpty(this.Location)) { this.Location = GetLocationFromVm(this.ResourceGroupName, this.VMName); } var parameters = new VirtualMachineExtension { Location = this.Location, Publisher = DscExtensionCmdletConstants.ExtensionPublishedNamespace, VirtualMachineExtensionType = DscExtensionCmdletConstants.ExtensionPublishedName, TypeHandlerVersion = Version, // Define the public and private property bags that will be passed to the extension. Settings = publicSettings, //PrivateConfuguration contains sensitive data in a plain text ProtectedSettings = privateSettings, AutoUpgradeMinorVersion = AutoUpdate.IsPresent }; //Add retry logic due to CRP service restart known issue CRP bug: 3564713 var count = 1; Rest.Azure.AzureOperationResponse<VirtualMachineExtension> op = null; while (count <= 2) { try { op = VirtualMachineExtensionClient.CreateOrUpdateWithHttpMessagesAsync( ResourceGroupName, VMName, Name ?? DscExtensionCmdletConstants.ExtensionPublishedNamespace + "." + DscExtensionCmdletConstants.ExtensionPublishedName, parameters).GetAwaiter().GetResult(); } catch (Rest.Azure.CloudException ex) { var errorReturned = JsonConvert.DeserializeObject<ComputeLongRunningOperationError>(ex.Response.Content.ReadAsStringAsync().Result); if (ComputeOperationStatus.Failed.Equals(errorReturned.Status) && errorReturned.Error != null && "InternalExecutionError".Equals(errorReturned.Error.Code)) { count++; } else { break; } } } var result = Mapper.Map<PSAzureOperationResponse>(op); WriteObject(result); } /// <summary> /// Uploading configuration data to blob storage. /// </summary> /// <returns>ConfigurationUris collection that represent artifacts of uploading</returns> private ConfigurationUris UploadConfigurationDataToBlob() { // // Get a reference to the container in blob storage // var storageAccount = new CloudStorageAccount(_storageCredentials, ArchiveStorageEndpointSuffix, true); var blobClient = storageAccount.CreateCloudBlobClient(); var containerReference = blobClient.GetContainerReference(ArchiveContainerName); // // Get a reference to the configuration blob and create a SAS token to access it // var blobAccessPolicy = new SharedAccessBlobPolicy { SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1), Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Delete }; var configurationBlobName = ArchiveBlobName; var configurationBlobReference = containerReference.GetBlockBlobReference(configurationBlobName); var configurationBlobSasToken = configurationBlobReference.GetSharedAccessSignature(blobAccessPolicy); // // Upload the configuration data to blob storage and get a SAS token // string configurationDataBlobUri = null; if (ConfigurationData != null) { var guid = Guid.NewGuid(); // there may be multiple VMs using the same configuration var configurationDataBlobName = string.Format( CultureInfo.InvariantCulture, "{0}-{1}.psd1", ConfigurationName, guid); var configurationDataBlobReference = containerReference.GetBlockBlobReference(configurationDataBlobName); ConfirmAction( true, string.Empty, string.Format( CultureInfo.CurrentUICulture, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscUploadToBlobStorageAction, ConfigurationData), configurationDataBlobReference.Uri.AbsoluteUri, () => { if (!Force && configurationDataBlobReference.Exists()) { ThrowTerminatingError( new ErrorRecord( new UnauthorizedAccessException( string.Format( CultureInfo.CurrentUICulture, Microsoft.Azure.Commands.Compute.Properties.Resources.AzureVMDscStorageBlobAlreadyExists, configurationDataBlobName)), "StorageBlobAlreadyExists", ErrorCategory.PermissionDenied, null)); } configurationDataBlobReference.UploadFromFile(ConfigurationData, FileMode.Open); var configurationDataBlobSasToken = configurationDataBlobReference.GetSharedAccessSignature(blobAccessPolicy); configurationDataBlobUri = configurationDataBlobReference.StorageUri.PrimaryUri.AbsoluteUri + configurationDataBlobSasToken; }); } return new ConfigurationUris { ModulesUrl = configurationBlobReference.StorageUri.PrimaryUri.AbsoluteUri, SasToken = configurationBlobSasToken, DataBlobUri = configurationDataBlobUri }; } /// <summary> /// Class represent info about uploaded Configuration. /// </summary> private class ConfigurationUris { public string SasToken { get; set; } public string DataBlobUri { get; set; } public string ModulesUrl { get; set; } } } }
// <copyright file="MlkBiCgStabTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // 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. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex32; using MathNet.Numerics.LinearAlgebra.Complex32.Solvers; using MathNet.Numerics.LinearAlgebra.Solvers; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Solvers.Iterative { using Numerics; /// <summary> /// Tests for Multiple-Lanczos Bi-Conjugate Gradient stabilized iterative matrix solver. /// </summary> [TestFixture, Category("LASolver")] public class MlkBiCgStabTest { /// <summary> /// Convergence boundary. /// </summary> const float ConvergenceBoundary = 1e-5f; /// <summary> /// Maximum iterations. /// </summary> const int MaximumIterations = 1000; /// <summary> /// Solve wide matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void SolveWideMatrixThrowsArgumentException() { var matrix = new SparseMatrix(2, 3); var input = new DenseVector(2); var solver = new MlkBiCgStab(); Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException); } /// <summary> /// Solve long matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void SolveLongMatrixThrowsArgumentException() { var matrix = new SparseMatrix(3, 2); var input = new DenseVector(3); var solver = new MlkBiCgStab(); Assert.That(() => matrix.SolveIterative(input, solver), Throws.ArgumentException); } /// <summary> /// Solve unit matrix and back multiply. /// </summary> [Test] public void SolveUnitMatrixAndBackMultiply() { // Create the identity matrix var matrix = SparseMatrix.CreateIdentity(100); // Create the y vector var y = Vector<Complex32>.Build.Dense(matrix.RowCount, 1); // Create an iteration monitor which will keep track of iterative convergence var monitor = new Iterator<Complex32>( new IterationCountStopCriterion<Complex32>(MaximumIterations), new ResidualStopCriterion<Complex32>(ConvergenceBoundary), new DivergenceStopCriterion<Complex32>(), new FailureStopCriterion<Complex32>()); var solver = new MlkBiCgStab(); // Solve equation Ax = y var x = matrix.SolveIterative(y, solver, monitor); // Now compare the results Assert.IsNotNull(x, "#02"); Assert.AreEqual(y.Count, x.Count, "#03"); // Back multiply the vector var z = matrix.Multiply(x); // Check that the solution converged Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04"); // Now compare the vectors for (var i = 0; i < y.Count; i++) { Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i); } } /// <summary> /// Solve scaled unit matrix and back multiply. /// </summary> [Test] public void SolveScaledUnitMatrixAndBackMultiply() { // Create the identity matrix var matrix = SparseMatrix.CreateIdentity(100); // Scale it with a funny number matrix.Multiply((float)Math.PI, matrix); // Create the y vector var y = Vector<Complex32>.Build.Dense(matrix.RowCount, 1); // Create an iteration monitor which will keep track of iterative convergence var monitor = new Iterator<Complex32>( new IterationCountStopCriterion<Complex32>(MaximumIterations), new ResidualStopCriterion<Complex32>(ConvergenceBoundary), new DivergenceStopCriterion<Complex32>(), new FailureStopCriterion<Complex32>()); var solver = new MlkBiCgStab(); // Solve equation Ax = y var x = matrix.SolveIterative(y, solver, monitor); // Now compare the results Assert.IsNotNull(x, "#02"); Assert.AreEqual(y.Count, x.Count, "#03"); // Back multiply the vector var z = matrix.Multiply(x); // Check that the solution converged Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04"); // Now compare the vectors for (var i = 0; i < y.Count; i++) { Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i); } } /// <summary> /// Solve poisson matrix and back multiply. /// </summary> [Test] public void SolvePoissonMatrixAndBackMultiply() { // Create the matrix var matrix = new SparseMatrix(25); // Assemble the matrix. We assume we're solving the Poisson equation // on a rectangular 5 x 5 grid const int GridSize = 5; // The pattern is: // 0 .... 0 -1 0 0 0 0 0 0 0 0 -1 4 -1 0 0 0 0 0 0 0 0 -1 0 0 ... 0 for (var i = 0; i < matrix.RowCount; i++) { // Insert the first set of -1's if (i > (GridSize - 1)) { matrix[i, i - GridSize] = -1; } // Insert the second set of -1's if (i > 0) { matrix[i, i - 1] = -1; } // Insert the centerline values matrix[i, i] = 4; // Insert the first trailing set of -1's if (i < matrix.RowCount - 1) { matrix[i, i + 1] = -1; } // Insert the second trailing set of -1's if (i < matrix.RowCount - GridSize) { matrix[i, i + GridSize] = -1; } } // Create the y vector var y = Vector<Complex32>.Build.Dense(matrix.RowCount, 1); // Create an iteration monitor which will keep track of iterative convergence var monitor = new Iterator<Complex32>( new IterationCountStopCriterion<Complex32>(MaximumIterations), new ResidualStopCriterion<Complex32>(ConvergenceBoundary), new DivergenceStopCriterion<Complex32>(), new FailureStopCriterion<Complex32>()); var solver = new MlkBiCgStab(); // Solve equation Ax = y var x = matrix.SolveIterative(y, solver, monitor); // Now compare the results Assert.IsNotNull(x, "#02"); Assert.AreEqual(y.Count, x.Count, "#03"); // Back multiply the vector var z = matrix.Multiply(x); // Check that the solution converged Assert.IsTrue(monitor.Status == IterationStatus.Converged, "#04"); // Now compare the vectors for (var i = 0; i < y.Count; i++) { Assert.GreaterOrEqual(ConvergenceBoundary, (y[i] - z[i]).Magnitude, "#05-" + i); } } /// <summary> /// Can solve for a random vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(4)] public void CanSolveForRandomVector(int order) { for (var iteration = 5; iteration > 3; iteration--) { var matrixA = Matrix<Complex32>.Build.Random(order, order, 1); var vectorb = Vector<Complex32>.Build.Random(order, 1); var monitor = new Iterator<Complex32>( new IterationCountStopCriterion<Complex32>(1000), new ResidualStopCriterion<Complex32>(Math.Pow(1.0/10.0, iteration))); var solver = new MlkBiCgStab(); var resultx = matrixA.SolveIterative(vectorb, solver, monitor); if (monitor.Status != IterationStatus.Converged) { // Solution was not found, try again downgrading convergence boundary continue; } Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA*resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { Assert.AreEqual(vectorb[i].Real, matrixBReconstruct[i].Real, (float)Math.Pow(1.0/10.0, iteration - 3)); Assert.AreEqual(vectorb[i].Imaginary, matrixBReconstruct[i].Imaginary, (float)Math.Pow(1.0/10.0, iteration - 3)); } return; } Assert.Fail("Solution was not found in 3 tries"); } /// <summary> /// Can solve for random matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(4)] public void CanSolveForRandomMatrix(int order) { for (var iteration = 5; iteration > 3; iteration--) { var matrixA = Matrix<Complex32>.Build.Random(order, order, 1); var matrixB = Matrix<Complex32>.Build.Random(order, order, 1); var monitor = new Iterator<Complex32>( new IterationCountStopCriterion<Complex32>(1000), new ResidualStopCriterion<Complex32>(Math.Pow(1.0/10.0, iteration))); var solver = new MlkBiCgStab(); var matrixX = matrixA.SolveIterative(matrixB, solver, monitor); if (monitor.Status != IterationStatus.Converged) { // Solution was not found, try again downgrading convergence boundary continue; } // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA*matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j].Real, matrixBReconstruct[i, j].Real, (float)Math.Pow(1.0/10.0, iteration - 3)); Assert.AreEqual(matrixB[i, j].Imaginary, matrixBReconstruct[i, j].Imaginary, (float)Math.Pow(1.0/10.0, iteration - 3)); } } return; } Assert.Fail("Solution was not found in 3 tries"); } } }
namespace KryptonFormExamples { partial class Form1 { /// <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(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.menu1ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.oneToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.twoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.threeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menu2ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.fourToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.fiveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menu3ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sixToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sevenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.eightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.newToolStripButton = new System.Windows.Forms.ToolStripButton(); this.openToolStripButton = new System.Windows.Forms.ToolStripButton(); this.saveToolStripButton = new System.Windows.Forms.ToolStripButton(); this.printToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator = new System.Windows.Forms.ToolStripSeparator(); this.cutToolStripButton = new System.Windows.Forms.ToolStripButton(); this.copyToolStripButton = new System.Windows.Forms.ToolStripButton(); this.pasteToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.helpToolStripButton = new System.Windows.Forms.ToolStripButton(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.toolStripStatusLabel1 = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer(); this.kryptonHeaderGroup3 = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup(); this.propertyGrid = new System.Windows.Forms.PropertyGrid(); this.kryptonHeaderGroup2 = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup(); this.kryptonNone = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonFixedSingle = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonFixed3D = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonFixedDialog = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonSizeableToolWindow = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonFixedToolWindow = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonSizable = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonHeaderGroup1 = new ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup(); this.kryptonOffice2010Black = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonOffice2010Silver = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonOffice2010Blue = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonSparkleOrange = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonSparkleBlue = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonOffice2003 = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonSystem = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonOffice2007Black = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonOffice2007Silver = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonOffice2007Blue = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.kryptonCheckSetPalettes = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components); this.kryptonCheckSetStyles = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components); this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); this.menuStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.toolStripContainer1.ContentPanel.SuspendLayout(); this.toolStripContainer1.TopToolStripPanel.SuspendLayout(); this.toolStripContainer1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup3.Panel)).BeginInit(); this.kryptonHeaderGroup3.Panel.SuspendLayout(); this.kryptonHeaderGroup3.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup2.Panel)).BeginInit(); this.kryptonHeaderGroup2.Panel.SuspendLayout(); this.kryptonHeaderGroup2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1.Panel)).BeginInit(); this.kryptonHeaderGroup1.Panel.SuspendLayout(); this.kryptonHeaderGroup1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonCheckSetPalettes)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonCheckSetStyles)).BeginInit(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Font = new System.Drawing.Font("Segoe UI", 9F); this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.menu1ToolStripMenuItem, this.menu2ToolStripMenuItem, this.menu3ToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(628, 24); this.menuStrip1.TabIndex = 0; this.menuStrip1.Text = "menuStrip1"; // // menu1ToolStripMenuItem // this.menu1ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.oneToolStripMenuItem, this.twoToolStripMenuItem, this.threeToolStripMenuItem}); this.menu1ToolStripMenuItem.Name = "menu1ToolStripMenuItem"; this.menu1ToolStripMenuItem.Size = new System.Drawing.Size(56, 20); this.menu1ToolStripMenuItem.Text = "Menu1"; // // oneToolStripMenuItem // this.oneToolStripMenuItem.Name = "oneToolStripMenuItem"; this.oneToolStripMenuItem.Size = new System.Drawing.Size(104, 22); this.oneToolStripMenuItem.Text = "One"; // // twoToolStripMenuItem // this.twoToolStripMenuItem.Name = "twoToolStripMenuItem"; this.twoToolStripMenuItem.Size = new System.Drawing.Size(104, 22); this.twoToolStripMenuItem.Text = "Two"; // // threeToolStripMenuItem // this.threeToolStripMenuItem.Name = "threeToolStripMenuItem"; this.threeToolStripMenuItem.Size = new System.Drawing.Size(104, 22); this.threeToolStripMenuItem.Text = "Three"; // // menu2ToolStripMenuItem // this.menu2ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fourToolStripMenuItem, this.fiveToolStripMenuItem}); this.menu2ToolStripMenuItem.Name = "menu2ToolStripMenuItem"; this.menu2ToolStripMenuItem.Size = new System.Drawing.Size(56, 20); this.menu2ToolStripMenuItem.Text = "Menu2"; // // fourToolStripMenuItem // this.fourToolStripMenuItem.Name = "fourToolStripMenuItem"; this.fourToolStripMenuItem.Size = new System.Drawing.Size(98, 22); this.fourToolStripMenuItem.Text = "Four"; // // fiveToolStripMenuItem // this.fiveToolStripMenuItem.Name = "fiveToolStripMenuItem"; this.fiveToolStripMenuItem.Size = new System.Drawing.Size(98, 22); this.fiveToolStripMenuItem.Text = "Five"; // // menu3ToolStripMenuItem // this.menu3ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sixToolStripMenuItem, this.sevenToolStripMenuItem, this.eightToolStripMenuItem}); this.menu3ToolStripMenuItem.Name = "menu3ToolStripMenuItem"; this.menu3ToolStripMenuItem.Size = new System.Drawing.Size(56, 20); this.menu3ToolStripMenuItem.Text = "Menu3"; // // sixToolStripMenuItem // this.sixToolStripMenuItem.Name = "sixToolStripMenuItem"; this.sixToolStripMenuItem.Size = new System.Drawing.Size(105, 22); this.sixToolStripMenuItem.Text = "Six"; // // sevenToolStripMenuItem // this.sevenToolStripMenuItem.Name = "sevenToolStripMenuItem"; this.sevenToolStripMenuItem.Size = new System.Drawing.Size(105, 22); this.sevenToolStripMenuItem.Text = "Seven"; // // eightToolStripMenuItem // this.eightToolStripMenuItem.Name = "eightToolStripMenuItem"; this.eightToolStripMenuItem.Size = new System.Drawing.Size(105, 22); this.eightToolStripMenuItem.Text = "Eight"; // // toolStrip1 // this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip1.Font = new System.Drawing.Font("Segoe UI", 9F); this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripButton, this.openToolStripButton, this.saveToolStripButton, this.printToolStripButton, this.toolStripSeparator, this.cutToolStripButton, this.copyToolStripButton, this.pasteToolStripButton, this.toolStripSeparator1, this.helpToolStripButton}); this.toolStrip1.Location = new System.Drawing.Point(3, 0); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(208, 25); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; // // newToolStripButton // this.newToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.newToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("newToolStripButton.Image"))); this.newToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.newToolStripButton.Name = "newToolStripButton"; this.newToolStripButton.Size = new System.Drawing.Size(23, 22); this.newToolStripButton.Text = "&New"; // // openToolStripButton // this.openToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.openToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("openToolStripButton.Image"))); this.openToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.openToolStripButton.Name = "openToolStripButton"; this.openToolStripButton.Size = new System.Drawing.Size(23, 22); this.openToolStripButton.Text = "&Open"; // // saveToolStripButton // this.saveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.saveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("saveToolStripButton.Image"))); this.saveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.saveToolStripButton.Name = "saveToolStripButton"; this.saveToolStripButton.Size = new System.Drawing.Size(23, 22); this.saveToolStripButton.Text = "&Save"; // // printToolStripButton // this.printToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.printToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("printToolStripButton.Image"))); this.printToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.printToolStripButton.Name = "printToolStripButton"; this.printToolStripButton.Size = new System.Drawing.Size(23, 22); this.printToolStripButton.Text = "&Print"; // // toolStripSeparator // this.toolStripSeparator.Name = "toolStripSeparator"; this.toolStripSeparator.Size = new System.Drawing.Size(6, 25); // // cutToolStripButton // this.cutToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.cutToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("cutToolStripButton.Image"))); this.cutToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.cutToolStripButton.Name = "cutToolStripButton"; this.cutToolStripButton.Size = new System.Drawing.Size(23, 22); this.cutToolStripButton.Text = "C&ut"; // // copyToolStripButton // this.copyToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.copyToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("copyToolStripButton.Image"))); this.copyToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.copyToolStripButton.Name = "copyToolStripButton"; this.copyToolStripButton.Size = new System.Drawing.Size(23, 22); this.copyToolStripButton.Text = "&Copy"; // // pasteToolStripButton // this.pasteToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.pasteToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("pasteToolStripButton.Image"))); this.pasteToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.pasteToolStripButton.Name = "pasteToolStripButton"; this.pasteToolStripButton.Size = new System.Drawing.Size(23, 22); this.pasteToolStripButton.Text = "&Paste"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // helpToolStripButton // this.helpToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.helpToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("helpToolStripButton.Image"))); this.helpToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.helpToolStripButton.Name = "helpToolStripButton"; this.helpToolStripButton.Size = new System.Drawing.Size(23, 22); this.helpToolStripButton.Text = "He&lp"; // // statusStrip1 // this.statusStrip1.Font = new System.Drawing.Font("Segoe UI", 9F); this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripStatusLabel1}); this.statusStrip1.Location = new System.Drawing.Point(0, 471); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode; this.statusStrip1.Size = new System.Drawing.Size(628, 22); this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "statusStrip1"; // // toolStripStatusLabel1 // this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new System.Drawing.Size(160, 17); this.toolStripStatusLabel1.Text = "Example StatusStrip label text"; // // toolStripContainer1 // // // toolStripContainer1.ContentPanel // this.toolStripContainer1.ContentPanel.Controls.Add(this.kryptonHeaderGroup3); this.toolStripContainer1.ContentPanel.Controls.Add(this.kryptonHeaderGroup2); this.toolStripContainer1.ContentPanel.Controls.Add(this.kryptonHeaderGroup1); this.toolStripContainer1.ContentPanel.RenderMode = System.Windows.Forms.ToolStripRenderMode.ManagerRenderMode; this.toolStripContainer1.ContentPanel.Size = new System.Drawing.Size(628, 422); this.toolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill; this.toolStripContainer1.Location = new System.Drawing.Point(0, 24); this.toolStripContainer1.Name = "toolStripContainer1"; this.toolStripContainer1.Size = new System.Drawing.Size(628, 447); this.toolStripContainer1.TabIndex = 3; this.toolStripContainer1.Text = "toolStripContainer1"; // // toolStripContainer1.TopToolStripPanel // this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStrip1); // // kryptonHeaderGroup3 // this.kryptonHeaderGroup3.HeaderVisibleSecondary = false; this.kryptonHeaderGroup3.Location = new System.Drawing.Point(395, 12); this.kryptonHeaderGroup3.Name = "kryptonHeaderGroup3"; // // kryptonHeaderGroup3.Panel // this.kryptonHeaderGroup3.Panel.Controls.Add(this.propertyGrid); this.kryptonHeaderGroup3.Size = new System.Drawing.Size(218, 398); this.kryptonHeaderGroup3.TabIndex = 2; this.kryptonHeaderGroup3.ValuesPrimary.Heading = "Form Properties"; this.kryptonHeaderGroup3.ValuesPrimary.Image = null; // // propertyGrid // this.propertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.propertyGrid.HelpVisible = false; this.propertyGrid.Location = new System.Drawing.Point(0, 0); this.propertyGrid.Name = "propertyGrid"; this.propertyGrid.Size = new System.Drawing.Size(216, 367); this.propertyGrid.TabIndex = 0; this.propertyGrid.ToolbarVisible = false; // // kryptonHeaderGroup2 // this.kryptonHeaderGroup2.HeaderVisibleSecondary = false; this.kryptonHeaderGroup2.Location = new System.Drawing.Point(191, 12); this.kryptonHeaderGroup2.Name = "kryptonHeaderGroup2"; // // kryptonHeaderGroup2.Panel // this.kryptonHeaderGroup2.Panel.Controls.Add(this.kryptonNone); this.kryptonHeaderGroup2.Panel.Controls.Add(this.kryptonFixedSingle); this.kryptonHeaderGroup2.Panel.Controls.Add(this.kryptonFixed3D); this.kryptonHeaderGroup2.Panel.Controls.Add(this.kryptonFixedDialog); this.kryptonHeaderGroup2.Panel.Controls.Add(this.kryptonSizeableToolWindow); this.kryptonHeaderGroup2.Panel.Controls.Add(this.kryptonFixedToolWindow); this.kryptonHeaderGroup2.Panel.Controls.Add(this.kryptonSizable); this.kryptonHeaderGroup2.Size = new System.Drawing.Size(191, 398); this.kryptonHeaderGroup2.TabIndex = 1; this.kryptonHeaderGroup2.ValuesPrimary.Heading = "Form Border Styles"; this.kryptonHeaderGroup2.ValuesPrimary.Image = null; // // kryptonNone // this.kryptonNone.AutoSize = true; this.kryptonNone.Location = new System.Drawing.Point(26, 14); this.kryptonNone.Name = "kryptonNone"; this.kryptonNone.Size = new System.Drawing.Size(138, 27); this.kryptonNone.TabIndex = 11; this.kryptonNone.Values.Text = "None"; // // kryptonFixedSingle // this.kryptonFixedSingle.AutoSize = true; this.kryptonFixedSingle.Location = new System.Drawing.Point(26, 48); this.kryptonFixedSingle.Name = "kryptonFixedSingle"; this.kryptonFixedSingle.Size = new System.Drawing.Size(138, 27); this.kryptonFixedSingle.TabIndex = 10; this.kryptonFixedSingle.Values.Text = "Fixed Single"; // // kryptonFixed3D // this.kryptonFixed3D.AutoSize = true; this.kryptonFixed3D.Location = new System.Drawing.Point(26, 82); this.kryptonFixed3D.Name = "kryptonFixed3D"; this.kryptonFixed3D.Size = new System.Drawing.Size(138, 27); this.kryptonFixed3D.TabIndex = 9; this.kryptonFixed3D.Values.Text = "Fixed 3D"; // // kryptonFixedDialog // this.kryptonFixedDialog.AutoSize = true; this.kryptonFixedDialog.Location = new System.Drawing.Point(26, 116); this.kryptonFixedDialog.Name = "kryptonFixedDialog"; this.kryptonFixedDialog.Size = new System.Drawing.Size(138, 27); this.kryptonFixedDialog.TabIndex = 8; this.kryptonFixedDialog.Values.Text = "Fixed Dialog"; // // kryptonSizeableToolWindow // this.kryptonSizeableToolWindow.AutoSize = true; this.kryptonSizeableToolWindow.Location = new System.Drawing.Point(26, 218); this.kryptonSizeableToolWindow.Name = "kryptonSizeableToolWindow"; this.kryptonSizeableToolWindow.Size = new System.Drawing.Size(138, 27); this.kryptonSizeableToolWindow.TabIndex = 7; this.kryptonSizeableToolWindow.Values.Text = "Sizable Tool Window"; // // kryptonFixedToolWindow // this.kryptonFixedToolWindow.AutoSize = true; this.kryptonFixedToolWindow.Location = new System.Drawing.Point(26, 184); this.kryptonFixedToolWindow.Name = "kryptonFixedToolWindow"; this.kryptonFixedToolWindow.Size = new System.Drawing.Size(138, 27); this.kryptonFixedToolWindow.TabIndex = 6; this.kryptonFixedToolWindow.Values.Text = "Fixed Tool Window"; // // kryptonSizable // this.kryptonSizable.AutoSize = true; this.kryptonSizable.Checked = true; this.kryptonSizable.Location = new System.Drawing.Point(26, 150); this.kryptonSizable.Name = "kryptonSizable"; this.kryptonSizable.Size = new System.Drawing.Size(138, 27); this.kryptonSizable.TabIndex = 5; this.kryptonSizable.Values.Text = "Sizable"; // // kryptonHeaderGroup1 // this.kryptonHeaderGroup1.HeaderVisibleSecondary = false; this.kryptonHeaderGroup1.Location = new System.Drawing.Point(12, 12); this.kryptonHeaderGroup1.Name = "kryptonHeaderGroup1"; // // kryptonHeaderGroup1.Panel // this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonOffice2010Black); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonOffice2010Silver); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonOffice2010Blue); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonSparkleOrange); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonSparkleBlue); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonOffice2003); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonSystem); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonOffice2007Black); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonOffice2007Silver); this.kryptonHeaderGroup1.Panel.Controls.Add(this.kryptonOffice2007Blue); this.kryptonHeaderGroup1.Size = new System.Drawing.Size(166, 398); this.kryptonHeaderGroup1.TabIndex = 0; this.kryptonHeaderGroup1.ValuesPrimary.Heading = "Palettes"; this.kryptonHeaderGroup1.ValuesPrimary.Image = null; // // kryptonOffice2010Black // this.kryptonOffice2010Black.AutoSize = true; this.kryptonOffice2010Black.Location = new System.Drawing.Point(20, 82); this.kryptonOffice2010Black.Name = "kryptonOffice2010Black"; this.kryptonOffice2010Black.Size = new System.Drawing.Size(118, 27); this.kryptonOffice2010Black.TabIndex = 2; this.kryptonOffice2010Black.Values.Text = "Office 2010 Black"; // // kryptonOffice2010Silver // this.kryptonOffice2010Silver.AutoSize = true; this.kryptonOffice2010Silver.Location = new System.Drawing.Point(20, 48); this.kryptonOffice2010Silver.Name = "kryptonOffice2010Silver"; this.kryptonOffice2010Silver.Size = new System.Drawing.Size(118, 27); this.kryptonOffice2010Silver.TabIndex = 1; this.kryptonOffice2010Silver.Values.Text = "Office 2010 Silver"; // // kryptonOffice2010Blue // this.kryptonOffice2010Blue.AutoSize = true; this.kryptonOffice2010Blue.Checked = true; this.kryptonOffice2010Blue.Location = new System.Drawing.Point(20, 14); this.kryptonOffice2010Blue.Name = "kryptonOffice2010Blue"; this.kryptonOffice2010Blue.Size = new System.Drawing.Size(118, 27); this.kryptonOffice2010Blue.TabIndex = 0; this.kryptonOffice2010Blue.Values.Text = "Office 2010 Blue"; // // kryptonSparkleOrange // this.kryptonSparkleOrange.AutoSize = true; this.kryptonSparkleOrange.Location = new System.Drawing.Point(20, 285); this.kryptonSparkleOrange.Name = "kryptonSparkleOrange"; this.kryptonSparkleOrange.Size = new System.Drawing.Size(118, 27); this.kryptonSparkleOrange.TabIndex = 8; this.kryptonSparkleOrange.Values.Text = "Sparkle - Orange"; // // kryptonSparkleBlue // this.kryptonSparkleBlue.AutoSize = true; this.kryptonSparkleBlue.Location = new System.Drawing.Point(20, 252); this.kryptonSparkleBlue.Name = "kryptonSparkleBlue"; this.kryptonSparkleBlue.Size = new System.Drawing.Size(118, 27); this.kryptonSparkleBlue.TabIndex = 7; this.kryptonSparkleBlue.Values.Text = "Sparkle - Blue"; // // kryptonOffice2003 // this.kryptonOffice2003.AutoSize = true; this.kryptonOffice2003.Location = new System.Drawing.Point(20, 218); this.kryptonOffice2003.Name = "kryptonOffice2003"; this.kryptonOffice2003.Size = new System.Drawing.Size(118, 27); this.kryptonOffice2003.TabIndex = 6; this.kryptonOffice2003.Values.Text = "Office 2003"; // // kryptonSystem // this.kryptonSystem.AutoSize = true; this.kryptonSystem.Location = new System.Drawing.Point(20, 320); this.kryptonSystem.Name = "kryptonSystem"; this.kryptonSystem.Size = new System.Drawing.Size(118, 27); this.kryptonSystem.TabIndex = 9; this.kryptonSystem.Values.Text = "System"; // // kryptonOffice2007Black // this.kryptonOffice2007Black.AutoSize = true; this.kryptonOffice2007Black.Location = new System.Drawing.Point(20, 184); this.kryptonOffice2007Black.Name = "kryptonOffice2007Black"; this.kryptonOffice2007Black.Size = new System.Drawing.Size(118, 27); this.kryptonOffice2007Black.TabIndex = 5; this.kryptonOffice2007Black.Values.Text = "Office 2007 Black"; // // kryptonOffice2007Silver // this.kryptonOffice2007Silver.AutoSize = true; this.kryptonOffice2007Silver.Location = new System.Drawing.Point(20, 150); this.kryptonOffice2007Silver.Name = "kryptonOffice2007Silver"; this.kryptonOffice2007Silver.Size = new System.Drawing.Size(118, 27); this.kryptonOffice2007Silver.TabIndex = 4; this.kryptonOffice2007Silver.Values.Text = "Office 2007 Silver"; // // kryptonOffice2007Blue // this.kryptonOffice2007Blue.AutoSize = true; this.kryptonOffice2007Blue.Location = new System.Drawing.Point(20, 116); this.kryptonOffice2007Blue.Name = "kryptonOffice2007Blue"; this.kryptonOffice2007Blue.Size = new System.Drawing.Size(118, 27); this.kryptonOffice2007Blue.TabIndex = 3; this.kryptonOffice2007Blue.Values.Text = "Office 2007 Blue"; // // kryptonCheckSetPalettes // this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonSystem); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonOffice2007Black); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonOffice2007Silver); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonOffice2007Blue); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonOffice2003); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonSparkleBlue); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonSparkleOrange); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonOffice2010Black); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonOffice2010Silver); this.kryptonCheckSetPalettes.CheckButtons.Add(this.kryptonOffice2010Blue); this.kryptonCheckSetPalettes.CheckedButton = this.kryptonOffice2010Blue; this.kryptonCheckSetPalettes.CheckedButtonChanged += new System.EventHandler(this.kryptonCheckSetPalettes_CheckedButtonChanged); // // kryptonCheckSetStyles // this.kryptonCheckSetStyles.CheckButtons.Add(this.kryptonSizable); this.kryptonCheckSetStyles.CheckButtons.Add(this.kryptonFixedToolWindow); this.kryptonCheckSetStyles.CheckButtons.Add(this.kryptonSizeableToolWindow); this.kryptonCheckSetStyles.CheckButtons.Add(this.kryptonFixedDialog); this.kryptonCheckSetStyles.CheckButtons.Add(this.kryptonFixed3D); this.kryptonCheckSetStyles.CheckButtons.Add(this.kryptonFixedSingle); this.kryptonCheckSetStyles.CheckButtons.Add(this.kryptonNone); this.kryptonCheckSetStyles.CheckedButton = this.kryptonSizable; this.kryptonCheckSetStyles.CheckedButtonChanged += new System.EventHandler(this.kryptonCheckSetStyles_CheckedButtonChanged); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(628, 493); this.Controls.Add(this.toolStripContainer1); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.menuStrip1); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.MinimumSize = new System.Drawing.Size(644, 531); this.Name = "Form1"; this.Text = "KryptonForm Examples"; this.TextExtra = "(ExtraText)"; this.Load += new System.EventHandler(this.Form1_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.toolStripContainer1.ContentPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false); this.toolStripContainer1.TopToolStripPanel.PerformLayout(); this.toolStripContainer1.ResumeLayout(false); this.toolStripContainer1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup3.Panel)).EndInit(); this.kryptonHeaderGroup3.Panel.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup3)).EndInit(); this.kryptonHeaderGroup3.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup2.Panel)).EndInit(); this.kryptonHeaderGroup2.Panel.ResumeLayout(false); this.kryptonHeaderGroup2.Panel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup2)).EndInit(); this.kryptonHeaderGroup2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1.Panel)).EndInit(); this.kryptonHeaderGroup1.Panel.ResumeLayout(false); this.kryptonHeaderGroup1.Panel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonHeaderGroup1)).EndInit(); this.kryptonHeaderGroup1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.kryptonCheckSetPalettes)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kryptonCheckSetStyles)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem menu1ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem oneToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem twoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem threeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem menu2ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem fourToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem fiveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem menu3ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sixToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem sevenToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem eightToolStripMenuItem; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton newToolStripButton; private System.Windows.Forms.ToolStripButton openToolStripButton; private System.Windows.Forms.ToolStripButton saveToolStripButton; private System.Windows.Forms.ToolStripButton printToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator; private System.Windows.Forms.ToolStripButton cutToolStripButton; private System.Windows.Forms.ToolStripButton copyToolStripButton; private System.Windows.Forms.ToolStripButton pasteToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripButton helpToolStripButton; private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.ToolStripContainer toolStripContainer1; private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroup2; private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroup1; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonOffice2007Blue; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonSystem; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonOffice2007Black; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonOffice2007Silver; private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kryptonCheckSetPalettes; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonOffice2003; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonNone; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonFixedSingle; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonFixed3D; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonFixedDialog; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonSizeableToolWindow; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonFixedToolWindow; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonSizable; private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kryptonCheckSetStyles; private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager; private ComponentFactory.Krypton.Toolkit.KryptonHeaderGroup kryptonHeaderGroup3; private System.Windows.Forms.PropertyGrid propertyGrid; private System.Windows.Forms.ToolStripStatusLabel toolStripStatusLabel1; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonSparkleBlue; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonSparkleOrange; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonOffice2010Black; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonOffice2010Silver; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton kryptonOffice2010Blue; } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // OrderPreservingPipeliningSpoolingTask.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Collections.Generic; using System.Linq; using System.Linq.Parallel; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Diagnostics; namespace System.Linq.Parallel { class OrderPreservingPipeliningSpoolingTask<TOutput, TKey> : SpoolingTaskBase { private readonly QueryTaskGroupState _taskGroupState; // State shared among tasks. private readonly QueryOperatorEnumerator<TOutput, TKey> _partition; // The source partition. private readonly bool[] _consumerWaiting; // Whether a consumer is waiting on a particular producer private readonly bool[] _producerWaiting; // Whether a particular producer is waiting on the consumer private readonly bool[] _producerDone; // Whether each producer is done private readonly int _partitionIndex; // Index of the partition owned by this task. private readonly Queue<Pair<TKey, TOutput>>[] _buffers; // The buffer for the results private readonly object _bufferLock; // A lock for the buffer /// <summary> /// Whether the producer is allowed to buffer up elements before handing a chunk to the consumer. /// If false, the producer will make each result available to the consumer immediately after it is /// produced. /// </summary> private readonly bool _autoBuffered; /// <summary> /// The number of elements to accumulate on the producer before copying the elements to the /// producer-consumer buffer. This constant is only used in the AutoBuffered mode. /// /// Experimentally, 16 appears to be sufficient buffer size to compensate for the synchronization /// cost. /// </summary> private const int PRODUCER_BUFFER_AUTO_SIZE = 16; /// <summary> /// Constructor /// </summary> internal OrderPreservingPipeliningSpoolingTask( QueryOperatorEnumerator<TOutput, TKey> partition, QueryTaskGroupState taskGroupState, bool[] consumerWaiting, bool[] producerWaiting, bool[] producerDone, int partitionIndex, Queue<Pair<TKey, TOutput>>[] buffers, object bufferLock, bool autoBuffered) : base(partitionIndex, taskGroupState) { Debug.Assert(partition != null); Debug.Assert(taskGroupState != null); Debug.Assert(consumerWaiting != null); Debug.Assert(producerWaiting != null && producerWaiting.Length == consumerWaiting.Length); Debug.Assert(producerDone != null && producerDone.Length == consumerWaiting.Length); Debug.Assert(buffers != null && buffers.Length == consumerWaiting.Length); Debug.Assert(partitionIndex >= 0 && partitionIndex < consumerWaiting.Length); _partition = partition; _taskGroupState = taskGroupState; _producerDone = producerDone; _consumerWaiting = consumerWaiting; _producerWaiting = producerWaiting; _partitionIndex = partitionIndex; _buffers = buffers; _bufferLock = bufferLock; _autoBuffered = autoBuffered; } /// <summary> /// This method is responsible for enumerating results and enqueuing them to /// the output buffer as appropriate. Each base class implements its own. /// </summary> protected override void SpoolingWork() { TOutput element = default(TOutput); TKey key = default(TKey); int chunkSize = _autoBuffered ? PRODUCER_BUFFER_AUTO_SIZE : 1; Pair<TKey, TOutput>[] chunk = new Pair<TKey, TOutput>[chunkSize]; var partition = _partition; CancellationToken cancelToken = _taskGroupState.CancellationState.MergedCancellationToken; int lastChunkSize; do { lastChunkSize = 0; while (lastChunkSize < chunkSize && partition.MoveNext(ref element, ref key)) { chunk[lastChunkSize] = new Pair<TKey, TOutput>(key, element); lastChunkSize++; } if (lastChunkSize == 0) break; lock (_bufferLock) { // Check if the query has been cancelled. if (cancelToken.IsCancellationRequested) { break; } for (int i = 0; i < lastChunkSize; i++) { _buffers[_partitionIndex].Enqueue(chunk[i]); } if (_consumerWaiting[_partitionIndex]) { Monitor.Pulse(_bufferLock); _consumerWaiting[_partitionIndex] = false; } // If the producer buffer is too large, wait. // Note: we already checked for cancellation after acquiring the lock on this producer. // That guarantees that the consumer will eventually wake up the producer. if (_buffers[_partitionIndex].Count >= OrderPreservingPipeliningMergeHelper<TOutput, TKey>.MAX_BUFFER_SIZE) { _producerWaiting[_partitionIndex] = true; Monitor.Wait(_bufferLock); } } } while (lastChunkSize == chunkSize); } /// <summary> /// Creates and begins execution of a new set of spooling tasks. /// </summary> public static void Spool( QueryTaskGroupState groupState, PartitionedStream<TOutput, TKey> partitions, bool[] consumerWaiting, bool[] producerWaiting, bool[] producerDone, Queue<Pair<TKey, TOutput>>[] buffers, object[] bufferLocks, TaskScheduler taskScheduler, bool autoBuffered) { Debug.Assert(groupState != null); Debug.Assert(partitions != null); Debug.Assert(producerDone != null && producerDone.Length == partitions.PartitionCount); Debug.Assert(buffers != null && buffers.Length == partitions.PartitionCount); Debug.Assert(bufferLocks != null); int degreeOfParallelism = partitions.PartitionCount; // Initialize the buffers and buffer locks. for (int i = 0; i < degreeOfParallelism; i++) { buffers[i] = new Queue<Pair<TKey, TOutput>>(OrderPreservingPipeliningMergeHelper<TOutput, TKey>.INITIAL_BUFFER_SIZE); bufferLocks[i] = new object(); } // Ensure all tasks in this query are parented under a common root. Because this // is a pipelined query, we detach it from the parent (to avoid blocking the calling // thread), and run the query on a separate thread. Task rootTask = new Task( () => { for (int i = 0; i < degreeOfParallelism; i++) { QueryTask asyncTask = new OrderPreservingPipeliningSpoolingTask<TOutput, TKey>( partitions[i], groupState, consumerWaiting, producerWaiting, producerDone, i, buffers, bufferLocks[i], autoBuffered); asyncTask.RunAsynchronously(taskScheduler); } }); // Begin the query on the calling thread. groupState.QueryBegin(rootTask); // And schedule it for execution. This is done after beginning to ensure no thread tries to // end the query before its root task has been recorded properly. rootTask.Start(taskScheduler); // We don't call QueryEnd here; when we return, the query is still executing, and the // last enumerator to be disposed of will call QueryEnd for us. } /// <summary> /// Dispose the underlying enumerator and wake up the consumer if necessary. /// </summary> protected override void SpoolingFinally() { // Let the consumer know that this producer is done. lock (_bufferLock) { _producerDone[_partitionIndex] = true; if (_consumerWaiting[_partitionIndex]) { Monitor.Pulse(_bufferLock); _consumerWaiting[_partitionIndex] = false; } } // Call the base implementation. base.SpoolingFinally(); // Dispose of the source enumerator *after* signaling that the task is done. // We call Dispose() last to ensure that if it throws an exception, we will not cause a deadlock. _partition.Dispose(); } } }
using System; using System.Collections.Generic; using System.Text; // Copyright (c) 2006, 2007 by Hugh Pyle, inguzaudio.com namespace DSPUtil { /// <summary> /// 0dbfs signal generators /// </summary> public class SignalGenerator : SoundObj { protected const double twopi = 2 * Math.PI; protected double _freq; protected double _gain; public SignalGenerator(ushort numChannels, uint sampleRate, double freq, double gain) { NumChannels = numChannels; SampleRate = sampleRate; _freq = freq; _gain = gain; } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { yield break; } } /// <summary> Number of iterations expected to do the signal processing </summary> public override int Iterations { get { return int.MaxValue; } } } public class SineGenerator : SignalGenerator { public SineGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { ushort nc = NumChannels; uint sr = SampleRate; double mul = twopi * _freq / sr; int n = 0; Sample s = new Sample(nc); while (true) { double v = _gain * Math.Sin(n * mul); for (int c = 0; c < nc; c++) { s[c] = v; } n++; yield return s; } } } } public class SineQuadGenerator : SignalGenerator { public SineQuadGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { ushort nc = NumChannels; if (nc < 2) { throw new ArgumentOutOfRangeException("NumChannels", "Quadrature requires two channels."); } uint sr = SampleRate; double mul = twopi * _freq / sr; int n = 0; Sample s = new Sample(nc); while (true) { s[0] = _gain * Math.Cos(n * mul); s[1] = _gain * Math.Sin(n * mul); n++; yield return s; } } } } public class SquareGenerator : SignalGenerator { public SquareGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { ushort nc = NumChannels; uint sr = SampleRate; double mul = 2 * _freq / sr; int n = 0; Sample s = new Sample(nc); while (true) { double saw = ((n * mul) % 2) - 1; double v = saw >0 ? _gain : -_gain; for (int c = 0; c < nc; c++) { s[c] = v; } n++; yield return s; } } } } public class Harmonic { public double Gain; public double Phase; public Harmonic(double gain) { Gain = gain; Phase = 0; } public Harmonic(double gain, double phase) { Gain = gain; Phase = phase; } } public abstract class HarmonicGenerator : SignalGenerator { public HarmonicGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } public virtual List<Harmonic> Harmonics { get { List<Harmonic> harmonics = new List<Harmonic>(); return harmonics; } } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { ushort nc = NumChannels; uint sr = SampleRate; double mul = twopi * _freq / sr; int n = 0; List<Harmonic> lH = Harmonics; List<Sample> samples = new List<Sample>((int)sr); while(n<sr) { double v = 0; for (int nH = 0; nH < lH.Count; nH++) { Harmonic h = lH[nH]; if (h.Gain > 0) v += h.Gain * Math.Sin((nH * n * mul) + h.Phase); } Sample s = new Sample(nc); for (int c = 0; c < nc; c++) { s[c] = v; } n++; samples.Add(s); } while (true) { foreach (Sample s in samples) { yield return s; } } } } } public class BandLimitedSquareGenerator : HarmonicGenerator { public BandLimitedSquareGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } public override List<Harmonic> Harmonics { get { List<Harmonic> harmonics = new List<Harmonic>(); uint sr = SampleRate; int nH = 0; double g = _gain * 4 / Math.PI; while (true) { double fN = _freq * (nH + 1); if (fN > sr / 2) { // Above Nyquist; stop break; } Harmonic h = new Harmonic(nH % 2 == 0 ? 0 : g / nH); harmonics.Add(h); nH++; } return harmonics; } } } public class TriangleGenerator : SignalGenerator { public TriangleGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { ushort nc = NumChannels; uint sr = SampleRate; double mul = 2 * _freq / sr; int n = 0; Sample s = new Sample(nc); while (true) { double saw = ((n * mul) % 2); double v = 2 * saw; if (v > 1) v = 2 - v; if (v < -1) v = -2 - v; for (int c = 0; c < nc; c++) { s[c] = _gain * v; } n++; yield return s; } } } } public class BandLimitedTriangleGenerator : HarmonicGenerator { public BandLimitedTriangleGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } public override List<Harmonic> Harmonics { get { List<Harmonic> harmonics = new List<Harmonic>(); uint sr = SampleRate; int nH = 0; double g = _gain * 8 / (Math.PI * Math.PI); while (true) { double fN = _freq * (nH + 1); if (fN > sr / 2) { // Above Nyquist; stop break; } Harmonic h = new Harmonic(nH % 2 == 0 ? 0 : g / (nH * nH), nH % 4 == 1 ? Math.PI : 0); harmonics.Add(h); nH++; } return harmonics; } } } public class SawtoothGenerator : SignalGenerator { public SawtoothGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } /// <summary> /// Get an iterator for samples /// </summary> public override IEnumerator<ISample> Samples { get { ushort nc = NumChannels; uint sr = SampleRate; double mul = 2 * _freq / sr; int n = 0; Sample s = new Sample(nc); while (true) { double saw = ((n * mul) % 2) - 1; double v = _gain * saw; for (int c = 0; c < nc; c++) { s[c] = v; } n++; yield return s; } } } } public class BandLimitedSawtoothGenerator : HarmonicGenerator { public BandLimitedSawtoothGenerator(ushort numChannels, uint sampleRate, double freq, double gain) : base(numChannels, sampleRate, freq, gain) { } public override List<Harmonic> Harmonics { get { List<Harmonic> harmonics = new List<Harmonic>(); uint sr = SampleRate; int nH = 1; double g = _gain * 2 / Math.PI; harmonics.Add(new Harmonic(0,0)); while (true) { double fN = _freq * (nH + 1); if (fN > sr / 2) { // Above Nyquist; stop break; } Harmonic h = new Harmonic(g / nH, Math.PI); harmonics.Add(h); nH++; } return harmonics; } } } }
using System; using System.Linq; using NRules.Fluent.Dsl; using NRules.IntegrationTests.TestAssets; using NRules.RuleModel; using Xunit; namespace NRules.IntegrationTests { public class ForwardChainingLinkedTest : BaseRuleTestFixture { [Fact] public void Fire_OneMatchingFact_FiresFirstRuleAndChainsSecond() { //Arrange var fact1 = new FactType1 { TestProperty = "Valid Value 1", ChainProperty = "Valid Value 1" }; Session.Insert(fact1); //Act Session.Fire(); //Assert AssertFiredOnce<ForwardChainingFirstRule>(); AssertFiredOnce<ForwardChainingSecondRule>(); } [Fact] public void Fire_OneMatchingFactInsertedThenUpdated_FiresFirstRuleAndChainsSecondLinkedFactsUpdated() { //Arrange FactType2 matchedFact2 = null; FactType3 matchedFact3 = null; Session.Events.FactInsertedEvent += (sender, args) => { if (args.Fact.Type == typeof(FactType2)) matchedFact2 = (FactType2) args.Fact.Value; if (args.Fact.Type == typeof(FactType3)) matchedFact3 = (FactType3) args.Fact.Value; }; Session.Events.FactUpdatedEvent += (sender, args) => { if (args.Fact.Type == typeof(FactType2)) matchedFact2 = (FactType2) args.Fact.Value; if (args.Fact.Type == typeof(FactType3)) matchedFact3 = (FactType3) args.Fact.Value; }; var fact1 = new FactType1 { TestProperty = "Valid Value 1", ChainProperty = "Valid Value 1" }; Session.Insert(fact1); //Act - I Session.Fire(); //Assert - I AssertFiredOnce<ForwardChainingFirstRule>(); AssertFiredOnce<ForwardChainingSecondRule>(); Assert.Equal(1, matchedFact2.UpdateCount); Assert.Equal("Valid Value 1", matchedFact2.TestProperty); Assert.Equal("Valid Value 1", matchedFact3.TestProperty); //Act - II fact1.ChainProperty = "Valid Value 2"; Session.Update(fact1); Session.Fire(); //Assert - II AssertFiredTwice<ForwardChainingFirstRule>(); AssertFiredTwice<ForwardChainingSecondRule>(); Assert.Equal(2, matchedFact2.UpdateCount); Assert.Equal("Valid Value 2", matchedFact2.TestProperty); Assert.Equal("Valid Value 2", matchedFact3.TestProperty); } [Fact] public void Fire_OneMatchingFactInsertedThenRetracted_FiresFirstRuleAndChainsSecondLinkedFactsRetracted() { //Arrange var fact1 = new FactType1 { TestProperty = "Valid Value 1", ChainProperty = "Valid Value 1" }; Session.Insert(fact1); //Act - I Session.Fire(); //Assert - I AssertFiredOnce<ForwardChainingFirstRule>(); AssertFiredOnce<ForwardChainingSecondRule>(); Assert.Equal(1, Session.Query<FactType2>().Count()); Assert.Equal(1, Session.Query<FactType3>().Count()); //Act - II Session.Retract(fact1); Session.Fire(); //Assert - II Assert.Equal(0, Session.Query<FactType2>().Count()); Assert.Equal(0, Session.Query<FactType3>().Count()); } [Fact] public void Fire_OneMatchingFact_LinkedFactHasSource() { //Arrange IFact matchedFact2 = null; IFact matchedFact3 = null; Session.Events.FactInsertedEvent += (sender, args) => { if (args.Fact.Type == typeof(FactType2)) matchedFact2 = args.Fact; if (args.Fact.Type == typeof(FactType3)) matchedFact3 = args.Fact; }; var fact1 = new FactType1 { TestProperty = "Valid Value 1", ChainProperty = "Valid Value 1" }; Session.Insert(fact1); //Act Session.Fire(); //Assert Assert.NotNull(matchedFact2); Assert.NotNull(matchedFact3); Assert.NotNull(matchedFact2.Source); Assert.Equal(FactSourceType.Linked, matchedFact2.Source.SourceType); Assert.Single(matchedFact2.Source.Facts, x => x.Value == fact1); var linkedSource = (ILinkedFactSource)matchedFact2.Source; Assert.NotNull(linkedSource.Rule); Assert.Contains(nameof(ForwardChainingFirstRule), linkedSource.Rule.Name); } [Fact] public void Fire_DirectUpdateOfLinkedFact_Fails() { //Arrange var fact1 = new FactType1 { TestProperty = "Valid Value 1", ChainProperty = "Valid Value 1" }; Session.Insert(fact1); Session.Fire(); var linkedFacts = Session.Query<FactType2>(); //Act - Assert Assert.Throws<ArgumentException>(() => Session.UpdateAll(linkedFacts)); } [Fact] public void Fire_DirectRetractOfLinkedFact_Fails() { //Arrange var fact1 = new FactType1 { TestProperty = "Valid Value 1", ChainProperty = "Valid Value 1" }; Session.Insert(fact1); Session.Fire(); var linkedFacts = Session.Query<FactType2>(); //Act - Assert Assert.Throws<ArgumentException>(() => Session.RetractAll(linkedFacts)); } protected override void SetUpRules() { SetUpRule<ForwardChainingFirstRule>(); SetUpRule<ForwardChainingSecondRule>(); } public class FactType1 { public string TestProperty { get; set; } public string ChainProperty { get; set; } } public class FactType2 { public int UpdateCount { get; set; } = 1; public string TestProperty { get; set; } } public class FactType3 { public string TestProperty { get; set; } } public class ForwardChainingFirstRule : Rule { public override void Define() { FactType1 fact1 = null; When() .Match<FactType1>(() => fact1, f => f.TestProperty.StartsWith("Valid")); Then() .Yield(ctx => Create(fact1), (ctx, fact2) => Update(fact1, fact2)) .Yield(ctx => new FactType3 {TestProperty = fact1.ChainProperty}); } private static FactType2 Create(FactType1 fact1) { var fact2 = new FactType2 {TestProperty = fact1.ChainProperty}; return fact2; } private static FactType2 Update(FactType1 fact1, FactType2 fact2) { fact2.TestProperty = fact1.ChainProperty; fact2.UpdateCount++; return fact2; } } public class ForwardChainingSecondRule : Rule { public override void Define() { FactType2 fact2 = null; FactType3 fact3 = null; When() .Match<FactType2>(() => fact2, f => f.TestProperty.StartsWith("Valid")) .Match<FactType3>(() => fact3, f => f.TestProperty.StartsWith("Valid")); Then() .Do(ctx => ctx.NoOp()); } } } }
// 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.Azure.AcceptanceTestsPaging { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestPagingTestService : ServiceClient<AutoRestPagingTestService>, IAutoRestPagingTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public 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> /// 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 IPagingOperations. /// </summary> public virtual IPagingOperations Paging { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService 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 AutoRestPagingTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestPagingTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestPagingTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService 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="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Paging = new PagingOperations(this); this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using System; using System.Linq; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Web; namespace EmergeTk { public class TypeLoader { private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(TypeLoader)); static Assembly standardAssembly = null; public TypeLoader() { } static TypeLoader() { Assembly assembly = null; String assemblyPath = String.Empty; if( false && HttpContext.Current != null ) { //loadAssemblyPath( HttpContext.Current.Server.MapPath("/bin") ); } else { log.Info("TypeLoader ctor - HttpContext is null, so going to attempt getting path from Assembly.GetEntryAssembly"); assembly = Assembly.GetEntryAssembly(); if (assembly != null) { assemblyPath = new FileInfo(assembly.Location).Directory.FullName; log.InfoFormat("TypeLoader ctor - GetEntryAssembly returned assemblyPath {0}, using that to load assemblies", assemblyPath); } if (String.IsNullOrEmpty(assemblyPath)) { assemblyPath = System.Environment.CurrentDirectory; log.InfoFormat("TypeLoader ctor - GetEntryAssembly returned null - using System.Environment.CurrentDirectory = {0} to load assemblies", assemblyPath); } loadAssemblyPath(assemblyPath); } } private static bool? isRunningOnMono = null; public static bool IsRunningOnMono() { if (isRunningOnMono == null) isRunningOnMono = (Type.GetType("Mono.Runtime") != null); return Convert.ToBoolean(isRunningOnMono); } static private void loadAssemblyPath(string path ) { foreach( string s in Directory.GetFiles(path, "*.dll") ) { FileInfo fi = new FileInfo(s); log.Debug("loading assembly ", fi.Name ); Assembly.Load( fi.Name.Replace(".dll","") ); } } static Dictionary<string, Type> typeRef = new Dictionary<string,Type>(); public static Type GetType( string type ) { if( typeRef.ContainsKey( type ) ) return typeRef[type]; string genericParameter = null; string originalTypeName = type; if( type.Contains( "`1" ) ) { string[] parts = type.Split(new string[]{"`1[["}, 2, StringSplitOptions.None); if( parts.Length == 2 ) { type = parts[0]; genericParameter = parts[1].Trim(']'); } } else if( type.Contains( "<" ) ) { string[] parts = type.Split(new char[]{'<','>',',',' '}, StringSplitOptions.RemoveEmptyEntries ); type = parts[0]; genericParameter = parts[1]; } Type t = null; if( ( t = Type.GetType(type) ) != null ) { //we want to store a separate instance, to avoid future changes to the type (i.e if the type is made generic typeRef[type] = Type.GetType(type); return t; } else if( standardAssembly != null && ( t = standardAssembly.GetType( type, false,true ) ) != null ) { //get a new copy of the type. typeRef[type] = standardAssembly.GetType( type, false,true ); return t; } else { foreach( Assembly a in AppDomain.CurrentDomain.GetAssemblies() ) { //System.Console.WriteLine("looking for {1} in assembly {0}", a.FullName, type); if( ( t = a.GetType(type,false,true) ) != null ) { standardAssembly = a; typeRef[type] = t; return t; } else if ((t = a.GetType(type + "`1", false, true)) != null) { standardAssembly = a; if( genericParameter != null ) { log.Debug( "creating generic type with parameter", genericParameter ); Type gp = GetType(genericParameter); typeRef[originalTypeName] = t.MakeGenericType(gp); //get a new copy of the type. t = t.MakeGenericType(gp); } else { //store copy typeRef[type] = a.GetType(type + "`1", false, true); } return t; } } } typeRef[type] = null; return null; } public static Type CreateGenericType( Type genericType, Type genericParameter ) { return genericType.MakeGenericType( genericParameter ); } public static IEnumerable<Type> GetTypesOfBaseType( Type baseType ) { foreach( Assembly a in AppDomain.CurrentDomain.GetAssemblies() ) { Type[] types = null; try { types = a.GetTypes (); } catch (Exception e) { log.Error ("Error getting types", e); continue; } foreach( Type t in types ) { if( t.IsSubclassOf( baseType ) ) { yield return t; } } } } public static Type[] GetTypesOfInterface( Type iface ) { if( iface == null ) return null; List<Type> types = new List<Type>(); foreach( Assembly a in AppDomain.CurrentDomain.GetAssemblies() ) { try { foreach( Type t in a.GetTypes() ) { if( t.GetInterface(iface.Name ) != null ) { types.Add( t ); } } } catch (Exception e) { log.Error ("Error loading assembly: " + a, e); } } return types.ToArray(); } public static Type[] GetTypesWithAttribute( Type attribute, bool inherit, out Attribute[] attributes ) { List<Type> types = new List<Type>(); List<Attribute> listAtts = new List<Attribute>(); foreach( Assembly a in AppDomain.CurrentDomain.GetAssemblies() ) { try { foreach( Type t in a.GetTypes() ) { object[] atts = t.GetCustomAttributes(attribute, inherit); if( atts != null && atts.Length > 0 ) { types.Add( t ); listAtts.Add( (Attribute)atts[0] ); } } } catch (Exception e) { log.Error("Error loading assembly " + a, e ); } } attributes = listAtts.ToArray(); return types.ToArray(); } public static GenericInvoker MakeGenericMethod( Type baseType, string methodName, params Type[] genericTypeParams ) { return MakeGenericMethod(baseType,methodName,genericTypeParams,null); } bool okayToReadInvokers = true; public static GenericInvoker MakeGenericMethod( Type baseType, string methodName, Type[] genericTypeParams, Type[] parameterTypes ) { GenericInvokerInfo invoker = new GenericInvokerInfo(baseType,methodName,genericTypeParams,parameterTypes); // log.DebugFormat("looking for generic invoker type {0}, name {1}, genericTypes [{2}], paramTypes [{3}] ", // baseType, methodName, genericTypeParams.Join(","), parameterTypes.Join(",") ); try { return invokers[invoker]; } catch { //log.Warn("failed to find invoker ", baseType, methodName, genericTypeParams.JoinToString(","), parameterTypes.Join(","), invoker.GetHashCode() ); //log.Warn("failed to find invoker ", baseType, methodName, genericTypeParams.JoinToString(","), parameterTypes.Join(",")); invoker.Invoker = DynamicMethods.GenericMethodInvokerMethod(baseType, methodName, genericTypeParams, parameterTypes); invoker.IsValid = true; lock(invokers) { invokers[invoker] = invoker.Invoker; } return invoker.Invoker; } } public static object InvokeGenericMethod ( Type baseType, string methodName, Type[] genericTypeParams, object baseObject, object[] arguments ) { return InvokeGenericMethod(baseType, methodName, genericTypeParams, baseObject, null, arguments ); } public static object InvokeGenericMethod ( Type baseType, string methodName, Type[] genericTypeParams, object baseObject, Type[] parameterTypes, object[] arguments ) { // log.Debug("invoking method with arugments: ", arguments, 1 ); // foreach( object o in arguments ) // log.DebugFormat("Arg '{0}' type '{1}' null ? {2}", o, o != null ? o.GetType() : null, o == null ); GenericInvoker invoker = MakeGenericMethod(baseType, methodName, genericTypeParams, parameterTypes ); return invoker( baseObject, arguments ); } public static Attribute GetAttribute(Type attribute, PropertyInfo prop) { object[] atts = prop.GetCustomAttributes(attribute, true); if (atts != null && atts.Length > 0) { return (Attribute)atts[0]; } return null; } private static Dictionary<GenericInvokerInfo,GenericInvoker> invokers = new Dictionary<GenericInvokerInfo,GenericInvoker>(); private static Dictionary<GenericPropertyKey,GenericPropertyInfo> properties = new Dictionary<GenericPropertyKey,GenericPropertyInfo>(); public static void SetProperty( object o, string p, object v ) { GetGenericPropertyInfo(o,p).Setter(o,v); } public static GenericPropertyInfo GetGenericPropertyInfo(object o, string p) { GenericPropertyKey key = new GenericPropertyKey(o.GetType(),p); try { return properties[key]; } catch { //log.Debug("missed"); GenericPropertyInfo gpi; PropertyInfo pi = null; try { pi = key.Type.GetProperty(p); } catch (System.Reflection.AmbiguousMatchException e) { pi = key.Type.GetProperty(p, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance); log.Warn("Ambiguous match. ", Util.BuildExceptionOutput(e)); } gpi = new GenericPropertyInfo(); gpi.Type = key.Type; gpi.Property = p; if( pi != null ) { gpi.Setter = DynamicMethods.CreateSetMethod(pi); gpi.Getter = DynamicMethods.CreateGetMethod(pi); } gpi.PropertyInfo = pi; lock(properties) { properties[key] = gpi; } return gpi; } } public static object GetProperty( object o, string p ) { return GetGenericPropertyInfo(o,p).Getter(o); } } public struct GenericInvokerInfo { //private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(GenericInvokerInfo)); public bool IsValid; public Type Type; public string MethodName; public Type[] GenericTypeParams; public Type[] ParameterTypes; public GenericInvoker Invoker; public GenericInvokerInfo(Type t, string m, Type[] gens, Type[] parms ) { this.Type = t; this.MethodName = m; this.GenericTypeParams = gens; this.ParameterTypes = parms; this.IsValid = false; this.Invoker = null; } public override int GetHashCode() { if (ParameterTypes != null) { return (int)(((long)this.Type.GetHashCode() + (long)this.MethodName.GetHashCode() + (long) getTypeArrayHashCode(GenericTypeParams) + (long)getTypeArrayHashCode(ParameterTypes)) % int.MaxValue); } else { return (int)(((long)this.Type.GetHashCode() + (long) this.MethodName.GetHashCode() + (long) getTypeArrayHashCode(GenericTypeParams)) % int.MaxValue); } } private int getTypeArrayHashCode(Type[] types) { long hash = 0; foreach(Type t in types) hash = ( hash + t.GetHashCode() ) % int.MaxValue; return (int)hash; } public override bool Equals( object obj ) { //log.Debug("calling equals on GenericInvokerInfo"); GenericInvokerInfo x= this, y = (GenericInvokerInfo)obj; if( x.Type != y.Type ) return false; if( x.MethodName != y.MethodName ) return false; if( x.GenericTypeParams.Length != y.GenericTypeParams.Length ) return false; for( int i = 0; i < x.GenericTypeParams.Length; i++ ) if( x.GenericTypeParams[i] != y.GenericTypeParams[i] ) return false; if( x.ParameterTypes == null && y.ParameterTypes == null ) return true; if( x.ParameterTypes == null ) return false; if( y.ParameterTypes == null ) return false; if( x.ParameterTypes.Length != y.ParameterTypes.Length ) return false; for( int i = 0; i < x.ParameterTypes.Length; i++ ) if( x.ParameterTypes[i] != y.ParameterTypes[i] ) return false; return true; } } public struct GenericPropertyKey { public Type Type; public string Property; public GenericPropertyKey(Type t, string p) { this.Type = t; this.Property = p; } } public struct GenericPropertyInfo { //private static readonly EmergeTkLog log = EmergeTkLogManager.GetLogger(typeof(GenericPropertyInfo)); public Type Type; public string Property; public PropertyInfo PropertyInfo; public GenericSetter Setter; public GenericGetter Getter; public override int GetHashCode () { return this.Type.GetHashCode() + this.Property.GetHashCode(); } public override bool Equals (object obj) { //log.Debug("calling equals on GenericPropertyInfo"); GenericPropertyInfo other = (GenericPropertyInfo)obj; return this.Type == other.Type && this.Property == other.Property; } } }
using System; using System.Collections; using QuickGraph.Collections; using QuickGraph.Concepts; using QuickGraph.Concepts.Algorithms; using QuickGraph.Concepts.Traversals; using QuickGraph.Concepts.Collections; using QuickGraph.Collections.Filtered; using QuickGraph.Predicates; namespace QuickGraph.Algorithms.Ranking { /// <summary> /// Algorithm that computes the PageRank ranking over a graph. /// </summary> /// <remarks> /// <para> /// <b>PageRank</b> is a method that initially designed to rank web pages /// objectively and mechanically. In fact, it is one of the building block /// of the famous Google search engine. /// </para> /// <para> /// The idea behind PageRank is simple and intuitive: pages that are important are referenced /// by other important pages. There is an important literature on the web that explains /// PageRank: http://www-db.stanford.edu/~backrub/google.html, /// http://www.webworkshop.net/pagerank.html, /// http://www.miswebdesign.com/resources/articles/pagerank-2.html /// </para> /// <para> /// The PageRank is computed by using the following iterative formula: /// <code> /// PR(A) = (1-d) + d (PR(T1)/C(T1) + ... + PR(Tn)/C(Tn)) /// </code> /// where <c>PR</c> is the PageRank, <c>d</c> is a damping factor usually set to 0.85, /// <c>C(v)</c> is the number of out edgesof <c>v</c>. /// </para> /// </remarks> public class PageRankAlgorithm : IAlgorithm { private IBidirectionalVertexListGraph visitedGraph; private VertexDoubleDictionary ranks = new VertexDoubleDictionary(); private int maxIterations = 60; private double tolerance = 2*double.Epsilon; private double damping = 0.85; /// <summary> /// Creates a PageRank algorithm around the visited graph /// </summary> /// <param name="visitedGraph"> /// Visited <see cref="IBidirectionalVertexListGraph"/> instance. /// </param> /// <exception cref="ArgumentNullException"> /// <param name="visitedGraph"/> is a null reference (Nothing in Visual Basic). /// </exception> public PageRankAlgorithm(IBidirectionalVertexListGraph visitedGraph) { if (visitedGraph==null) throw new ArgumentNullException("visitedGraph"); this.visitedGraph = visitedGraph; } /// <summary> /// Gets the visited graph /// </summary> /// <value> /// A <see cref="IVertexListGraph"/> instance /// </value> public IBidirectionalVertexListGraph VisitedGraph { get { return this.visitedGraph; } } /// <summary> /// Gets the page rank dictionary /// </summary> /// <value> /// The <see cref="VertexDoubleDictionary"/> of <see cref="IVertex"/> - rank entries.ank entries. /// </value> public VertexDoubleDictionary Ranks { get { return this.ranks; } } /// <summary> /// Gets or sets the damping factor in the PageRank iteration. /// </summary> /// <value> /// Damping factor in the PageRank formula (<c>d</c>). /// </value> public double Damping { get { return this.damping; } set { this.damping =value; } } /// <summary> /// Gets or sets the tolerance to stop iteration /// </summary> /// <value> /// The tolerance to stop iteration. /// </value> public double Tolerance { get { return this.tolerance; } set { this.tolerance = value; } } /// <summary> /// Gets or sets the maximum number of iterations /// </summary> /// <value> /// The maximum number of iteration. /// </value> public int MaxIteration { get { return this.maxIterations; } set { this.maxIterations = value; } } #region IAlgorithm Members object IAlgorithm.VisitedGraph { get { return this.VisitedGraph; } } #endregion /// <summary> /// Initializes the rank map. /// </summary> /// <remarks> /// <para> /// This method clears the rank map and populates it with rank to one for all vertices. /// </para> /// </remarks> public void InitializeRanks() { this.ranks.Clear(); foreach(IVertex v in this.VisitedGraph.Vertices) { this.ranks.Add(v,0); } this.RemoveDanglingLinks(); } /// <summary> /// Iteratively removes the dangling links from the rank map /// </summary> public void RemoveDanglingLinks() { VertexCollection danglings = new VertexCollection(); do { danglings.Clear(); // create filtered graph IVertexListGraph fg = new FilteredVertexListGraph( this.VisitedGraph, new InDictionaryVertexPredicate(this.ranks) ); // iterate over of the vertices in the rank map foreach(IVertex v in this.ranks.Keys) { // if v does not have out-edge in the filtered graph, remove if ( fg.OutDegree(v) == 0) danglings.Add(v); } // remove from ranks foreach(IVertex v in danglings) this.ranks.Remove(v); // iterate until no dangling was removed }while(danglings.Count != 0); } /// <summary> /// Computes the PageRank over the <see cref="VisitedGraph"/>. /// </summary> public void Compute() { VertexDoubleDictionary tempRanks = new VertexDoubleDictionary(); // create filtered graph FilteredBidirectionalGraph fg = new FilteredBidirectionalGraph( this.VisitedGraph, Preds.KeepAllEdges(), new InDictionaryVertexPredicate(this.ranks) ); int iter = 0; double error = 0; do { // compute page ranks error = 0; foreach(DictionaryEntry de in this.Ranks) { IVertex v = (IVertex)de.Key; double rank = (double)de.Value; // compute ARi double r = 0; foreach(IEdge e in fg.InEdges(v)) { r += this.ranks[e.Source] / fg.OutDegree(e.Source); } // add sourceRank and store double newRank = (1-this.damping) + this.damping * r; tempRanks[v] = newRank; // compute deviation error += Math.Abs(rank - newRank); } // swap ranks VertexDoubleDictionary temp = ranks; ranks = tempRanks; tempRanks = temp; iter++; }while( error > this.tolerance && iter < this.maxIterations); Console.WriteLine("{0}, {1}",iter,error); } public double GetRanksSum() { double sum = 0; foreach(double rank in this.ranks.Values) { sum+=rank; } return sum; } public double GetRanksMean() { return GetRanksSum()/this.ranks.Count; } private static void swapRanks(VertexDoubleDictionary left, VertexDoubleDictionary right) { VertexDoubleDictionary temp = left; left = right; right = temp; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Amazon.S3; using NUnit; using NUnit.Framework; using Radosgw.AdminAPI; namespace Radosgw.AdminAPI.Tests { public class RadosGWAdminConnectionTests { private static Random Random = new Random(); private RadosGWAdminConnection RadosGWAdminClient; private readonly string SubuserId = "subuser"; private readonly string SubuserAccess = "subuserAccess"; private string SubuserSecret = "subuserSecret"; private User MainUser; private string endpoint; [OneTimeSetUp] public void Setup() { var access = Environment.GetEnvironmentVariable("RADOSGWADMIN_TESTS_ACCESS"); var secret = Environment.GetEnvironmentVariable("RADOSGWADMIN_TESTS_SECRET"); endpoint = Environment.GetEnvironmentVariable("RADOSGWADMIN_TESTS_ENDPOINT"); var adminPath = Environment.GetEnvironmentVariable("RADOSGWADMIN_TESTS_PATH"); RadosGWAdminClient = new RadosGWAdminConnection(endpoint, access, secret, adminPath); } [OneTimeTearDown] public async Task TearDown() { try { await RadosGWAdminClient.RemoveUserAsync( MainUser.UserId, MainUser.Tenant, true); } catch (Exception) { } } public static string RandomString(int length) { const string chars = "abcdefghijklmnopqrstuvwxyz"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[Random.Next(s.Length)]).ToArray()); } private AmazonS3Client GetMainUserClient() => GetUserClient( MainUser.Keys.First().AccessKey, MainUser.Keys.First().SecretKey); private AmazonS3Client GetUserClient(string access, string secret) { return new AmazonS3Client( access, secret, new AmazonS3Config() { ServiceURL = endpoint, UseHttp = endpoint.StartsWith("http://"), ForcePathStyle = true, } ); } [Test, NonParallelizable, Order(1)] public async Task EnsureRadosGWAdminCanCreateUsers() { MainUser = await RadosGWAdminClient.CreateUserAsync( "userUid", "userDisplayName", "userTenant", "[email protected]", "s3", "userAccess", "userSecret", generateKey: false); Assert.AreEqual(MainUser.UserId, "userUid"); Assert.AreEqual(MainUser.DisplayName, "userDisplayName"); Assert.AreEqual(MainUser.Tenant, "userTenant"); Assert.AreEqual(MainUser.Email, "[email protected]"); Assert.AreEqual(MainUser.Keys.First().AccessKey, "userAccess"); Assert.AreEqual(MainUser.Keys.First().SecretKey, "userSecret"); var s3Client = GetMainUserClient(); var bucketCreationResponse = await s3Client.PutBucketAsync(RandomString(12)); Assert.LessOrEqual((int)bucketCreationResponse.HttpStatusCode, 299); } [Test, NonParallelizable, Order(2)] public async Task EnsureRadosGWAdminCanModifyUsers() { var newuserDisplayName = "newUserDisplayName"; var newMail = "[email protected]"; var newUserAccess = "newUserAccess"; var newUserSecret = "newUserSecret"; MainUser = await RadosGWAdminClient.ModifyUserAsync( MainUser.UserId, newuserDisplayName, MainUser.Tenant, newMail, "s3", newUserAccess, newUserSecret, generateKey: false); Assert.AreEqual(MainUser.UserId, "userUid"); Assert.AreEqual(MainUser.DisplayName, newuserDisplayName); Assert.AreEqual(MainUser.Tenant, "userTenant"); Assert.AreEqual(MainUser.Email, newMail); Assert.AreEqual(MainUser.Keys.First().AccessKey, newUserAccess); Assert.AreEqual(MainUser.Keys.First().SecretKey, newUserSecret); var s3Client = GetMainUserClient(); var bucketCreationResponse = await s3Client.PutBucketAsync(RandomString(12)); Assert.LessOrEqual((int)bucketCreationResponse.HttpStatusCode, 299); } [Test, NonParallelizable, Order(3)] public async Task EnsureRadosGWAdminCanDeleteUsers() { var bucket = RandomString(12); var s3Client = GetMainUserClient(); var bucketCreationResponse = await s3Client.PutBucketAsync(bucket); Assert.LessOrEqual((int)bucketCreationResponse.HttpStatusCode, 299); var buckets = await s3Client.ListBucketsAsync(); Assert.True(buckets.Buckets.Select(b => b.BucketName).Contains(bucket)); await RadosGWAdminClient.RemoveBucketAsync(bucket, MainUser.Tenant); buckets = await s3Client.ListBucketsAsync(); Assert.False(buckets.Buckets.Select(b => b.BucketName).Contains(bucket)); } [Test, NonParallelizable, Order(4)] public async Task EnsureRadosGWAdminCanCreateSubUsers() { var subusers = await RadosGWAdminClient.CreateSubuserAsync( MainUser.UserId, MainUser.Tenant, SubuserId, "s3", "readwrite", SubuserAccess, SubuserSecret, generateSecret: false); // ensure sub user containet main tenant and id and subuser id Assert.AreEqual(subusers.First().Id, $"{MainUser.Tenant}${MainUser.UserId}:{SubuserId}"); // ensure the sub user have write access(bucket creation) var successBucket = RandomString(12); var subuserClient = GetUserClient(SubuserAccess, SubuserSecret); var bucketCreationResponse = await subuserClient.PutBucketAsync(successBucket); Assert.LessOrEqual((int)bucketCreationResponse.HttpStatusCode, 299); // ensure main client can see new bucket var mainUserClient = GetMainUserClient(); var buckets = await mainUserClient.ListBucketsAsync(); Assert.True(buckets.Buckets.Select(b => b.BucketName).Contains(successBucket)); } [Test, NonParallelizable, Order(5)] public async Task EnsureRadosGWAdminCanModifySubUserKeys() { SubuserSecret = "newsubusersecret"; await RadosGWAdminClient.CreateKeyAsync( // create or update for existing key MainUser.UserId, MainUser.Tenant, SubuserId, "s3", SubuserAccess, SubuserSecret, generateKey: false); // ensure the sub user have write access(bucket creation) var successBucket = RandomString(12); var subuserClient = GetUserClient(SubuserAccess, SubuserSecret); var bucketCreationResponse = await subuserClient.PutBucketAsync(successBucket); Assert.LessOrEqual((int)bucketCreationResponse.HttpStatusCode, 299); // ensure main client can see new bucket var mainUserClient = GetMainUserClient(); var buckets = await mainUserClient.ListBucketsAsync(); Assert.True(buckets.Buckets.Select(b => b.BucketName).Contains(successBucket)); } [Test, NonParallelizable, Order(6)] public async Task EnsureRadosGWAdminCanModifySubUsers() { await RadosGWAdminClient.ModifySubuserAsync( MainUser.UserId, SubuserId, MainUser.Tenant, "s3", "read"); try { var subuserClient = GetUserClient(SubuserAccess, SubuserSecret); var bucketCreationResponse = await subuserClient.PutBucketAsync(RandomString(12)); Assert.Greater((int)bucketCreationResponse.HttpStatusCode, 299); } catch (Exception) { Assert.Pass(); } } [Test, NonParallelizable, Order(7)] public async Task EnsureRadosGWAdminCanDeleteSubUsers() { await RadosGWAdminClient.RemoveSubuserAsync( MainUser.UserId, MainUser.Tenant, SubuserId, purgeKeys: true); try { var subuserClient = GetUserClient(SubuserAccess, SubuserSecret); var bucketCreationResponse = await subuserClient.PutBucketAsync(RandomString(12)); Assert.Greater((int)bucketCreationResponse.HttpStatusCode, 299); } catch (Exception) { Assert.Pass(); } } [Test, NonParallelizable, Order(99)] public async Task EnsureRadosGWAdminCanRemoveUsers() { await RadosGWAdminClient.RemoveUserAsync( MainUser.UserId, MainUser.Tenant, true); try { var s3Client = GetMainUserClient(); var bucketCreationResponse = await s3Client.PutBucketAsync(RandomString(12)); Assert.Greater((int)bucketCreationResponse.HttpStatusCode, 299); } catch (Exception) { Assert.Pass(); } } } }
// 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.Memory.Tests; using Microsoft.Xunit.Performance; using Xunit; namespace System.Buffers.Tests { public class Rerf_ReadOnlySequence_GetPosition { private const int InnerCount = 10_000; volatile static int _volatileInt = 0; [Benchmark(InnerIterationCount = InnerCount)] [InlineData(10_000, 100)] private static void Byte_Array(int bufSize, int bufOffset) { var buffer = new ReadOnlySequence<byte>(new byte[bufSize], bufOffset, bufSize - 2 * bufOffset); int offset = (int)buffer.Length / 10; SequencePosition end = buffer.GetPosition(0, buffer.End); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { int localInt = 0; using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { SequencePosition pos = buffer.Start; while (!pos.Equals(end)) { pos = buffer.GetPosition(offset, pos); localInt ^= pos.GetInteger(); } } } _volatileInt = localInt; } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData(10_000, 100)] private static void Byte_MultiSegment(int bufSize, int bufOffset) { var segment1 = new BufferSegment<byte>(new byte[bufSize / 10]); BufferSegment<byte> segment2 = segment1; for (int j = 0; j < 10; j++) segment2 = segment2.Append(new byte[bufSize / 10]); var buffer = new ReadOnlySequence<byte>(segment1, bufOffset, segment2, bufSize / 10 - bufOffset); int offset = (int)buffer.Length / 10; SequencePosition end = buffer.GetPosition(0, buffer.End); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { int localInt = 0; using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { SequencePosition pos = buffer.Start; while (!pos.Equals(end)) { pos = buffer.GetPosition(offset, pos); localInt ^= pos.GetInteger(); } } } _volatileInt = localInt; } } [Benchmark(InnerIterationCount = InnerCount * 10)] private static void Byte_Empty() { ReadOnlySequence<byte> buffer = ReadOnlySequence<byte>.Empty; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { int localInt = 0; using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { SequencePosition pos = buffer.GetPosition(0); localInt ^= pos.GetInteger(); } } _volatileInt = localInt; } } [Benchmark(InnerIterationCount = InnerCount * 10)] private static void Byte_Default() { ReadOnlySequence<byte> buffer = default; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { int localInt = 0; using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { SequencePosition pos = buffer.GetPosition(0); localInt ^= pos.GetInteger(); } } _volatileInt = localInt; } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData(10_000, 100)] private static void Char_MultiSegment(int bufSize, int bufOffset) { var segment1 = new BufferSegment<char>(new char[bufSize / 10]); BufferSegment<char> segment2 = segment1; for (int j = 0; j < 10; j++) segment2 = segment2.Append(new char[bufSize / 10]); var buffer = new ReadOnlySequence<char>(segment1, bufOffset, segment2, bufSize / 10 - bufOffset); int offset = (int)buffer.Length / 10; SequencePosition end = buffer.GetPosition(0, buffer.End); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { int localInt = 0; using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { SequencePosition pos = buffer.Start; while (!pos.Equals(end)) { pos = buffer.GetPosition(offset, pos); localInt ^= pos.GetInteger(); } } } _volatileInt = localInt; } } [Benchmark(InnerIterationCount = InnerCount)] [InlineData(10_000, 100)] private static void String(int bufSize, int bufOffset) { ReadOnlyMemory<char> memory = new string('a', bufSize).AsMemory(); memory = memory.Slice(bufOffset, bufSize - 2 * bufOffset); var buffer = new ReadOnlySequence<char>(memory); int offset = (int)buffer.Length / 10; SequencePosition end = buffer.GetPosition(0, buffer.End); foreach (BenchmarkIteration iteration in Benchmark.Iterations) { int localInt = 0; using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { SequencePosition pos = buffer.Start; while (!pos.Equals(end)) { pos = buffer.GetPosition(offset, pos); localInt ^= pos.GetInteger(); } } } _volatileInt = localInt; } } [Benchmark(InnerIterationCount = InnerCount * 10)] private static void Char_Empty() { ReadOnlySequence<char> buffer = ReadOnlySequence<char>.Empty; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { int localInt = 0; using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { SequencePosition p = buffer.GetPosition(0); localInt ^= p.GetInteger(); } } _volatileInt = localInt; } } [Benchmark(InnerIterationCount = InnerCount * 10)] private static void Char_Default() { ReadOnlySequence<char> buffer = default; foreach (BenchmarkIteration iteration in Benchmark.Iterations) { int localInt = 0; using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { SequencePosition p = buffer.GetPosition(0); localInt ^= p.GetInteger(); } } _volatileInt = localInt; } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Versioning; using System.Xml.Linq; using NuGet.Resources; namespace NuGet { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public class ProjectManager : IProjectManager { public event EventHandler<PackageOperationEventArgs> PackageReferenceAdding; public event EventHandler<PackageOperationEventArgs> PackageReferenceAdded; public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoving; public event EventHandler<PackageOperationEventArgs> PackageReferenceRemoved; private ILogger _logger; private IPackageConstraintProvider _constraintProvider; private readonly IPackageReferenceRepository _packageReferenceRepository; private readonly IDictionary<FileTransformExtensions, IPackageFileTransformer> _fileTransformers = new Dictionary<FileTransformExtensions, IPackageFileTransformer>() { { new FileTransformExtensions(".transform", ".transform"), new XmlTransformer(GetConfigMappings()) }, { new FileTransformExtensions(".pp", ".pp"), new Preprocessor() }, { new FileTransformExtensions(".install.xdt", ".uninstall.xdt"), new XdtTransformer() } }; public ProjectManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IProjectSystem project, IPackageRepository localRepository) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (project == null) { throw new ArgumentNullException("project"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } SourceRepository = sourceRepository; Project = project; PathResolver = pathResolver; LocalRepository = localRepository; _packageReferenceRepository = LocalRepository as IPackageReferenceRepository; } public IPackagePathResolver PathResolver { get; private set; } public IPackageRepository LocalRepository { get; private set; } public IPackageRepository SourceRepository { get; private set; } public IPackageConstraintProvider ConstraintProvider { get { return _constraintProvider ?? NullConstraintProvider.Instance; } set { _constraintProvider = value; } } public IProjectSystem Project { get; private set; } public ILogger Logger { get { return _logger ?? NullLogger.Instance; } set { _logger = value; } } public virtual void AddPackageReference(string packageId) { AddPackageReference(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version) { AddPackageReference(packageId, version: version, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void AddPackageReference(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions) { IPackage package = PackageRepositoryHelper.ResolvePackage(SourceRepository, LocalRepository, NullConstraintProvider.Instance, packageId, version, allowPrereleaseVersions); AddPackageReference(package, ignoreDependencies, allowPrereleaseVersions); } public virtual void AddPackageReference(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions) { Execute(package, new UpdateWalker(LocalRepository, SourceRepository, new DependentsWalker(LocalRepository, GetPackageTargetFramework(package.Id)), ConstraintProvider, Project.TargetFramework, NullLogger.Instance, !ignoreDependencies, allowPrereleaseVersions) { AcceptedTargets = PackageTargets.Project }); } private void Execute(IPackage package, IPackageOperationResolver resolver) { IEnumerable<PackageOperation> operations = resolver.ResolveOperations(package); if (operations.Any()) { foreach (PackageOperation operation in operations) { Execute(operation); } } else if (LocalRepository.Exists(package)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, package.GetFullName()); } } protected void Execute(PackageOperation operation) { bool packageExists = LocalRepository.Exists(operation.Package); if (operation.Action == PackageAction.Install) { // If the package is already installed, then skip it if (packageExists) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ProjectAlreadyReferencesPackage, Project.ProjectName, operation.Package.GetFullName()); } else { AddPackageReferenceToProject(operation.Package); } } else { if (packageExists) { RemovePackageReferenceFromProject(operation.Package); } } } protected void AddPackageReferenceToProject(IPackage package) { string packageFullName = package.GetFullName(); Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginAddPackageReference, packageFullName, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceAdding(args); if (args.Cancel) { return; } ExtractPackageFilesToProject(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyAddedPackageReference, packageFullName, Project.ProjectName); OnPackageReferenceAdded(args); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] protected virtual void ExtractPackageFilesToProject(IPackage package) { // BUG 491: Installing a package with incompatible binaries still does a partial install. // Resolve assembly references and content files first so that if this fails we never do anything to the project List<IPackageAssemblyReference> assemblyReferences = Project.GetCompatibleItemsCore(package.AssemblyReferences).ToList(); List<FrameworkAssemblyReference> frameworkReferences = Project.GetCompatibleItemsCore(package.FrameworkAssemblies).ToList(); List<IPackageFile> contentFiles = Project.GetCompatibleItemsCore(package.GetContentFiles()).ToList(); List<IPackageFile> buildFiles = Project.GetCompatibleItemsCore(package.GetBuildFiles()).ToList(); // If the package doesn't have any compatible assembly references or content files, // throw, unless it's a meta package. if (assemblyReferences.Count == 0 && frameworkReferences.Count == 0 && contentFiles.Count == 0 && buildFiles.Count == 0 && (package.FrameworkAssemblies.Any() || package.AssemblyReferences.Any() || package.GetContentFiles().Any() || package.GetBuildFiles().Any())) { // for portable framework, we want to show the friendly short form (e.g. portable-win8+net45+wp8) instead of ".NETPortable, Profile=Profile104". FrameworkName targetFramework = Project.TargetFramework; string targetFrameworkString = targetFramework.IsPortableFramework() ? VersionUtility.GetShortFrameworkName(targetFramework) : targetFramework != null ? targetFramework.ToString() : null; throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToFindCompatibleItems, package.GetFullName(), targetFrameworkString)); } // IMPORTANT: this filtering has to be done AFTER the 'if' statement above, // so that we don't throw the exception in case the <References> filters out all assemblies. FilterAssemblyReferences(assemblyReferences, package.PackageAssemblyReferences); try { // Add content files Project.AddFiles(contentFiles, _fileTransformers); // Add the references to the reference path foreach (IPackageAssemblyReference assemblyReference in assemblyReferences) { if (assemblyReference.IsEmptyFolder()) { continue; } // Get the physical path of the assembly reference string referencePath = Path.Combine(PathResolver.GetInstallPath(package), assemblyReference.Path); string relativeReferencePath = PathUtility.GetRelativePath(Project.Root, referencePath); if (Project.ReferenceExists(assemblyReference.Name)) { Project.RemoveReference(assemblyReference.Name); } // The current implementation of all ProjectSystem does not use the Stream parameter at all. // We can't change the API now, so just pass in a null stream. Project.AddReference(relativeReferencePath, Stream.Null); } // Add GAC/Framework references foreach (FrameworkAssemblyReference frameworkReference in frameworkReferences) { if (!Project.ReferenceExists(frameworkReference.AssemblyName)) { Project.AddFrameworkReference(frameworkReference.AssemblyName); } } foreach (var importFile in buildFiles) { string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path); Project.AddImport( fullImportFilePath, importFile.Path.EndsWith(".props", StringComparison.OrdinalIgnoreCase) ? ProjectImportLocation.Top : ProjectImportLocation.Bottom); } } finally { if (_packageReferenceRepository != null) { // save the used project's framework if the repository supports it. _packageReferenceRepository.AddPackage(package.Id, package.Version, package.DevelopmentDependency, Project.TargetFramework); } else { // Add package to local repository in the finally so that the user can uninstall it // if any exception occurs. This is easier than rolling back since the user can just // manually uninstall things that may have failed. // If this fails then the user is out of luck. LocalRepository.AddPackage(package); } } } private void FilterAssemblyReferences(List<IPackageAssemblyReference> assemblyReferences, ICollection<PackageReferenceSet> packageAssemblyReferences) { if (packageAssemblyReferences != null && packageAssemblyReferences.Count > 0) { var packageReferences = Project.GetCompatibleItemsCore(packageAssemblyReferences).FirstOrDefault(); if (packageReferences != null) { // remove all assemblies of which names do not appear in the References list assemblyReferences.RemoveAll(assembly => !packageReferences.References.Contains(assembly.Name, StringComparer.OrdinalIgnoreCase)); } } } public bool IsInstalled(IPackage package) { return LocalRepository.Exists(package); } public void RemovePackageReference(string packageId) { RemovePackageReference(packageId, forceRemove: false, removeDependencies: false); } public void RemovePackageReference(string packageId, bool forceRemove) { RemovePackageReference(packageId, forceRemove: forceRemove, removeDependencies: false); } public virtual void RemovePackageReference(string packageId, bool forceRemove, bool removeDependencies) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage package = LocalRepository.FindPackage(packageId); if (package == null) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } RemovePackageReference(package, forceRemove, removeDependencies); } public virtual void RemovePackageReference(IPackage package, bool forceRemove, bool removeDependencies) { FrameworkName targetFramework = GetPackageTargetFramework(package.Id); Execute(package, new UninstallWalker(LocalRepository, new DependentsWalker(LocalRepository, targetFramework), targetFramework, NullLogger.Instance, removeDependencies, forceRemove)); } [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] private void RemovePackageReferenceFromProject(IPackage package) { string packageFullName = package.GetFullName(); Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginRemovePackageReference, packageFullName, Project.ProjectName); PackageOperationEventArgs args = CreateOperation(package); OnPackageReferenceRemoving(args); if (args.Cancel) { return; } // Get other packages IEnumerable<IPackage> otherPackages = from p in LocalRepository.GetPackages() where p.Id != package.Id select p; // Get other references var otherAssemblyReferences = from p in otherPackages let assemblyReferences = GetFilteredAssembliesToDelete(p) from assemblyReference in assemblyReferences ?? Enumerable.Empty<IPackageAssemblyReference>() // This can happen if package installed left the project in a bad state select assemblyReference; // Get content files from other packages // Exclude transform files since they are treated specially var otherContentFiles = from p in otherPackages from file in GetCompatibleInstalledItemsForPackage(p.Id, p.GetContentFiles()) where !IsTransformFile(file.Path) select file; // Get the files and references for this package, that aren't in use by any other packages so we don't have to do reference counting var assemblyReferencesToDelete = GetFilteredAssembliesToDelete(package) .Except(otherAssemblyReferences, PackageFileComparer.Default); var contentFilesToDelete = GetCompatibleInstalledItemsForPackage(package.Id, package.GetContentFiles()) .Except(otherContentFiles, PackageFileComparer.Default); var buildFilesToDelete = GetCompatibleInstalledItemsForPackage(package.Id, package.GetBuildFiles()); // Delete the content files Project.DeleteFiles(contentFilesToDelete, otherPackages, _fileTransformers); // Remove references foreach (IPackageAssemblyReference assemblyReference in assemblyReferencesToDelete) { Project.RemoveReference(assemblyReference.Name); } // remove the <Import> statement from projects for the .targets and .props files foreach (var importFile in buildFilesToDelete) { string fullImportFilePath = Path.Combine(PathResolver.GetInstallPath(package), importFile.Path); Project.RemoveImport(fullImportFilePath); } // Remove package to the repository LocalRepository.RemovePackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyRemovedPackageReference, packageFullName, Project.ProjectName); OnPackageReferenceRemoved(args); } private bool IsTransformFile(string path) { return _fileTransformers.Keys.Any( file => path.EndsWith(file.InstallExtension, StringComparison.OrdinalIgnoreCase) || path.EndsWith(file.UninstallExtension, StringComparison.OrdinalIgnoreCase)); } private IList<IPackageAssemblyReference> GetFilteredAssembliesToDelete(IPackage package) { List<IPackageAssemblyReference> assemblyReferences = GetCompatibleInstalledItemsForPackage(package.Id, package.AssemblyReferences).ToList(); if (assemblyReferences.Count == 0) { return assemblyReferences; } var packageReferences = GetCompatibleInstalledItemsForPackage(package.Id, package.PackageAssemblyReferences).FirstOrDefault(); if (packageReferences != null) { assemblyReferences.RemoveAll(p => !packageReferences.References.Contains(p.Name, StringComparer.OrdinalIgnoreCase)); } return assemblyReferences; } public void UpdatePackageReference(string packageId) { UpdatePackageReference(packageId, version: null, updateDependencies: true, allowPrereleaseVersions: false); } public void UpdatePackageReference(string packageId, SemanticVersion version) { UpdatePackageReference(packageId, version: version, updateDependencies: true, allowPrereleaseVersions: false); } public void UpdatePackageReference(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference( packageId, () => SourceRepository.FindPackage(packageId, versionSpec, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: versionSpec != null); } public virtual void UpdatePackageReference(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackageReference(packageId, () => SourceRepository.FindPackage(packageId, version, ConstraintProvider, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions, targetVersionSetExplicitly: version != null); } private void UpdatePackageReference(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions, bool targetVersionSetExplicitly) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage oldPackage = LocalRepository.FindPackage(packageId); // Check to see if this package is installed if (oldPackage == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.ProjectDoesNotHaveReference, Project.ProjectName, packageId)); } Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId); IPackage package = resolvePackage(); // the condition (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version) // is to fix bug 1574. We want to do nothing if, let's say, you have package 2.0alpha installed, and you do: // update-package // without specifying a version explicitly, and the feed only has version 1.0 as the latest stable version. if (package != null && oldPackage.Version != package.Version && (allowPrereleaseVersions || targetVersionSetExplicitly || oldPackage.IsReleaseVersion() || !package.IsReleaseVersion() || oldPackage.Version < package.Version)) { Logger.Log(MessageLevel.Info, NuGetResources.Log_UpdatingPackages, package.Id, oldPackage.Version, package.Version, Project.ProjectName); UpdatePackageReference(package, updateDependencies, allowPrereleaseVersions); } else { IVersionSpec constraint = ConstraintProvider.GetConstraint(packageId); if (constraint != null) { Logger.Log(MessageLevel.Info, NuGetResources.Log_ApplyingConstraints, packageId, VersionUtility.PrettyPrint(constraint), ConstraintProvider.Source); } Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailableForProject, packageId, Project.ProjectName); } } protected void UpdatePackageReference(IPackage package) { UpdatePackageReference(package, updateDependencies: true, allowPrereleaseVersions: false); } protected void UpdatePackageReference(IPackage package, bool updateDependencies, bool allowPrereleaseVersions) { AddPackageReference(package, !updateDependencies, allowPrereleaseVersions); } private void OnPackageReferenceAdding(PackageOperationEventArgs e) { if (PackageReferenceAdding != null) { PackageReferenceAdding(this, e); } } private void OnPackageReferenceAdded(PackageOperationEventArgs e) { if (PackageReferenceAdded != null) { PackageReferenceAdded(this, e); } } private void OnPackageReferenceRemoved(PackageOperationEventArgs e) { if (PackageReferenceRemoved != null) { PackageReferenceRemoved(this, e); } } private void OnPackageReferenceRemoving(PackageOperationEventArgs e) { if (PackageReferenceRemoving != null) { PackageReferenceRemoving(this, e); } } private FrameworkName GetPackageTargetFramework(string packageId) { if (_packageReferenceRepository != null) { return _packageReferenceRepository.GetPackageTargetFramework(packageId) ?? Project.TargetFramework; } return Project.TargetFramework; } /// <summary> /// This method uses the 'targetFramework' attribute in the packages.config to determine compatible items. /// Hence, it's only good for uninstall operations. /// </summary> private IEnumerable<T> GetCompatibleInstalledItemsForPackage<T>(string packageId, IEnumerable<T> items) where T : IFrameworkTargetable { FrameworkName packageFramework = GetPackageTargetFramework(packageId); if (packageFramework == null) { return items; } IEnumerable<T> compatibleItems; if (VersionUtility.TryGetCompatibleItems(packageFramework, items, out compatibleItems)) { return compatibleItems; } return Enumerable.Empty<T>(); } private PackageOperationEventArgs CreateOperation(IPackage package) { return new PackageOperationEventArgs(package, Project, PathResolver.GetInstallPath(package)); } private static IDictionary<XName, Action<XElement, XElement>> GetConfigMappings() { // REVIEW: This might be an edge case, but we're setting this rule for all xml files. // If someone happens to do a transform where the xml file has a configSections node // we will add it first. This is probably fine, but this is a config specific scenario return new Dictionary<XName, Action<XElement, XElement>>() { { "configSections" , (parent, element) => parent.AddFirst(element) } }; } private class PackageFileComparer : IEqualityComparer<IPackageFile> { internal readonly static PackageFileComparer Default = new PackageFileComparer(); private PackageFileComparer() { } public bool Equals(IPackageFile x, IPackageFile y) { // technically, this check will fail if, for example, 'x' is a content file and 'y' is a lib file. // However, because we only use this comparer to compare files within the same folder type, // this check is sufficient. return x.TargetFramework == y.TargetFramework && x.EffectivePath.Equals(y.EffectivePath, StringComparison.OrdinalIgnoreCase); } public int GetHashCode(IPackageFile obj) { return obj.Path.GetHashCode(); } } } }
namespace PokerTell.Repository.Tests.Database { using System.Collections.Generic; using Infrastructure.Interfaces.DatabaseSetup; using Machine.Specifications; using Moq; using PokerTell.Repository.Database; using It = Machine.Specifications.It; // Resharper disable InconsistentNaming public abstract class PokerOfficeHandHistoryRetrieverSpecs { static Mock<IDataProvider> _dataProvider_Mock; static PokerOfficeHandHistoryRetrieverSut _sut; Establish specContext = () => { _sut = new PokerOfficeHandHistoryRetrieverSut(); _dataProvider_Mock = new Mock<IDataProvider>(); }; [Subject(typeof(PokerOfficeHandHistoryRetriever), "Using")] public class when_told_to_use_a_dataprovider : PokerOfficeHandHistoryRetrieverSpecs { const int numberOfCashGameHistories = 1; const int numberOfTournamentHistories = 2; Establish context = () => { _sut.DoneWithCashGameHandHistories = true; _sut.DoneWithTournamentHandHistories = true; _dataProvider_Mock .Setup(dp => dp.ExecuteScalar(PokerOfficeHandHistoryRetriever.NumberOfCashGameHistoriesQuery)) .Returns(numberOfCashGameHistories); _dataProvider_Mock .Setup(dp => dp.ExecuteScalar(PokerOfficeHandHistoryRetriever.NumberOfTournamentHistoriesQuery)) .Returns(numberOfTournamentHistories); }; Because of = () => _sut.Using(_dataProvider_Mock.Object); It should_not_be_done_with_CashGameHistories = () => _sut.DoneWithCashGameHandHistories.ShouldBeFalse(); It should_not_be_done_with_TournamentHistories = () => _sut.DoneWithTournamentHandHistories.ShouldBeFalse(); It should_reset_last_retrieved_cash_game_table_row = () => _sut.LastCashGameTableRowRetrieved.ShouldEqual(-1); It should_reset_last_retrieved_tournament_table_row = () => _sut.LastTournamentTableRowRetrieved.ShouldEqual(-1); It should_set_the_number_of_cash_game_histories_to_the_once_returned_from_the_dataprovider_when_queried = () => _sut.NumberOfCashGameHandHistories.ShouldEqual(numberOfCashGameHistories); It should_set_the_number_of_tournament_histories_to_the_once_returned_from_the_dataprovider_when_queried = () => _sut.NumberOfTournamentHandHistories.ShouldEqual(numberOfTournamentHistories); } [Subject(typeof(PokerOfficeHandHistoryRetriever), "GetNext")] public class when_not_done_with_cash_game_last_cash_game_hand_retrieved_is_1_number_of_CashGameHands_is_10_and_told_to_get_the_next_2_hands : PokerOfficeHandHistoryRetrieverSpecs { const int numberOfCashGameHistories = 10; const int lastCashGameRowRetrieved = 1; const int batchSize = 2; Establish context = () => { _sut.NumberOfCashGameHandHistories = numberOfCashGameHistories; _sut.LastCashGameTableRowRetrieved = lastCashGameRowRetrieved; }; Because of = () => _sut.GetNext(batchSize); It should_query_the_next_handhistories_between_2_and_4 = () => { _sut.MinForWhichHandHistoriesWereQueried.ShouldEqual(2); _sut.MaxForWhichHandHistoriesWereQueried.ShouldEqual(4); }; It should_update_the_last_cash_game_hand_retrieved_to_4 = () => _sut.LastCashGameTableRowRetrieved.ShouldEqual(4); It should_not_be_done_with_CashGameHistories = () => _sut.DoneWithCashGameHandHistories.ShouldBeFalse(); } [Subject(typeof(PokerOfficeHandHistoryRetriever), "GetNext")] public class when_not_done_with_cash_game_last_cash_game_hand_retrieved_is_7_number_of_CashGameHands_is_10_and_told_to_get_the_next_5_hands : PokerOfficeHandHistoryRetrieverSpecs { const int numberOfCashGameHistories = 10; const int lastCashGameRowRetrieved = 7; const int batchSize = 5; Establish context = () => { _sut.NumberOfCashGameHandHistories = numberOfCashGameHistories; _sut.LastCashGameTableRowRetrieved = lastCashGameRowRetrieved; }; Because of = () => _sut.GetNext(batchSize); It should_query_the_next_handhistories_between_8_and_13 = () => { _sut.MinForWhichHandHistoriesWereQueried.ShouldEqual(8); _sut.MaxForWhichHandHistoriesWereQueried.ShouldEqual(13); }; It should_update_the_last_cash_game_hand_retrieved_to_13 = () => _sut.LastCashGameTableRowRetrieved.ShouldEqual(13); It should_be_done_with_CashGameHistories = () => _sut.DoneWithCashGameHandHistories.ShouldBeTrue(); } [Subject(typeof(PokerOfficeHandHistoryRetriever), "GetNext")] public class when_done_with_cash_game_last_tournament_hand_retrieved_is_1_number_of_TournamentHands_is_10_and_told_to_get_the_next_2_hands : PokerOfficeHandHistoryRetrieverSpecs { const int numberOfTournamentHistories = 10; const int lastTournamentRowRetrieved = 1; const int batchSize = 2; Establish context = () => { _sut.DoneWithCashGameHandHistories = true; _sut.NumberOfTournamentHandHistories = numberOfTournamentHistories; _sut.LastTournamentTableRowRetrieved = lastTournamentRowRetrieved; }; Because of = () => _sut.GetNext(batchSize); It should_query_the_next_handhistories_between_2_and_4 = () => { _sut.MinForWhichHandHistoriesWereQueried.ShouldEqual(2); _sut.MaxForWhichHandHistoriesWereQueried.ShouldEqual(4); }; It should_update_the_last_tournament_hand_retrieved_to_4 = () => _sut.LastTournamentTableRowRetrieved.ShouldEqual(4); It should_not_be_done_with_TournamentHistories = () => _sut.DoneWithTournamentHandHistories.ShouldBeFalse(); } [Subject(typeof(PokerOfficeHandHistoryRetriever), "GetNext")] public class when_done_with_cash_game_last_tournament_hand_retrieved_is_7_number_of_TournamentHands_is_10_and_told_to_get_the_next_5_hands : PokerOfficeHandHistoryRetrieverSpecs { const int numberOfTournamentHistories = 10; const int lastTournamentRowRetrieved = 7; const int batchSize = 5; Establish context = () => { _sut.DoneWithCashGameHandHistories = true; _sut.NumberOfTournamentHandHistories = numberOfTournamentHistories; _sut.LastTournamentTableRowRetrieved = lastTournamentRowRetrieved; }; Because of = () => _sut.GetNext(batchSize); It should_query_the_next_handhistories_between_8_and_13 = () => { _sut.MinForWhichHandHistoriesWereQueried.ShouldEqual(8); _sut.MaxForWhichHandHistoriesWereQueried.ShouldEqual(13); }; It should_update_the_last_tournament_hand_retrieved_to_13 = () => _sut.LastTournamentTableRowRetrieved.ShouldEqual(13); It should_be_done_with_TournamentHistories = () => _sut.DoneWithTournamentHandHistories.ShouldBeTrue(); } } public class PokerOfficeHandHistoryRetrieverSut : PokerOfficeHandHistoryRetriever { public int MinForWhichHandHistoriesWereQueried; public int MaxForWhichHandHistoriesWereQueried; public int NumberOfCashGameHandHistories { get { return _numberOfCashGameHandHistories; } set { _numberOfCashGameHandHistories = value; } } public int NumberOfTournamentHandHistories { get { return _numberOfTournamentHandHistories; } set { _numberOfTournamentHandHistories = value; } } public bool DoneWithCashGameHandHistories { get { return _doneWithCashGameHandHistories; } set { _doneWithCashGameHandHistories = value; } } public bool DoneWithTournamentHandHistories { get { return _doneWithTournamentHandHistories; } set { _doneWithTournamentHandHistories = value; } } public int LastCashGameTableRowRetrieved { get { return _lastCashGameTableRowRetrieved; } set { _lastCashGameTableRowRetrieved = value; } } public int LastTournamentTableRowRetrieved { get { return _lastTournamentTableRowRetrieved; } set { _lastTournamentTableRowRetrieved = value; } } protected override IEnumerable<string> QueryHandHistories(int min, int max) { MinForWhichHandHistoriesWereQueried = min; MaxForWhichHandHistoriesWereQueried = max; return new List<string>(); } } }
// 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.Net.NetworkInformation; using System.Net.Sockets; using Xunit; namespace System.Net.Tests { public class WebProxyTest { public static IEnumerable<object[]> Ctor_ExpectedPropertyValues_MemberData() { yield return new object[] { new WebProxy(), null, false, false, Array.Empty<string>(), null }; yield return new object[] { new WebProxy("http://anything"), new Uri("http://anything"), false, false, Array.Empty<string>(), null }; yield return new object[] { new WebProxy("anything", 42), new Uri("http://anything:42"), false, false, Array.Empty<string>(), null }; yield return new object[] { new WebProxy(new Uri("http://anything")), new Uri("http://anything"), false, false, Array.Empty<string>(), null }; yield return new object[] { new WebProxy("http://anything", true), new Uri("http://anything"), false, true, Array.Empty<string>(), null }; yield return new object[] { new WebProxy(new Uri("http://anything"), true), new Uri("http://anything"), false, true, Array.Empty<string>(), null }; yield return new object[] { new WebProxy("http://anything.com", true, new[] { ".*.com" }), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, null }; yield return new object[] { new WebProxy(new Uri("http://anything.com"), true, new[] { ".*.com" }), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, null }; var c = new DummyCredentials(); yield return new object[] { new WebProxy("http://anything.com", true, new[] { ".*.com" }, c), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, c }; yield return new object[] { new WebProxy(new Uri("http://anything.com"), true, new[] { ".*.com" }, c), new Uri("http://anything.com"), false, true, new[] { ".*.com" }, c }; } [Theory] [MemberData(nameof(Ctor_ExpectedPropertyValues_MemberData))] public static void Ctor_ExpectedPropertyValues( WebProxy p, Uri address, bool useDefaultCredentials, bool bypassLocal, string[] bypassedAddresses, ICredentials creds) { Assert.Equal(address, p.Address); Assert.Equal(useDefaultCredentials, p.UseDefaultCredentials); Assert.Equal(bypassLocal, p.BypassProxyOnLocal); Assert.Equal(bypassedAddresses, p.BypassList); Assert.Equal(bypassedAddresses, (string[])p.BypassArrayList.ToArray(typeof(string))); Assert.Equal(creds, p.Credentials); } [Fact] public static void BypassList_Roundtrip() { var p = new WebProxy(); Assert.Empty(p.BypassList); Assert.Empty(p.BypassArrayList); string[] strings; strings = new string[] { "hello", "world" }; p.BypassList = strings; Assert.Equal(strings, p.BypassList); Assert.Equal(strings, (string[])p.BypassArrayList.ToArray(typeof(string))); strings = new string[] { "hello" }; p.BypassList = strings; Assert.Equal(strings, p.BypassList); Assert.Equal(strings, (string[])p.BypassArrayList.ToArray(typeof(string))); } [Fact] public static void UseDefaultCredentials_Roundtrip() { var p = new WebProxy(); Assert.False(p.UseDefaultCredentials); Assert.Null(p.Credentials); p.UseDefaultCredentials = true; Assert.True(p.UseDefaultCredentials); Assert.NotNull(p.Credentials); p.UseDefaultCredentials = false; Assert.False(p.UseDefaultCredentials); Assert.Null(p.Credentials); } [Fact] public static void BypassProxyOnLocal_Roundtrip() { var p = new WebProxy(); Assert.False(p.BypassProxyOnLocal); p.BypassProxyOnLocal = true; Assert.True(p.BypassProxyOnLocal); p.BypassProxyOnLocal = false; Assert.False(p.BypassProxyOnLocal); } [Fact] public static void Address_Roundtrip() { var p = new WebProxy(); Assert.Null(p.Address); p.Address = new Uri("http://hello"); Assert.Equal(new Uri("http://hello"), p.Address); p.Address = null; Assert.Null(p.Address); } [Fact] public static void InvalidArgs_Throws() { var p = new WebProxy(); AssertExtensions.Throws<ArgumentNullException>("destination", () => p.GetProxy(null)); AssertExtensions.Throws<ArgumentNullException>("host", () => p.IsBypassed(null)); AssertExtensions.Throws<ArgumentNullException>("c", () => p.BypassList = null); Assert.Throws<ArgumentException>(() => p.BypassList = new string[] { "*.com" }); } [Fact] public static void InvalidBypassUrl_AddedDirectlyToList_SilentlyEaten() { var p = new WebProxy("http://bing.com"); p.BypassArrayList.Add("*.com"); p.IsBypassed(new Uri("http://microsoft.com")); // exception should be silently eaten } [Fact] public static void BypassList_DoesntContainUrl_NotBypassed() { var p = new WebProxy("http://microsoft.com"); Assert.Equal(new Uri("http://microsoft.com"), p.GetProxy(new Uri("http://bing.com"))); } [Fact] public static void BypassList_ContainsUrl_IsBypassed() { var p = new WebProxy("http://microsoft.com", false, new[] { "hello", "bing.*", "world" }); Assert.Equal(new Uri("http://bing.com"), p.GetProxy(new Uri("http://bing.com"))); } public static IEnumerable<object[]> BypassOnLocal_MemberData() { // Local yield return new object[] { new Uri($"http://nodotinhostname"), true }; yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}"), true }; foreach (IPAddress address in Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList) { if (address.AddressFamily == AddressFamily.InterNetwork) { Uri uri; try { uri = new Uri($"http://{address}"); } catch (UriFormatException) { continue; } yield return new object[] { uri, true }; } } string domain = IPGlobalProperties.GetIPGlobalProperties().DomainName; if (!string.IsNullOrWhiteSpace(domain)) { Uri uri = null; try { new Uri($"http://{Guid.NewGuid().ToString("N")}.{domain}"); } catch (UriFormatException) { } if (uri != null) { yield return new object[] { uri, true }; } } // Non-local yield return new object[] { new Uri($"http://{Guid.NewGuid().ToString("N")}.com"), false }; yield return new object[] { new Uri($"http://{IPAddress.None}"), false }; } [Theory] [MemberData(nameof(BypassOnLocal_MemberData))] public static void BypassOnLocal_MatchesExpected(Uri destination, bool isLocal) { Uri proxyUri = new Uri("http://microsoft.com"); Assert.Equal(isLocal, new WebProxy(proxyUri, true).IsBypassed(destination)); Assert.False(new WebProxy(proxyUri, false).IsBypassed(destination)); Assert.Equal(isLocal ? destination : proxyUri, new WebProxy(proxyUri, true).GetProxy(destination)); Assert.Equal(proxyUri, new WebProxy(proxyUri, false).GetProxy(destination)); } [Fact] public static void BypassOnLocal_SpecialCases() { Assert.True(new WebProxy().IsBypassed(new Uri("http://anything.com"))); Assert.True(new WebProxy((string)null).IsBypassed(new Uri("http://anything.com"))); Assert.True(new WebProxy((Uri)null).IsBypassed(new Uri("http://anything.com"))); Assert.True(new WebProxy("microsoft", true).IsBypassed(new Uri($"http://{IPAddress.Loopback}"))); Assert.True(new WebProxy("microsoft", false).IsBypassed(new Uri($"http://{IPAddress.Loopback}"))); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void GetDefaultProxy_NotSupported() { #pragma warning disable 0618 // obsolete method Assert.Throws<PlatformNotSupportedException>(() => WebProxy.GetDefaultProxy()); #pragma warning restore 0618 } private class DummyCredentials : ICredentials { public NetworkCredential GetCredential(Uri uri, string authType) => null; } } }
// // Copyright (c) 2004-2016 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. // namespace NLog.UnitTests.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Targets; using NLog.Targets.Wrappers; using Xunit; public class PostFilteringTargetWrapperTests : NLogTestBase { [Fact] public void PostFilteringTargetWrapperUsingDefaultFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule { Exists = "level >= LogLevel.Error", Filter = "true", }, }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all Info events went through Assert.Equal(3, target.Events.Count); Assert.Same(events[1].LogEvent, target.Events[0]); Assert.Same(events[2].LogEvent, target.Events[1]); Assert.Same(events[5].LogEvent, target.Events[2]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Warn, "Logger1", "Hello").WithContinuation(exceptions.Add), }; string result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Trace Running PostFilteringWrapper Target[(unnamed)](MyTarget) on 7 events") != -1); Assert.True(result.IndexOf("Trace Rule matched: (level >= Warn)") != -1); Assert.True(result.IndexOf("Trace Filter to apply: (level >= Debug)") != -1); Assert.True(result.IndexOf("Trace After filtering: 6 events.") != -1); Assert.True(result.IndexOf("Trace Sending to MyTarget") != -1); // make sure all Debug,Info,Warn events went through Assert.Equal(6, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[5].LogEvent, target.Events[4]); Assert.Same(events[6].LogEvent, target.Events[5]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperUsingDefaultNonFilterTest2() { // in this case both rules would match, but first one is picked var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, Rules = { // when there is an error, emit everything new FilteringRule("level >= LogLevel.Error", "true"), // if we had any warnings, log debug too new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"), }, // by default log info and above DefaultFilter = "level >= LogLevel.Info", }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new [] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; var result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace); Assert.True(result.IndexOf("Trace Running PostFilteringWrapper Target[(unnamed)](MyTarget) on 7 events") != -1); Assert.True(result.IndexOf("Trace Rule matched: (level >= Error)") != -1); Assert.True(result.IndexOf("Trace Filter to apply: True") != -1); Assert.True(result.IndexOf("Trace After filtering: 7 events.") != -1); Assert.True(result.IndexOf("Trace Sending to MyTarget") != -1); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } [Fact] public void PostFilteringTargetWrapperNoFiltersDefined() { var target = new MyTarget(); var wrapper = new PostFilteringTargetWrapper() { WrappedTarget = target, }; wrapper.Initialize(null); target.Initialize(null); var exceptions = new List<Exception>(); var events = new[] { new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add), new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add), }; wrapper.WriteAsyncLogEvents(events); // make sure all events went through Assert.Equal(7, target.Events.Count); Assert.Same(events[0].LogEvent, target.Events[0]); Assert.Same(events[1].LogEvent, target.Events[1]); Assert.Same(events[2].LogEvent, target.Events[2]); Assert.Same(events[3].LogEvent, target.Events[3]); Assert.Same(events[4].LogEvent, target.Events[4]); Assert.Same(events[5].LogEvent, target.Events[5]); Assert.Same(events[6].LogEvent, target.Events[6]); Assert.Equal(events.Length, exceptions.Count); } public class MyTarget : Target { public MyTarget() { this.Events = new List<LogEventInfo>(); } public List<LogEventInfo> Events { get; set; } protected override void Write(LogEventInfo logEvent) { this.Events.Add(logEvent); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Headers; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using k8s.Authentication; using k8s.Exceptions; using k8s.KubeConfigModels; using k8s.Models; using k8s.Tests.Mock; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Https; using k8s.Autorest; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Pkcs; using Org.BouncyCastle.Security; using Xunit; using Xunit.Abstractions; namespace k8s.Tests { public class AuthTests { private readonly ITestOutputHelper testOutput; public AuthTests(ITestOutputHelper testOutput) { this.testOutput = testOutput; } private static HttpOperationResponse<V1PodList> ExecuteListPods(IKubernetes client) { return client.ListNamespacedPodWithHttpMessagesAsync("default").Result; } [Fact] public void Anonymous() { using (var server = new MockKubeApiServer(testOutput)) { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString() }); var listTask = ExecuteListPods(client); Assert.True(listTask.Response.IsSuccessStatusCode); Assert.Equal(1, listTask.Body.Items.Count); } using (var server = new MockKubeApiServer(testOutput, cxt => { cxt.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.FromResult(false); })) { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString() }); ShouldThrowUnauthorized(client); } } private static void PeelAggregate(Action testcode) { try { testcode(); } catch (AggregateException e) { if (e.InnerExceptions.Count == 1) { throw e.InnerExceptions.First(); } throw; } } [Fact] public void BasicAuth() { const string testName = "test_name"; const string testPassword = "test_password"; using (var server = new MockKubeApiServer(testOutput, cxt => { var header = cxt.Request.Headers["Authorization"].FirstOrDefault(); var expect = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{testName}:{testPassword}"))) .ToString(); if (header != expect) { cxt.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.FromResult(false); } return Task.FromResult(true); })) { { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), Username = testName, Password = testPassword, }); var listTask = ExecuteListPods(client); Assert.True(listTask.Response.IsSuccessStatusCode); Assert.Equal(1, listTask.Body.Items.Count); } { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), Username = "wrong name", Password = testPassword, }); ShouldThrowUnauthorized(client); } { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), Username = testName, Password = "wrong password", }); ShouldThrowUnauthorized(client); } { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), Username = "both wrong", Password = "wrong password", }); ShouldThrowUnauthorized(client); } { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString() }); ShouldThrowUnauthorized(client); } { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), Username = "xx", }); ShouldThrowUnauthorized(client); } } } // this test doesn't work on OSX and is inconsistent on windows [OperatingSystemDependentFact(Exclude = OperatingSystems.OSX | OperatingSystems.Windows)] public void Cert() { var serverCertificateData = File.ReadAllText("assets/apiserver-pfx-data.txt"); var clientCertificateKeyData = File.ReadAllText("assets/client-key-data.txt"); var clientCertificateData = File.ReadAllText("assets/client-certificate-data.txt"); X509Certificate2 serverCertificate = null; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { using (var serverCertificateStream = new MemoryStream(Convert.FromBase64String(serverCertificateData))) { serverCertificate = OpenCertificateStore(serverCertificateStream); } } else { serverCertificate = new X509Certificate2(Convert.FromBase64String(serverCertificateData), ""); } var clientCertificate = new X509Certificate2(Convert.FromBase64String(clientCertificateData), ""); var clientCertificateValidationCalled = false; using (var server = new MockKubeApiServer(testOutput, listenConfigure: options => { options.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = serverCertificate, ClientCertificateMode = ClientCertificateMode.RequireCertificate, ClientCertificateValidation = (certificate, chain, valid) => { clientCertificateValidationCalled = true; return clientCertificate.Equals(certificate); }, }); })) { { clientCertificateValidationCalled = false; var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), ClientCertificateData = clientCertificateData, ClientCertificateKeyData = clientCertificateKeyData, SslCaCerts = new X509Certificate2Collection(serverCertificate), SkipTlsVerify = false, }); var listTask = ExecuteListPods(client); Assert.True(clientCertificateValidationCalled); Assert.True(listTask.Response.IsSuccessStatusCode); Assert.Equal(1, listTask.Body.Items.Count); } { clientCertificateValidationCalled = false; var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), ClientCertificateData = clientCertificateData, ClientCertificateKeyData = clientCertificateKeyData, SkipTlsVerify = true, }); var listTask = ExecuteListPods(client); Assert.True(clientCertificateValidationCalled); Assert.True(listTask.Response.IsSuccessStatusCode); Assert.Equal(1, listTask.Body.Items.Count); } { clientCertificateValidationCalled = false; var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), ClientCertificateFilePath = "assets/client.crt", // TODO amazoning why client.crt != client-data.txt ClientKeyFilePath = "assets/client.key", SkipTlsVerify = true, }); Assert.ThrowsAny<Exception>(() => ExecuteListPods(client)); Assert.True(clientCertificateValidationCalled); } { clientCertificateValidationCalled = false; var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), SkipTlsVerify = true, }); Assert.ThrowsAny<Exception>(() => ExecuteListPods(client)); Assert.False(clientCertificateValidationCalled); } } } [OperatingSystemDependentFact(Exclude = OperatingSystems.OSX | OperatingSystems.Windows)] public void ExternalCertificate() { const string name = "testing_irrelevant"; var serverCertificateData = Convert.FromBase64String(File.ReadAllText("assets/apiserver-pfx-data.txt")); var clientCertificateKeyData = Convert.FromBase64String(File.ReadAllText("assets/client-key-data.txt")); var clientCertificateData = Convert.FromBase64String(File.ReadAllText("assets/client-certificate-data.txt")); X509Certificate2 serverCertificate = null; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { using (var serverCertificateStream = new MemoryStream(serverCertificateData)) { serverCertificate = OpenCertificateStore(serverCertificateStream); } } else { serverCertificate = new X509Certificate2(serverCertificateData, ""); } var clientCertificate = new X509Certificate2(clientCertificateData, ""); var clientCertificateValidationCalled = false; using (var server = new MockKubeApiServer(testOutput, listenConfigure: options => { options.UseHttps(new HttpsConnectionAdapterOptions { ServerCertificate = serverCertificate, ClientCertificateMode = ClientCertificateMode.RequireCertificate, ClientCertificateValidation = (certificate, chain, valid) => { clientCertificateValidationCalled = true; return clientCertificate.Equals(certificate); }, }); })) { { var clientCertificateText = Encoding.ASCII.GetString(clientCertificateData).Replace("\n", "\\n"); var clientCertificateKeyText = Encoding.ASCII.GetString(clientCertificateKeyData).Replace("\n", "\\n"); var responseJson = $"{{\"apiVersion\":\"testingversion\",\"status\":{{\"clientCertificateData\":\"{clientCertificateText}\",\"clientKeyData\":\"{clientCertificateKeyText}\"}}}}"; var kubernetesConfig = GetK8SConfiguration(server.Uri.ToString(), responseJson, name); var clientConfig = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfig, name); var client = new Kubernetes(clientConfig); var listTask = ExecuteListPods(client); Assert.True(listTask.Response.IsSuccessStatusCode); Assert.Equal(1, listTask.Body.Items.Count); } { var clientCertificateText = File.ReadAllText("assets/client.crt").Replace("\n", "\\n"); var clientCertificateKeyText = File.ReadAllText("assets/client.key").Replace("\n", "\\n"); var responseJson = $"{{\"apiVersion\":\"testingversion\",\"status\":{{\"clientCertificateData\":\"{clientCertificateText}\",\"clientKeyData\":\"{clientCertificateKeyText}\"}}}}"; var kubernetesConfig = GetK8SConfiguration(server.Uri.ToString(), responseJson, name); var clientConfig = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfig, name); var client = new Kubernetes(clientConfig); Assert.ThrowsAny<Exception>(() => ExecuteListPods(client)); Assert.True(clientCertificateValidationCalled); } } } [Fact] public void ExternalToken() { const string token = "testingtoken"; const string name = "testing_irrelevant"; using (var server = new MockKubeApiServer(testOutput, cxt => { var header = cxt.Request.Headers["Authorization"].FirstOrDefault(); var expect = new AuthenticationHeaderValue("Bearer", token).ToString(); if (header != expect) { cxt.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.FromResult(false); } return Task.FromResult(true); })) { { var responseJson = $"{{\"apiVersion\":\"testingversion\",\"status\":{{\"token\":\"{token}\"}}}}"; var kubernetesConfig = GetK8SConfiguration(server.Uri.ToString(), responseJson, name); var clientConfig = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfig, name); var client = new Kubernetes(clientConfig); var listTask = ExecuteListPods(client); Assert.True(listTask.Response.IsSuccessStatusCode); Assert.Equal(1, listTask.Body.Items.Count); } { var responseJson = "{\"apiVersion\":\"testingversion\",\"status\":{\"token\":\"wrong_token\"}}"; var kubernetesConfig = GetK8SConfiguration(server.Uri.ToString(), responseJson, name); var clientConfig = KubernetesClientConfiguration.BuildConfigFromConfigObject(kubernetesConfig, name); var client = new Kubernetes(clientConfig); ShouldThrowUnauthorized(client); } } } [Fact] public void Token() { const string token = "testingtoken"; using (var server = new MockKubeApiServer(testOutput, cxt => { var header = cxt.Request.Headers["Authorization"].FirstOrDefault(); var expect = new AuthenticationHeaderValue("Bearer", token).ToString(); if (header != expect) { cxt.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.FromResult(false); } return Task.FromResult(true); })) { { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), AccessToken = token, }); var listTask = ExecuteListPods(client); Assert.True(listTask.Response.IsSuccessStatusCode); Assert.Equal(1, listTask.Body.Items.Count); } { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), AccessToken = "wrong token", }); ShouldThrowUnauthorized(client); } { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), Username = "wrong name", Password = "same password", }); ShouldThrowUnauthorized(client); } { var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString() }); ShouldThrowUnauthorized(client); } } } [Fact] public void Oidc() { var clientId = "CLIENT_ID"; var clientSecret = "CLIENT_SECRET"; var idpIssuerUrl = "https://idp.issuer.url"; var unexpiredIdToken = "eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjAsImV4cCI6MjAwMDAwMDAwMH0.8Ata5uKlrqYfeIaMwS91xVgVFHu7ntHx1sGN95i2Zho"; var expiredIdToken = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjB9.f37LFpIw_XIS5TZt3wdtEjjyCNshYy03lOWpyDViRM0"; var refreshToken = "REFRESH_TOKEN"; using (var server = new MockKubeApiServer(testOutput, cxt => { var header = cxt.Request.Headers["Authorization"].FirstOrDefault(); var expect = new AuthenticationHeaderValue("Bearer", unexpiredIdToken).ToString(); if (header != expect) { cxt.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return Task.FromResult(false); } return Task.FromResult(true); })) { { // use unexpired id token as bearer, do not attempt to refresh var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), AccessToken = unexpiredIdToken, TokenProvider = new OidcTokenProvider(clientId, clientSecret, idpIssuerUrl, unexpiredIdToken, refreshToken), }); var listTask = ExecuteListPods(client); Assert.True(listTask.Response.IsSuccessStatusCode); Assert.Equal(1, listTask.Body.Items.Count); } { // attempt to refresh id token when expired var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), AccessToken = expiredIdToken, TokenProvider = new OidcTokenProvider(clientId, clientSecret, idpIssuerUrl, expiredIdToken, refreshToken), }); try { PeelAggregate(() => ExecuteListPods(client)); Assert.True(false, "should not be here"); } catch (KubernetesClientException e) { Assert.StartsWith("Unable to refresh OIDC token.", e.Message); } } { // attempt to refresh id token when null var client = new Kubernetes(new KubernetesClientConfiguration { Host = server.Uri.ToString(), AccessToken = expiredIdToken, TokenProvider = new OidcTokenProvider(clientId, clientSecret, idpIssuerUrl, null, refreshToken), }); try { PeelAggregate(() => ExecuteListPods(client)); Assert.True(false, "should not be here"); } catch (KubernetesClientException e) { Assert.StartsWith("Unable to refresh OIDC token.", e.Message); } } } } private static void ShouldThrowUnauthorized(Kubernetes client) { try { PeelAggregate(() => ExecuteListPods(client)); Assert.True(false, "should not be here"); } catch (HttpOperationException e) { Assert.Equal(HttpStatusCode.Unauthorized, e.Response.StatusCode); } } private X509Certificate2 OpenCertificateStore(Stream stream) { var store = new Pkcs12Store(); store.Load(stream, new char[] { }); var keyAlias = store.Aliases.Cast<string>().SingleOrDefault(a => store.IsKeyEntry(a)); var key = (RsaPrivateCrtKeyParameters)store.GetKey(keyAlias).Key; var bouncyCertificate = store.GetCertificate(keyAlias).Certificate; var certificate = new X509Certificate2(DotNetUtilities.ToX509Certificate(bouncyCertificate)); var parameters = DotNetUtilities.ToRSAParameters(key); var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(parameters); certificate = RSACertificateExtensions.CopyWithPrivateKey(certificate, rsa); return certificate; } private K8SConfiguration GetK8SConfiguration(string serverUri, string responseJson, string name) { const string username = "testinguser"; var contexts = new List<Context> { new Context { Name = name, ContextDetails = new ContextDetails { Cluster = name, User = username } }, }; { var clusters = new List<Cluster> { new Cluster { Name = name, ClusterEndpoint = new ClusterEndpoint { SkipTlsVerify = true, Server = serverUri }, }, }; var command = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "echo"; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { command = "printf"; } var arguments = new string[] { }; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { arguments = new[] { "/c", "echo", responseJson }; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { arguments = new[] { responseJson.Replace("\"", "\\\"") }; } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { arguments = new[] { "\"%s\"", responseJson.Replace("\"", "\\\"") }; } var users = new List<User> { new User { Name = username, UserCredentials = new UserCredentials { ExternalExecution = new ExternalExecution { ApiVersion = "testingversion", Command = command, Arguments = arguments.ToList(), }, }, }, }; var kubernetesConfig = new K8SConfiguration { Clusters = clusters, Users = users, Contexts = contexts }; return kubernetesConfig; } } } }
using System; using System.Globalization; using System.Runtime.InteropServices; using log4net.Layout; namespace log4net.Appender { /// <summary> /// Appends logging events to the console. /// </summary> /// <remarks> /// <para> /// ColoredConsoleAppender appends log events to the standard output stream /// or the error output stream using a layout specified by the /// user. It also allows the color of a specific type of message to be set. /// </para> /// <para> /// By default, all output is written to the console's standard output stream. /// The <see cref="Target"/> property can be set to direct the output to the /// error stream. /// </para> /// <para> /// NOTE: This appender writes directly to the application's attached console /// not to the <c>System.Console.Out</c> or <c>System.Console.Error</c> <c>TextWriter</c>. /// The <c>System.Console.Out</c> and <c>System.Console.Error</c> streams can be /// programatically redirected (for example NUnit does this to capture program ouput). /// This appender will ignore these redirections because it needs to use Win32 /// API calls to colorise the output. To respect these redirections the <see cref="ConsoleAppender"/> /// must be used. /// </para> /// <para> /// When configuring the colored console appender, mapping should be /// specified to map a logging level to a color. For example: /// </para> /// <code> /// &lt;mapping&gt; /// &lt;level value="ERROR" /&gt; /// &lt;foreColor value="White" /&gt; /// &lt;backColor value="Red, HighIntensity" /&gt; /// &lt;/mapping&gt; /// &lt;mapping&gt; /// &lt;level value="DEBUG" /&gt; /// &lt;backColor value="Green" /&gt; /// &lt;/mapping&gt; /// </code> /// <para> /// The Level is the standard log4net logging level and ForeColor and BackColor can be any /// combination of: /// <list type="bullet"> /// <item><term>Blue</term><description>color is blue</description></item> /// <item><term>Green</term><description>color is red</description></item> /// <item><term>Red</term><description>color is green</description></item> /// <item><term>White</term><description>color is white</description></item> /// <item><term>Yellow</term><description>color is yellow</description></item> /// <item><term>Purple</term><description>color is purple</description></item> /// <item><term>Cyan</term><description>color is cyan</description></item> /// <item><term>HighIntensity</term><description>color is intensified</description></item> /// </list> /// </para> /// /// </remarks> public class ColoredConsoleAppender : AppenderSkeleton { #region Colors Enum /// <summary> /// The enum of possible color values for use with the color mapping method /// </summary> [Flags] public enum Colors : int { /// <summary> /// color is blue /// </summary> Blue = 0x0001, /// <summary> /// color is green /// </summary> Green = 0x0002, /// <summary> /// color is red /// </summary> Red = 0x0004, /// <summary> /// color is white /// </summary> White = Blue | Green | Red, /// <summary> /// color is yellow /// </summary> Yellow = Red | Green, /// <summary> /// color is purple /// </summary> Purple = Red | Blue, /// <summary> /// color is cyan /// </summary> Cyan = Green | Blue, /// <summary> /// color is inensified /// </summary> HighIntensity = 0x0008, } #endregion #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class. /// </summary> /// <remarks> /// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write /// to the standard output stream. /// </remarks> public ColoredConsoleAppender() { } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class /// with the specified layout. /// </summary> /// <param name="layout">the layout to use for this appender</param> /// <remarks> /// The instance of the <see cref="ColoredConsoleAppender" /> class is set up to write /// to the standard output stream. /// </remarks> public ColoredConsoleAppender(ILayout layout) : this(layout, false) { } /// <summary> /// Initializes a new instance of the <see cref="ColoredConsoleAppender" /> class /// with the specified layout. /// </summary> /// <param name="layout">the layout to use for this appender</param> /// <param name="writeToErrorStream">flag set to <c>true</c> to write to the console error stream</param> /// <remarks> /// When <paramref name="writeToErrorStream" /> is set to <c>true</c>, output is written to /// the standard error output stream. Otherwise, output is written to the standard /// output stream. /// </remarks> public ColoredConsoleAppender(ILayout layout, bool writeToErrorStream) { Layout = layout; m_writeToErrorStream = writeToErrorStream; } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </summary> /// <value> /// Target is the value of the console output stream. /// This is either <c>"Console.Out"</c> or <c>"Console.Error"</c>. /// </value> virtual public string Target { get { return m_writeToErrorStream ? CONSOLE_ERR : CONSOLE_OUT; } set { string v = value.Trim(); if (string.Compare(CONSOLE_ERR, v, true, CultureInfo.InvariantCulture) == 0) { m_writeToErrorStream = true; } else { m_writeToErrorStream = false; } } } /// <summary> /// Add a mapping of level to color - done by the config file /// </summary> /// <param name="mapping">The mapping to add</param> public void AddMapping(ColoredConsoleAppenderLevelColorMapping mapping) { m_Level2ColorMap[mapping.Level] = ((uint)mapping.ForeColor) + (((uint)mapping.BackColor) << 4); } /// <summary> /// A class to act as a mapping between the level that a logging call is made at and /// the color it should be displayed as. /// </summary> public class ColoredConsoleAppenderLevelColorMapping { private log4net.spi.Level m_level; private Colors m_foreColor; private Colors m_backColor; /// <summary> /// The level to map to a color /// </summary> public log4net.spi.Level Level { get { return m_level; } set { m_level = value; } } /// <summary> /// The mapped foreground color for the specified level /// </summary> public Colors ForeColor { get { return m_foreColor; } set { m_foreColor = value; } } /// <summary> /// The mapped background color for the specified level /// </summary> public Colors BackColor { get { return m_backColor; } set { m_backColor = value; } } } #endregion Public Instance Properties #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="AppenderSkeleton.DoAppend"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Writes the event to the console. /// </para> /// <para> /// The format of the output will depend on the appender's layout. /// </para> /// </remarks> override protected void Append(log4net.spi.LoggingEvent loggingEvent) { IntPtr iConsoleHandle = IntPtr.Zero; if (m_writeToErrorStream) { // Write to the error stream iConsoleHandle = GetStdHandle(STD_ERROR_HANDLE); } else { // Write to the output stream iConsoleHandle = GetStdHandle(STD_OUTPUT_HANDLE); } // set the output parameters // Default to white on black UInt32 uiColorInfo = (UInt32)(Colors.Red | Colors.Blue | Colors.Green); // see if there is a lookup. Object colLookup = m_Level2ColorMap[loggingEvent.Level]; if(colLookup != null) { uiColorInfo = (uint)colLookup; } // set the console. SetConsoleTextAttribute(iConsoleHandle, uiColorInfo); string strLoggingMessage = RenderLoggingEvent(loggingEvent); // write the output. UInt32 uiWritten = 0; WriteConsoleW( iConsoleHandle, strLoggingMessage, (UInt32)strLoggingMessage.Length, out (UInt32)uiWritten, IntPtr.Zero); } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> override protected bool RequiresLayout { get { return true; } } #endregion Override implementation of AppenderSkeleton #region Public Static Fields /// <summary> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard output stream. /// </summary> public const string CONSOLE_OUT = "Console.Out"; /// <summary> /// The <see cref="ColoredConsoleAppender.Target"/> to use when writing to the Console /// standard error output stream. /// </summary> public const string CONSOLE_ERR = "Console.Error"; #endregion Public Static Fields #region Private Instances Fields private bool m_writeToErrorStream = false; private System.Collections.Hashtable m_Level2ColorMap = new System.Collections.Hashtable(); #endregion Private Instances Fields #region Win32 Methods [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern bool SetConsoleTextAttribute( IntPtr hConsoleHandle, UInt32 uiAttributes); [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] private static extern bool WriteConsoleW( IntPtr hConsoleHandle, [MarshalAs(UnmanagedType.LPWStr)] string strBuffer, UInt32 uiBufferLen, out UInt32 uiWritten, IntPtr pReserved); //private static readonly UInt32 STD_INPUT_HANDLE = unchecked((UInt32)(-10)); private static readonly UInt32 STD_OUTPUT_HANDLE = unchecked((UInt32)(-11)); private static readonly UInt32 STD_ERROR_HANDLE = unchecked((UInt32)(-12)); [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] private static extern IntPtr GetStdHandle( UInt32 uiType); #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using NBitcoin.Secp256k1; using WalletWasabi.Crypto.Groups; namespace WalletWasabi.Helpers { public static class Guard { public static bool True(string parameterName, bool? value, string? description = null) => AssertBool(parameterName, true, value, description); public static bool False(string parameterName, bool? value, string? description = null) => AssertBool(parameterName, false, value, description); private static bool AssertBool(string parameterName, bool expectedValue, bool? value, string? description = null) { NotNull(parameterName, value); if (value != expectedValue) { throw new ArgumentOutOfRangeException(parameterName, value, description ?? $"Parameter must be {expectedValue}."); } return (bool)value; } [return: NotNull] public static T NotNull<T>(string parameterName, T value) { AssertCorrectParameterName(parameterName); return value ?? throw new ArgumentNullException(parameterName, "Parameter cannot be null."); } private static void AssertCorrectParameterName(string parameterName) { if (parameterName is null) { throw new ArgumentNullException(nameof(parameterName), "Parameter cannot be null."); } if (parameterName.Length == 0) { throw new ArgumentException("Parameter cannot be empty.", nameof(parameterName)); } if (parameterName.Trim().Length == 0) { throw new ArgumentException("Parameter cannot be whitespace.", nameof(parameterName)); } } public static T Same<T>(string parameterName, T expected, T actual) { AssertCorrectParameterName(parameterName); T expected2 = NotNull(nameof(expected), expected); if (!expected2.Equals(actual)) { throw new ArgumentException($"Parameter must be {expected2}. Actual: {actual}.", parameterName); } return actual; } public static IEnumerable<T> NotNullOrEmpty<T>(string parameterName, IEnumerable<T> value) { NotNull(parameterName, value); if (!value.Any()) { throw new ArgumentException("Parameter cannot be empty.", parameterName); } return value; } public static T[] NotNullOrEmpty<T>(string parameterName, T[] value) { NotNull(parameterName, value); if (!value.Any()) { throw new ArgumentException("Parameter cannot be empty.", parameterName); } return value; } public static IDictionary<TKey, TValue> NotNullOrEmpty<TKey, TValue>(string parameterName, IDictionary<TKey, TValue> value) { NotNull(parameterName, value); if (!value.Any()) { throw new ArgumentException("Parameter cannot be empty.", parameterName); } return value; } public static Dictionary<TKey, TValue> NotNullOrEmpty<TKey, TValue>(string parameterName, Dictionary<TKey, TValue> value) where TKey : notnull { NotNull(parameterName, value); if (!value.Any()) { throw new ArgumentException("Parameter cannot be empty.", parameterName); } return value; } public static string NotNullOrEmptyOrWhitespace(string parameterName, string value, bool trim = false) { NotNullOrEmpty(parameterName, value); string trimmedValue = value.Trim(); if (trimmedValue.Length == 0) { throw new ArgumentException("Parameter cannot be whitespace.", parameterName); } if (trim) { return trimmedValue; } else { return value; } } public static T MinimumAndNotNull<T>(string parameterName, T value, T smallest) where T : IComparable { NotNull(parameterName, value); if (value.CompareTo(smallest) < 0) { throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter cannot be less than {smallest}."); } return value; } public static T MaximumAndNotNull<T>(string parameterName, T value, T greatest) where T : IComparable { NotNull(parameterName, value); if (value.CompareTo(greatest) > 0) { throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter cannot be greater than {greatest}."); } return value; } public static T InRangeAndNotNull<T>(string parameterName, T value, T smallest, T greatest) where T : IComparable { NotNull(parameterName, value); if (value.CompareTo(smallest) < 0) { throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter cannot be less than {smallest}."); } if (value.CompareTo(greatest) > 0) { throw new ArgumentOutOfRangeException(parameterName, value, $"Parameter cannot be greater than {greatest}."); } return value; } /// <summary> /// Corrects the string: /// If the string is null, it'll be empty. /// Trims the string. /// </summary> [return: NotNull] public static string Correct(string? str) { return string.IsNullOrWhiteSpace(str) ? "" : str.Trim(); } [DebuggerStepThrough] public static GroupElement NotNullOrInfinity(string parameterName, GroupElement groupElement) => groupElement?.IsInfinity switch { null => throw new ArgumentNullException(parameterName), true => throw new ArgumentException("Point at infinity is not a valid value.", parameterName), false => groupElement }; [DebuggerStepThrough] public static IEnumerable<GroupElement> NotNullOrInfinity(string parameterName, IEnumerable<GroupElement> groupElements) => groupElements switch { null => throw new ArgumentNullException(parameterName), _ when !groupElements.Any() => throw new ArgumentException(parameterName), _ => groupElements.Select((ge, i) => NotNullOrInfinity($"{parameterName}[{i}]", ge)).ToList() }; [DebuggerStepThrough] public static Scalar NotZero(string parameterName, Scalar scalar) => scalar switch { _ when scalar.IsZero => throw new ArgumentException("Value cannot be zero.", parameterName), _ => scalar }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. #if FEATURE_CTYPES using System; using System.Collections.Generic; using System.Numerics; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Modules { /// <summary> /// Provides support for interop with native code from Python code. /// </summary> public static partial class CTypes { /// <summary> /// The meta class for ctypes simple data types. These include primitives like ints, /// floats, etc... char/wchar pointers, and untyped pointers. /// </summary> [PythonType, PythonHidden] public class SimpleType : PythonType, INativeType { internal readonly SimpleTypeKind _type; private readonly char _charType; private readonly string _format; private readonly bool _swap; public SimpleType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict) : base(context, name, bases, dict) { string sVal; const string allowedTypes = "?cbBghHiIlLdfuzZqQPXOv"; const string swappedTypes = "fdhHiIlLqQ"; if (!TryGetBoundCustomMember(context, "_type_", out object val) || (sVal = StringOps.AsString(val)) == null || sVal.Length != 1 || allowedTypes.IndexOf(sVal[0]) == -1) { throw PythonOps.AttributeError("AttributeError: class must define a '_type_' attribute which must be a single character string containing one of '{0}'.", allowedTypes); } _charType = sVal[0]; switch (_charType) { case '?': _type = SimpleTypeKind.Boolean; break; case 'c': _type = SimpleTypeKind.Char; break; case 'b': _type = SimpleTypeKind.SignedByte; break; case 'B': _type = SimpleTypeKind.UnsignedByte; break; case 'h': _type = SimpleTypeKind.SignedShort; break; case 'H': _type = SimpleTypeKind.UnsignedShort; break; case 'i': _type = SimpleTypeKind.SignedInt; break; case 'I': _type = SimpleTypeKind.UnsignedInt; break; case 'l': _type = SimpleTypeKind.SignedLong; break; case 'L': _type = SimpleTypeKind.UnsignedLong; break; case 'f': _type = SimpleTypeKind.Single; break; case 'g': // long double, new in 2.6 case 'd': _type = SimpleTypeKind.Double; break; case 'q': _type = SimpleTypeKind.SignedLongLong; break; case 'Q': _type = SimpleTypeKind.UnsignedLongLong; break; case 'O': _type = SimpleTypeKind.Object; break; case 'P': _type = SimpleTypeKind.Pointer; break; case 'z': _type = SimpleTypeKind.CharPointer; break; case 'Z': _type = SimpleTypeKind.WCharPointer; break; case 'u': _type = SimpleTypeKind.WChar; break; case 'v': _type = SimpleTypeKind.VariantBool; break; case 'X': _type = SimpleTypeKind.BStr; break; default: throw new NotImplementedException("simple type " + sVal); } if (!name.EndsWith("_be") && !name.EndsWith("_le") && swappedTypes.IndexOf(_charType) != -1) { CreateSwappedType(context, name, bases, dict); } _format = (BitConverter.IsLittleEndian ? '<' : '>') + _charType.ToString(); } private SimpleType(Type underlyingSystemType) : base(underlyingSystemType) { } private SimpleType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict, bool isLittleEndian) : this(context, name, bases, dict) { _format = (isLittleEndian ? '<' : '>') + _charType.ToString(); _swap = isLittleEndian != BitConverter.IsLittleEndian; } private void CreateSwappedType(CodeContext/*!*/ context, string name, PythonTuple bases, PythonDictionary dict) { SimpleType swapped = new SimpleType(context, name + (BitConverter.IsLittleEndian ? "_be" : "_le"), bases, dict, !BitConverter.IsLittleEndian); if (BitConverter.IsLittleEndian) { AddSlot("__ctype_be__", new PythonTypeUserDescriptorSlot(swapped)); AddSlot("__ctype_le__", new PythonTypeUserDescriptorSlot(this)); swapped.AddSlot("__ctype_le__", new PythonTypeUserDescriptorSlot(this)); swapped.AddSlot("__ctype_be__", new PythonTypeUserDescriptorSlot(swapped)); } else { AddSlot("__ctype_le__", new PythonTypeUserDescriptorSlot(swapped)); AddSlot("__ctype_be__", new PythonTypeUserDescriptorSlot(this)); swapped.AddSlot("__ctype_le__", new PythonTypeUserDescriptorSlot(swapped)); swapped.AddSlot("__ctype_be__", new PythonTypeUserDescriptorSlot(this)); } } public static ArrayType/*!*/ operator *(SimpleType type, int count) { return MakeArrayType(type, count); } public static ArrayType/*!*/ operator *(int count, SimpleType type) { return MakeArrayType(type, count); } internal static PythonType MakeSystemType(Type underlyingSystemType) { return PythonType.SetPythonType(underlyingSystemType, new SimpleType(underlyingSystemType)); } public SimpleCData from_address(CodeContext/*!*/ context, int address) { return from_address(context, new IntPtr(address)); } public SimpleCData from_address(CodeContext/*!*/ context, BigInteger address) { return from_address(context, new IntPtr((long)address)); } public SimpleCData from_address(CodeContext/*!*/ context, IntPtr ptr) { SimpleCData res = (SimpleCData)CreateInstance(context); res.SetAddress(ptr); return res; } public SimpleCData from_buffer(ArrayModule.array array, [DefaultParameterValue(0)]int offset) { ValidateArraySizes(array, offset, ((INativeType)this).Size); SimpleCData res = (SimpleCData)CreateInstance(Context.SharedContext); IntPtr addr = array.GetArrayAddress(); res._memHolder = new MemoryHolder(addr.Add(offset), ((INativeType)this).Size); res._memHolder.AddObject("ffffffff", array); return res; } public SimpleCData from_buffer_copy(ArrayModule.array array, [DefaultParameterValue(0)]int offset) { ValidateArraySizes(array, offset, ((INativeType)this).Size); SimpleCData res = (SimpleCData)CreateInstance(Context.SharedContext); res._memHolder = new MemoryHolder(((INativeType)this).Size); res._memHolder.CopyFrom(array.GetArrayAddress().Add(offset), new IntPtr(((INativeType)this).Size)); GC.KeepAlive(array); return res; } /// <summary> /// Converts an object into a function call parameter. /// </summary> public object from_param(object obj) { // TODO: This isn't right as we have an obj associated w/ the argument, CPython doesn't. return new NativeArgument((CData)PythonCalls.Call(this, obj), _charType.ToString()); } public SimpleCData in_dll(CodeContext/*!*/ context, object library, string name) { IntPtr handle = GetHandleFromObject(library, "in_dll expected object with _handle attribute"); IntPtr addr = NativeFunctions.LoadFunction(handle, name); if (addr == IntPtr.Zero) { throw PythonOps.ValueError("{0} not found when attempting to load {1} from dll", name, Name); } SimpleCData res = (SimpleCData)CreateInstance(context); res.SetAddress(addr); return res; } #region INativeType Members int INativeType.Size { get { switch (_type) { case SimpleTypeKind.Char: case SimpleTypeKind.SignedByte: case SimpleTypeKind.UnsignedByte: case SimpleTypeKind.Boolean: return 1; case SimpleTypeKind.SignedShort: case SimpleTypeKind.UnsignedShort: case SimpleTypeKind.WChar: case SimpleTypeKind.VariantBool: return 2; case SimpleTypeKind.SignedInt: case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: case SimpleTypeKind.SignedLong: case SimpleTypeKind.Single: return 4; case SimpleTypeKind.Double: case SimpleTypeKind.UnsignedLongLong: case SimpleTypeKind.SignedLongLong: return 8; case SimpleTypeKind.Object: case SimpleTypeKind.Pointer: case SimpleTypeKind.CharPointer: case SimpleTypeKind.WCharPointer: case SimpleTypeKind.BStr: return IntPtr.Size; } throw new InvalidOperationException(_type.ToString()); } } int INativeType.Alignment { get { return ((INativeType)this).Size; } } object INativeType.GetValue(MemoryHolder/*!*/ owner, object readingFrom, int offset, bool raw) { object res; switch (_type) { case SimpleTypeKind.Boolean: res = owner.ReadByte(offset) != 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; break; case SimpleTypeKind.Char: res = new string((char)owner.ReadByte(offset), 1); break; case SimpleTypeKind.SignedByte: res = GetIntReturn((int)(sbyte)owner.ReadByte(offset)); break; case SimpleTypeKind.UnsignedByte: res = GetIntReturn((int)owner.ReadByte(offset)); break; case SimpleTypeKind.SignedShort: res = GetIntReturn(owner.ReadInt16(offset, _swap)); break; case SimpleTypeKind.WChar: res = new string((char)owner.ReadInt16(offset), 1); break; case SimpleTypeKind.UnsignedShort: res = GetIntReturn((ushort)owner.ReadInt16(offset, _swap)); break; case SimpleTypeKind.VariantBool: res = owner.ReadInt16(offset, _swap) != 0 ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; break; case SimpleTypeKind.SignedInt: res = GetIntReturn(owner.ReadInt32(offset, _swap)); break; case SimpleTypeKind.UnsignedInt: res = GetIntReturn((uint)owner.ReadInt32(offset, _swap)); break; case SimpleTypeKind.UnsignedLong: res = GetIntReturn((uint)owner.ReadInt32(offset, _swap)); break; case SimpleTypeKind.SignedLong: res = GetIntReturn(owner.ReadInt32(offset, _swap)); break; case SimpleTypeKind.Single: res = GetSingleReturn(owner.ReadInt32(offset, _swap)); break; case SimpleTypeKind.Double: res = GetDoubleReturn(owner.ReadInt64(offset, _swap)); break; case SimpleTypeKind.UnsignedLongLong: res = GetIntReturn((ulong)owner.ReadInt64(offset, _swap)); break; case SimpleTypeKind.SignedLongLong: res = GetIntReturn(owner.ReadInt64(offset, _swap)); break; case SimpleTypeKind.Object: res = GetObjectReturn(owner.ReadIntPtr(offset)); break; case SimpleTypeKind.Pointer: res = owner.ReadIntPtr(offset).ToPython(); break; case SimpleTypeKind.CharPointer: res = owner.ReadMemoryHolder(offset).ReadAnsiString(0); break; case SimpleTypeKind.WCharPointer: res = owner.ReadMemoryHolder(offset).ReadUnicodeString(0); break; case SimpleTypeKind.BStr: res = Marshal.PtrToStringBSTR(owner.ReadIntPtr(offset)); break; default: throw new InvalidOperationException(); } if (!raw && IsSubClass) { res = PythonCalls.Call(this, res); } return res; } /// <summary> /// Helper function for reading char/wchar's. This is used for reading from /// arrays and pointers to avoid creating lots of 1-char strings. /// </summary> internal char ReadChar(MemoryHolder/*!*/ owner, int offset) { switch (_type) { case SimpleTypeKind.Char: return (char)owner.ReadByte(offset); case SimpleTypeKind.WChar: return (char)owner.ReadInt16(offset); default: throw new InvalidOperationException(); } } object INativeType.SetValue(MemoryHolder/*!*/ owner, int offset, object value) { if (value is SimpleCData data && data.NativeType == this) { data._memHolder.CopyTo(owner, offset, ((INativeType)this).Size); return null; } switch (_type) { case SimpleTypeKind.Boolean: owner.WriteByte(offset, ModuleOps.GetBoolean(value, this)); break; case SimpleTypeKind.Char: owner.WriteByte(offset, ModuleOps.GetChar(value, this)); break; case SimpleTypeKind.SignedByte: owner.WriteByte(offset, ModuleOps.GetSignedByte(value, this)); break; case SimpleTypeKind.UnsignedByte: owner.WriteByte(offset, ModuleOps.GetUnsignedByte(value, this)); break; case SimpleTypeKind.WChar: owner.WriteInt16(offset, (short)ModuleOps.GetWChar(value, this)); break; case SimpleTypeKind.SignedShort: owner.WriteInt16(offset, ModuleOps.GetSignedShort(value, this), _swap); break; case SimpleTypeKind.UnsignedShort: owner.WriteInt16(offset, ModuleOps.GetUnsignedShort(value, this), _swap); break; case SimpleTypeKind.VariantBool: owner.WriteInt16(offset, (short)ModuleOps.GetVariantBool(value, this), _swap); break; case SimpleTypeKind.SignedInt: owner.WriteInt32(offset, ModuleOps.GetSignedInt(value, this), _swap); break; case SimpleTypeKind.UnsignedInt: owner.WriteInt32(offset, ModuleOps.GetUnsignedInt(value, this), _swap); break; case SimpleTypeKind.UnsignedLong: owner.WriteInt32(offset, ModuleOps.GetUnsignedLong(value, this), _swap); break; case SimpleTypeKind.SignedLong: owner.WriteInt32(offset, ModuleOps.GetSignedLong(value, this), _swap); break; case SimpleTypeKind.Single: owner.WriteInt32(offset, ModuleOps.GetSingleBits(value), _swap); break; case SimpleTypeKind.Double: owner.WriteInt64(offset, ModuleOps.GetDoubleBits(value), _swap); break; case SimpleTypeKind.UnsignedLongLong: owner.WriteInt64(offset, ModuleOps.GetUnsignedLongLong(value, this), _swap); break; case SimpleTypeKind.SignedLongLong: owner.WriteInt64(offset, ModuleOps.GetSignedLongLong(value, this), _swap); break; case SimpleTypeKind.Object: owner.WriteIntPtr(offset, ModuleOps.GetObject(value)); break; case SimpleTypeKind.Pointer: owner.WriteIntPtr(offset, ModuleOps.GetPointer(value)); break; case SimpleTypeKind.CharPointer: owner.WriteIntPtr(offset, ModuleOps.GetCharPointer(value)); return value; case SimpleTypeKind.WCharPointer: owner.WriteIntPtr(offset, ModuleOps.GetWCharPointer(value)); return value; case SimpleTypeKind.BStr: owner.WriteIntPtr(offset, ModuleOps.GetBSTR(value)); return value; default: throw new InvalidOperationException(); } return null; } Type/*!*/ INativeType.GetNativeType() { switch (_type) { case SimpleTypeKind.Boolean: return typeof(bool); case SimpleTypeKind.Char: return typeof(byte); case SimpleTypeKind.SignedByte: return typeof(sbyte); case SimpleTypeKind.UnsignedByte: return typeof(byte); case SimpleTypeKind.SignedShort: case SimpleTypeKind.VariantBool: return typeof(short); case SimpleTypeKind.UnsignedShort: return typeof(ushort); case SimpleTypeKind.WChar: return typeof(char); case SimpleTypeKind.SignedInt: case SimpleTypeKind.SignedLong: return typeof(int); case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: return typeof(uint); case SimpleTypeKind.Single: return typeof(float); case SimpleTypeKind.Double: return typeof(double); case SimpleTypeKind.UnsignedLongLong: return typeof(ulong); case SimpleTypeKind.SignedLongLong: return typeof(long); case SimpleTypeKind.Object: return typeof(IntPtr); case SimpleTypeKind.Pointer: case SimpleTypeKind.CharPointer: case SimpleTypeKind.WCharPointer: case SimpleTypeKind.BStr: return typeof(IntPtr); } throw new InvalidOperationException(); } MarshalCleanup INativeType.EmitMarshalling(ILGenerator/*!*/ method, LocalOrArg argIndex, List<object>/*!*/ constantPool, int constantPoolArgument) { MarshalCleanup cleanup = null; Label marshalled = method.DefineLabel(); Type argumentType = argIndex.Type; if (!argumentType.IsValueType && _type != SimpleTypeKind.Object && _type != SimpleTypeKind.Pointer) { // check if we have an explicit CData instance. If we have a CData but it's the // wrong type CheckSimpleCDataType will throw. Label primitive = method.DefineLabel(); argIndex.Emit(method); constantPool.Add(this); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CheckSimpleCDataType")); method.Emit(OpCodes.Brfalse, primitive); argIndex.Emit(method); method.Emit(OpCodes.Castclass, typeof(CData)); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Ldobj, ((INativeType)this).GetNativeType()); method.Emit(OpCodes.Br, marshalled); method.MarkLabel(primitive); } argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } switch (_type) { case SimpleTypeKind.Boolean: case SimpleTypeKind.Char: case SimpleTypeKind.SignedByte: case SimpleTypeKind.UnsignedByte: case SimpleTypeKind.SignedShort: case SimpleTypeKind.UnsignedShort: case SimpleTypeKind.WChar: case SimpleTypeKind.SignedInt: case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: case SimpleTypeKind.SignedLong: case SimpleTypeKind.Single: case SimpleTypeKind.Double: case SimpleTypeKind.UnsignedLongLong: case SimpleTypeKind.SignedLongLong: case SimpleTypeKind.VariantBool: constantPool.Add(this); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("Get" + _type)); break; case SimpleTypeKind.Pointer: Label done = method.DefineLabel(); TryBytesConversion(method, done); Label nextTry = method.DefineLabel(); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } method.Emit(OpCodes.Isinst, typeof(string)); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); LocalBuilder lb = method.DeclareLocal(typeof(string), true); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); method.Emit(OpCodes.Conv_I); method.Emit(OpCodes.Ldc_I4, RuntimeHelpers.OffsetToStringData); method.Emit(OpCodes.Add); method.Emit(OpCodes.Br, done); method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("GetPointer")); method.MarkLabel(done); break; case SimpleTypeKind.Object: // TODO: Need cleanup here method.Emit(OpCodes.Call, typeof(CTypes).GetMethod("PyObj_ToPtr")); break; case SimpleTypeKind.CharPointer: done = method.DefineLabel(); TryToCharPtrConversion(method, argIndex, argumentType, done); cleanup = MarshalCharPointer(method, argIndex); method.MarkLabel(done); break; case SimpleTypeKind.WCharPointer: done = method.DefineLabel(); TryArrayToWCharPtrConversion(method, argIndex, argumentType, done); MarshalWCharPointer(method, argIndex); method.MarkLabel(done); break; case SimpleTypeKind.BStr: throw new NotImplementedException("BSTR marshalling"); } method.MarkLabel(marshalled); return cleanup; } private static void TryBytesConversion(ILGenerator method, Label done) { Label nextTry = method.DefineLabel(); LocalBuilder lb = method.DeclareLocal(typeof(byte).MakeByRefType(), true); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("TryCheckBytes")); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Ldelema, typeof(Byte)); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); method.Emit(OpCodes.Br, done); method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); } internal static void TryArrayToWCharPtrConversion(ILGenerator method, LocalOrArg argIndex, Type argumentType, Label done) { Label nextTry = method.DefineLabel(); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("TryCheckWCharArray")); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Br, done); method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } } internal static void TryToCharPtrConversion(ILGenerator method, LocalOrArg argIndex, Type argumentType, Label done) { TryBytesConversion(method, done); Label nextTry = method.DefineLabel(); argIndex.Emit(method); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("TryCheckCharArray")); method.Emit(OpCodes.Dup); method.Emit(OpCodes.Brfalse, nextTry); method.Emit(OpCodes.Call, typeof(CData).GetMethod("get_UnsafeAddress")); method.Emit(OpCodes.Br, done); method.MarkLabel(nextTry); method.Emit(OpCodes.Pop); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } } internal static void MarshalWCharPointer(ILGenerator method, LocalOrArg argIndex) { Type argumentType = argIndex.Type; Label isNull; Label done; LocalBuilder lb; isNull = method.DefineLabel(); done = method.DefineLabel(); method.Emit(OpCodes.Brfalse, isNull); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } lb = method.DeclareLocal(typeof(string), true); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); method.Emit(OpCodes.Conv_I); method.Emit(OpCodes.Ldc_I4, RuntimeHelpers.OffsetToStringData); method.Emit(OpCodes.Add); method.Emit(OpCodes.Br, done); method.MarkLabel(isNull); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_I); method.MarkLabel(done); } internal static MarshalCleanup MarshalCharPointer(ILGenerator method, LocalOrArg argIndex) { Type argumentType = argIndex.Type; Label isNull, done; LocalBuilder lb; isNull = method.DefineLabel(); done = method.DefineLabel(); method.Emit(OpCodes.Brfalse, isNull); argIndex.Emit(method); if (argumentType.IsValueType) { method.Emit(OpCodes.Box, argumentType); } lb = method.DeclareLocal(typeof(IntPtr)); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("StringToHGlobalAnsi")); method.Emit(OpCodes.Stloc, lb); method.Emit(OpCodes.Ldloc, lb); method.Emit(OpCodes.Br, done); method.MarkLabel(isNull); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_I); method.MarkLabel(done); return new StringCleanup(lb); } Type/*!*/ INativeType.GetPythonType() { if (IsSubClass) { return typeof(object); } return GetPythonTypeWorker(); } private Type GetPythonTypeWorker() { switch (_type) { case SimpleTypeKind.Boolean: return typeof(bool); case SimpleTypeKind.CharPointer: case SimpleTypeKind.WCharPointer: case SimpleTypeKind.WChar: case SimpleTypeKind.Char: case SimpleTypeKind.BStr: return typeof(string); case SimpleTypeKind.VariantBool: case SimpleTypeKind.SignedByte: case SimpleTypeKind.UnsignedByte: case SimpleTypeKind.SignedShort: case SimpleTypeKind.UnsignedShort: case SimpleTypeKind.SignedInt: case SimpleTypeKind.SignedLong: return typeof(int); case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: case SimpleTypeKind.UnsignedLongLong: case SimpleTypeKind.SignedLongLong: case SimpleTypeKind.Pointer: case SimpleTypeKind.Object: return typeof(object); case SimpleTypeKind.Single: case SimpleTypeKind.Double: return typeof(double); default: throw new InvalidOperationException(); } } void INativeType.EmitReverseMarshalling(ILGenerator method, LocalOrArg value, List<object> constantPool, int constantPoolArgument) { value.Emit(method); switch (_type) { case SimpleTypeKind.SignedByte: case SimpleTypeKind.UnsignedByte: case SimpleTypeKind.SignedShort: case SimpleTypeKind.UnsignedShort: case SimpleTypeKind.VariantBool: method.Emit(OpCodes.Conv_I4); break; case SimpleTypeKind.SignedInt: case SimpleTypeKind.SignedLong: case SimpleTypeKind.Boolean: break; case SimpleTypeKind.Single: method.Emit(OpCodes.Conv_R8); break; case SimpleTypeKind.Double: break; case SimpleTypeKind.UnsignedInt: case SimpleTypeKind.UnsignedLong: EmitInt32ToObject(method, value); break; case SimpleTypeKind.UnsignedLongLong: case SimpleTypeKind.SignedLongLong: EmitInt64ToObject(method, value); break; case SimpleTypeKind.Object: method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("IntPtrToObject")); break; case SimpleTypeKind.WCharPointer: method.Emit(OpCodes.Call, typeof(Marshal).GetMethod("PtrToStringUni", new[] { typeof(IntPtr) })); break; case SimpleTypeKind.CharPointer: method.Emit(OpCodes.Call, typeof(Marshal).GetMethod("PtrToStringAnsi", new[] { typeof(IntPtr) })); break; case SimpleTypeKind.BStr: method.Emit(OpCodes.Call, typeof(Marshal).GetMethod("PtrToStringBSTR", new[] { typeof(IntPtr) })); break; case SimpleTypeKind.Char: method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CharToString")); break; case SimpleTypeKind.WChar: method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("WCharToString")); break; case SimpleTypeKind.Pointer: Label done, notNull; done = method.DefineLabel(); notNull = method.DefineLabel(); if (IntPtr.Size == 4) { LocalBuilder tmpLocal = method.DeclareLocal(typeof(uint)); method.Emit(OpCodes.Conv_U4); method.Emit(OpCodes.Stloc, tmpLocal); method.Emit(OpCodes.Ldloc, tmpLocal); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_U4); method.Emit(OpCodes.Bne_Un, notNull); method.Emit(OpCodes.Ldnull); method.Emit(OpCodes.Br, done); method.MarkLabel(notNull); method.Emit(OpCodes.Ldloc, tmpLocal); EmitInt32ToObject(method, new Local(tmpLocal)); } else { LocalBuilder tmpLocal = method.DeclareLocal(typeof(long)); method.Emit(OpCodes.Conv_I8); method.Emit(OpCodes.Stloc, tmpLocal); method.Emit(OpCodes.Ldloc, tmpLocal); method.Emit(OpCodes.Ldc_I4_0); method.Emit(OpCodes.Conv_U8); method.Emit(OpCodes.Bne_Un, notNull); method.Emit(OpCodes.Ldnull); method.Emit(OpCodes.Br, done); method.MarkLabel(notNull); method.Emit(OpCodes.Ldloc, tmpLocal); EmitInt64ToObject(method, new Local(tmpLocal)); } method.MarkLabel(done); break; } if (IsSubClass) { LocalBuilder tmp = method.DeclareLocal(typeof(object)); if (GetPythonTypeWorker().IsValueType) { method.Emit(OpCodes.Box, GetPythonTypeWorker()); } method.Emit(OpCodes.Stloc, tmp); constantPool.Add(this); method.Emit(OpCodes.Ldarg, constantPoolArgument); method.Emit(OpCodes.Ldc_I4, constantPool.Count - 1); method.Emit(OpCodes.Ldelem_Ref); method.Emit(OpCodes.Ldloc, tmp); method.Emit(OpCodes.Call, typeof(ModuleOps).GetMethod("CreateSubclassInstance")); } } private static void EmitInt64ToObject(ILGenerator method, LocalOrArg value) { Label done; Label bigInt = method.DefineLabel(); done = method.DefineLabel(); method.Emit(OpCodes.Ldc_I4, Int32.MaxValue); method.Emit(OpCodes.Conv_I8); method.Emit(OpCodes.Bgt, bigInt); value.Emit(method); method.Emit(OpCodes.Ldc_I4, Int32.MinValue); method.Emit(OpCodes.Conv_I8); method.Emit(OpCodes.Blt, bigInt); value.Emit(method); method.Emit(OpCodes.Conv_I4); method.Emit(OpCodes.Box, typeof(int)); method.Emit(OpCodes.Br, done); method.MarkLabel(bigInt); value.Emit(method); method.Emit(OpCodes.Call, typeof(BigInteger).GetMethod("op_Implicit", new[] { value.Type })); method.Emit(OpCodes.Box, typeof(BigInteger)); method.MarkLabel(done); } private static void EmitInt32ToObject(ILGenerator method, LocalOrArg value) { Label intVal, done; intVal = method.DefineLabel(); done = method.DefineLabel(); method.Emit(OpCodes.Ldc_I4, Int32.MaxValue); method.Emit(value.Type == typeof(uint) ? OpCodes.Conv_U4 : OpCodes.Conv_U8); method.Emit(OpCodes.Ble, intVal); value.Emit(method); method.Emit(OpCodes.Call, typeof(BigInteger).GetMethod("op_Implicit", new[] { value.Type })); method.Emit(OpCodes.Box, typeof(BigInteger)); method.Emit(OpCodes.Br, done); method.MarkLabel(intVal); value.Emit(method); method.Emit(OpCodes.Conv_I4); method.Emit(OpCodes.Box, typeof(int)); method.MarkLabel(done); } private bool IsSubClass { get { return BaseTypes.Count != 1 || BaseTypes[0] != CTypes._SimpleCData; } } private object GetObjectReturn(IntPtr intPtr) { GCHandle handle = GCHandle.FromIntPtr(intPtr); object res = handle.Target; // TODO: handle lifetime management return res; } private object GetDoubleReturn(long p) { return BitConverter.ToDouble(BitConverter.GetBytes(p), 0); } private object GetSingleReturn(int p) { return BitConverter.ToSingle(BitConverter.GetBytes(p), 0); } private static object GetIntReturn(int value) { return ScriptingRuntimeHelpers.Int32ToObject((int)value); } private static object GetIntReturn(uint value) { if (value > Int32.MaxValue) { return (BigInteger)value; } return ScriptingRuntimeHelpers.Int32ToObject((int)value); } private static object GetIntReturn(long value) { if (value <= Int32.MaxValue && value >= Int32.MinValue) { return (int)value; } return (BigInteger)value; } private static object GetIntReturn(ulong value) { if (value <= Int32.MaxValue) { return (int)value; } return (BigInteger)value; } string INativeType.TypeFormat { get { return _format; } } #endregion } } } #endif
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Backoffice_Referensi_Layanan_ListRawatJalan : System.Web.UI.Page { public int NoKe = 0; protected string dsReportSessionName = "dsListRefLayanan"; protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Session["SIMRS.UserId"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/login.aspx"); } int UserId = (int)Session["SIMRS.UserId"]; if (Session["LayananManagement"] == null) { Response.Redirect(Request.ApplicationPath + "/Backoffice/UnAuthorize.aspx"); } else { btnNew.Text = "<img alt=\"New\" src=\"" + Request.ApplicationPath + "/images/new_f2.gif\" align=\"middle\" border=\"0\" name=\"new\" value=\"new\">" + Resources.GetString("Referensi", "AddLayanan"); } btnSearch.Text = Resources.GetString("", "Search"); ImageButtonFirst.ImageUrl = Request.ApplicationPath + "/images/navigator/nbFirst.gif"; ImageButtonPrev.ImageUrl = Request.ApplicationPath + "/images/navigator/nbPrevpage.gif"; ImageButtonNext.ImageUrl = Request.ApplicationPath + "/images/navigator/nbNextpage.gif"; ImageButtonLast.ImageUrl = Request.ApplicationPath + "/images/navigator/nbLast.gif"; GetListPoliklinik(); GetListKelompokLayanan(); UpdateDataView(true); } } public void GetListKelompokLayanan() { string KelompokLayananId = ""; if (Request.QueryString["KelompokLayananId"] != null && Request.QueryString["KelompokLayananId"].ToString() != "") KelompokLayananId = Request.QueryString["KelompokLayananId"].ToString(); SIMRS.DataAccess.RS_KelompokLayanan myObj = new SIMRS.DataAccess.RS_KelompokLayanan(); DataTable dt = myObj.GetList(); cmbKelompokLayanan.Items.Clear(); int i = 0; cmbKelompokLayanan.Items.Add(""); cmbKelompokLayanan.Items[i].Text = ""; cmbKelompokLayanan.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbKelompokLayanan.Items.Add(""); cmbKelompokLayanan.Items[i].Text = dr["Kode"].ToString() + ". " + dr["Nama"].ToString(); cmbKelompokLayanan.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == KelompokLayananId) cmbKelompokLayanan.SelectedIndex = i; i++; } } public void GetListPoliklinik() { string PoliklinikId = ""; if (Request.QueryString["PoliklinikId"] != null && Request.QueryString["PoliklinikId"].ToString() != "") PoliklinikId = Request.QueryString["PoliklinikId"].ToString(); SIMRS.DataAccess.RS_Poliklinik myObj = new SIMRS.DataAccess.RS_Poliklinik(); DataTable dt = myObj.GetList(); cmbPoliklinik.Items.Clear(); int i = 0; cmbPoliklinik.Items.Add(""); cmbPoliklinik.Items[i].Text = ""; cmbPoliklinik.Items[i].Value = ""; i++; foreach (DataRow dr in dt.Rows) { cmbPoliklinik.Items.Add(""); cmbPoliklinik.Items[i].Text = "[" + dr["Kode"].ToString() + "] " + dr["Nama"].ToString() + " (" + dr["KelompokPoliklinikNama"].ToString() + ")"; cmbPoliklinik.Items[i].Value = dr["Id"].ToString(); if (dr["Id"].ToString() == PoliklinikId) cmbPoliklinik.SelectedIndex = i; i++; } } #region .Update View Data ////////////////////////////////////////////////////////////////////// // PhysicalDataRead // ------------------------------------------------------------------ /// <summary> /// This function is responsible for loading data from database. /// </summary> /// <returns>DataSet</returns> public DataSet PhysicalDataRead() { // Local variables DataSet oDS = new DataSet(); // Get Data SIMRS.DataAccess.RS_Layanan myObj = new SIMRS.DataAccess.RS_Layanan(); DataTable myData = myObj.SelectAllTarifRawatJalan(); oDS.Tables.Add(myData); return oDS; } /// <summary> /// This function is responsible for binding data to Datagrid. /// </summary> /// <param name="dv"></param> private void BindData(DataView dv) { // Sets the sorting order dv.Sort = DataGridList.Attributes["SortField"]; if (DataGridList.Attributes["SortAscending"] == "no") dv.Sort += " DESC"; if (dv.Count > 0) { DataGridList.ShowFooter = false; int intRowCount = dv.Count; int intPageSaze = DataGridList.PageSize; int intPageCount = intRowCount / intPageSaze; if (intRowCount - (intPageCount * intPageSaze) > 0) intPageCount = intPageCount + 1; if (DataGridList.CurrentPageIndex >= intPageCount) DataGridList.CurrentPageIndex = intPageCount - 1; } else { DataGridList.ShowFooter = true; DataGridList.CurrentPageIndex = 0; } // Re-binds the grid NoKe = DataGridList.PageSize * DataGridList.CurrentPageIndex; DataGridList.DataSource = dv; DataGridList.DataBind(); int CurrentPage = DataGridList.CurrentPageIndex + 1; lblCurrentPage.Text = CurrentPage.ToString(); lblTotalPage.Text = DataGridList.PageCount.ToString(); lblTotalRecord.Text = dv.Count.ToString(); } /// <summary> /// This function is responsible for loading data from database and store to Session. /// </summary> /// <param name="strDataSessionName"></param> public void DataFromSourceToMemory(String strDataSessionName) { // Gets rows from the data source DataSet oDS = PhysicalDataRead(); // Stores it in the session cache Session[strDataSessionName] = oDS; } /// <summary> /// This function is responsible for update data view from datagrid. /// </summary> /// <param name="requery">true = get data from database, false= get data from session</param> public void UpdateDataView(bool requery) { // Retrieves the data if ((Session[dsReportSessionName] == null) || (requery)) { if (Request.QueryString["CurrentPage"] != null && Request.QueryString["CurrentPage"].ToString() != "") DataGridList.CurrentPageIndex = int.Parse(Request.QueryString["CurrentPage"].ToString()); DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; DataView dv = ds.Tables[0].DefaultView; string filter = ""; if (cmbPoliklinik.SelectedIndex > 0) { filter += filter != "" ? " AND " : ""; filter += " PoliklinikId = " + cmbPoliklinik.SelectedItem.Value; } if (cmbKelompokLayanan.SelectedIndex > 0) { filter += filter != "" ? " AND " : ""; filter += " KelompokLayananId = " + cmbKelompokLayanan.SelectedItem.Value; } dv.RowFilter = filter; BindData(dv); } public void UpdateDataView() { // Retrieves the data if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; BindData(ds.Tables[0].DefaultView); } #endregion #region .Event DataGridList ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // HANDLERs // ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageChanged(Object sender, DataGridPageChangedEventArgs e) { DataGridList.CurrentPageIndex = e.NewPageIndex; DataGridList.SelectedIndex = -1; UpdateDataView(); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a new page. /// </summary> /// <param name="sender"></param> /// <param name="nPageIndex"></param> public void GoToPage(Object sender, int nPageIndex) { DataGridPageChangedEventArgs evPage; evPage = new DataGridPageChangedEventArgs(sender, nPageIndex); PageChanged(sender, evPage); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a first page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToFirst(Object sender, ImageClickEventArgs e) { GoToPage(sender, 0); } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a previous page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToPrev(Object sender, ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex > 0) { GoToPage(sender, DataGridList.CurrentPageIndex - 1); } else { GoToPage(sender, 0); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a next page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToNext(Object sender, System.Web.UI.ImageClickEventArgs e) { if (DataGridList.CurrentPageIndex < (DataGridList.PageCount - 1)) { GoToPage(sender, DataGridList.CurrentPageIndex + 1); } } /// <summary> /// This function is responsible for loading the content of the new /// page when you click on the pager to move to a last page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void GoToLast(Object sender, ImageClickEventArgs e) { GoToPage(sender, DataGridList.PageCount - 1); } /// <summary> /// This function is invoked when you click on a column's header to /// sort by that. It just saves the current sort field name and /// refreshes the grid. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void SortByColumn(Object sender, DataGridSortCommandEventArgs e) { String strSortBy = DataGridList.Attributes["SortField"]; String strSortAscending = DataGridList.Attributes["SortAscending"]; // Sets the new sorting field DataGridList.Attributes["SortField"] = e.SortExpression; // Sets the order (defaults to ascending). If you click on the // sorted column, the order reverts. DataGridList.Attributes["SortAscending"] = "yes"; if (e.SortExpression == strSortBy) DataGridList.Attributes["SortAscending"] = (strSortAscending == "yes" ? "no" : "yes"); // Refreshes the view OnClearSelection(null, null); UpdateDataView(); } /// <summary> /// The function gets invoked when a new item is being created in /// the datagrid. This applies to pager, header, footer, regular /// and alternating items. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void PageItemCreated(Object sender, DataGridItemEventArgs e) { // Get the newly created item ListItemType itemType = e.Item.ItemType; ////////////////////////////////////////////////////////// // Is it the HEADER? if (itemType == ListItemType.Header) { for (int i = 0; i < DataGridList.Columns.Count; i++) { // draw to reflect sorting if (DataGridList.Attributes["SortField"] == DataGridList.Columns[i].SortExpression) { ////////////////////////////////////////////// // Should be much easier this way: // ------------------------------------------ // TableCell cell = e.Item.Cells[i]; // Label lblSorted = new Label(); // lblSorted.Font = "webdings"; // lblSorted.Text = strOrder; // cell.Controls.Add(lblSorted); // // but it seems it doesn't work <g> ////////////////////////////////////////////// // Add a non-clickable triangle to mean desc or asc. // The </a> ensures that what follows is non-clickable TableCell cell = e.Item.Cells[i]; LinkButton lb = (LinkButton)cell.Controls[0]; //lb.Text += "</a>&nbsp;<span style=font-family:webdings;>" + GetOrderSymbol() + "</span>"; lb.Text += "</a>&nbsp;<img src=" + Request.ApplicationPath + "/images/icons/" + GetOrderSymbol() + " >"; } } } ////////////////////////////////////////////////////////// // Is it the PAGER? if (itemType == ListItemType.Pager) { // There's just one control in the list... TableCell pager = (TableCell)e.Item.Controls[0]; // Enumerates all the items in the pager... for (int i = 0; i < pager.Controls.Count; i += 2) { // It can be either a Label or a Link button try { Label l = (Label)pager.Controls[i]; l.Text = "Hal " + l.Text; l.CssClass = "CurrentPage"; } catch { LinkButton h = (LinkButton)pager.Controls[i]; h.Text = "[ " + h.Text + " ]"; h.CssClass = "HotLink"; } } } } /// <summary> /// Verifies whether the current sort is ascending or descending and /// returns an appropriate display text (i.e., a webding) /// </summary> /// <returns></returns> private String GetOrderSymbol() { bool bDescending = (bool)(DataGridList.Attributes["SortAscending"] == "no"); //return (bDescending ? " 6" : " 5"); return (bDescending ? "downbr.gif" : "upbr.gif"); } /// <summary> /// When clicked clears the current selection if any /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnClearSelection(Object sender, EventArgs e) { DataGridList.SelectedIndex = -1; } #endregion #region .Event Button /// <summary> /// When clicked, redirect to form add for inserts a new record to the database /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnNewRecord(Object sender, EventArgs e) { string PoliklinikId = ""; if (cmbPoliklinik.SelectedIndex > 0) PoliklinikId = cmbPoliklinik.SelectedItem.Value; string KelompokLayananId = ""; if (cmbKelompokLayanan.SelectedIndex > 0) KelompokLayananId = cmbKelompokLayanan.SelectedItem.Value; string CurrentPage = DataGridList.CurrentPageIndex.ToString(); Response.Redirect("AddRawatJalan.aspx?CurrentPage=" + CurrentPage + "&PoliklinikId=" + PoliklinikId + "&KelompokLayananId=" + KelompokLayananId); } /// <summary> /// When clicked, filter data. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OnSearch(Object sender, System.EventArgs e) { if ((Session[dsReportSessionName] == null)) { DataFromSourceToMemory(dsReportSessionName); } DataSet ds = (DataSet)Session[dsReportSessionName]; DataView dv = ds.Tables[0].DefaultView; string filter = ""; if (cmbPoliklinik.SelectedIndex > 0) { filter += filter != "" ? " AND ":""; filter += " PoliklinikId = " + cmbPoliklinik.SelectedItem.Value; } if (cmbKelompokLayanan.SelectedIndex > 0) { filter += filter != "" ? " AND " : ""; filter += " KelompokLayananId = " + cmbKelompokLayanan.SelectedItem.Value; } dv.RowFilter = filter; BindData(dv); } #endregion #region .Update Link Item Butom /// <summary> /// The function is responsible for get link button form. /// </summary> /// <param name="szId"></param> /// <param name="CurrentPage"></param> /// <returns></returns> public string GetLinkButton(string Id, string Nama, string CurrentPage) { string szResult = ""; if (Session["LayananManagement"] != null) { szResult += "<a class=\"toolbar\" href=\"EditRawatJalan.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" "; szResult += ">" + Resources.GetString("", "Edit") + "</a>"; szResult += "<a class=\"toolbar\" href=\"DeleteRawatJalan.aspx?CurrentPage=" + CurrentPage + "&Id=" + Id + "\" "; szResult += ">" + Resources.GetString("", "Delete") + "</a>"; } return szResult; } #endregion }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (the "License"). // You may not use this file except in compliance with the // License. A copy of the License is located at // // http://aws.amazon.com/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.IO; using Amazon.Runtime; namespace Amazon.Runtime.Internal.Util { /// <summary> /// A wrapper stream that encrypts the base stream as it /// is being read. /// </summary> public abstract class EncryptUploadPartStream : WrapperStream { #region Properties protected IEncryptionWrapper Algorithm { get; set; } private byte[] internalBuffer; public byte[] InitializationVector { get; protected set; } internal const int InternalEncryptionBlockSize = 16; #endregion #region Constructors /// <summary> /// Initializes an EncryptStream for Multipart uploads with an encryption algorithm and a base stream. /// </summary> /// <param name="baseStream">Stream to perform encryption on..</param> protected EncryptUploadPartStream(Stream baseStream) : base(baseStream) { internalBuffer = new byte[InternalEncryptionBlockSize]; InitializationVector = new byte[InternalEncryptionBlockSize]; ValidateBaseStream(); } #endregion #region Stream overrides /// <summary> /// Reads a sequence of bytes from the current stream and advances the position /// within the stream by the number of bytes read. /// </summary> /// <param name="buffer"> /// An array of bytes. When this method returns, the buffer contains the specified /// byte array with the values between offset and (offset + count - 1) replaced /// by the bytes read from the current source. /// </param> /// <param name="offset"> /// The zero-based byte offset in buffer at which to begin storing the data read /// from the current stream. /// </param> /// <param name="count"> /// The maximum number of bytes to be read from the current stream. /// </param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the /// number of bytes requested if that many bytes are not currently available, /// or zero (0) if the end of the stream has been reached. /// </returns> public override int Read(byte[] buffer, int offset, int count) { int readBytes = base.Read(buffer, offset, count); if (readBytes == 0) return 0; int numBytesRead = 0; while (numBytesRead < readBytes) { numBytesRead += Algorithm.AppendBlock(buffer, offset, InternalEncryptionBlockSize, internalBuffer, 0); Buffer.BlockCopy(internalBuffer, 0, buffer, offset, InternalEncryptionBlockSize); offset = offset + InternalEncryptionBlockSize; } Buffer.BlockCopy(buffer, numBytesRead - InternalEncryptionBlockSize, InitializationVector, 0, InternalEncryptionBlockSize); return numBytesRead; } public override void Close() { base.Close(); } /// <summary> /// Gets a value indicating whether the current stream supports seeking. /// </summary> public override bool CanSeek { get { return true; } } /// <summary> /// Returns encrypted content length. /// </summary> public override long Length { get { if (base.Length % InternalEncryptionBlockSize == 0) { return (base.Length); } else { return (base.Length + InternalEncryptionBlockSize - (base.Length % InternalEncryptionBlockSize)); } } } /// <summary> /// Gets or sets the position within the current stream. /// </summary> public override long Position { get { return BaseStream.Position; } set { Seek(offset: value, origin: SeekOrigin.Begin); } } /// <summary> /// Sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the origin parameter.</param> /// <param name="origin"> /// A value of type System.IO.SeekOrigin indicating the reference point used /// to obtain the new position.</param> /// <returns>The new position within the current stream.</returns> public override long Seek(long offset, SeekOrigin origin) { long position = BaseStream.Seek(offset, origin); this.Algorithm.Reset(); return position; } #endregion #region Private methods /// <summary> /// Validates the underlying stream. /// </summary> private void ValidateBaseStream() { if (!BaseStream.CanRead && !BaseStream.CanWrite) throw new InvalidDataException("EncryptStreamForUploadPart does not support base streams that are not capable of reading or writing"); } #endregion } /// <summary> /// A wrapper stream that encrypts the base stream as it /// is being read. /// </summary> public class EncryptUploadPartStream<T> : EncryptUploadPartStream where T : class, IEncryptionWrapper, new() { #region Constructors /// <summary> /// Initializes an EncryptStream with an encryption algorithm and a base stream. /// </summary> /// <param name="baseStream">Stream to perform encryption on..</param> /// <param name="key">Symmetric key to perform encryption</param> /// <param name="IV">Initialization vector to perform encryption</param> public EncryptUploadPartStream(Stream baseStream, byte[] key, byte[] IV) : base(baseStream) { Algorithm = new T(); Algorithm.SetEncryptionData(key, IV); Algorithm.CreateEncryptor(); } #endregion } /// <summary> /// A wrapper stream that encrypts the base stream as it /// is being read. /// </summary> public class AESEncryptionUploadPartStream : EncryptUploadPartStream<EncryptionWrapperAES> { #region Constructors /// <summary> /// Initializes an AESEncryptionStream with a base stream. /// </summary> /// <param name="baseStream">Stream to perform encryption on..</param> /// <param name="key">Symmetric key to perform encryption</param> /// <param name="IV">Initialization vector to perform encryption</param> public AESEncryptionUploadPartStream(Stream baseStream, byte[] key, byte[] IV) : base(baseStream, key, IV) { } #endregion } }
using System.Linq; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using Infrastructure; using System.Text; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System; using ICSharpCode.SharpZipLib.Zip.Compression; namespace ZxSpectrum.Tests { [TestClass] public class UnitTest1 { //const string FileName = "the hobbit.01.go see elrond.rzx"; const string FileName = "starquake.rzx"; [TestMethod] public void StarQuake_ReadHeaderBlock() { //using (FileStream inputStream = File.Open("starquake.rzx", FileMode.Open)) using (FileStream inputStream = File.Open(FileName, FileMode.Open)) using (BinaryReader reader = new BinaryReader(inputStream, Encoding.ASCII)) { var header = reader.ReadRZXHeader(); Assert.AreEqual("RZX!", header.Signature); Assert.AreEqual(0x00, header.MajorRevisionNumber); Assert.AreEqual(0x0C, header.MinorRevisionNumber, "The spec says this should be 0x0C, but obviously the starquake is running from an older spec of 12"); Assert.AreEqual((uint)0, header.Flags, "Thankfully the flags are empty"); Assert.IsNotNull(header.RZXBlocksSequence); } } [TestMethod] public void StarQuake_ReadCreatorInformationBlock() { using (FileStream inputStream = File.Open(FileName, FileMode.Open)) using (BinaryReader reader = new BinaryReader(inputStream, Encoding.ASCII)) { var rzx = reader.ReadRZXHeader(); CreatorInformationBlock block = (CreatorInformationBlock)rzx.RZXBlocksSequence.First(); Assert.AreEqual(0x10, block.BlockID); Assert.AreEqual((uint)29, block.BlockLength); Assert.AreEqual("RealSpectrum\0\0\0\0\0\0\0\0", block.CreatorsIdentification); Assert.AreEqual(0, block.CreatorsMajorVersionNumber); Assert.AreEqual(147, block.CreatorsMinorVersionNumber); Assert.AreEqual(0, block.CreatorsCustomData.Count()); } } } public static class Extensions { public static void Validate<T>(this T source) { var validationResults = new List<ValidationResult>(); var vc = new ValidationContext(source, null, null); Validator.ValidateObject(source, vc, true); } private static byte[] Inflate(this byte[] input) { MemoryStream inflatedStream = new MemoryStream(); Inflater inflater = new Inflater(false); inflater.SetInput(input); byte[] buffer = new byte[4096]; while (!inflater.IsFinished) { int readed = inflater.Inflate(buffer, 0, buffer.Length); inflatedStream.Write(buffer, 0, readed); } return inflatedStream.ToArray(); } public static RZXHeader ReadRZXHeader(this BinaryReader reader) { var result = new RZXHeader( signature: reader.ReadChars(4), majorRevisionNumber: reader.ReadByte(), minorRevisionNumber: reader.ReadByte(), flags: reader.ReadUInt32(), rzxBlocksSequence: reader.ReadRZXBlocksSequence() ); result.Validate(); return result; } public static IEnumerable<IBlock> ReadRZXBlocksSequence(this BinaryReader reader) { var result = new List<IBlock>(); while (reader.BaseStream.Position < reader.BaseStream.Length) { byte blockID = reader.ReadByte(); uint blockLength = reader.ReadUInt32(); switch (blockID) { case (0x10): result.Add(reader.ReadCreatorInformationBlock(blockID, blockLength)); break; case (0x20): case (0x21): throw new NotSupportedException("I'm skipping the security crap"); case (0x30): result.Add(reader.ReadSnapshotBlock(blockID, blockLength)); break; case (0x80): result.Add(reader.ReadInputRecordingBlock(blockID, blockLength)); break; default: throw new NotSupportedException(String.Format("WTF? {0:x4}", blockID)); //break; } } return result; } public static CreatorInformationBlock ReadCreatorInformationBlock( this BinaryReader reader, byte blockID, uint blockLength ) { var result = new CreatorInformationBlock( blockID: blockID, blockLength: blockLength, creatorsIdentification: new string(reader.ReadChars(20)), creatorsMajorVersionNumber: reader.ReadUInt16(), creatorsMinorVersionNumber: reader.ReadUInt16(), //creatorsCustomData: (blockLength <= 29 ? /*new List<byte>()*/reader.ReadBytes(0).ToList() : reader.ReadBytes((int)blockLength - 29).ToList())); creatorsCustomData: reader.ReadBytes((int)blockLength - 29).ToList()); result.Validate(); return result; } public static SnapshotBlock ReadSnapshotBlock( this BinaryReader reader, byte blockID, uint blockLength ) { var result = new SnapshotBlock( blockID: blockID, blockLength: blockLength, flags: reader.ReadUInt32(), snapshotFilenameExtension: new string(reader.ReadChars(4)), uncompressedSnapshotLength: reader.ReadUInt32(), snapshotDataOrDescriptor: reader.ReadBytes((int)blockLength - 17).Inflate() ); result.Validate(); return result; } public static InputRecordingBlock ReadInputRecordingBlock( this BinaryReader reader, byte blockID, uint blockLength ) { var result = new InputRecordingBlock( blockID: blockID, blockLength: blockLength, numberOfFramesInTheBlock: reader.ReadUInt32(), reserved: reader.ReadByte(), tSTATESCounterAtTheBeginning: reader.ReadUInt32(), flags: reader.ReadUInt32(), sequenceOfInputFrames: reader.ReadBytes((int)blockLength - 18) .Inflate() .GetRecordingFrames() ); result.Validate(); return result; } private static Queue<IORecordingFrame> GetRecordingFrames(this byte[] inputRecordingData) { Queue<IORecordingFrame> queue = new Queue<IORecordingFrame>(); byte[] lastFrameInput = null; MemoryStream ms = new MemoryStream(inputRecordingData); using (BinaryReader reader = new BinaryReader(ms)) { while (reader.BaseStream.Position < reader.BaseStream.Length) { var fetchCounter = reader.ReadUInt16(); var inCounter = reader.ReadUInt16(); byte[] inValues; if (inCounter == 0xFFFF) { if (lastFrameInput == null) throw new InvalidOperationException(); inCounter = (ushort)lastFrameInput.Length; inValues = (byte[])lastFrameInput.Clone(); } else { lastFrameInput = reader.ReadBytes(inCounter); inValues = (byte[])lastFrameInput.Clone(); } IORecordingFrame frame = new IORecordingFrame( fetchCounterTillNextInterrupt: fetchCounter, inCounter: inCounter, returnValuesForTheCPU_IO_PortReads: inValues ); queue.Enqueue(frame); } } return queue; } } }
/* Microsoft Automatic Graph Layout,MSAGL 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.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Core.Layout; using Microsoft.Msagl.Drawing; using Color = System.Drawing.Color; using GLEEEdge = Microsoft.Msagl.Core.Layout.Edge; using DrawingEdge = Microsoft.Msagl.Drawing.Edge; using GLEENode = Microsoft.Msagl.Core.Layout.Node; using DrawingNode = Microsoft.Msagl.Drawing.Node; namespace Microsoft.Msagl.GraphViewerGdi { /// <summary> /// it is a class holding Microsoft.Msagl.Drawing.Node and Microsoft.Msagl.Node /// </summary> public sealed class DNode : DObject, IViewerNode, IHavingDLabel { readonly Set<Port> portsToDraw = new Set<Port>(); float dashSize; internal List<DEdge> inEdges = new List<DEdge>(); internal List<DEdge> outEdges = new List<DEdge>(); internal List<DEdge> selfEdges = new List<DEdge>(); internal DNode(DrawingNode drawingNodeParam, GViewer gviewer) : base(gviewer) { DrawingNode = drawingNodeParam; } /// <summary> /// the corresponding drawing node /// </summary> public DrawingNode DrawingNode { get; set; } /// <summary> /// return the color of a node /// </summary> public Color Color { get { return Draw.MsaglColorToDrawingColor(DrawingNode.Attr.Color); } } /// <summary> /// Fillling color of a node /// </summary> public Color FillColor { get { return Draw.MsaglColorToDrawingColor(DrawingNode.Attr.FillColor); } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal GLEENode GeometryNode { get { return DrawingNode.GeometryNode; } } #region IHavingDLabel Members /// <summary> /// gets / sets the rendered label of the object /// </summary> public DLabel Label { get; set; } #endregion #region IViewerNode Members /// <summary> /// /// </summary> public void SetStrokeFill() { } /// <summary> /// returns the corresponding DrawingNode /// </summary> public DrawingNode Node { get { return DrawingNode; } } /// <summary> /// return incoming edges /// </summary> public IEnumerable<IViewerEdge> InEdges { get { foreach (DEdge e in inEdges) yield return e; } } /// <summary> /// returns outgoing edges /// </summary> public IEnumerable<IViewerEdge> OutEdges { get { foreach (DEdge e in outEdges) yield return e; } } /// <summary> /// returns self edges /// </summary> public IEnumerable<IViewerEdge> SelfEdges { get { foreach (DEdge e in selfEdges) yield return e; } } public event Action<IViewerNode> IsCollapsedChanged; /// <summary> /// returns the corresponding drawing object /// </summary> public override DrawingObject DrawingObject { get { return DrawingNode; } } /// <summary> /// /// </summary> public void AddPort(Port port) { portsToDraw.Insert(port); } /// <summary> /// it is a class holding Microsoft.Msagl.Drawing.Node and Microsoft.Msagl.Node /// </summary> public void RemovePort(Port port) { portsToDraw.Remove(port); } #endregion internal void AddOutEdge(DEdge edge) { outEdges.Add(edge); } internal void AddInEdge(DEdge edge) { inEdges.Add(edge); } internal void AddSelfEdge(DEdge edge) { selfEdges.Add(edge); } internal override float DashSize() { if (dashSize > 0) return dashSize; var w = (float) DrawingNode.Attr.LineWidth; if (w < 0) w = 1; var dashSizeInPoints = (float) (Draw.dashSize*GViewer.Dpi); return dashSize = dashSizeInPoints/w; } /// <summary> /// /// </summary> protected internal override void Invalidate() { } /// <summary> /// calculates the rendered rectangle and RenderedBox to it /// </summary> public override void UpdateRenderedBox() { DrawingNode node = DrawingNode; double del = node.Attr.LineWidth/2; Rectangle box = node.GeometryNode.BoundaryCurve.BoundingBox; box.Pad(del); RenderedBox = box; } internal void RemoveOutEdge(DEdge de) { outEdges.Remove(de); } internal void RemoveInEdge(DEdge de) { inEdges.Remove(de); } internal void RemoveSelfEdge(DEdge de) { selfEdges.Remove(de); } } }
// 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 Xunit; namespace Tests.Collections { public enum CollectionOrder { Unspecified, Sequential } public abstract class IEnumerableTest<T> { private const int EnumerableSize = 16; protected T DefaultValue => default(T); protected bool MoveNextAtEndThrowsOnModifiedCollection => true; protected virtual CollectionOrder CollectionOrder => CollectionOrder.Sequential; protected abstract bool IsResetNotSupported { get; } protected abstract bool IsGenericCompatibility { get; } protected abstract object GenerateItem(); protected object[] GenerateItems(int size) { var ret = new object[size]; for (var i = 0; i < size; i++) { ret[i] = GenerateItem(); } return ret; } /// <summary> /// When overridden in a derived class, Gets an instance of the enumerable under test containing the given items. /// </summary> /// <param name="items">The items to initialize the enumerable with.</param> /// <returns>An instance of the enumerable under test containing the given items.</returns> protected abstract IEnumerable GetEnumerable(object[] items); /// <summary> /// When overridden in a derived class, invalidates any enumerators for the given IEnumerable. /// </summary> /// <param name="enumerable">The <see cref="IEnumerable" /> to invalidate enumerators for.</param> /// <returns>The new set of items in the <see cref="IEnumerable" /></returns> protected abstract object[] InvalidateEnumerator(IEnumerable enumerable); private void RepeatTest( Action<IEnumerator, object[], int> testCode, int iters = 3) { object[] items = GenerateItems(32); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); for (var i = 0; i < iters; i++) { testCode(enumerator, items, i); if (IsResetNotSupported) { enumerator = enumerable.GetEnumerator(); } else { enumerator.Reset(); } } } private void RepeatTest( Action<IEnumerator, object[]> testCode, int iters = 3) { RepeatTest((e, i, it) => testCode(e, i), iters); } [Fact] public void MoveNextHitsAllItems() { RepeatTest( (enumerator, items) => { var iterations = 0; while (enumerator.MoveNext()) { iterations++; } Assert.Equal(items.Length, iterations); }); } [Fact] public void CurrentThrowsAfterEndOfCollection() { if (IsGenericCompatibility) { return; // apparently it is okay if enumerator.Current doesn't throw when the collection is generic. } RepeatTest( (enumerator, items) => { while (enumerator.MoveNext()) { } Assert.Throws<InvalidOperationException>( () => enumerator.Current); }); } [Fact] public void MoveNextFalseAfterEndOfCollection() { RepeatTest( (enumerator, items) => { while (enumerator.MoveNext()) { } Assert.False(enumerator.MoveNext()); }); } [Fact] public void Current() { // Verify that current returns proper result. RepeatTest( (enumerator, items, iteration) => { if (iteration == 1) { VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); } else { VerifyEnumerator(enumerator, items); } }); } [Fact] public void Reset() { if (IsResetNotSupported) { RepeatTest( (enumerator, items) => { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); }); RepeatTest( (enumerator, items, iter) => { if (iter == 1) { VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); for (var i = 0; i < 3; i++) { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); } VerifyEnumerator( enumerator, items, items.Length/2, items.Length - (items.Length/2), false, true); } else if (iter == 2) { VerifyEnumerator(enumerator, items); for (var i = 0; i < 3; i++) { Assert.Throws<NotSupportedException>( () => enumerator.Reset()); } VerifyEnumerator( enumerator, items, 0, 0, false, true); } else { VerifyEnumerator(enumerator, items); } }); } else { RepeatTest( (enumerator, items, iter) => { if (iter == 1) { VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); enumerator.Reset(); enumerator.Reset(); } else if (iter == 3) { VerifyEnumerator(enumerator, items); enumerator.Reset(); enumerator.Reset(); } else { VerifyEnumerator(enumerator, items); } }, 5); } } [Fact] public void ModifyCollectionWithNewEnumerator() { IEnumerable enumerable = GetEnumerable(GenerateItems(EnumerableSize)); IEnumerator enumerator = enumerable.GetEnumerator(); InvalidateEnumerator(enumerable); VerifyModifiedEnumerator(enumerator, null, true, false); } [Fact] public void EnumerateFirstItemThenModify() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); VerifyEnumerator(enumerator, items, 0, 1, true, false); object currentItem = enumerator.Current; InvalidateEnumerator(enumerable); VerifyModifiedEnumerator( enumerator, currentItem, false, false); } [Fact] public void EnumeratePartOfCollectionThenModify() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); object currentItem = enumerator.Current; InvalidateEnumerator(enumerable); VerifyModifiedEnumerator( enumerator, currentItem, false, false); } [Fact] public void EnumerateEntireCollectionThenModify() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); VerifyEnumerator( enumerator, items, 0, items.Length, true, false); object currentItem = enumerator.Current; InvalidateEnumerator(enumerable); VerifyModifiedEnumerator( enumerator, currentItem, false, true); } [Fact] public void EnumerateThenModifyThrows() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); VerifyEnumerator( enumerator, items, 0, items.Length/2, true, false); object currentItem = enumerator.Current; InvalidateEnumerator(enumerable); Assert.Equal(currentItem, enumerator.Current); Assert.Throws<InvalidOperationException>( () => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>( () => enumerator.Reset()); } [Fact] [ActiveIssue(1170)] public void EnumeratePastEndThenModify() { object[] items = GenerateItems(EnumerableSize); IEnumerable enumerable = GetEnumerable(items); IEnumerator enumerator = enumerable.GetEnumerator(); // enumerate to the end VerifyEnumerator(enumerator, items); // add elements to the collection InvalidateEnumerator(enumerable); // check that it throws proper exceptions VerifyModifiedEnumerator( enumerator, DefaultValue, true, true); } private void VerifyModifiedEnumerator( IEnumerator enumerator, object expectedCurrent, bool expectCurrentThrow, bool atEnd) { if (expectCurrentThrow) { Assert.Throws<InvalidOperationException>( () => enumerator.Current); } else { object current = enumerator.Current; for (var i = 0; i < 3; i++) { Assert.Equal(expectedCurrent, current); current = enumerator.Current; } } if (!atEnd || MoveNextAtEndThrowsOnModifiedCollection) { Assert.Throws<InvalidOperationException>( () => enumerator.MoveNext()); } else { Assert.False(enumerator.MoveNext()); } if (!IsResetNotSupported) { Assert.Throws<InvalidOperationException>( () => enumerator.Reset()); } } private void VerifyEnumerator( IEnumerator enumerator, object[] expectedItems) { VerifyEnumerator( enumerator, expectedItems, 0, expectedItems.Length, true, true); } private void VerifyEnumerator( IEnumerator enumerator, object[] expectedItems, int startIndex, int count, bool validateStart, bool validateEnd) { bool needToMatchAllExpectedItems = count - startIndex == expectedItems.Length; if (validateStart) { for (var i = 0; i < 3; i++) { Assert.Throws<InvalidOperationException>( () => enumerator.Current); } } int iterations; if (CollectionOrder == CollectionOrder.Unspecified) { var itemsVisited = new BitArray( needToMatchAllExpectedItems ? count : expectedItems.Length, false); for (iterations = 0; iterations < count && enumerator.MoveNext(); iterations++) { object currentItem = enumerator.Current; var itemFound = false; for (var i = 0; i < itemsVisited.Length; ++i) { if (!itemsVisited[i] && Equals( currentItem, expectedItems[ i + (needToMatchAllExpectedItems ? startIndex : 0)])) { itemsVisited[i] = true; itemFound = true; break; } } Assert.True(itemFound, "itemFound"); for (var i = 0; i < 3; i++) { object tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } } if (needToMatchAllExpectedItems) { for (var i = 0; i < itemsVisited.Length; i++) { Assert.True(itemsVisited[i]); } } else { var visitedItemCount = 0; for (var i = 0; i < itemsVisited.Length; i++) { if (itemsVisited[i]) { ++visitedItemCount; } } Assert.Equal(count, visitedItemCount); } } else if (CollectionOrder == CollectionOrder.Sequential) { for (iterations = 0; iterations < count && enumerator.MoveNext(); iterations++) { object currentItem = enumerator.Current; Assert.Equal(expectedItems[iterations], currentItem); for (var i = 0; i < 3; i++) { object tempItem = enumerator.Current; Assert.Equal(currentItem, tempItem); } } } else { throw new ArgumentException( "CollectionOrder is invalid."); } Assert.Equal(count, iterations); if (validateEnd) { for (var i = 0; i < 3; i++) { Assert.False( enumerator.MoveNext(), "enumerator.MoveNext() returned true past the expected end."); } if (IsGenericCompatibility) { return; } // apparently it is okay if enumerator.Current doesn't throw when the collection is generic. for (var i = 0; i < 3; i++) { Assert.Throws<InvalidOperationException>( () => enumerator.Current); } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Azure.Batch.Unit.Tests { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using BatchTestCommon; using Microsoft.Azure.Batch; using Microsoft.Azure.Batch.Common; using Microsoft.Azure.Batch.FileStaging; using TestUtilities; using Xunit; using Xunit.Abstractions; using Protocol = Microsoft.Azure.Batch.Protocol; public class PropertyUnitTests { private readonly ITestOutputHelper testOutputHelper; private readonly ObjectFactory defaultObjectFactory; private readonly ObjectFactory customizedObjectFactory; private readonly ObjectComparer objectComparer; private readonly IList<ComparerPropertyMapping> proxyPropertyToObjectModelMapping; private const int TestRunCount = 1000; public PropertyUnitTests(ITestOutputHelper testOutputHelper) { this.testOutputHelper = testOutputHelper; //Define the factories this.defaultObjectFactory = new ObjectFactory(); this.proxyPropertyToObjectModelMapping = new List<ComparerPropertyMapping>() { new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "AutoScaleEnabled", "EnableAutoScale"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "VirtualMachineSize", "VmSize"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "MaxTasksPerComputeNode", "MaxTasksPerNode"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "Statistics", "Stats"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "CurrentDedicatedComputeNodes", "CurrentDedicatedNodes"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "CurrentLowPriorityComputeNodes", "CurrentLowPriorityNodes"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.CloudPool), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "VirtualMachineSize", "VmSize"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "AutoScaleEnabled", "EnableAutoScale"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "MaxTasksPerComputeNode", "MaxTasksPerNode"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"), new ComparerPropertyMapping(typeof(CloudPool), typeof(Protocol.Models.PoolAddParameter), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"), new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "AutoScaleEnabled", "EnableAutoScale"), new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "VirtualMachineSize", "VmSize"), new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "MaxTasksPerComputeNode", "MaxTasksPerNode"), new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "InterComputeNodeCommunicationEnabled", "EnableInterNodeCommunication"), new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "CurrentDedicatedComputeNodes", "CurrentDedicatedNodes"), new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "CurrentLowPriorityComputeNodes", "CurrentLowPriorityNodes"), new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "TargetDedicatedComputeNodes", "TargetDedicatedNodes"), new ComparerPropertyMapping(typeof(PoolSpecification), typeof(Protocol.Models.PoolSpecification), "TargetLowPriorityComputeNodes", "TargetLowPriorityNodes"), new ComparerPropertyMapping(typeof(CloudServiceConfiguration), typeof(Protocol.Models.CloudServiceConfiguration), "OSFamily", "OsFamily"), new ComparerPropertyMapping(typeof(CloudServiceConfiguration), typeof(Protocol.Models.CloudServiceConfiguration), "OSVersion", "OsVersion"), new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "TaskExecutionInformation"), new ComparerPropertyMapping(typeof(AutoPoolSpecification), typeof(Protocol.Models.AutoPoolSpecification), "PoolSpecification", "Pool"), new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeId", "NodeId"), new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "ComputeNodeUrl", "NodeUrl"), new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobPreparationTaskExecutionInformation", "JobPreparationTaskExecutionInfo"), new ComparerPropertyMapping(typeof(JobPreparationAndReleaseTaskExecutionInformation), typeof(Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation), "JobReleaseTaskExecutionInformation", "JobReleaseTaskExecutionInfo"), new ComparerPropertyMapping(typeof(JobPreparationTaskExecutionInformation), typeof(Protocol.Models.JobPreparationTaskExecutionInformation), "FailureInformation", "FailureInfo"), new ComparerPropertyMapping(typeof(JobPreparationTaskExecutionInformation), typeof(Protocol.Models.JobPreparationTaskExecutionInformation), "ContainerInformation", "ContainerInfo"), new ComparerPropertyMapping(typeof(JobReleaseTaskExecutionInformation), typeof(Protocol.Models.JobReleaseTaskExecutionInformation), "FailureInformation", "FailureInfo"), new ComparerPropertyMapping(typeof(JobReleaseTaskExecutionInformation), typeof(Protocol.Models.JobReleaseTaskExecutionInformation), "ContainerInformation", "ContainerInfo"), new ComparerPropertyMapping(typeof(TaskExecutionInformation), typeof(Protocol.Models.TaskExecutionInformation), "FailureInformation", "FailureInfo"), new ComparerPropertyMapping(typeof(TaskExecutionInformation), typeof(Protocol.Models.TaskExecutionInformation), "ContainerInformation", "ContainerInfo"), new ComparerPropertyMapping(typeof(SubtaskInformation), typeof(Protocol.Models.SubtaskInformation), "FailureInformation", "FailureInfo"), new ComparerPropertyMapping(typeof(SubtaskInformation), typeof(Protocol.Models.SubtaskInformation), "ContainerInformation", "ContainerInfo"), new ComparerPropertyMapping(typeof(StartTaskInformation), typeof(Protocol.Models.StartTaskInformation), "FailureInformation", "FailureInfo"), new ComparerPropertyMapping(typeof(StartTaskInformation), typeof(Protocol.Models.StartTaskInformation), "ContainerInformation", "ContainerInfo"), new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "UsageStatistics", "UsageStats"), new ComparerPropertyMapping(typeof(PoolStatistics), typeof(Protocol.Models.PoolStatistics), "ResourceStatistics", "ResourceStats"), new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "UserCpuTime", "UserCPUTime"), new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "KernelCpuTime", "KernelCPUTime"), new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "SucceededTaskCount", "NumSucceededTasks"), new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "FailedTaskCount", "NumFailedTasks"), new ComparerPropertyMapping(typeof(JobStatistics), typeof(Protocol.Models.JobStatistics), "TaskRetryCount", "NumTaskRetries"), new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "UserCpuTime", "UserCPUTime"), new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "KernelCpuTime", "KernelCPUTime"), new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "SucceededTaskCount", "NumSucceededTasks"), new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "FailedTaskCount", "NumFailedTasks"), new ComparerPropertyMapping(typeof(JobScheduleStatistics), typeof(Protocol.Models.JobScheduleStatistics), "TaskRetryCount", "NumTaskRetries"), new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageCpuPercentage", "AvgCPUPercentage"), new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageMemoryGiB", "AvgMemoryGiB"), new ComparerPropertyMapping(typeof(ResourceStatistics), typeof(Protocol.Models.ResourceStatistics), "AverageDiskGiB", "AvgDiskGiB"), new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "UserCpuTime", "UserCPUTime"), new ComparerPropertyMapping(typeof(TaskStatistics), typeof(Protocol.Models.TaskStatistics), "KernelCpuTime", "KernelCPUTime"), new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "PoolInformation", "PoolInfo"), new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "ExecutionInformation", "ExecutionInfo"), new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.CloudJob), "Statistics", "Stats"), new ComparerPropertyMapping(typeof(CloudJob), typeof(Protocol.Models.JobAddParameter), "PoolInformation", "PoolInfo"), new ComparerPropertyMapping(typeof(JobSpecification), typeof(Protocol.Models.JobSpecification), "PoolInformation", "PoolInfo"), new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "ExecutionInformation", "ExecutionInfo"), new ComparerPropertyMapping(typeof(CloudJobSchedule), typeof(Protocol.Models.CloudJobSchedule), "Statistics", "Stats"), new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "AffinityInformation", "AffinityInfo"), new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ExecutionInformation", "ExecutionInfo"), new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "ComputeNodeInformation", "NodeInfo"), new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.CloudTask), "Statistics", "Stats"), new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "AffinityInformation", "AffinityInfo"), new ComparerPropertyMapping(typeof(CloudTask), typeof(Protocol.Models.TaskAddParameter), "ComputeNodeInformation", "NodeInfo"), new ComparerPropertyMapping(typeof(ExitConditions), typeof(Protocol.Models.ExitConditions), "Default", "DefaultProperty"), new ComparerPropertyMapping(typeof(TaskInformation), typeof(Protocol.Models.TaskInformation), "ExecutionInformation", "ExecutionInfo"), new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "IPAddress", "IpAddress"), new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "VirtualMachineSize", "VmSize"), new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "StartTaskInformation", "StartTaskInfo"), new ComparerPropertyMapping(typeof(ComputeNode), typeof(Protocol.Models.ComputeNode), "NodeAgentInformation", "NodeAgentInfo"), new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeId", "NodeId"), new ComparerPropertyMapping(typeof(ComputeNodeInformation), typeof(Protocol.Models.ComputeNodeInformation), "ComputeNodeUrl", "NodeUrl"), new ComparerPropertyMapping(typeof(JobPreparationTask), typeof(Protocol.Models.JobPreparationTask), "RerunOnComputeNodeRebootAfterSuccess", "RerunOnNodeRebootAfterSuccess"), new ComparerPropertyMapping(typeof(ImageReference), typeof(Protocol.Models.ImageReference), "SkuId", "Sku"), new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "NodeAgentSkuId", "NodeAgentSKUId"), new ComparerPropertyMapping(typeof(VirtualMachineConfiguration), typeof(Protocol.Models.VirtualMachineConfiguration), "OSDisk", "OsDisk"), new ComparerPropertyMapping(typeof(TaskSchedulingPolicy), typeof(Protocol.Models.TaskSchedulingPolicy), "ComputeNodeFillType", "NodeFillType"), new ComparerPropertyMapping(typeof(PoolEndpointConfiguration), typeof(Protocol.Models.PoolEndpointConfiguration), "InboundNatPools", "InboundNATPools"), new ComparerPropertyMapping(typeof(InboundEndpoint), typeof(Protocol.Models.InboundEndpoint), "PublicFqdn", "PublicFQDN"), new ComparerPropertyMapping(typeof(ImageInformation), typeof(Protocol.Models.ImageInformation), "NodeAgentSkuId", "NodeAgentSKUId"), new ComparerPropertyMapping(typeof(ImageInformation), typeof(Protocol.Models.ImageInformation), "OSType", "OsType"), }; Random rand = new Random(); object omTaskRangeBuilder() { int rangeLimit1 = rand.Next(0, int.MaxValue); int rangeLimit2 = rand.Next(0, int.MaxValue); return new TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2)); } object iFileStagingProviderBuilder() => null; object batchClientBehaviorBuilder() => null; object taskRangeBuilder() { int rangeLimit1 = rand.Next(0, int.MaxValue); int rangeLimit2 = rand.Next(0, int.MaxValue); return new Protocol.Models.TaskIdRange(Math.Min(rangeLimit1, rangeLimit2), Math.Max(rangeLimit1, rangeLimit2)); } ObjectFactoryConstructionSpecification certificateReferenceSpecification = new ObjectFactoryConstructionSpecification( typeof(Protocol.Models.CertificateReference), () => BuildCertificateReference(rand)); ObjectFactoryConstructionSpecification authenticationTokenSettingsSpecification = new ObjectFactoryConstructionSpecification( typeof(Protocol.Models.AuthenticationTokenSettings), () => BuildAuthenticationTokenSettings(rand)); ObjectFactoryConstructionSpecification taskRangeSpecification = new ObjectFactoryConstructionSpecification( typeof(Protocol.Models.TaskIdRange), taskRangeBuilder); ObjectFactoryConstructionSpecification omTaskRangeSpecification = new ObjectFactoryConstructionSpecification( typeof(TaskIdRange), omTaskRangeBuilder); ObjectFactoryConstructionSpecification batchClientBehaviorSpecification = new ObjectFactoryConstructionSpecification( typeof(BatchClientBehavior), batchClientBehaviorBuilder); ObjectFactoryConstructionSpecification fileStagingProviderSpecification = new ObjectFactoryConstructionSpecification( typeof(IFileStagingProvider), iFileStagingProviderBuilder); this.customizedObjectFactory = new ObjectFactory(new List<ObjectFactoryConstructionSpecification> { certificateReferenceSpecification, authenticationTokenSettingsSpecification, taskRangeSpecification, omTaskRangeSpecification, fileStagingProviderSpecification, batchClientBehaviorSpecification, }); // We need a custom comparison rule for certificate references because they are a different type in the proxy vs // the object model (string in proxy, flags enum in OM ComparisonRule certificateReferenceComparisonRule = ComparisonRule.Create<CertificateVisibility?, List<Protocol.Models.CertificateVisibility>>( typeof(CertificateReference), typeof(Protocol.Models.CertificateReference), // This is the type that hold the target property (visibility, proxyVisibility) => { CertificateVisibility? convertedProxyVisibility = UtilitiesInternal.ParseCertificateVisibility(proxyVisibility); //Treat null as None for the purposes of comparison: bool areEqual = convertedProxyVisibility == visibility || !visibility.HasValue && convertedProxyVisibility == CertificateVisibility.None; return areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("Certificate visibility doesn't match"); }, type1PropertyName: "Visibility", type2PropertyName: "Visibility"); ComparisonRule accessScopeComparisonRule = ComparisonRule.Create<AccessScope, List<Protocol.Models.AccessScope>>( typeof(AuthenticationTokenSettings), typeof(Protocol.Models.AuthenticationTokenSettings), // This is the type that hold the target property (scope, proxyVisibility) => { AccessScope convertedProxyAccessScope = UtilitiesInternal.ParseAccessScope(proxyVisibility); //Treat null as None for the purposes of comparison: bool areEqual = convertedProxyAccessScope == scope || convertedProxyAccessScope == AccessScope.None; return areEqual ? ObjectComparer.CheckEqualityResult.True : ObjectComparer.CheckEqualityResult.False("AccessScope doesn't match"); }, type1PropertyName: "Access", type2PropertyName: "Access"); this.objectComparer = new ObjectComparer( comparisonRules: new List<ComparisonRule>() { certificateReferenceComparisonRule, accessScopeComparisonRule }, propertyMappings: this.proxyPropertyToObjectModelMapping, shouldThrowOnPropertyReadException: e => !(e.InnerException is InvalidOperationException) || !e.InnerException.Message.Contains("while the object is in the Unbound")); } private Protocol.Models.CertificateReference BuildCertificateReference(Random rand) { //Build cert visibility (which is a required property) IList values = Enum.GetValues(typeof(CertificateVisibility)); IList<object> valuesToSelect = new List<object>(); foreach (object value in values) { valuesToSelect.Add(value); } int valuesToPick = rand.Next(0, values.Count); CertificateVisibility? visibility = null; // If valuesToPick is 0, we want to allow visibility to be null (since null is a valid value) // so only set visibility to be None if valuesToPick > 0 if (valuesToPick > 0) { visibility = CertificateVisibility.None; for (int i = 0; i < valuesToPick; i++) { int selectedValueIndex = rand.Next(valuesToSelect.Count); object selectedValue = valuesToSelect[selectedValueIndex]; visibility |= (CertificateVisibility)selectedValue; valuesToSelect.RemoveAt(selectedValueIndex); } } Protocol.Models.CertificateReference reference = this.defaultObjectFactory.GenerateNew<Protocol.Models.CertificateReference>(); //Set certificate visibility since it is required reference.Visibility = visibility == null ? null : UtilitiesInternal.CertificateVisibilityToList(visibility.Value); return reference; } private Protocol.Models.AuthenticationTokenSettings BuildAuthenticationTokenSettings(Random rand) { //Build access scope (which is a required property) IList values = Enum.GetValues(typeof(AccessScope)); IList<object> valuesToSelect = new List<object>(); foreach (object value in values) { valuesToSelect.Add(value); } int valuesToPick = rand.Next(0, values.Count); AccessScope? accessScope = null; // If valuesToPick is 0, we want to allow access scope to be null (since null is a valid value) // so only set access scope to be None if valuesToPick > 0 if (valuesToPick > 0) { accessScope = AccessScope.None; for (int i = 0; i < valuesToPick; i++) { int selectedValueIndex = rand.Next(valuesToSelect.Count); object selectedValue = valuesToSelect[selectedValueIndex]; accessScope |= (AccessScope)selectedValue; valuesToSelect.RemoveAt(selectedValueIndex); } } Protocol.Models.AuthenticationTokenSettings tokenSettings = this.defaultObjectFactory.GenerateNew<Protocol.Models.AuthenticationTokenSettings>(); //Set access scope since it is required tokenSettings.Access = accessScope == null ? null : UtilitiesInternal.AccessScopeToList(accessScope.Value); return tokenSettings; } #region Reflection based tests [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestRandomBoundCloudPoolProperties() { using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); for (int i = 0; i < TestRunCount; i++) { Protocol.Models.CloudPool poolModel = this.customizedObjectFactory.GenerateNew<Protocol.Models.CloudPool>(); CloudPool boundPool = new CloudPool(client, poolModel, client.CustomBehaviors); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundPool, poolModel); Assert.True(result.Equal, result.Message); } } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestRandomBoundCloudJobProperties() { using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); for (int i = 0; i < TestRunCount; i++) { Protocol.Models.CloudJob jobModel = this.customizedObjectFactory.GenerateNew<Protocol.Models.CloudJob>(); CloudJob boundJob = new CloudJob(client.JobOperations.ParentBatchClient, jobModel, client.CustomBehaviors); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundJob, jobModel); Assert.True(result.Equal, result.Message); } } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestRandomBoundCloudJobScheduleProperties() { using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); for (int i = 0; i < TestRunCount; i++) { Protocol.Models.CloudJobSchedule jobScheduleModel = this.customizedObjectFactory.GenerateNew<Protocol.Models.CloudJobSchedule>(); CloudJobSchedule boundJobSchedule = new CloudJobSchedule(client, jobScheduleModel, client.CustomBehaviors); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundJobSchedule, jobScheduleModel); Assert.True(result.Equal, result.Message); } } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestRandomBoundCloudTaskProperties() { using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); for (int i = 0; i < TestRunCount; i++) { Protocol.Models.CloudTask taskModel = this.customizedObjectFactory.GenerateNew<Protocol.Models.CloudTask>(); CloudTask boundTask = new CloudTask(client, "Foo", taskModel, client.CustomBehaviors); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundTask, taskModel); Assert.True(result.Equal, result.Message); } } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestRandomBoundComputeNodeProperties() { using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); for (int i = 0; i < TestRunCount; i++) { Protocol.Models.ComputeNode computeNodeModel = this.customizedObjectFactory.GenerateNew<Protocol.Models.ComputeNode>(); ComputeNode boundComputeNode = new ComputeNode(client, "Foo", computeNodeModel, client.CustomBehaviors); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundComputeNode, computeNodeModel); Assert.True(result.Equal, result.Message); } } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestRandomBoundCertificateProperties() { using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); for (int i = 0; i < TestRunCount; i++) { Protocol.Models.Certificate certificateModel = this.customizedObjectFactory.GenerateNew<Protocol.Models.Certificate>(); Certificate boundCertificate = new Certificate(client, certificateModel, client.CustomBehaviors); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundCertificate, certificateModel); Assert.True(result.Equal, result.Message); } } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestRandomBoundImageInformationProperties() { using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); for (int i = 0; i < TestRunCount; i++) { Protocol.Models.ImageInformation imageModel = this.customizedObjectFactory.GenerateNew<Protocol.Models.ImageInformation>(); ImageInformation boundImageInfo = new ImageInformation(imageModel); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundImageInfo, imageModel); Assert.True(result.Equal, result.Message); } } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestRandomBoundPrepReleaseTaskExecutionInformationProperties() { using BatchClient client = ClientUnitTestCommon.CreateDummyClient(); for (int i = 0; i < TestRunCount; i++) { Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation jobPrepReleaseExecutionInfo = this.customizedObjectFactory.GenerateNew<Protocol.Models.JobPreparationAndReleaseTaskExecutionInformation>(); JobPreparationAndReleaseTaskExecutionInformation boundJobPrepReleaseExecutionInfo = new JobPreparationAndReleaseTaskExecutionInformation(jobPrepReleaseExecutionInfo); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(boundJobPrepReleaseExecutionInfo, jobPrepReleaseExecutionInfo); Assert.True(result.Equal, result.Message); } } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestIReadOnlyMakesPropertiesReadOnly() { //Use reflection to traverse the set of objects in the DLL, find those that implement IReadOnly, and ensure that IReadOnly works for all //properties of those objects. Type iReadOnlyType = typeof(IReadOnly); List<Type> typesWithIReadOnlyBase = GetTypesWhichImplementInterface(iReadOnlyType.GetTypeInfo().Assembly, iReadOnlyType, requirePublicConstructor: false).ToList(); foreach (Type type in typesWithIReadOnlyBase) { this.testOutputHelper.WriteLine("Reading/Setting properties of type: {0}", type.ToString()); //Create an instance of that type IReadOnly objectUnderTest = this.customizedObjectFactory.CreateInstance<IReadOnly>(type); //Mark this object as readonly objectUnderTest.IsReadOnly = true; //Get the properties for the object under test IEnumerable<PropertyInfo> properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties.Where(p => p.Name != "CustomBehaviors")) { if (property.CanWrite) { this.testOutputHelper.WriteLine("Attempting to write property: {0}", property.Name); //Attempt to write //Note that for value types null is mapped to default(valueType). See: https://msdn.microsoft.com/en-us/library/xb5dd1f1%28v=vs.110%29.aspx TargetInvocationException e = Assert.Throws<TargetInvocationException>(() => property.SetValue(objectUnderTest, null)); Assert.IsType<InvalidOperationException>(e.InnerException); } if (property.CanRead) { this.testOutputHelper.WriteLine("Attempting to read property: {0}", property.Name); //Attempt to read try { property.GetValue(objectUnderTest); } catch (TargetInvocationException e) { if (e.InnerException is InvalidOperationException inner) { if (!inner.Message.Contains("while the object is in the Unbound state")) { throw; } } else { throw; } } } } this.testOutputHelper.WriteLine(string.Empty); } Assert.True(typesWithIReadOnlyBase.Count > 0); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestGetTransportObjectDoesntMissProperties() { const int objectsToValidate = 100; //Use reflection to traverse the set of objects in the DLL, find those that implement ITransportObjectProvider, ensure that GetTransportObject works for all //properties of those objects. Type iTransportObjectProviderType = typeof(ITransportObjectProvider<>); IEnumerable<Type> types = GetTypesWhichImplementInterface(iTransportObjectProviderType.GetTypeInfo().Assembly, iTransportObjectProviderType, requirePublicConstructor: false); foreach (Type type in types) { this.testOutputHelper.WriteLine("Generating {0} objects of type {1}", objectsToValidate, type); for (int i = 0; i < objectsToValidate; i++) { object o = this.customizedObjectFactory.GenerateNew(type); Type concreteInterfaceType = o.GetType().GetInterfaces().First(iFace => iFace.GetTypeInfo().IsGenericType && iFace.GetGenericTypeDefinition() == iTransportObjectProviderType); //object protocolObject = concreteInterfaceType.GetMethod("GetTransportObject").Invoke(o, BindingFlags.Instance | BindingFlags.NonPublic, null, null, null); object protocolObject = concreteInterfaceType.GetMethod("GetTransportObject").Invoke(o, null); ObjectComparer.CheckEqualityResult result = this.objectComparer.CheckEquality(o, protocolObject); Assert.True(result.Equal, result.Message); } } } private static IEnumerable<Type> GetTypesWhichImplementInterface(Assembly assembly, Type interfaceType, bool requirePublicConstructor) { Func<Type, bool> requirePublicConstructorFunc; if (requirePublicConstructor) { requirePublicConstructorFunc = (t => t.GetConstructors(BindingFlags.Public | BindingFlags.Instance).Any()); } else { requirePublicConstructorFunc = (t => true); } if (!interfaceType.GetTypeInfo().IsGenericType) { return assembly.GetTypes().Where(t => interfaceType.IsAssignableFrom(t) && !t.GetTypeInfo().IsInterface && t.GetTypeInfo().IsVisible && requirePublicConstructorFunc(t)); } else { return assembly.GetTypes().Where(t => t.GetInterfaces().Any(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == interfaceType) && !t.GetTypeInfo().IsInterface && t.GetTypeInfo().IsVisible && requirePublicConstructorFunc(t)); } } #endregion [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void Bug1432987CloudTaskTaskConstraints() { using BatchClient batchCli = ClientUnitTestCommon.CreateDummyClient(); CloudTask badTask = new CloudTask("bug1432987TaskConstraints", "hostname"); TaskConstraints isThisBroken = badTask.Constraints; TaskConstraints trySettingThem = new TaskConstraints(null, null, null); badTask.Constraints = trySettingThem; TaskConstraints readThemBack = badTask.Constraints; } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestCertificateReferenceVisibilityGet() { CertificateReference certificateReference = new CertificateReference(); Assert.Null(certificateReference.Visibility); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestResourceFilePropertiesArePropagatedToTransportObject() { const string filePath = "Foo"; const string blobPath = "Bar"; const string mode = "0700"; ResourceFile resourceFile = ResourceFile.FromUrl(blobPath, filePath, mode); Protocol.Models.ResourceFile protoFile = resourceFile.GetTransportObject(); Assert.Equal(filePath, protoFile.FilePath); Assert.Equal(blobPath, protoFile.HttpUrl); Assert.Equal(mode, protoFile.FileMode); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestAutoPoolSpecificationUnboundConstraints() { const string idPrefix = "Bar"; const bool keepAlive = false; const PoolLifetimeOption poolLifetimeOption = PoolLifetimeOption.Job; PoolSpecification poolSpecification = new PoolSpecification(); AutoPoolSpecification autoPoolSpecification = new AutoPoolSpecification(); //Properties should start out as their defaults Assert.Equal(default, autoPoolSpecification.AutoPoolIdPrefix); Assert.Equal(default, autoPoolSpecification.KeepAlive); Assert.Equal(default, autoPoolSpecification.PoolLifetimeOption); Assert.Equal(default, autoPoolSpecification.PoolSpecification); Assert.False(((IModifiable)autoPoolSpecification).HasBeenModified); //Should be able to set all properties autoPoolSpecification.AutoPoolIdPrefix = idPrefix; autoPoolSpecification.KeepAlive = keepAlive; autoPoolSpecification.PoolLifetimeOption = poolLifetimeOption; autoPoolSpecification.PoolSpecification = poolSpecification; Assert.True(((IModifiable)autoPoolSpecification).HasBeenModified); Protocol.Models.AutoPoolSpecification protoAutoPoolSpecification = autoPoolSpecification.GetTransportObject(); ((IReadOnly)autoPoolSpecification).IsReadOnly = true; //Forces read-onlyness //After MarkReadOnly, the original object should be unsettable Assert.Throws<InvalidOperationException>(() => autoPoolSpecification.AutoPoolIdPrefix = "bar"); Assert.Throws<InvalidOperationException>(() => autoPoolSpecification.KeepAlive = false); Assert.Throws<InvalidOperationException>(() => autoPoolSpecification.PoolLifetimeOption = PoolLifetimeOption.JobSchedule); InvalidOperationException e = Assert.Throws<InvalidOperationException>(() => autoPoolSpecification.PoolSpecification = new PoolSpecification()); this.testOutputHelper.WriteLine(e.ToString()); //After GetProtocolObject, the child objects should be unreadable too Assert.Throws<InvalidOperationException>(() => poolSpecification.TaskSlotsPerNode = 4); //The original data should be on the protocol specification Assert.Equal(idPrefix, protoAutoPoolSpecification.AutoPoolIdPrefix); Assert.Equal(keepAlive, protoAutoPoolSpecification.KeepAlive); Assert.Equal(poolLifetimeOption, UtilitiesInternal.MapEnum<Protocol.Models.PoolLifetimeOption, PoolLifetimeOption>(protoAutoPoolSpecification.PoolLifetimeOption)); } [Fact] [Trait(TestTraits.Duration.TraitName, TestTraits.Duration.Values.VeryShortDuration)] public void TestAutoPoolSpecificationBoundConstraints() { Protocol.Models.AutoPoolSpecification protoAutoPoolSpecification = new Protocol.Models.AutoPoolSpecification { KeepAlive = true, PoolLifetimeOption = Protocol.Models.PoolLifetimeOption.JobSchedule, AutoPoolIdPrefix = "Matt", Pool = new Protocol.Models.PoolSpecification { CloudServiceConfiguration = new Protocol.Models.CloudServiceConfiguration( "4"), ResizeTimeout = TimeSpan.FromDays(1), StartTask = new Protocol.Models.StartTask { CommandLine = "Bar" } } }; AutoPoolSpecification autoPoolSpecification = new AutoPoolSpecification(protoAutoPoolSpecification); //Assert that the wrapped properties are equal as we expect Assert.Equal(protoAutoPoolSpecification.AutoPoolIdPrefix, autoPoolSpecification.AutoPoolIdPrefix); Assert.Equal(protoAutoPoolSpecification.KeepAlive, autoPoolSpecification.KeepAlive); Assert.Equal(UtilitiesInternal.MapEnum<Protocol.Models.PoolLifetimeOption, PoolLifetimeOption>(protoAutoPoolSpecification.PoolLifetimeOption), autoPoolSpecification.PoolLifetimeOption); Assert.NotNull(autoPoolSpecification.PoolSpecification); Assert.NotNull(protoAutoPoolSpecification.Pool.CloudServiceConfiguration); Assert.Equal(protoAutoPoolSpecification.Pool.CloudServiceConfiguration.OsFamily, autoPoolSpecification.PoolSpecification.CloudServiceConfiguration.OSFamily); Assert.Equal(protoAutoPoolSpecification.Pool.ResizeTimeout, autoPoolSpecification.PoolSpecification.ResizeTimeout); Assert.NotNull(autoPoolSpecification.PoolSpecification.StartTask); Assert.Equal(protoAutoPoolSpecification.Pool.StartTask.CommandLine, autoPoolSpecification.PoolSpecification.StartTask.CommandLine); //When we change a property on the underlying object PoolSpecification, AutoPoolSpecification should notice the change Assert.False(((IModifiable)autoPoolSpecification).HasBeenModified); autoPoolSpecification.PoolSpecification.ResizeTimeout = TimeSpan.FromSeconds(122); Assert.True(((IModifiable)autoPoolSpecification).HasBeenModified); } } }
// // Copyright (c) 2004-2018 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 System; using System.Collections.Generic; using System.Linq; using NLog.Common; using Xunit; namespace NLog.UnitTests.Internal { public class EnumHelpersTests : NLogTestBase { enum TestEnum { Foo, bar, } #region tryparse - no ignorecase parameter [Fact] public void EnumParse1() { TestEnumParseCaseSentisive("Foo", TestEnum.Foo, true); } [Fact] public void EnumParse2() { TestEnumParseCaseSentisive("foo", TestEnum.Foo, false); } [Fact] public void EnumParseDefault() { TestEnumParseCaseSentisive("BAR", TestEnum.Foo, false); } [Fact] public void EnumParseDefault2() { TestEnumParseCaseSentisive("x", TestEnum.Foo, false); } [Fact] public void EnumParseBar() { TestEnumParseCaseSentisive("bar", TestEnum.bar, true); } [Fact] public void EnumParseBar2() { TestEnumParseCaseSentisive(" bar ", TestEnum.bar, true); } [Fact] public void EnumParseBar3() { TestEnumParseCaseSentisive(" \r\nbar ", TestEnum.bar, true); } [Fact] public void EnumParse_null() { TestEnumParseCaseSentisive(null, TestEnum.Foo, false); } [Fact] public void EnumParse_emptystring() { TestEnumParseCaseSentisive(string.Empty, TestEnum.Foo, false); } [Fact] public void EnumParse_whitespace() { TestEnumParseCaseSentisive(" ", TestEnum.Foo, false); } [Fact] public void EnumParse_ArgumentException() { double result; Assert.Throws<ArgumentException>(() => ConversionHelpers.TryParse("not enum", out result)); } [Fact] public void EnumParse_null_ArgumentException() { //even with null, first ArgumentException double result; Assert.Throws<ArgumentException>(() => ConversionHelpers.TryParse(null, out result)); } #endregion #region tryparse - ignorecase parameter: false [Fact] public void EnumParse1_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("Foo", false, TestEnum.Foo, true); } [Fact] public void EnumParse2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("foo", false, TestEnum.Foo, false); } [Fact] public void EnumParseDefault_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("BAR", false, TestEnum.Foo, false); } [Fact] public void EnumParseDefault2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("x", false, TestEnum.Foo, false); } [Fact] public void EnumParseBar_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam("bar", false, TestEnum.bar, true); } [Fact] public void EnumParseBar2_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" bar ", false, TestEnum.bar, true); } [Fact] public void EnumParseBar3_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" \r\nbar ", false, TestEnum.bar, true); } [Fact] public void EnumParse_null_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(null, false, TestEnum.Foo, false); } [Fact] public void EnumParse_emptystring_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(string.Empty, false, TestEnum.Foo, false); } [Fact] public void EnumParse_whitespace_ignoreCaseFalse() { TestEnumParseCaseIgnoreCaseParam(" ", false, TestEnum.Foo, false); } [Fact] public void EnumParse_ArgumentException_ignoreCaseFalse() { double result; Assert.Throws<ArgumentException>(() => ConversionHelpers.TryParse("not enum", false, out result)); } [Fact] public void EnumParse_null_ArgumentException_ignoreCaseFalse() { //even with null, first ArgumentException double result; Assert.Throws<ArgumentException>(() => ConversionHelpers.TryParse(null, false, out result)); } #endregion #region tryparse - ignorecase parameter: true [Fact] public void EnumParse1_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("Foo", true, TestEnum.Foo, true); } [Fact] public void EnumParse2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("foo", true, TestEnum.Foo, true); } [Fact] public void EnumParseDefault_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("BAR", true, TestEnum.bar, true); } [Fact] public void EnumParseDefault2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("x", true, TestEnum.Foo, false); } [Fact] public void EnumParseBar_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam("bar", true, TestEnum.bar, true); } [Fact] public void EnumParseBar2_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" bar ", true, TestEnum.bar, true); } [Fact] public void EnumParseBar3_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" \r\nbar ", true, TestEnum.bar, true); } [Fact] public void EnumParse_null_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(null, true, TestEnum.Foo, false); } [Fact] public void EnumParse_emptystring_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(string.Empty, true, TestEnum.Foo, false); } [Fact] public void EnumParse_whitespace_ignoreCaseTrue() { TestEnumParseCaseIgnoreCaseParam(" ", true, TestEnum.Foo, false); } [Fact] public void EnumParse_ArgumentException_ignoreCaseTrue() { double result; Assert.Throws<ArgumentException>(() => ConversionHelpers.TryParse("not enum", true, out result)); } [Fact] public void EnumParse_null_ArgumentException_ignoreCaseTrue() { //even with null, first ArgumentException double result; Assert.Throws<ArgumentException>(() => ConversionHelpers.TryParse(null, true, out result)); } #endregion #region helpers private static void TestEnumParseCaseSentisive(string value, TestEnum expected, bool expectedReturn) { TestEnum result; var returnResult = ConversionHelpers.TryParse(value, out result); Assert.Equal(expected, result); Assert.Equal(expectedReturn, returnResult); } private static void TestEnumParseCaseIgnoreCaseParam(string value, bool ignoreCase, TestEnum expected, bool expectedReturn) { TestEnum result; var returnResult = ConversionHelpers.TryParse(value, ignoreCase, out result); Assert.Equal(expected, result); Assert.Equal(expectedReturn, returnResult); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Claims; using System.Threading.Tasks; using AngleSharp.Dom.Html; using Identity.DefaultUI.WebSite; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.AspNetCore.TestHost; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Testing; using Xunit; using Xunit.Abstractions; namespace Microsoft.AspNetCore.Identity.FunctionalTests { public abstract class ManagementTests<TStartup, TContext> : IClassFixture<ServerFactory<TStartup, TContext>> where TStartup : class where TContext : DbContext { public ManagementTests(ServerFactory<TStartup, TContext> serverFactory) { ServerFactory = serverFactory; } public ServerFactory<TStartup, TContext> ServerFactory { get; } [Fact] public async Task CanEnableTwoFactorAuthentication() { // Arrange var client = ServerFactory .CreateClient(); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; var index = await UserStories.RegisterNewUserAsync(client, userName, password); // Act & Assert Assert.NotNull(await UserStories.EnableTwoFactorAuthentication(index)); } [Fact] public async Task CannotEnableTwoFactorAuthenticationWithoutCookieConsent() { // Arrange var client = ServerFactory .CreateClient(); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; var index = await UserStories.RegisterNewUserAsync(client, userName, password); // Act & Assert Assert.Null(await UserStories.EnableTwoFactorAuthentication(index, consent: false)); } [Fact] public async Task CanConfirmEmail() { // Arrange var emails = new ContosoEmailSender(); void ConfigureTestServices(IServiceCollection services) => services.SetupTestEmailSender(emails); var server = ServerFactory .WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices)); var client = server.CreateClient(); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; var index = await UserStories.RegisterNewUserAsync(client, userName, password); var manageIndex = await UserStories.SendEmailConfirmationLinkAsync(index); // Act & Assert Assert.Equal(2, emails.SentEmails.Count); var email = emails.SentEmails[1]; await UserStories.ConfirmEmailAsync(email, client); } [Fact] public async Task CanChangeEmail() { // Arrange var emails = new ContosoEmailSender(); void ConfigureTestServices(IServiceCollection services) => services.SetupTestEmailSender(emails); var server = ServerFactory .WithWebHostBuilder(whb => whb.ConfigureServices(ConfigureTestServices)); var client = server.CreateClient(); var newClient = server.CreateClient(); var failedClient = server.CreateClient(); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; var newEmail = "[email protected]"; var index = await UserStories.RegisterNewUserAsync(client, userName, password); var email = await UserStories.SendUpdateEmailAsync(index, newEmail); // Act & Assert Assert.Equal(2, emails.SentEmails.Count); await UserStories.ConfirmEmailAsync(emails.SentEmails[1], client); // Verify can login with new email, fails with old await UserStories.LoginExistingUserAsync(newClient, newEmail, password); await UserStories.LoginFailsWithWrongPasswordAsync(failedClient, userName, password); } [Fact] public async Task CanChangePassword() { // Arrange var principals = new List<ClaimsPrincipal>(); void ConfigureTestServices(IServiceCollection services) => services.SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme); var server = ServerFactory .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices)); var client = server.CreateClient(); var newClient = server.CreateClient(); var userName = $"{Guid.NewGuid()}@example.com"; var password = "[PLACEHOLDER]-1a"; var newPassword = "[PLACEHOLDER]-1a-updated"; var index = await UserStories.RegisterNewUserAsync(client, userName, password); // Act 1 var changedPassword = await UserStories.ChangePasswordAsync(index, password, newPassword); // Assert 1 // RefreshSignIn generates a new security stamp claim AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp"); // Act 2 await UserStories.LoginExistingUserAsync(newClient, userName, newPassword); // Assert 2 // Signing in again with a different client uses the same security stamp claim AssertClaimsEqual(principals[1], principals[2], "AspNet.Identity.SecurityStamp"); } [Fact] public async Task CanSetPasswordWithExternalLogin() { // Arrange var principals = new List<ClaimsPrincipal>(); void ConfigureTestServices(IServiceCollection services) => services .SetupTestThirdPartyLogin() .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme); var server = ServerFactory .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices)); var client = server.CreateClient(); var newClient = server.CreateClient(); var loginAfterSetPasswordClient = server.CreateClient(); var guid = Guid.NewGuid(); var userName = $"{guid}"; var email = $"{guid}@example.com"; // Act 1 var index = await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); index = await UserStories.LoginWithSocialLoginAsync(newClient, userName); // Assert 1 Assert.NotNull(principals[1].Identities.Single().Claims.Single(c => c.Type == ClaimTypes.AuthenticationMethod).Value); // Act 2 await UserStories.SetPasswordAsync(index, "[PLACEHOLDER]-1a-updated"); // Assert 2 // RefreshSignIn uses the same AuthenticationMethod claim value AssertClaimsEqual(principals[1], principals[2], ClaimTypes.AuthenticationMethod); // Act & Assert 3 // Can log in with the password set above await UserStories.LoginExistingUserAsync(loginAfterSetPasswordClient, email, "[PLACEHOLDER]-1a-updated"); } [Fact] public async Task CanRemoveExternalLogin() { // Arrange var principals = new List<ClaimsPrincipal>(); void ConfigureTestServices(IServiceCollection services) => services .SetupTestThirdPartyLogin() .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme); var server = ServerFactory .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices)); var client = server.CreateClient(); var guid = Guid.NewGuid(); var userName = $"{guid}"; var email = $"{guid}@example.com"; // Act var index = await UserStories.RegisterNewUserAsync(client, email, "[PLACEHOLDER]-1a"); var linkLogin = await UserStories.LinkExternalLoginAsync(index, email); await UserStories.RemoveExternalLoginAsync(linkLogin, email); // RefreshSignIn generates a new security stamp claim AssertClaimsNotEqual(principals[0], principals[1], "AspNet.Identity.SecurityStamp"); } [Fact] public async Task CanSeeExternalLoginProviderDisplayName() { // Arrange void ConfigureTestServices(IServiceCollection services) => services.SetupTestThirdPartyLogin(); var server = ServerFactory .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices)); var client = server.CreateClient(); // Act var userName = Guid.NewGuid().ToString(); var email = $"{userName}@example.com"; var index = await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email); var manage = await index.ClickManageLinkWithExternalLoginAsync(); var externalLogins = await manage.ClickExternalLoginsAsync(); // Assert Assert.Contains("Contoso", externalLogins.ExternalLoginDisplayName.TextContent); } [Fact] public async Task CanResetAuthenticator() { // Arrange var principals = new List<ClaimsPrincipal>(); void ConfigureTestServices(IServiceCollection services) => services .SetupTestThirdPartyLogin() .SetupGetUserClaimsPrincipal(user => principals.Add(user), IdentityConstants.ApplicationScheme); var server = ServerFactory .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices)); var client = server.CreateClient(); var newClient = server.CreateClient(); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; // Act var loggedIn = await UserStories.RegisterNewUserAsync(client, userName, password); var showRecoveryCodes = await UserStories.EnableTwoFactorAuthentication(loggedIn); var twoFactorKey = showRecoveryCodes.Context.AuthenticatorKey; // Use a new client to simulate a new browser session. await UserStories.AcceptCookiePolicy(newClient); var index = await UserStories.LoginExistingUser2FaAsync(newClient, userName, password, twoFactorKey); await UserStories.ResetAuthenticator(index); // RefreshSignIn generates a new security stamp claim AssertClaimsNotEqual(principals[1], principals[2], "AspNet.Identity.SecurityStamp"); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public async Task CanDownloadPersonalData(bool twoFactor, bool social) { // Arrange void ConfigureTestServices(IServiceCollection services) => services.SetupTestThirdPartyLogin(); var client = ServerFactory .WithWebHostBuilder(whb => whb.ConfigureTestServices(ConfigureTestServices)) .CreateClient(); var userName = $"{Guid.NewGuid()}@example.com"; var guid = Guid.NewGuid(); var email = userName; var index = social ? await UserStories.RegisterNewUserWithSocialLoginAsync(client, userName, email) : await UserStories.RegisterNewUserAsync(client, email, "[PLACEHOLDER]-1a"); if (twoFactor) { await UserStories.EnableTwoFactorAuthentication(index); } // Act & Assert var jsonData = await UserStories.DownloadPersonalData(index, userName); Assert.NotNull(jsonData); Assert.True(jsonData.ContainsKey("Id")); Assert.NotNull(jsonData["Id"]); Assert.True(jsonData.ContainsKey("UserName")); Assert.Equal(userName, (string)jsonData["UserName"]); Assert.True(jsonData.ContainsKey("Email")); Assert.Equal(userName, (string)jsonData["Email"]); Assert.True(jsonData.ContainsKey("EmailConfirmed")); Assert.False((bool)jsonData["EmailConfirmed"]); Assert.True(jsonData.ContainsKey("PhoneNumber")); Assert.Equal("null", (string)jsonData["PhoneNumber"]); Assert.True(jsonData.ContainsKey("PhoneNumberConfirmed")); Assert.False((bool)jsonData["PhoneNumberConfirmed"]); Assert.Equal(twoFactor, (bool)jsonData["TwoFactorEnabled"]); if (twoFactor) { Assert.NotNull(jsonData["Authenticator Key"]); } else { Assert.Null((string)jsonData["Authenticator Key"]); } if (social) { Assert.Equal(userName, (string)jsonData["Contoso external login provider key"]); } else { Assert.Null((string)jsonData["Contoso external login provider key"]); } } [Fact] public async Task GetOnDownloadPersonalData_ReturnsNotFound() { // Arrange var client = ServerFactory .CreateClient(); await UserStories.RegisterNewUserAsync(client); // Act var response = await client.GetAsync("/Identity/Account/Manage/DownloadPersonalData"); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } [Fact] public async Task CanDeleteUser() { // Arrange var client = ServerFactory .CreateClient(); var userName = $"{Guid.NewGuid()}@example.com"; var password = $"[PLACEHOLDER]-1a"; var index = await UserStories.RegisterNewUserAsync(client, userName, password); // Act & Assert await UserStories.DeleteUser(index, password); } private void AssertClaimsEqual(ClaimsPrincipal expectedPrincipal, ClaimsPrincipal actualPrincipal, string claimType) { var expectedPrincipalClaim = expectedPrincipal.Identities.Single().Claims.Single(c => c.Type == claimType).Value; var actualPrincipalClaim = actualPrincipal.Identities.Single().Claims.Single(c => c.Type == claimType).Value; Assert.Equal(expectedPrincipalClaim, actualPrincipalClaim); } private void AssertClaimsNotEqual(ClaimsPrincipal expectedPrincipal, ClaimsPrincipal actualPrincipal, string claimType) { var expectedPrincipalClaim = expectedPrincipal.Identities.Single().Claims.Single(c => c.Type == claimType).Value; var actualPrincipalClaim = actualPrincipal.Identities.Single().Claims.Single(c => c.Type == claimType).Value; Assert.NotEqual(expectedPrincipalClaim, actualPrincipalClaim); } } }
using System; using System.Collections; using System.Collections.Generic; using InAudioLeanTween; using InAudioSystem; using InAudioSystem.ExtensionMethods; using InAudioSystem.Internal; using InAudioSystem.Runtime; using UnityEngine; using UnityEngine.SceneManagement; using Object = UnityEngine.Object; /// <summary> /// The InAudio class it the primary way to interact with InAudio via code. /// It is used to play all audio & events, while the music player can be accessed via InAudio.Music. /// </summary> #if UNITY_EDITOR [ExecuteInEditMode] #endif public class InAudio : MonoBehaviour { /******************/ /*Public interface*/ /******************/ #region Public fields /// <summary> /// The active listener in the scene. Some features will not work if not set, like the spline system. /// </summary> public AudioListener activeAudioListener; public static AudioListener ActiveListener { get { if (instance != null) return instance.activeAudioListener; return null; } set { if (instance != null) instance.activeAudioListener = ActiveListener; } } public static bool DoesExist { get { return instance != null; } } #endregion #region Music private static MusicPlayer music; public static MusicPlayer Music { get { if (music == null) { #if UNITY_5_2 Debug.LogError("InAudio: Could not find music player. Please ensure that InAudio is loaded before accessing it."); #else Debug.LogError("InAudio: Could not find music player. Please ensure that InAudio is loaded before accessing it.\nIs the scene with InAudio loaded after the script trying to access it?"); #endif } return music; } set { music = value; } } #endregion #region Audio player #region Play /// <summary> /// Play an audio node directly /// </summary> /// <param name="gameObject">The game object to attach to and be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer Play(GameObject gameObject, InAudioNode audioNode, AudioParameters parameters = null) { if (instance != null && gameObject != null && audioNode != null) return instance._inAudioEventWorker.PlayConnectedTo(gameObject, audioNode, gameObject, parameters); else InDebug.MissingArguments("Play", gameObject, audioNode); return null; } /// <summary> /// Play an audio node directly, attached to another game object /// </summary> /// <param name="gameObject">The game object to be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="attachedTo">The object to be attached to</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> [Obsolete("Use PlayFollowing() instead.")] public static InPlayer PlayAttachedTo(GameObject gameObject, InAudioNode audioNode, GameObject attachedTo, AudioParameters parameters = null) { if (instance != null && gameObject != null && audioNode != null) return instance._inAudioEventWorker.PlayConnectedTo(gameObject, audioNode, attachedTo, parameters); else InDebug.MissingArguments("PlayAttachedTo", gameObject, audioNode); return null; } /// <summary> /// Play an audio node directly with a custom fade, following a game object and persists even if the GO is destroyed. /// </summary> /// <param name="gameObject">The game object to be controlled by and follow</param> /// <param name="audioNode">The node to play</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer PlayFollowing(GameObject gameObject, InAudioNode audioNode, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder || gameObject == null) { InDebug.MissingArguments("PlayFollowing", gameObject, audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayFollowing(gameObject, audioNode, parameters); return player; } /// <summary> /// Play an audio node directly, at this position in world space /// </summary> /// <param name="gameObject">The game object to attach to and be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="position">The world position to play at</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer PlayAtPosition(GameObject gameObject, InAudioNode audioNode, Vector3 position, AudioParameters parameters = null) { if (instance != null && gameObject != null && audioNode != null) return instance._inAudioEventWorker.PlayAtPosition(gameObject, audioNode, position, parameters); else InDebug.MissingArguments("PlayAtPosition", gameObject, audioNode); return null; } /// <summary> /// Play an audio node directly with fade in time /// </summary> /// <param name="gameObject">The game object to attach to and be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="fadeTime">How long it should take to fade in from 0 to 1 in volume</param> /// <param name="tweeenType">The curve of fading</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer Play(GameObject gameObject, InAudioNode audioNode, float fadeTime, LeanTweenType tweeenType, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder) { InDebug.MissingArguments("Play (tween)", gameObject, audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayConnectedTo(gameObject, audioNode, gameObject, parameters); player.Volume = 0.0f; LTDescr tweever = LeanTween.value(gameObject, (f, o) => { (o as InPlayer).Volume = f; }, 0, 1.0f, fadeTime); tweever.onUpdateParam = player; tweever.tweenType = tweeenType; return player; } /// <summary> /// Play an audio node directly with fade in time, attached to another game object /// </summary> /// <param name="gameObject">The game object to be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="attachedTo">The game object to attach to</param> /// <param name="fadeTime">How long it should take to fade in from 0 to 1 in volume</param> /// <param name="tweeenType">The curve of fading</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> [Obsolete("Use PlayFollowing() instead.")] public static InPlayer PlayAttachedTo(GameObject gameObject, InAudioNode audioNode, GameObject attachedTo, float fadeTime, LeanTweenType tweeenType, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder) { InDebug.MissingArguments("PlayAttachedTo (tween)", gameObject, audioNode); } InPlayer player = instance._inAudioEventWorker.PlayConnectedTo(gameObject, audioNode, attachedTo, parameters); player.Volume = 0.0f; LTDescr tweever = LeanTween.value(gameObject, (f, o) => { (o as InPlayer).Volume = f; }, 0, 1.0f, fadeTime); tweever.onUpdateParam = player; tweever.tweenType = tweeenType; return player; } /// <summary> /// Play an audio node directly with a fade, following a game object and persists even if the GO is destroyed. /// </summary> /// <param name="gameObject">The game object to be controlled by and follow</param> /// <param name="audioNode">The node to play</param> /// <param name="fadeTime">How long it should take to fade in from 0 to 1 in volume</param> /// <param name="tweeenType">The curve of fading</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer PlayFollowing(GameObject gameObject, InAudioNode audioNode, float fadeTime, LeanTweenType tweeenType, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder || gameObject == null) { InDebug.MissingArguments("PlayFollowing (tween)", gameObject, audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayFollowing(gameObject, audioNode, parameters); player.Volume = 0.0f; LTDescr tweever = LeanTween.value(gameObject, (f, o) => { (o as InPlayer).Volume = f; }, 0.0f, 1f, fadeTime); tweever.onUpdateParam = player; tweever.tweenType = tweeenType; return player; } /// <summary> /// Play an audio node directly with fade in time, attached to another game object /// </summary> /// <param name="gameObject">The game object to attach to and be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="position">The position in world space to play the audio</param> /// <param name="fadeTime">How long it should take to fade in from 0 to 1 in volume</param> /// <param name="tweeenType">The curve of fading</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer PlayAtPosition(GameObject gameObject, InAudioNode audioNode, Vector3 position, float fadeTime, LeanTweenType tweeenType, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder) { InDebug.MissingArguments("PlayAtPosition (tween)", gameObject, audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayAtPosition(gameObject, audioNode, position, parameters); player.Volume = 0.0f; LTDescr tweever = LeanTween.value(gameObject, (f, o) => { (o as InPlayer).Volume = f; }, 0, 1.0f, fadeTime); tweever.onUpdateParam = player; tweever.tweenType = tweeenType; return player; } /// <summary> /// Play an audio node directly with custom fading /// </summary> /// <param name="gameObject">The game object to attach to and be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="fadeTime">How long it should take to fade in from 0 to 1 in volume</param> /// <param name="tweeenType">The curve of fading</param> /// <param name="startVolume">The starting volume</param> /// <param name="endVolume">The end volume</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer Play(GameObject gameObject, InAudioNode audioNode, float fadeTime, LeanTweenType tweeenType, float startVolume, float endVolume, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder) { InDebug.MissingArguments("Play (tween specific)", gameObject, audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayConnectedTo(gameObject, audioNode, gameObject, parameters); player.Volume = startVolume; LTDescr tweever = LeanTween.value(gameObject, (f, o) => { (o as InPlayer).Volume = f; }, startVolume, endVolume, fadeTime); tweever.onUpdateParam = player; tweever.tweenType = tweeenType; return player; } /// <summary> /// Play an audio node directly with a custom fade, attached to another game object /// </summary> /// <param name="gameObject">The game object to be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="attachedTo">The game object to attach to</param> /// <param name="fadeTime">How long it should take to fade in from 0 to 1 in volume</param> /// <param name="tweeenType">The curve of fading</param> /// <param name="startVolume">The starting volume</param> /// <param name="endVolume">The end volume</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> [Obsolete("Use PlayFollowing() instead.")] public static InPlayer PlayAttachedTo(GameObject gameObject, InAudioNode audioNode, GameObject attachedTo, float fadeTime, LeanTweenType tweeenType, float startVolume, float endVolume, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder) { InDebug.MissingArguments("PlayAttachedTo (tween specific)", gameObject, audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayConnectedTo(gameObject, audioNode, attachedTo, parameters); player.Volume = startVolume; LTDescr tweever = LeanTween.value(gameObject, (f, o) => { (o as InPlayer).Volume = f; }, startVolume, endVolume, fadeTime); tweever.onUpdateParam = player; tweever.tweenType = tweeenType; return player; } /// <summary> /// Play an audio node directly with a custom fade, following a game object and persists even if the GO is destroyed. /// </summary> /// <param name="gameObject">The game object to be controlled by and follow</param> /// <param name="audioNode">The node to play</param> /// <param name="fadeTime">How long it should take to fade in from 0 to 1 in volume</param> /// <param name="tweeenType">The curve of fading</param> /// <param name="startVolume">The starting volume</param> /// <param name="endVolume">The end volume</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer PlayFollowing(GameObject gameObject, InAudioNode audioNode, float fadeTime, LeanTweenType tweeenType, float startVolume, float endVolume, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder || gameObject == null) { InDebug.MissingArguments("PlayFollowing (tween specific)", gameObject, audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayFollowing(gameObject, audioNode, parameters); player.Volume = startVolume; LTDescr tweever = LeanTween.value(gameObject, (f, o) => { (o as InPlayer).Volume = f; }, startVolume, endVolume, fadeTime); tweever.onUpdateParam = player; tweever.tweenType = tweeenType; return player; } /// <summary> /// Play an audio node in world space with a custom fade, attached to another game object /// </summary> /// <param name="gameObject">The game object to attach to and be controlled by</param> /// <param name="audioNode">The node to play</param> /// <param name="position">The world position to play at</param> /// <param name="fadeTime">How long it should take to fade in from 0 to 1 in volume</param> /// <param name="tweeenType">The curve of fading</param> /// <param name="startVolume">The starting volume</param> /// <param name="endVolume">The end volume</param> /// <param name="parameters">Parameters to set initial values directly</param> /// <returns>A controller for the playing node</returns> public static InPlayer PlayAtPosition(GameObject gameObject, InAudioNode audioNode, Vector3 position, float fadeTime, LeanTweenType tweeenType, float startVolume, float endVolume, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder) { InDebug.MissingArguments("PlayAtPosition (tween specific)", gameObject, audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayAtPosition(gameObject, audioNode, position, parameters); player.Volume = startVolume; LTDescr tweever = LeanTween.value(gameObject, (f, o) => { (o as InPlayer).Volume = f; }, startVolume, endVolume, fadeTime); tweever.onUpdateParam = player; tweever.tweenType = tweeenType; return player; } /// <summary> /// Play an audio node on InAudio directly so it does not get destroyed in scene transition. /// No fade in as code would not get called during scene transition. Works best with simple sound effects /// </summary> /// <param name="gameObject">The game object to attach to and be controlled by</param> /// <param name="audioNode">The node to play</param> /// <returns>A controller for the playing node</returns> /// <param name="parameters">Parameters to set initial values directly</param> public static InPlayer PlayPersistent(Vector3 position, InAudioNode audioNode, AudioParameters parameters = null) { if (instance == null || audioNode == null || audioNode.IsRootOrFolder) { InDebug.MissingArgumentsForNode("PlayPersistent", audioNode); return null; } InPlayer player = instance._inAudioEventWorker.PlayAtPosition(instance.gameObject, audioNode, position, parameters); return player; } #endregion #region Stop /// <summary> /// Stop all instances of the this audio node on the game object /// </summary> /// <param name="gameObject"></param> /// <param name="audioNode"></param> public static void Stop(GameObject gameObject, InAudioNode audioNode) { if (instance != null && gameObject != null && audioNode != null) instance._inAudioEventWorker.StopByNode(gameObject, audioNode); else { InDebug.MissingArguments("Stop", gameObject, audioNode); } } /// <summary> /// Stop all instances of the this audio node on the game object with a fade out time /// </summary> /// <param name="gameObject"></param> /// <param name="audioNode"></param> /// <param name="fadeOutTime"></param> public static void Stop(GameObject gameObject, InAudioNode audioNode, float fadeOutTime) { if (instance != null && gameObject != null && audioNode != null) instance._inAudioEventWorker.StopByNode(gameObject, audioNode, fadeOutTime); else { InDebug.MissingArguments("Stop (Fadeout)", gameObject, audioNode); } } /// <summary> /// Breaks all looping instances of this node on the game object /// </summary> /// <param name="gameObject"></param> /// <param name="audioNode"></param> public static void Break(GameObject gameObject, InAudioNode audioNode) { if (instance != null && gameObject != null && audioNode != null) instance._inAudioEventWorker.Break(gameObject, audioNode); else { InDebug.MissingArguments("Break", gameObject, audioNode); } } /// <summary> /// Stop all sound effects /// </summary> /// <param name="gameObject"></param> public static void StopAllOfNode(InAudioNode audioNode) { if (instance != null && audioNode != null) instance._inAudioEventWorker.StopAll(0, LeanTweenType.notUsed); else { InDebug.MissingArgumentsForNode("StopAllOfNode", audioNode); } } /// <summary> /// Stop all sound effects /// </summary> /// <param name="gameObject"></param> public static void StopAllOfNode(InAudioNode audioNode, float fadeOutDuration, LeanTweenType leanTweenType = LeanTweenType.easeInOutQuad) { if (instance != null) instance._inAudioEventWorker.StopAll(0, leanTweenType); else { InDebug.MissingArgumentsForNode("StopAllOfNode", audioNode); } } /// <summary> /// Stop all sound effects /// </summary> /// <param name="gameObject"></param> public static void StopAll() { if (instance != null) instance._inAudioEventWorker.StopAll(0, LeanTweenType.notUsed); else { InDebug.InstanceMissing("StopAll"); } } /// <summary> /// Stop all sounds & music /// </summary> /// <param name="gameObject"></param> public static void StopAllAndMusic() { if (instance != null) { instance._inAudioEventWorker.StopAll(0, LeanTweenType.notUsed); Music.StopAll(0, LeanTweenType.notUsed); } else { InDebug.InstanceMissing("StopAllAndMusic"); } } /// <summary> /// Stop all sounds playing with fade out time /// </summary> /// <param name="gameObject"></param> /// <param name="fadeOut">Time to fade out</param> /// <param name="fadeType">Fade type</param> public static void StopAll(float fadeOut, LeanTweenType fadeType) { if (instance != null) { instance._inAudioEventWorker.StopAll(fadeOut, fadeType); } else { InDebug.InstanceMissing("StopAll (fade)"); } } /// <summary> /// Stop all sounds playing on this game object /// </summary> /// <param name="gameObject"></param> public static void StopAll(GameObject gameObject) { if (instance != null && gameObject != null) { instance._inAudioEventWorker.StopAll(gameObject, 0, LeanTweenType.notUsed); } else { InDebug.MissingArguments("StopAll (on GameObject)", gameObject, null); } } /// <summary> /// Stop all sounds playing on this game object with fade out time /// </summary> /// <param name="gameObject"></param> /// <param name="fadeOut">Time to fade out</param> /// <param name="fadeType">Fade type</param> public static void StopAll(GameObject gameObject, float fadeOut, LeanTweenType fadeType) { if (instance != null && gameObject != null) { instance._inAudioEventWorker.StopAll(gameObject, 0, LeanTweenType.notUsed); } else { InDebug.MissingArguments("StopAll (on GameObject)", gameObject, null); } } #endregion #region Players /// <summary> /// Get a list of all players attached to this game object /// </summary> /// <param name="gameObject"></param> /// <returns></returns> public static InPlayer[] PlayersOnGO(GameObject gameObject) { if (instance != null && gameObject != null) { return instance._inAudioEventWorker.GetPlayers(gameObject); } else { InDebug.MissingArguments("PlayersOnGO", gameObject, null); } return null; } /// <summary> /// Copy the list of playing sounds on this game object to a preallocated array /// </summary> /// <param name="gameObject"></param> /// <param name="copyToList">If the list is too short, the partial list will be copied</param> public static void PlayersOnGO(GameObject gameObject, IList<InPlayer> copyToList) { if (instance != null && gameObject != null && copyToList != null) { instance._inAudioEventWorker.GetPlayers(gameObject, copyToList); } else { if (copyToList == null) { Debug.LogWarning("InAudio: Missing argument CopyToList on function PlayersOnGO"); } else { InDebug.MissingArguments("PlayersOnGO", gameObject, null); } } } #endregion #endregion #region Set/Get Parameters /// <summary> /// Sets the volume for all instances of this audio node on the object. /// </summary> /// <param name="gameObject"></param> /// <param name="audioNode"></param> /// <param name="volume"></param> public static void SetVolumeForNode(GameObject gameObject, InAudioNode audioNode, float volume) { if (instance != null && gameObject != null && audioNode != null) { if (!audioNode.IsRootOrFolder) { instance._inAudioEventWorker.SetVolumeForNode(gameObject, audioNode, volume); } else { Debug.LogWarning("InAudio: Cannot change volume for audio folders here, use SetVolumeForAudioFolder() instead."); } } else { InDebug.MissingArguments("SetVolumeForNode", gameObject, audioNode); } } public static void SetVolumeForAudioFolder(InAudioNode folderNode, float volume) { if (instance != null && folderNode != null && folderNode.IsRootOrFolder) { var data = folderNode._nodeData as InFolderData; if (data != null) { data.runtimeVolume = Mathf.Clamp01(volume); } else { Debug.LogWarning("InAudio: Cannot set folder volume node that isn't a folder"); } } else { InDebug.MissingArgumentsForNode("SetVolumeForNode", folderNode); } } /// <summary> /// Sets the volume for all audio playing on this game object /// </summary> /// <param name="gameObject"></param> /// <param name="volume"></param> public static void SetVolumeForAll(GameObject gameObject, float volume) { if (instance != null && gameObject != null) { instance._inAudioEventWorker.SetVolumeForGameObject(gameObject, volume); } else { InDebug.MissingArguments("SetVolumeForAll", gameObject, null); } } #endregion #region Post Event by reference /// <summary> /// Post all actions in this event attached to this gameobject /// </summary> /// <param name="controllingObject">The controlling object and the future parent the played audio files</param> /// <param name="postEvent">The event to post the actions of</param> public static void PostEvent(GameObject controllingObject, InAudioEventNode postEvent) { if (instance != null && controllingObject != null && postEvent != null) instance.OnPostEvent(controllingObject, postEvent, controllingObject); else { if (instance == null) InDebug.InAudioInstanceMissing(controllingObject); else if (controllingObject == null) { InDebug.MissingControllingObject(); } else if (postEvent == null) { InDebug.MissingEvent(controllingObject); } } } /// <summary> /// Post all actions in this event attached to this another game object than the one controlling it /// </summary> /// <param name="controllingObject">The controlling object of the played sources</param> /// <param name="postEvent">The event to post the actions of</param> /// <param name="attachedToOther">The audio source to attach any audio sources to</param> public static void PostEventAttachedTo(GameObject controllingObject, InAudioEventNode postEvent, GameObject attachedToOther) { if (instance != null && controllingObject != null && postEvent != null) instance.OnPostEvent(controllingObject, postEvent, attachedToOther); else { if (instance == null) InDebug.InAudioInstanceMissing(controllingObject); else if (controllingObject == null) { InDebug.MissingControllingObject(); } else if (postEvent == null) { InDebug.MissingEvent(controllingObject); } } } /// <summary> /// Post all actions in this event at this position with this game object as the controller /// </summary> /// <param name="controllingObject">The controlling object of the played audio files</param> /// <param name="postEvent">The event to post the actions of</param> /// <param name="position">The position in world space of the sound</param> public static void PostEventAtPosition(GameObject controllingObject, InAudioEventNode postEvent, Vector3 position) { if (instance != null && controllingObject != null && postEvent != null) instance.OnPostEventAtPosition(controllingObject, postEvent, position); else { if (instance == null) InDebug.InAudioInstanceMissing(controllingObject); else if (controllingObject == null) { InDebug.MissingControllingObject(); } else if (postEvent == null) { InDebug.MissingEvent(controllingObject); } } } #endregion #region Post Event lists (inspector lists) /// <summary> /// Post all actions in this event in accordance to the data specified in the inspector, but overrides which object is it attached to. /// </summary> /// <param name="controllingObject">The controlling game object and the future parent of the audio files</param> /// <param name="eventList">All the events to post as added in the inspector</param> public static void PostEvent(GameObject controllingObject, InAudioEvent eventList) { if (instance != null && controllingObject != null && eventList != null && eventList.Events != null) { int count = eventList.Events.Count; Vector3 position = controllingObject.transform.position; for (int i = 0; i < count; i++) { EventHookListData eventData = eventList.Events[i]; if (eventData != null && eventData.Event != null) { if (eventData.PostAt == EventHookListData.PostEventAt.AttachedTo) instance.OnPostEvent(controllingObject, eventData.Event, controllingObject); else //if post at position instance.OnPostEvent(controllingObject, eventData.Event, position); } } } else { if (instance == null) InDebug.InAudioInstanceMissing(controllingObject); else if (controllingObject == null) { InDebug.MissingControllingObject(); } else if (eventList == null || eventList.Events == null) { InDebug.MissingEventList(controllingObject); } } } /// <summary> /// Post all actions in this event in accordance to the data specified in the inspector, but overrides which object is it attached to. /// </summary> /// <param name="controllingObject">The controlling game object and the future parent of the audio files</param> /// <param name="eventList">All the events to post as added in the inspector</param> /// <param name="attachedToOther">The object to attach the events to</param> public static void PostEventAttachedTo(GameObject controllingObject, InAudioEvent eventList, GameObject attachedToOther) { if (instance != null && controllingObject != null && eventList != null && eventList.Events != null) { int count = eventList.Events.Count; Vector3 position = controllingObject.transform.position; for (int i = 0; i < count; i++) { EventHookListData eventData = eventList.Events[i]; if (eventData != null && eventData.Event != null) { if (eventData.PostAt == EventHookListData.PostEventAt.AttachedTo) instance.OnPostEvent(controllingObject, eventData.Event, attachedToOther); else //if post at position instance.OnPostEvent(controllingObject, eventData.Event, position); } } } else { if (instance == null) InDebug.InAudioInstanceMissing(controllingObject); else if (controllingObject == null) { InDebug.MissingControllingObject(); } else if (eventList == null || eventList.Events == null) { InDebug.MissingEventList(controllingObject); } } } /// <summary> /// Post all actions in this event in accordance to the data specified in the inspector, but overrides another place to fire the sound from /// </summary> /// <param name="controllingObject">The controlling game object and the future parent of the audio files</param> /// <param name="eventList">All the events to post as added in the inspector</param> /// <param name="postAt">The new position to play at</param> public static void PostEventAtPosition(GameObject controllingObject, InAudioEvent eventList, Vector3 postAt) { if (instance != null && controllingObject != null && eventList != null && eventList.Events != null) { int count = eventList.Events.Count; for (int i = 0; i < count; i++) { EventHookListData eventData = eventList.Events[i]; if (eventData != null && eventData.Event != null) { instance.OnPostEvent(controllingObject, eventData.Event, postAt); } } } else { if (instance == null) InDebug.InAudioInstanceMissing(controllingObject); else if (controllingObject == null) { InDebug.MissingControllingObject(); } else if (eventList == null || eventList.Events == null) { InDebug.MissingEventList(controllingObject); } } } #endregion #region Find Event by ID /// <summary> /// Find an Audio Event by id so it can be posted directly /// </summary> /// <param name="id">The ID of the event to post. The ID is found in the InAudio Event window</param> /// <returns>The found audio event. Returns null if not found</returns> public static InAudioEventNode FindEventByID(int id) { InAudioEventNode postEvent = null; if (instance != null) { instance.runtimeData.Events.TryGetValue(id, out postEvent); } else { Debug.LogWarning("InAudio: Could not try to find event with id " + id + " as no InAudio instance was found"); } return postEvent; } #endregion #region Find audio node by ID /// <summary> /// Finds an audio node based on the ID specified /// </summary> /// <param name="id">The id to search for</param> /// <returns>The found bus, null if not found</returns> public static InAudioNode FindAudioNodeById(int id) { if (instance != null) { return TreeWalker.FindById(InAudioInstanceFinder.DataManager.AudioTree, id); } else { Debug.LogWarning("InAudio: Could not bus with id " + id); } return null; } #endregion /*Internal systems*/ #region Internal system private void HandleEventAction(GameObject controllingObject, AudioEventAction eventData, GameObject attachedTo, Vector3 playAt = new Vector3()) { InAudioNode audioNode; //Because we can't create variables in the scope of the switch with the same name InEventSnapshotAction snapshotData; InEventMixerValueAction mixerData; InEventMusicControl musicControl; InEventMusicFade musicFade; InEventSoloMuteMusic musicSoloMute; if (eventData.Target == null && eventData._eventActionType != EventActionTypes.StopAll) { InDebug.MissingActionTarget(controllingObject, eventData); return; } switch (eventData._eventActionType) { case EventActionTypes.Play: var audioPlayData = ((InEventAudioAction)eventData); audioNode = audioPlayData.Node; if (audioNode != null) { if (attachedTo != null) _inAudioEventWorker.PlayConnectedTo(controllingObject, audioNode, attachedTo, null, audioPlayData.Fadetime, audioPlayData.TweenType); else _inAudioEventWorker.PlayAtPosition(controllingObject, audioNode, playAt, null, audioPlayData.Fadetime, audioPlayData.TweenType); } break; case EventActionTypes.Stop: var data = ((InEventAudioAction)eventData); audioNode = data.Node; _inAudioEventWorker.StopByNode(controllingObject, audioNode, data.Fadetime, data.TweenType); break; case EventActionTypes.StopAll: var stopAlLData = ((InEventAudioAction)eventData); _inAudioEventWorker.StopAll(controllingObject, stopAlLData.Fadetime, stopAlLData.TweenType); break; case EventActionTypes.Break: audioNode = ((InEventAudioAction)eventData).Node; _inAudioEventWorker.Break(controllingObject, audioNode); break; case EventActionTypes.SetSnapshot: snapshotData = ((InEventSnapshotAction)eventData); snapshotData.Snapshot.TransitionTo(snapshotData.TransitionTime); break; case EventActionTypes.MixerValue: mixerData = ((InEventMixerValueAction)eventData); var mixer = mixerData.Mixer; var parameter = mixerData.Parameter; if (mixerData.TransitionTime > 0) { float v; if (mixer.GetFloat(parameter, out v)) { var tween = LeanTween.value(gameObject, f => mixer.SetFloat(parameter, f), v, mixerData.Value, mixerData.TransitionTime); tween.onUpdateParam = this; tween.tweenType = mixerData.TransitionType; } else { Debug.LogError("InAudio: Could not find parameter \"" + parameter + "\" on \"" + mixer + "\""); } } else mixerData.Mixer.SetFloat(mixerData.Parameter, mixerData.Value); break; case EventActionTypes.BankLoading: Debug.LogWarning("InAudio: The bank event is deprecated and unsupported."); break; case EventActionTypes.CrossfadeMusic: musicFade = eventData as InEventMusicFade; InAudio.Music.SwapCrossfadeVolume(musicFade.From, musicFade.To, musicFade.Duration, musicFade.TweenType); break; case EventActionTypes.FadeMusic: musicFade = eventData as InEventMusicFade; if (musicFade.Target != null) { switch (musicFade.DoAtEndTo) { case MusicState.Playing: case MusicState.Nothing: InAudio.Music.FadeVolume(musicFade.To, musicFade.ToVolumeTarget, musicFade.Duration, musicFade.TweenType); break; case MusicState.Paused: InAudio.Music.FadeAndPause(musicFade.To, musicFade.ToVolumeTarget, musicFade.Duration, musicFade.TweenType); break; case MusicState.Stopped: InAudio.Music.FadeAndStop(musicFade.To, musicFade.ToVolumeTarget, musicFade.Duration, musicFade.TweenType); break; default: Debug.LogError("InAudio: Unsuported action at end of fade"); break; } } else { InDebug.MissingActionTarget(controllingObject, eventData); } break; case EventActionTypes.PlayMusic: musicControl = eventData as InEventMusicControl; if (musicControl.Target != null) { if (!musicControl.Fade) { if (musicControl.ChangeVolume) { InAudio.Music.SetVolume(musicControl.MusicGroup, musicControl.VolumeTarget); } InAudio.Music.Play(musicControl.MusicGroup); } else { if (musicControl.ChangeVolume) InAudio.Music.PlayWithFadeIn(musicControl.MusicGroup, musicControl.VolumeTarget, musicControl.Duration, musicControl.TweenType); else InAudio.Music.PlayWithFadeIn(musicControl.MusicGroup, musicControl.Duration, musicControl.TweenType); } } else { InDebug.MissingActionTarget(controllingObject, eventData); } break; case EventActionTypes.StopMusic: musicControl = eventData as InEventMusicControl; if (musicControl.Target != null) { if (!musicControl.Fade) { if (musicControl.ChangeVolume) { InAudio.Music.SetVolume(musicControl.MusicGroup, musicControl.VolumeTarget); } InAudio.Music.Stop(musicControl.MusicGroup); } else { if (musicControl.ChangeVolume) InAudio.Music.FadeAndStop(musicControl.MusicGroup, musicControl.VolumeTarget, musicControl.Duration, musicControl.TweenType); else InAudio.Music.FadeAndStop(musicControl.MusicGroup, musicControl.Duration, musicControl.TweenType); } } else { InDebug.MissingActionTarget(controllingObject, eventData); } break; case EventActionTypes.PauseMusic: musicControl = eventData as InEventMusicControl; if (musicControl.Target != null) { if (!musicControl.Fade) { if (musicControl.ChangeVolume) { InAudio.Music.SetVolume(musicControl.MusicGroup, musicControl.VolumeTarget); } InAudio.Music.Pause(musicControl.MusicGroup); } else { if (musicControl.ChangeVolume) InAudio.Music.FadeAndPause(musicControl.MusicGroup, musicControl.VolumeTarget, musicControl.Duration, musicControl.TweenType); else InAudio.Music.FadeAndPause(musicControl.MusicGroup, musicControl.Duration, musicControl.TweenType); } } else { InDebug.MissingActionTarget(controllingObject, eventData); } break; case EventActionTypes.SoloMuteMusic: { musicSoloMute = eventData as InEventSoloMuteMusic; if (musicSoloMute.Target != null) { if (musicSoloMute.SetSolo) Music.Solo(musicSoloMute.MusicGroup, musicSoloMute.SoloTarget); if (musicSoloMute.SetMute) Music.Solo(musicSoloMute.MusicGroup, musicSoloMute.MuteTarget); } else { InDebug.MissingActionTarget(controllingObject, eventData); } break; } case EventActionTypes.StopAllMusic: musicFade = eventData as InEventMusicFade; if (musicFade.Target != null) { if (musicFade.Duration > 0) { InAudio.Music.StopAll(musicFade.Duration, musicFade.TweenType); } else { InAudio.Music.StopAll(); } } else { InDebug.MissingActionTarget(controllingObject, eventData); } break; default: InDebug.UnusedActionType(gameObject, eventData); break; } } #region Debug public static InDebug InDebug = new InDebug(); #endregion #region Internal event handling #region Post attached to private void OnPostEvent(GameObject controllingObject, InAudioEventNode postEvent, GameObject attachedToOther) { bool areAnyDelayed = false; if (postEvent.Delay > 0) { StartCoroutine(DelayedEvent(controllingObject, postEvent, attachedToOther)); } else { areAnyDelayed = PostUndelayedActions(controllingObject, postEvent, attachedToOther); } if (areAnyDelayed) { for (int i = 0; i < postEvent._actionList.Count; ++i) { var eventData = postEvent._actionList[i]; if (eventData != null && eventData.Delay > 0) StartCoroutine(PostDelayedActions(controllingObject, eventData, attachedToOther)); } } } private bool PostUndelayedActions(GameObject controllingObject, InAudioEventNode postEvent, GameObject attachedToOther) { bool areAnyDelayed = false; for (int i = 0; i < postEvent._actionList.Count; ++i) { var eventData = postEvent._actionList[i]; if (eventData == null) continue; if (eventData.Delay > 0) { areAnyDelayed = true; } else HandleEventAction(controllingObject, eventData, attachedToOther); } return areAnyDelayed; } private IEnumerator DelayedEvent(GameObject controllingObject, InAudioEventNode postEvent, GameObject attachedToOther) { yield return new WaitForSeconds(postEvent.Delay); PostUndelayedActions(controllingObject, postEvent, attachedToOther); } private IEnumerator PostDelayedActions(GameObject controllingObject, AudioEventAction eventData, GameObject attachedToOther) { yield return new WaitForSeconds(eventData.Delay); HandleEventAction(controllingObject, eventData, attachedToOther); } #endregion #region Post at position private void OnPostEventAtPosition(GameObject controllingObject, InAudioEventNode audioEvent, Vector3 position) { if (instance != null && controllingObject != null && audioEvent != null) instance.OnPostEvent(controllingObject, audioEvent, position); } private void OnPostEvent(GameObject controllingObject, InAudioEventNode postEvent, Vector3 postAt) { bool areAnyDelayed = false; if (postEvent.Delay > 0) { StartCoroutine(DelayedEvent(controllingObject, postEvent, postAt)); } else { areAnyDelayed = PostUndelayedActions(controllingObject, postEvent, postAt); } if (areAnyDelayed) { for (int i = 0; i < postEvent._actionList.Count; ++i) { var eventData = postEvent._actionList[i]; if (eventData != null && eventData.Delay > 0) StartCoroutine(PostDelayedActions(controllingObject, eventData, postAt)); } } } private bool PostUndelayedActions(GameObject controllingObject, InAudioEventNode postEvent, Vector3 postAt) { bool areAnyDelayed = false; for (int i = 0; i < postEvent._actionList.Count; ++i) { var eventData = postEvent._actionList[i]; if (eventData == null) continue; if (eventData.Delay > 0) { areAnyDelayed = true; } else HandleEventAction(controllingObject, eventData, null, postAt); } return areAnyDelayed; } private IEnumerator DelayedEvent(GameObject controllingObject, InAudioEventNode postEvent, Vector3 postAt) { yield return new WaitForSeconds(postEvent.Delay); PostUndelayedActions(controllingObject, postEvent, postAt); } private IEnumerator PostDelayedActions(GameObject controllingObject, AudioEventAction eventData, Vector3 postAt) { yield return new WaitForSeconds(eventData.Delay); HandleEventAction(controllingObject, eventData, null, postAt); } #endregion #endregion #region Internal data private InAudioEventWorker _inAudioEventWorker; private InRuntimeAudioData runtimeData; private static InAudio instance; #endregion #region Unity functions void Update() { #if UNITY_EDITOR if (InAudioInstanceFinder.Instance == null || InAudioInstanceFinder.DataManager == null || InAudioInstanceFinder.MusicPlayer == null) { Debug.LogError("There seems to be a problem with the InAudio prefab. Please try to remove it from the scene and re-add it from the prefab."); return; } #endif var musicTree = InAudioInstanceFinder.DataManager.MusicTree; if (musicTree != null) { bool anySolo = MusicUpdater.UpdateSoloMute(musicTree); MusicUpdater.UpdateVolumePitch(musicTree, 1.0f, 1.0f, anySolo); var audioTree = InAudioInstanceFinder.DataManager.AudioTree; if (audioTree != null) { AudioUpdater.AudioTreeUpdate(audioTree, 1.0f); } } #if UNITY_EDITOR //Remove condition in player, always update in build if (Application.isPlaying) #endif { var controllerPool = InAudioInstanceFinder.RuntimePlayerControllerPool; if (controllerPool != null) { controllerPool.DelayedRelease(); } var playerPool = InAudioInstanceFinder.InRuntimePlayerPool; if (playerPool != null) { playerPool.DelayedRelease(); } } } public const string CurrentVersion = "2.6.1"; private static AudioListener FindActiveListener() { return Object.FindObjectsOfType(typeof(AudioListener)).FindFirst(activeListener => (activeListener as AudioListener).gameObject.activeInHierarchy) as AudioListener; } void Awake() { #if UNITY_EDITOR if (Application.isPlaying) #endif { if(InAudio.instance == null) { Music = GetComponentInChildren<MusicPlayer>(); if (Music == null) { Debug.LogError( "InAudio: Could not find music player in InAudio Mananger object.\nPlease add the 'InAudio Manager' prefab to the scene again or reimport the project from the Asset Store and try again."); } } } } void OnEnable() { if (instance == null || instance == this) { if (activeAudioListener == null) activeAudioListener = FindActiveListener(); instance = this; InitializeInAudio(); } else { Object.Destroy(transform.gameObject); } } private void InitializeInAudio() { #if UNITY_EDITOR if (Application.isPlaying) #endif { //Music = InAudioInstanceFinder.MusicPlayer; DontDestroyOnLoad(transform.gameObject); _inAudioEventWorker = GetComponentInChildren<InAudioEventWorker>(); runtimeData = GetComponentInChildren<InRuntimeAudioData>(); if (InAudioInstanceFinder.DataManager.Loaded) { runtimeData.UpdateEvents(InAudioInstanceFinder.DataManager.EventTree); //See MusicPlayer for initialization of audio } else { Debug.LogError("InAudio: There was a problem loading the InAudio project. Have you created one?"); } } } #if UNITY_EDITOR void OnApplicationQuit() { InDebug.DoLog = false; } #endif #endregion #region Other public static InAudioEventWorker _getEventWorker() { if (instance != null) return instance._inAudioEventWorker; return null; } #endregion #endregion }
// 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; namespace System { public static class AppContext { [Flags] private enum SwitchValueState { HasFalseValue = 0x1, HasTrueValue = 0x2, HasLookedForOverride = 0x4, UnknownValue = 0x8 // Has no default and could not find an override } private static readonly Dictionary<string, SwitchValueState> s_switchMap = new Dictionary<string, SwitchValueState>(); public static string BaseDirectory { #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif get { // The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type. // Otherwise the caller will get invalid cast exception return (string) AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ?? AppDomain.CurrentDomain.BaseDirectory; } } public static string TargetFrameworkName { get { // Forward the value that is set on the current domain. return AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName; } } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public static object GetData(string name) { return AppDomain.CurrentDomain.GetData(name); } [System.Security.SecuritySafeCritical] public static void SetData(string name, object data) { AppDomain.CurrentDomain.SetData(name, data); } public static event UnhandledExceptionEventHandler UnhandledException { [System.Security.SecurityCritical] add { AppDomain.CurrentDomain.UnhandledException += value; } [System.Security.SecurityCritical] remove { AppDomain.CurrentDomain.UnhandledException -= value; } } public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException { [System.Security.SecurityCritical] add { AppDomain.CurrentDomain.FirstChanceException += value; } [System.Security.SecurityCritical] remove { AppDomain.CurrentDomain.FirstChanceException -= value; } } public static event System.EventHandler ProcessExit { [System.Security.SecurityCritical] add { AppDomain.CurrentDomain.ProcessExit += value; } [System.Security.SecurityCritical] remove { AppDomain.CurrentDomain.ProcessExit -= value; } } #region Switch APIs static AppContext() { // populate the AppContext with the default set of values AppContextDefaultValues.PopulateDefaultValues(); } /// <summary> /// Try to get the value of the switch. /// </summary> /// <param name="switchName">The name of the switch</param> /// <param name="isEnabled">A variable where to place the value of the switch</param> /// <returns>A return value of true represents that the switch was set and <paramref name="isEnabled"/> contains the value of the switch</returns> public static bool TryGetSwitch(string switchName, out bool isEnabled) { if (switchName == null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName)); // By default, the switch is not enabled. isEnabled = false; SwitchValueState switchValue; lock (s_switchMap) { if (s_switchMap.TryGetValue(switchName, out switchValue)) { // The value is in the dictionary. // There are 3 cases here: // 1. The value of the switch is 'unknown'. This means that the switch name is not known to the system (either via defaults or checking overrides). // Example: This is the case when, during a servicing event, a switch is added to System.Xml which ships before mscorlib. The value of the switch // Will be unknown to mscorlib.dll and we want to prevent checking the overrides every time we check this switch // 2. The switch has a valid value AND we have read the overrides for it // Example: TryGetSwitch is called for a switch set via SetSwitch // 3. The switch has the default value and we need to check for overrides // Example: TryGetSwitch is called for the first time for a switch that has a default value // 1. The value is unknown if (switchValue == SwitchValueState.UnknownValue) { isEnabled = false; return false; } // We get the value of isEnabled from the value that we stored in the dictionary isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue; // 2. The switch has a valid value AND we have checked for overrides if ((switchValue & SwitchValueState.HasLookedForOverride) == SwitchValueState.HasLookedForOverride) { return true; } // 3. The switch has a valid value, but we need to check for overrides. // Regardless of whether or not the switch has an override, we need to update the value to reflect // the fact that we checked for overrides. bool overrideValue; if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue)) { // we found an override! isEnabled = overrideValue; } // Update the switch in the dictionary to mark it as 'checked for override' s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; return true; } else { // The value is NOT in the dictionary // In this case we need to see if we have an override defined for the value. // There are 2 cases: // 1. The value has an override specified. In this case we need to add the value to the dictionary // and mark it as checked for overrides // Example: In a servicing event, System.Xml introduces a switch and an override is specified. // The value is not found in mscorlib (as System.Xml ships independent of mscorlib) // 2. The value does not have an override specified // In this case, we want to capture the fact that we looked for a value and found nothing by adding // an entry in the dictionary with the 'sentinel' value of 'SwitchValueState.UnknownValue'. // Example: This will prevent us from trying to find overrides for values that we don't have in the dictionary // 1. The value has an override specified. bool overrideValue; if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue)) { isEnabled = overrideValue; // Update the switch in the dictionary to mark it as 'checked for override' s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; return true; } // 2. The value does not have an override. s_switchMap[switchName] = SwitchValueState.UnknownValue; } } return false; // we did not find a value for the switch } /// <summary> /// Assign a switch a value /// </summary> /// <param name="switchName">The name of the switch</param> /// <param name="isEnabled">The value to assign</param> public static void SetSwitch(string switchName, bool isEnabled) { if (switchName == null) throw new ArgumentNullException(nameof(switchName)); if (switchName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), nameof(switchName)); SwitchValueState switchValue = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; lock (s_switchMap) { // Store the new value and the fact that we checked in the dictionary s_switchMap[switchName] = switchValue; } } /// <summary> /// This method is going to be called from the AppContextDefaultValues class when setting up the /// default values for the switches. !!!! This method is called during the static constructor so it does not /// take a lock !!!! If you are planning to use this outside of that, please ensure proper locking. /// </summary> internal static void DefineSwitchDefault(string switchName, bool isEnabled) { s_switchMap[switchName] = isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue; } #endregion } }
// 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.Diagnostics; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Security; using System.Xml.XPath; using System.Xml.Xsl.IlGen; using System.Xml.Xsl.Qil; using System.Xml.Xsl.Runtime; using System.Runtime.Versioning; namespace System.Xml.Xsl { internal delegate void ExecuteDelegate(XmlQueryRuntime runtime); /// <summary> /// This internal class is the entry point for creating Msil assemblies from QilExpression. /// </summary> /// <remarks> /// Generate will return an AssemblyBuilder with the following setup: /// Assembly Name = "MS.Internal.Xml.CompiledQuery" /// Module Dll Name = "MS.Internal.Xml.CompiledQuery.dll" /// public class MS.Internal.Xml.CompiledQuery.Test { /// public static void Execute(XmlQueryRuntime runtime); /// public static void Root(XmlQueryRuntime runtime); /// private static ... UserMethod1(XmlQueryRuntime runtime, ...); /// ... /// private static ... UserMethodN(XmlQueryRuntime runtime, ...); /// } /// /// XmlILGenerator incorporates a number of different technologies in order to generate efficient code that avoids caching /// large result sets in memory: /// /// 1. Code Iterators - Query results are computed using a set of composable, interlocking iterators that alone perform a /// simple task, but together execute complex queries. The iterators are actually little blocks of code /// that are connected to each other using a series of jumps. Because each iterator is not instantiated /// as a separate object, the number of objects and number of function calls is kept to a minimum during /// execution. Also, large result sets are often computed incrementally, with each iterator performing one step in a /// pipeline of sequence items. /// /// 2. Analyzers - During code generation, QilToMsil traverses the semantic tree representation of the query (QIL) several times. /// As visits to each node in the tree start and end, various Analyzers are invoked. These Analyzers incrementally /// collect and store information that is later used to generate faster and smaller code. /// </remarks> internal class XmlILGenerator { private QilExpression _qil; private GenerateHelper _helper; private XmlILOptimizerVisitor _optVisitor; private XmlILVisitor _xmlIlVisitor; private XmlILModule _module; /// <summary> /// Always output debug information in debug mode. /// </summary> public XmlILGenerator() { } /// <summary> /// Given the logical query plan (QilExpression) generate a physical query plan (MSIL) that can be executed. /// </summary> // SxS Note: The way the trace file names are created (hardcoded) is NOT SxS safe. However the files are // created only for internal tracing purposes. In addition XmlILTrace class is not compiled into retail // builds. As a result it is fine to suppress the FxCop SxS warning. public XmlILCommand Generate(QilExpression query, TypeBuilder typeBldr) { _qil = query; bool useLRE = ( !_qil.IsDebug && (typeBldr == null) #if DEBUG && !XmlILTrace.IsEnabled // Dump assembly to disk; can't do this when using LRE #endif ); bool emitSymbols = _qil.IsDebug; // In debug code, ensure that input QIL is correct QilValidationVisitor.Validate(_qil); #if DEBUG // Trace Qil before optimization XmlILTrace.WriteQil(_qil, "qilbefore.xml"); // Trace optimizations XmlILTrace.TraceOptimizations(_qil, "qilopt.xml"); #endif // Optimize and annotate the Qil graph _optVisitor = new XmlILOptimizerVisitor(_qil, !_qil.IsDebug); _qil = _optVisitor.Optimize(); // In debug code, ensure that output QIL is correct QilValidationVisitor.Validate(_qil); #if DEBUG // Trace Qil after optimization XmlILTrace.WriteQil(_qil, "qilafter.xml"); #endif // Create module in which methods will be generated if (typeBldr != null) { _module = new XmlILModule(typeBldr); } else { _module = new XmlILModule(useLRE, emitSymbols); } // Create a code generation helper for the module; enable optimizations if IsDebug is false _helper = new GenerateHelper(_module, _qil.IsDebug); // Create helper methods CreateHelperFunctions(); // Create metadata for the Execute function, which is the entry point to the query // public static void Execute(XmlQueryRuntime); MethodInfo methExec = _module.DefineMethod("Execute", typeof(void), Array.Empty<Type>(), Array.Empty<string>(), XmlILMethodAttributes.NonUser); // Create metadata for the root expression // public void Root() Debug.Assert(_qil.Root != null); XmlILMethodAttributes methAttrs = (_qil.Root.SourceLine == null) ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; MethodInfo methRoot = _module.DefineMethod("Root", typeof(void), Array.Empty<Type>(), Array.Empty<string>(), methAttrs); // Declare all early bound function objects foreach (EarlyBoundInfo info in _qil.EarlyBoundTypes) { _helper.StaticData.DeclareEarlyBound(info.NamespaceUri, info.EarlyBoundType); } // Create metadata for each QilExpression function that has at least one caller CreateFunctionMetadata(_qil.FunctionList); // Create metadata for each QilExpression global variable and parameter CreateGlobalValueMetadata(_qil.GlobalVariableList); CreateGlobalValueMetadata(_qil.GlobalParameterList); // Generate Execute method GenerateExecuteFunction(methExec, methRoot); // Visit the QilExpression graph _xmlIlVisitor = new XmlILVisitor(); _xmlIlVisitor.Visit(_qil, _helper, methRoot); // Collect all static information required by the runtime XmlQueryStaticData staticData = new XmlQueryStaticData( _qil.DefaultWriterSettings, _qil.WhitespaceRules, _helper.StaticData ); // Create static constructor that initializes XmlQueryStaticData instance at runtime if (typeBldr != null) { CreateTypeInitializer(staticData); // Finish up creation of the type _module.BakeMethods(); return null; } else { // Finish up creation of the type _module.BakeMethods(); // Create delegate over "Execute" method ExecuteDelegate delExec = (ExecuteDelegate)_module.CreateDelegate("Execute", typeof(ExecuteDelegate)); return new XmlILCommand(delExec, staticData); } } /// <summary> /// Create MethodBuilder metadata for the specified QilExpression function. Annotate ndFunc with the /// MethodBuilder. Also, each QilExpression argument type should be converted to a corresponding Clr type. /// Each argument QilExpression node should be annotated with the resulting ParameterBuilder. /// </summary> private void CreateFunctionMetadata(IList<QilNode> funcList) { MethodInfo methInfo; Type[] paramTypes; string[] paramNames; Type typReturn; XmlILMethodAttributes methAttrs; foreach (QilFunction ndFunc in funcList) { paramTypes = new Type[ndFunc.Arguments.Count]; paramNames = new string[ndFunc.Arguments.Count]; // Loop through all other parameters and save their types in the array for (int arg = 0; arg < ndFunc.Arguments.Count; arg++) { QilParameter ndParam = (QilParameter)ndFunc.Arguments[arg]; Debug.Assert(ndParam.NodeType == QilNodeType.Parameter); // Get the type of each argument as a Clr type paramTypes[arg] = XmlILTypeHelper.GetStorageType(ndParam.XmlType); // Get the name of each argument if (ndParam.DebugName != null) paramNames[arg] = ndParam.DebugName; } // Get the type of the return value if (XmlILConstructInfo.Read(ndFunc).PushToWriterLast) { // Push mode functions do not have a return value typReturn = typeof(void); } else { // Pull mode functions have a return value typReturn = XmlILTypeHelper.GetStorageType(ndFunc.XmlType); } // Create the method metadata methAttrs = ndFunc.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; methInfo = _module.DefineMethod(ndFunc.DebugName, typReturn, paramTypes, paramNames, methAttrs); for (int arg = 0; arg < ndFunc.Arguments.Count; arg++) { // Set location of parameter on Let node annotation XmlILAnnotation.Write(ndFunc.Arguments[arg]).ArgumentPosition = arg; } // Annotate function with the MethodInfo XmlILAnnotation.Write(ndFunc).FunctionBinding = methInfo; } } /// <summary> /// Generate metadata for a method that calculates a global value. /// </summary> private void CreateGlobalValueMetadata(IList<QilNode> globalList) { MethodInfo methInfo; Type typReturn; XmlILMethodAttributes methAttrs; foreach (QilReference ndRef in globalList) { // public T GlobalValue() typReturn = XmlILTypeHelper.GetStorageType(ndRef.XmlType); methAttrs = ndRef.SourceLine == null ? XmlILMethodAttributes.NonUser : XmlILMethodAttributes.None; methInfo = _module.DefineMethod(ndRef.DebugName.ToString(), typReturn, Array.Empty<Type>(), Array.Empty<string>(), methAttrs); // Annotate function with MethodBuilder XmlILAnnotation.Write(ndRef).FunctionBinding = methInfo; } } /// <summary> /// Generate the "Execute" method, which is the entry point to the query. /// </summary> private MethodInfo GenerateExecuteFunction(MethodInfo methExec, MethodInfo methRoot) { _helper.MethodBegin(methExec, null, false); // Force some or all global values to be evaluated at start of query EvaluateGlobalValues(_qil.GlobalVariableList); EvaluateGlobalValues(_qil.GlobalParameterList); // Root(runtime); _helper.LoadQueryRuntime(); _helper.Call(methRoot); _helper.MethodEnd(); return methExec; } /// <summary> /// Create and generate various helper methods, which are called by the generated code. /// </summary> private void CreateHelperFunctions() { MethodInfo meth; Label lblClone; // public static XPathNavigator SyncToNavigator(XPathNavigator, XPathNavigator); meth = _module.DefineMethod( "SyncToNavigator", typeof(XPathNavigator), new Type[] { typeof(XPathNavigator), typeof(XPathNavigator) }, new string[] { null, null }, XmlILMethodAttributes.NonUser | XmlILMethodAttributes.Raw); _helper.MethodBegin(meth, null, false); // if (navigatorThis != null && navigatorThis.MoveTo(navigatorThat)) // return navigatorThis; lblClone = _helper.DefineLabel(); _helper.Emit(OpCodes.Ldarg_0); _helper.Emit(OpCodes.Brfalse, lblClone); _helper.Emit(OpCodes.Ldarg_0); _helper.Emit(OpCodes.Ldarg_1); _helper.Call(XmlILMethods.NavMoveTo); _helper.Emit(OpCodes.Brfalse, lblClone); _helper.Emit(OpCodes.Ldarg_0); _helper.Emit(OpCodes.Ret); // LabelClone: // return navigatorThat.Clone(); _helper.MarkLabel(lblClone); _helper.Emit(OpCodes.Ldarg_1); _helper.Call(XmlILMethods.NavClone); _helper.MethodEnd(); } /// <summary> /// Generate code to force evaluation of some or all global variables and/or parameters. /// </summary> private void EvaluateGlobalValues(IList<QilNode> iterList) { MethodInfo methInfo; foreach (QilIterator ndIter in iterList) { // Evaluate global if generating debug code, or if global might have side effects if (_qil.IsDebug || OptimizerPatterns.Read(ndIter).MatchesPattern(OptimizerPatternName.MaybeSideEffects)) { // Get MethodInfo that evaluates the global value and discard its return value methInfo = XmlILAnnotation.Write(ndIter).FunctionBinding; Debug.Assert(methInfo != null, "MethodInfo for global value should have been created previously."); _helper.LoadQueryRuntime(); _helper.Call(methInfo); _helper.Emit(OpCodes.Pop); } } } /// <summary> /// Create static constructor that initializes XmlQueryStaticData instance at runtime. /// </summary> public void CreateTypeInitializer(XmlQueryStaticData staticData) { byte[] data; Type[] ebTypes; FieldInfo fldInitData, fldData, fldTypes; ConstructorInfo cctor; staticData.GetObjectData(out data, out ebTypes); fldInitData = _module.DefineInitializedData("__" + XmlQueryStaticData.DataFieldName, data); fldData = _module.DefineField(XmlQueryStaticData.DataFieldName, typeof(object)); fldTypes = _module.DefineField(XmlQueryStaticData.TypesFieldName, typeof(Type[])); cctor = _module.DefineTypeInitializer(); _helper.MethodBegin(cctor, null, false); // s_data = new byte[s_initData.Length] { s_initData }; _helper.LoadInteger(data.Length); _helper.Emit(OpCodes.Newarr, typeof(byte)); _helper.Emit(OpCodes.Dup); _helper.Emit(OpCodes.Ldtoken, fldInitData); _helper.Call(XmlILMethods.InitializeArray); _helper.Emit(OpCodes.Stsfld, fldData); if (ebTypes != null) { // Type[] types = new Type[s_ebTypes.Length]; LocalBuilder locTypes = _helper.DeclareLocal("$$$types", typeof(Type[])); _helper.LoadInteger(ebTypes.Length); _helper.Emit(OpCodes.Newarr, typeof(Type)); _helper.Emit(OpCodes.Stloc, locTypes); for (int idx = 0; idx < ebTypes.Length; idx++) { // types[idx] = ebTypes[idx]; _helper.Emit(OpCodes.Ldloc, locTypes); _helper.LoadInteger(idx); _helper.LoadType(ebTypes[idx]); _helper.Emit(OpCodes.Stelem_Ref); } // s_types = types; _helper.Emit(OpCodes.Ldloc, locTypes); _helper.Emit(OpCodes.Stsfld, fldTypes); } _helper.MethodEnd(); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the opsworks-2013-02-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.OpsWorks.Model { /// <summary> /// Describes an instance's RAID array. /// </summary> public partial class RaidArray { private string _availabilityZone; private string _createdAt; private string _device; private string _instanceId; private int? _iops; private string _mountPoint; private string _name; private int? _numberOfDisks; private string _raidArrayId; private int? _raidLevel; private int? _size; private string _stackId; private string _volumeType; /// <summary> /// Gets and sets the property AvailabilityZone. /// <para> /// The array's Availability Zone. For more information, see <a href="http://docs.aws.amazon.com/general/latest/gr/rande.html">Regions /// and Endpoints</a>. /// </para> /// </summary> public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property CreatedAt. /// <para> /// When the RAID array was created. /// </para> /// </summary> public string CreatedAt { get { return this._createdAt; } set { this._createdAt = value; } } // Check to see if CreatedAt property is set internal bool IsSetCreatedAt() { return this._createdAt != null; } /// <summary> /// Gets and sets the property Device. /// <para> /// The array's Linux device. For example /dev/mdadm0. /// </para> /// </summary> public string Device { get { return this._device; } set { this._device = value; } } // Check to see if Device property is set internal bool IsSetDevice() { return this._device != null; } /// <summary> /// Gets and sets the property InstanceId. /// <para> /// The instance ID. /// </para> /// </summary> public string InstanceId { get { return this._instanceId; } set { this._instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this._instanceId != null; } /// <summary> /// Gets and sets the property Iops. /// <para> /// For PIOPS volumes, the IOPS per disk. /// </para> /// </summary> public int Iops { get { return this._iops.GetValueOrDefault(); } set { this._iops = value; } } // Check to see if Iops property is set internal bool IsSetIops() { return this._iops.HasValue; } /// <summary> /// Gets and sets the property MountPoint. /// <para> /// The array's mount point. /// </para> /// </summary> public string MountPoint { get { return this._mountPoint; } set { this._mountPoint = value; } } // Check to see if MountPoint property is set internal bool IsSetMountPoint() { return this._mountPoint != null; } /// <summary> /// Gets and sets the property Name. /// <para> /// The array name. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property NumberOfDisks. /// <para> /// The number of disks in the array. /// </para> /// </summary> public int NumberOfDisks { get { return this._numberOfDisks.GetValueOrDefault(); } set { this._numberOfDisks = value; } } // Check to see if NumberOfDisks property is set internal bool IsSetNumberOfDisks() { return this._numberOfDisks.HasValue; } /// <summary> /// Gets and sets the property RaidArrayId. /// <para> /// The array ID. /// </para> /// </summary> public string RaidArrayId { get { return this._raidArrayId; } set { this._raidArrayId = value; } } // Check to see if RaidArrayId property is set internal bool IsSetRaidArrayId() { return this._raidArrayId != null; } /// <summary> /// Gets and sets the property RaidLevel. /// <para> /// The <a href="http://en.wikipedia.org/wiki/Standard_RAID_levels">RAID level</a>. /// </para> /// </summary> public int RaidLevel { get { return this._raidLevel.GetValueOrDefault(); } set { this._raidLevel = value; } } // Check to see if RaidLevel property is set internal bool IsSetRaidLevel() { return this._raidLevel.HasValue; } /// <summary> /// Gets and sets the property Size. /// <para> /// The array's size. /// </para> /// </summary> public int Size { get { return this._size.GetValueOrDefault(); } set { this._size = value; } } // Check to see if Size property is set internal bool IsSetSize() { return this._size.HasValue; } /// <summary> /// Gets and sets the property StackId. /// <para> /// The stack ID. /// </para> /// </summary> public string StackId { get { return this._stackId; } set { this._stackId = value; } } // Check to see if StackId property is set internal bool IsSetStackId() { return this._stackId != null; } /// <summary> /// Gets and sets the property VolumeType. /// <para> /// The volume type, standard or PIOPS. /// </para> /// </summary> public string VolumeType { get { return this._volumeType; } set { this._volumeType = value; } } // Check to see if VolumeType property is set internal bool IsSetVolumeType() { return this._volumeType != null; } } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // Copyright (c) 2011 Andy Pickett // 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 System.Diagnostics; using YamlDotNet.Core; using YamlDotNet.Core.Events; using System.Text; using YamlDotNet.Serialization; namespace YamlDotNet.RepresentationModel { /// <summary> /// Represents a sequence node in the YAML document. /// </summary> [DebuggerDisplay("Count = {children.Count}")] [Serializable] public sealed class YamlSequenceNode : YamlNode, IEnumerable<YamlNode>, IYamlConvertible { private readonly IList<YamlNode> children = new List<YamlNode>(); /// <summary> /// Gets the collection of child nodes. /// </summary> /// <value>The children.</value> public IList<YamlNode> Children { get { return children; } } /// <summary> /// Gets or sets the style of the node. /// </summary> /// <value>The style.</value> public SequenceStyle Style { get; set; } /// <summary> /// Initializes a new instance of the <see cref="YamlSequenceNode"/> class. /// </summary> internal YamlSequenceNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { var sequence = parser.Expect<SequenceStart>(); Load(sequence, state); Style = sequence.Style; bool hasUnresolvedAliases = false; while (!parser.Accept<SequenceEnd>()) { var child = ParseNode(parser, state); children.Add(child); hasUnresolvedAliases |= child is YamlAliasNode; } if (hasUnresolvedAliases) { state.AddNodeWithUnresolvedAliases(this); } parser.Expect<SequenceEnd>(); } /// <summary> /// Initializes a new instance of the <see cref="YamlSequenceNode"/> class. /// </summary> public YamlSequenceNode() { } /// <summary> /// Initializes a new instance of the <see cref="YamlSequenceNode"/> class. /// </summary> public YamlSequenceNode(params YamlNode[] children) : this((IEnumerable<YamlNode>)children) { } /// <summary> /// Initializes a new instance of the <see cref="YamlSequenceNode"/> class. /// </summary> public YamlSequenceNode(IEnumerable<YamlNode> children) { foreach (var child in children) { this.children.Add(child); } } /// <summary> /// Adds the specified child to the <see cref="Children"/> collection. /// </summary> /// <param name="child">The child.</param> public void Add(YamlNode child) { children.Add(child); } /// <summary> /// Adds a scalar node to the <see cref="Children"/> collection. /// </summary> /// <param name="child">The child.</param> public void Add(string child) { children.Add(new YamlScalarNode(child)); } /// <summary> /// Resolves the aliases that could not be resolved when the node was created. /// </summary> /// <param name="state">The state of the document.</param> internal override void ResolveAliases(DocumentLoadingState state) { for (int i = 0; i < children.Count; ++i) { if (children[i] is YamlAliasNode) { children[i] = state.GetNode(children[i].Anchor, true, children[i].Start, children[i].End); } } } /// <summary> /// Saves the current node to the specified emitter. /// </summary> /// <param name="emitter">The emitter where the node is to be saved.</param> /// <param name="state">The state.</param> internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new SequenceStart(Anchor, Tag, true, Style)); foreach (var node in children) { node.Save(emitter, state); } emitter.Emit(new SequenceEnd()); } /// <summary> /// Accepts the specified visitor by calling the appropriate Visit method on it. /// </summary> /// <param name="visitor"> /// A <see cref="IYamlVisitor"/>. /// </param> public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } /// <summary /> public override bool Equals(object obj) { var other = obj as YamlSequenceNode; if (other == null || !Equals(other) || children.Count != other.children.Count) { return false; } for (int i = 0; i < children.Count; ++i) { if (!SafeEquals(children[i], other.children[i])) { return false; } } return true; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { var hashCode = base.GetHashCode(); foreach (var item in children) { hashCode = CombineHashCodes(hashCode, GetHashCode(item)); } return hashCode; } /// <summary> /// Recursively enumerates all the nodes from the document, starting on the current node, /// and throwing <see cref="MaximumRecursionLevelReachedException"/> /// if <see cref="RecursionLevel.Maximum"/> is reached. /// </summary> internal override IEnumerable<YamlNode> SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (var child in children) { foreach (var node in child.SafeAllNodes(level)) { yield return node; } } level.Decrement(); } /// <summary> /// Gets the type of node. /// </summary> public override YamlNodeType NodeType { get { return YamlNodeType.Sequence; } } /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return MaximumRecursionLevelReachedToStringValue; } var text = new StringBuilder("[ "); foreach (var child in children) { if (text.Length > 2) { text.Append(", "); } text.Append(child.ToString(level)); } text.Append(" ]"); level.Decrement(); return text.ToString(); } #region IEnumerable<YamlNode> Members /// <summary /> public IEnumerator<YamlNode> GetEnumerator() { return Children.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } }
namespace StripeTests { using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Stripe; using Xunit; public class CreditNoteServiceTest : BaseStripeTest { private const string CreditNoteId = "cn_123"; private readonly CreditNoteService service; private readonly CreditNoteCreateOptions createOptions; private readonly CreditNoteUpdateOptions updateOptions; private readonly CreditNoteListOptions listOptions; private readonly CreditNoteListLineItemsOptions listLineItemsOptions; private readonly CreditNotePreviewOptions previewOptions; private readonly CreditNoteListPreviewLineItemsOptions listPreviewLineItemsOptions; private readonly CreditNoteVoidOptions voidOptions; public CreditNoteServiceTest( StripeMockFixture stripeMockFixture, MockHttpClientFixture mockHttpClientFixture) : base(stripeMockFixture, mockHttpClientFixture) { this.service = new CreditNoteService(this.StripeClient); this.createOptions = new CreditNoteCreateOptions { Amount = 100, Invoice = "in_123", Reason = "duplicate", }; this.updateOptions = new CreditNoteUpdateOptions { Metadata = new Dictionary<string, string> { { "key", "value" }, }, }; this.listOptions = new CreditNoteListOptions { Limit = 1, Invoice = "in_123", }; this.listLineItemsOptions = new CreditNoteListLineItemsOptions { Limit = 1, }; this.previewOptions = new CreditNotePreviewOptions { Amount = 1000, Invoice = "in_123", }; this.listPreviewLineItemsOptions = new CreditNoteListPreviewLineItemsOptions { Amount = 1000, Invoice = "in_123", }; this.voidOptions = new CreditNoteVoidOptions { }; } [Fact] public void Create() { var creditNote = this.service.Create(this.createOptions); this.AssertRequest(HttpMethod.Post, "/v1/credit_notes"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public async Task CreateAsync() { var creditNote = await this.service.CreateAsync(this.createOptions); this.AssertRequest(HttpMethod.Post, "/v1/credit_notes"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public void Get() { var creditNote = this.service.Get(CreditNoteId); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes/cn_123"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public async Task GetAsync() { var creditNote = await this.service.GetAsync(CreditNoteId); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes/cn_123"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public void List() { var creditNotes = this.service.List(this.listOptions); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes"); Assert.NotNull(creditNotes); Assert.Equal("list", creditNotes.Object); Assert.Single(creditNotes.Data); Assert.Equal("credit_note", creditNotes.Data[0].Object); } [Fact] public async Task ListAsync() { var creditNotes = await this.service.ListAsync(this.listOptions); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes"); Assert.NotNull(creditNotes); Assert.Equal("list", creditNotes.Object); Assert.Single(creditNotes.Data); Assert.Equal("credit_note", creditNotes.Data[0].Object); } [Fact] public void ListAutoPaging() { var creditNote = this.service.ListAutoPaging(this.listOptions).First(); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public async Task ListAutoPagingAsync() { var creditNote = await this.service.ListAutoPagingAsync(this.listOptions).FirstAsync(); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public void ListLineItems() { var lineItems = this.service.ListLineItems(CreditNoteId, this.listLineItemsOptions); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes/cn_123/lines"); Assert.NotNull(lineItems); Assert.Equal("list", lineItems.Object); Assert.Single(lineItems.Data); Assert.Equal("credit_note_line_item", lineItems.Data[0].Object); } [Fact] public async Task ListLineItemsAsync() { var lineItems = await this.service.ListLineItemsAsync(CreditNoteId, this.listLineItemsOptions); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes/cn_123/lines"); Assert.NotNull(lineItems); Assert.Equal("list", lineItems.Object); Assert.Single(lineItems.Data); Assert.Equal("credit_note_line_item", lineItems.Data[0].Object); } [Fact] public void ListLineItemsAutoPaging() { var lineItem = this.service.ListLineItemsAutoPaging(CreditNoteId, this.listLineItemsOptions).First(); Assert.NotNull(lineItem); Assert.Equal("credit_note_line_item", lineItem.Object); } [Fact] public async Task ListLineItemsAutoPagingAsync() { var lineItem = await this.service.ListLineItemsAutoPagingAsync(CreditNoteId, this.listLineItemsOptions).FirstAsync(); Assert.NotNull(lineItem); Assert.Equal("credit_note_line_item", lineItem.Object); } [Fact] public void Preview() { var creditNote = this.service.Preview(this.previewOptions); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes/preview"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public async Task PreviewAsync() { var creditNote = await this.service.PreviewAsync(this.previewOptions); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes/preview"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public void ListPreviewLineItems() { var lineItems = this.service.ListPreviewLineItems(this.listPreviewLineItemsOptions); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes/preview/lines"); Assert.NotNull(lineItems); Assert.Equal("list", lineItems.Object); Assert.Single(lineItems.Data); Assert.Equal("credit_note_line_item", lineItems.Data[0].Object); } [Fact] public async Task ListPreviewLineItemsAsync() { var lineItems = await this.service.ListPreviewLineItemsAsync(this.listPreviewLineItemsOptions); this.AssertRequest(HttpMethod.Get, "/v1/credit_notes/preview/lines"); Assert.NotNull(lineItems); Assert.Equal("list", lineItems.Object); Assert.Single(lineItems.Data); Assert.Equal("credit_note_line_item", lineItems.Data[0].Object); } [Fact] public void ListPreviewLineItemsAutoPaging() { var lineItem = this.service.ListPreviewLineItemsAutoPaging(this.listPreviewLineItemsOptions).First(); Assert.NotNull(lineItem); Assert.Equal("credit_note_line_item", lineItem.Object); } [Fact] public async Task ListPreviewLineItemsAutoPagingAsync() { var lineItem = await this.service.ListPreviewLineItemsAutoPagingAsync(this.listPreviewLineItemsOptions).FirstAsync(); Assert.NotNull(lineItem); Assert.Equal("credit_note_line_item", lineItem.Object); } [Fact] public void Update() { var creditNote = this.service.Update(CreditNoteId, this.updateOptions); this.AssertRequest(HttpMethod.Post, "/v1/credit_notes/cn_123"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public async Task UpdateAsync() { var creditNote = await this.service.UpdateAsync(CreditNoteId, this.updateOptions); this.AssertRequest(HttpMethod.Post, "/v1/credit_notes/cn_123"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public void VoidCreditNote() { var creditNote = this.service.VoidCreditNote(CreditNoteId, this.voidOptions); this.AssertRequest(HttpMethod.Post, "/v1/credit_notes/cn_123/void"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } [Fact] public async Task VoidCreditNoteAsync() { var creditNote = await this.service.VoidCreditNoteAsync(CreditNoteId, this.voidOptions); this.AssertRequest(HttpMethod.Post, "/v1/credit_notes/cn_123/void"); Assert.NotNull(creditNote); Assert.Equal("credit_note", creditNote.Object); } } }
using System; using Edustructures.SifWorks; namespace Edustructures.Metadata { public abstract class AbstractDef { protected AbstractDef( string name ) { this.Name = name; } /// <summary>A description of this object/field</summary> public virtual String Desc { get { return fDesc; } set { fDesc = value; } } /// <summary>The name of this object/field /// </summary> public virtual String Name { get { return fName; } set { fName = value; } } /// <summary> If the sequence # of this object or element has been overridden, this is /// the sequence # that will be assigned to the ADK's ElementDef instance for /// this object or element. Otherwise, -1. /// </summary> public virtual int SequenceOverride { get { return fSeqOverride; } set { fSeqOverride = value; } } /// <summary> /// Whether or not to validate this element, defaults to true /// </summary> public virtual bool ShouldValidate { get { return fValidate; } set { fValidate = value; } } public virtual bool Deprecated { get { return (fFlags & FLAG_DEPRECATED) != 0; } } public virtual void SetFlags( string flag ) { String ff = flag.ToUpper(); if ( ff.ToUpper().Equals( "O".ToUpper() ) ) { fFlags |= FLAG_OPTIONAL; } else if ( ff.ToUpper().Equals( "R".ToUpper() ) ) { fFlags |= FLAG_REQUIRED; } else if ( ff.ToUpper().Equals( "M".ToUpper() ) ) { fFlags |= FLAG_MANDATORY; } else if ( ff.ToUpper().Equals( "C".ToUpper() ) ) { fFlags |= FLAG_CONDITIONAL; } else if ( ff.ToUpper().Equals( "MR".ToUpper() ) ) { fFlags |= (FLAG_MANDATORY | FLAG_REPEATABLE); } else if ( ff.ToUpper().Equals( "OR".ToUpper() ) ) { fFlags |= (FLAG_OPTIONAL | FLAG_REPEATABLE); } else if ( ff.ToUpper().Equals( "CR".ToUpper() ) ) { fFlags |= (FLAG_CONDITIONAL | FLAG_REPEATABLE); } } /// <summary> /// Gets the Field's Flags as a string /// </summary> /// <returns></returns> public virtual string GetFlags() { if ( (fFlags & FLAG_REQUIRED) > 0 ) { return "R"; } else { string returnVal; if ( (fFlags & FLAG_MANDATORY) > 0 ) { returnVal = "M"; } else if ( (fFlags & FLAG_CONDITIONAL) > 0 ) { returnVal = "C"; } else { // Default to Optional, if nothing else specified returnVal = "O"; } if ( (fFlags & FLAG_REPEATABLE) > 0 ) { returnVal += "R"; } return returnVal; } } public bool FlagIntrinsicallyMatches( FieldDef counterpart ) { if (fFlags == counterpart.fFlags) { return true; } else if ((fFlags & FLAG_REPEATABLE) == 0 && ((fFlags & FLAG_REQUIRED) > 0 || (fFlags & FLAG_MANDATORY) > 0) ) { return ((counterpart.fFlags & FLAG_REQUIRED) > 0 || (counterpart.fFlags & FLAG_MANDATORY) > 0 ); } return GetFlags() == counterpart.GetFlags(); } /// <summary>Flags describing characteristics of this object/field /// </summary> public virtual int Flags { get { return fFlags; } set { fFlags = value; } } public virtual bool Draft { get { return (fFlags & FLAG_DRAFTOBJECT) != 0; } } /// <summary> Gets the earliest version of SIF this definition applies to. /// </summary> /// <summary> Sets the earliest version of SIF this definition applies to. /// * /// If the version is earlier than the current earliest version, it becomes /// the earliest version and will be returned by the getEarliestVersion /// method. Otherwise no action is taken. /// </summary> public virtual SifVersion EarliestVersion { get { return fMinVersion; } set { if ( fMinVersion == null || value.CompareTo( fMinVersion ) < 0 ) { fMinVersion = value; } } } /// <summary> Gets the latest version of SIF this definition applies to. /// </summary> /// <summary> Sets the latest version of SIF this definition applies to. /// </summary> public virtual SifVersion LatestVersion { get { return fMaxVersion; } set { fMaxVersion = value; if ( fMinVersion == null ) { fMinVersion = value; } } } public const int FLAG_REQUIRED = 0x00000001; public const int FLAG_REPEATABLE = 0x00000002; public const int FLAG_OPTIONAL = 0x00000004; public const int FLAG_MANDATORY = 0x00000008; public const int FLAG_CONDITIONAL = 0x00000010; public const int FLAG_DEPRECATED = 0x00000020; public const int FLAG_DRAFTOBJECT = 0x00000040; public const int FLAG_NO_SIFDTD = 0x00000080; /// <summary>A description of this object/field /// </summary> protected internal String fDesc; /// <summary>The name of this object/field /// </summary> protected internal String fName; /// <summary>Flags describing characteristics of this object/field /// </summary> protected internal int fFlags; /// <summary>The earliest version of SIF this definition applies to /// </summary> protected internal SifVersion fMinVersion; /// <summary>The latest version of SIF this definition applies to /// </summary> protected internal SifVersion fMaxVersion; /// /// <summary> If the sequence # of this object or element has been overridden, this is /// the sequence # that will be assigned to the ADK's ElementDef instance for /// this object or element. Otherwise, -1. /// </summary> protected internal int fSeqOverride = - 1; public virtual void setDraft() { fFlags |= FLAG_DRAFTOBJECT; } /// <summary> /// The source file that generated this object /// </summary> public string SourceLocation { get { return fSourceLocation; } set { fSourceLocation = value; } } /// <summary> /// Whether or not to validate this element, defaults to true /// </summary> private bool fValidate = true; /// <summary> /// The source file that generated this object /// </summary> private string fSourceLocation; } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// Implements the Goal profile message. /// </summary> public class GoalMesg : Mesg { #region Fields #endregion #region Constructors public GoalMesg() : base(Profile.mesgs[Profile.GoalIndex]) { } public GoalMesg(Mesg mesg) : base(mesg) { } #endregion // Constructors #region Methods ///<summary> /// Retrieves the MessageIndex field</summary> /// <returns>Returns nullable ushort representing the MessageIndex field</returns> public ushort? GetMessageIndex() { return (ushort?)GetFieldValue(254, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set MessageIndex field</summary> /// <param name="messageIndex_">Nullable field value to be set</param> public void SetMessageIndex(ushort? messageIndex_) { SetFieldValue(254, 0, messageIndex_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Sport field</summary> /// <returns>Returns nullable Sport enum representing the Sport field</returns> public Sport? GetSport() { object obj = GetFieldValue(0, 0, Fit.SubfieldIndexMainField); Sport? value = obj == null ? (Sport?)null : (Sport)obj; return value; } /// <summary> /// Set Sport field</summary> /// <param name="sport_">Nullable field value to be set</param> public void SetSport(Sport? sport_) { SetFieldValue(0, 0, sport_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the SubSport field</summary> /// <returns>Returns nullable SubSport enum representing the SubSport field</returns> public SubSport? GetSubSport() { object obj = GetFieldValue(1, 0, Fit.SubfieldIndexMainField); SubSport? value = obj == null ? (SubSport?)null : (SubSport)obj; return value; } /// <summary> /// Set SubSport field</summary> /// <param name="subSport_">Nullable field value to be set</param> public void SetSubSport(SubSport? subSport_) { SetFieldValue(1, 0, subSport_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the StartDate field</summary> /// <returns>Returns DateTime representing the StartDate field</returns> public DateTime GetStartDate() { return TimestampToDateTime((uint?)GetFieldValue(2, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set StartDate field</summary> /// <param name="startDate_">Nullable field value to be set</param> public void SetStartDate(DateTime startDate_) { SetFieldValue(2, 0, startDate_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the EndDate field</summary> /// <returns>Returns DateTime representing the EndDate field</returns> public DateTime GetEndDate() { return TimestampToDateTime((uint?)GetFieldValue(3, 0, Fit.SubfieldIndexMainField)); } /// <summary> /// Set EndDate field</summary> /// <param name="endDate_">Nullable field value to be set</param> public void SetEndDate(DateTime endDate_) { SetFieldValue(3, 0, endDate_.GetTimeStamp(), Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Type field</summary> /// <returns>Returns nullable Goal enum representing the Type field</returns> new public Goal? GetType() { object obj = GetFieldValue(4, 0, Fit.SubfieldIndexMainField); Goal? value = obj == null ? (Goal?)null : (Goal)obj; return value; } /// <summary> /// Set Type field</summary> /// <param name="type_">Nullable field value to be set</param> public void SetType(Goal? type_) { SetFieldValue(4, 0, type_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Value field</summary> /// <returns>Returns nullable uint representing the Value field</returns> public uint? GetValue() { return (uint?)GetFieldValue(5, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set Value field</summary> /// <param name="value_">Nullable field value to be set</param> public void SetValue(uint? value_) { SetFieldValue(5, 0, value_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Repeat field</summary> /// <returns>Returns nullable Bool enum representing the Repeat field</returns> public Bool? GetRepeat() { object obj = GetFieldValue(6, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set Repeat field</summary> /// <param name="repeat_">Nullable field value to be set</param> public void SetRepeat(Bool? repeat_) { SetFieldValue(6, 0, repeat_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the TargetValue field</summary> /// <returns>Returns nullable uint representing the TargetValue field</returns> public uint? GetTargetValue() { return (uint?)GetFieldValue(7, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set TargetValue field</summary> /// <param name="targetValue_">Nullable field value to be set</param> public void SetTargetValue(uint? targetValue_) { SetFieldValue(7, 0, targetValue_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Recurrence field</summary> /// <returns>Returns nullable GoalRecurrence enum representing the Recurrence field</returns> public GoalRecurrence? GetRecurrence() { object obj = GetFieldValue(8, 0, Fit.SubfieldIndexMainField); GoalRecurrence? value = obj == null ? (GoalRecurrence?)null : (GoalRecurrence)obj; return value; } /// <summary> /// Set Recurrence field</summary> /// <param name="recurrence_">Nullable field value to be set</param> public void SetRecurrence(GoalRecurrence? recurrence_) { SetFieldValue(8, 0, recurrence_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the RecurrenceValue field</summary> /// <returns>Returns nullable ushort representing the RecurrenceValue field</returns> public ushort? GetRecurrenceValue() { return (ushort?)GetFieldValue(9, 0, Fit.SubfieldIndexMainField); } /// <summary> /// Set RecurrenceValue field</summary> /// <param name="recurrenceValue_">Nullable field value to be set</param> public void SetRecurrenceValue(ushort? recurrenceValue_) { SetFieldValue(9, 0, recurrenceValue_, Fit.SubfieldIndexMainField); } ///<summary> /// Retrieves the Enabled field</summary> /// <returns>Returns nullable Bool enum representing the Enabled field</returns> public Bool? GetEnabled() { object obj = GetFieldValue(10, 0, Fit.SubfieldIndexMainField); Bool? value = obj == null ? (Bool?)null : (Bool)obj; return value; } /// <summary> /// Set Enabled field</summary> /// <param name="enabled_">Nullable field value to be set</param> public void SetEnabled(Bool? enabled_) { SetFieldValue(10, 0, enabled_, Fit.SubfieldIndexMainField); } #endregion // Methods } // Class } // namespace
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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.Collections.Generic; using System.Text; using System.IO; using System.Xml; using WebsitePanel.Setup.Common; namespace WebsitePanel.Setup.Actions { public class SetWebPortalWebSettingsAction : Action, IPrepareDefaultsAction { public const string LogStartMessage = "Retrieving default IP address of the component..."; void IPrepareDefaultsAction.Run(SetupVariables vars) { // if (String.IsNullOrEmpty(vars.WebSitePort)) vars.WebSitePort = Global.WebPortal.DefaultPort; // if (String.IsNullOrEmpty(vars.UserAccount)) vars.UserAccount = Global.WebPortal.ServiceAccount; // By default we use public ip for the component if (String.IsNullOrEmpty(vars.WebSiteIP)) { var serverIPs = WebUtils.GetIPv4Addresses(); // if (serverIPs != null && serverIPs.Length > 0) { vars.WebSiteIP = serverIPs[0]; } else { vars.WebSiteIP = Global.LoopbackIPv4; } } } } public class UpdateEnterpriseServerUrlAction : Action, IInstallAction { public const string LogStartInstallMessage = "Updating site settings..."; void IInstallAction.Run(SetupVariables vars) { try { Begin(LogStartInstallMessage); // Log.WriteStart(LogStartInstallMessage); // var path = Path.Combine(vars.InstallationFolder, @"App_Data\SiteSettings.config"); // if (!File.Exists(path)) { Log.WriteInfo(String.Format("File {0} not found", path)); // return; } // var doc = new XmlDocument(); doc.Load(path); // var urlNode = doc.SelectSingleNode("SiteSettings/EnterpriseServer") as XmlElement; if (urlNode == null) { Log.WriteInfo("EnterpriseServer setting not found"); return; } urlNode.InnerText = vars.EnterpriseServerURL; doc.Save(path); // Log.WriteEnd("Updated site settings"); // InstallLog.AppendLine("- Updated site settings"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; // Log.WriteError("Site settigs error", ex); // throw; } } } public class GenerateSessionValidationKeyAction : Action, IInstallAction { public const string LogStartInstallMessage = "Generating session validation key..."; void IInstallAction.Run(SetupVariables vars) { try { Begin(LogStartInstallMessage); Log.WriteStart(LogStartInstallMessage); string path = Path.Combine(vars.InstallationFolder, "web.config"); if (!File.Exists(path)) { Log.WriteInfo(string.Format("File {0} not found", path)); return; } Log.WriteStart("Updating configuration file (session validation key)"); XmlDocument doc = new XmlDocument(); doc.Load(path); XmlElement sessionKey = doc.SelectSingleNode("configuration/appSettings/add[@key='SessionValidationKey']") as XmlElement; if (sessionKey == null) { Log.WriteInfo("SessionValidationKey setting not found"); return; } sessionKey.SetAttribute("value", StringUtils.GenerateRandomString(16)); doc.Save(path); Log.WriteEnd("Generated session validation key"); InstallLog.AppendLine("- Generated session validation key"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; // Log.WriteError("Site settigs error", ex); // throw; } } } public class CreateDesktopShortcutsAction : Action, IInstallAction { public const string LogStartInstallMessage = "Creating shortcut..."; public const string ApplicationUrlNotFoundMessage = "Application url not found"; public const string Path2 = "WebsitePanel Software"; void IInstallAction.Run(SetupVariables vars) { // try { Begin(LogStartInstallMessage); // Log.WriteStart(LogStartInstallMessage); // var urls = Utils.GetApplicationUrls(vars.WebSiteIP, vars.WebSiteDomain, vars.WebSitePort, null); string url = null; if (urls.Length == 0) { Log.WriteInfo(ApplicationUrlNotFoundMessage); // return; } // Retrieve top-most url from the list url = "http://" + urls[0]; // Log.WriteStart("Creating menu shortcut"); // string programs = Environment.GetFolderPath(Environment.SpecialFolder.Programs); string fileName = "Login to WebsitePanel.url"; string path = Path.Combine(programs, Path2); // if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // WriteShortcutData(Path.Combine(path, fileName), url); // Log.WriteEnd("Created menu shortcut"); // Log.WriteStart("Creating desktop shortcut"); // string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); WriteShortcutData(Path.Combine(desktop, fileName), url); // Log.WriteEnd("Created desktop shortcut"); // InstallLog.AppendLine("- Created application shortcuts"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; // Log.WriteError("Create shortcut error", ex); } } private static void WriteShortcutData(string filePath, string url) { string iconFile = Path.Combine(Environment.SystemDirectory, "url.dll"); // using (StreamWriter sw = File.CreateText(filePath)) { sw.WriteLine("[InternetShortcut]"); sw.WriteLine("URL=" + url); sw.WriteLine("IconFile=" + iconFile); sw.WriteLine("IconIndex=0"); sw.WriteLine("HotKey=0"); // Log.WriteInfo(String.Format("Shortcut url: {0}", url)); } } } public class CopyWebConfigAction : Action, IInstallAction { void IInstallAction.Run(SetupVariables vars) { try { Log.WriteStart("Copying web.config"); string configPath = Path.Combine(vars.InstallationFolder, "web.config"); string config6Path = Path.Combine(vars.InstallationFolder, "web6.config"); bool iis6 = (vars.IISVersion.Major == 6); if (!File.Exists(config6Path)) { Log.WriteInfo(string.Format("File {0} not found", config6Path)); return; } if (iis6) { if (!File.Exists(configPath)) { Log.WriteInfo(string.Format("File {0} not found", configPath)); return; } FileUtils.DeleteFile(configPath); File.Move(config6Path, configPath); } else { FileUtils.DeleteFile(config6Path); } Log.WriteEnd("Copied web.config"); } catch (Exception ex) { if (Utils.IsThreadAbortException(ex)) return; // Log.WriteError("Copy web.config error", ex); // throw; } } } public class WebPortalActionManager : BaseActionManager { public static readonly List<Action> InstallScenario = new List<Action> { new SetCommonDistributiveParamsAction(), new SetWebPortalWebSettingsAction(), new EnsureServiceAccntSecured(), new CopyFilesAction(), new CopyWebConfigAction(), new CreateWindowsAccountAction(), new ConfigureAspNetTempFolderPermissionsAction(), new SetNtfsPermissionsAction(), new CreateWebApplicationPoolAction(), new CreateWebSiteAction(), new SwitchAppPoolAspNetVersion(), new UpdateEnterpriseServerUrlAction(), new GenerateSessionValidationKeyAction(), new SaveComponentConfigSettingsAction(), new CreateDesktopShortcutsAction() }; public WebPortalActionManager(SetupVariables sessionVars) : base(sessionVars) { Initialize += new EventHandler(WebPortalActionManager_Initialize); } void WebPortalActionManager_Initialize(object sender, EventArgs e) { // switch (SessionVariables.SetupAction) { case SetupActions.Install: // Install LoadInstallationScenario(); break; } } private void LoadInstallationScenario() { CurrentScenario.AddRange(InstallScenario); } } }
// // Options.cs // // Authors: // Jonathan Pryor <[email protected]> // Federico Di Gregorio <[email protected]> // Rolf Bjarne Kvinge <[email protected]> // // Copyright (C) 2008 Novell (http://www.novell.com) // Copyright (C) 2009 Federico Di Gregorio. // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com) // // 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. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // #if LINQ using System.Linq; #endif #if TEST using NDesk.Options; #endif #if NDESK_OPTIONS namespace NDesk.Options #else namespace Mono.Options #endif { using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; static class StringCoda { public static IEnumerable<string> WrappedLines(string self, params int[] widths) { IEnumerable<int> w = widths; return WrappedLines(self, w); } public static IEnumerable<string> WrappedLines(string self, IEnumerable<int> widths) { if (widths == null) throw new ArgumentNullException("widths"); return CreateWrappedLinesIterator(self, widths); } static IEnumerable<string> CreateWrappedLinesIterator(string self, IEnumerable<int> widths) { if (string.IsNullOrEmpty(self)) { yield return string.Empty; yield break; } using (IEnumerator<int> ewidths = widths.GetEnumerator()) { bool? hw = null; int width = GetNextWidth(ewidths, int.MaxValue, ref hw); int start = 0, end; do { end = GetLineEnd(start, width, self); char c = self[end - 1]; if (char.IsWhiteSpace(c)) --end; bool needContinuation = end != self.Length && !IsEolChar(c); string continuation = ""; if (needContinuation) { --end; continuation = "-"; } string line = self.Substring(start, end - start) + continuation; yield return line; start = end; if (char.IsWhiteSpace(c)) ++start; width = GetNextWidth(ewidths, width, ref hw); } while (start < self.Length); } } static int GetNextWidth(IEnumerator<int> ewidths, int curWidth, ref bool? eValid) { if (!eValid.HasValue || (eValid.HasValue && eValid.Value)) { curWidth = (eValid = ewidths.MoveNext()).Value ? ewidths.Current : curWidth; // '.' is any character, - is for a continuation const string minWidth = ".-"; if (curWidth < minWidth.Length) throw new ArgumentOutOfRangeException("widths", string.Format("Element must be >= {0}, was {1}.", minWidth.Length, curWidth)); return curWidth; } // no more elements, use the last element. return curWidth; } static bool IsEolChar(char c) { return !char.IsLetterOrDigit(c); } static int GetLineEnd(int start, int length, string description) { int end = Math.Min(start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { if (description[i] == '\n') return i + 1; if (IsEolChar(description[i])) sep = i + 1; } if (sep == -1 || end == description.Length) return end; return sep; } } public class OptionValueCollection : IList, IList<string> { readonly OptionContext c; readonly List<string> values = new List<string>(); internal OptionValueCollection(OptionContext c) { this.c = c; } #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator() { return values.GetEnumerator(); } #endregion public List<string> ToList() { return new List<string>(values); } public string[] ToArray() { return values.ToArray(); } public override string ToString() { return string.Join(", ", values.ToArray()); } #region ICollection void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); } bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } } object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } } #endregion #region ICollection<T> public void Add(string item) { values.Add(item); } public void Clear() { values.Clear(); } public bool Contains(string item) { return values.Contains(item); } public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); } public bool Remove(string item) { return values.Remove(item); } public int Count { get { return values.Count; } } public bool IsReadOnly { get { return false; } } #endregion #region IList int IList.Add(object value) { return (values as IList).Add(value); } bool IList.Contains(object value) { return (values as IList).Contains(value); } int IList.IndexOf(object value) { return (values as IList).IndexOf(value); } void IList.Insert(int index, object value) { (values as IList).Insert(index, value); } void IList.Remove(object value) { (values as IList).Remove(value); } void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); } bool IList.IsFixedSize { get { return false; } } object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } } #endregion #region IList<T> public int IndexOf(string item) { return values.IndexOf(item); } public void Insert(int index, string item) { values.Insert(index, item); } public void RemoveAt(int index) { values.RemoveAt(index); } void AssertValid(int index) { if (c.Option == null) throw new InvalidOperationException("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException(string.Format( c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } public string this[int index] { get { AssertValid(index); return index >= values.Count ? null : values[index]; } set { values[index] = value; } } #endregion } public class OptionContext { public OptionContext(OptionSet set) { OptionSet = set; OptionValues = new OptionValueCollection(this); } public Option Option { get; set; } public string OptionName { get; set; } public int OptionIndex { get; set; } public OptionSet OptionSet { get; } public OptionValueCollection OptionValues { get; } } public enum OptionValueType { None, Optional, Required } public abstract class Option { static readonly char[] NameTerminator = {'=', ':'}; protected Option(string prototype, string description) : this(prototype, description, 1, false) { } protected Option(string prototype, string description, int maxValueCount) : this(prototype, description, maxValueCount, false) { } protected Option(string prototype, string description, int maxValueCount, bool hidden) { if (prototype == null) throw new ArgumentNullException("prototype"); if (prototype.Length == 0) throw new ArgumentException("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException("maxValueCount"); Prototype = prototype; Description = description; MaxValueCount = maxValueCount; Names = (this is OptionSet.Category) // append GetHashCode() so that "duplicate" categories have distinct // names, e.g. adding multiple "" categories should be valid. ? new[] {prototype + GetHashCode()} : prototype.Split('|'); if (this is OptionSet.Category) return; OptionValueType = ParsePrototype(); Hidden = hidden; if (MaxValueCount == 0 && OptionValueType != OptionValueType.None) throw new ArgumentException( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (OptionValueType == OptionValueType.None && maxValueCount > 1) throw new ArgumentException( string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf(Names, "<>") >= 0 && ((Names.Length == 1 && OptionValueType != OptionValueType.None) || (Names.Length > 1 && MaxValueCount > 1))) throw new ArgumentException( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype { get; } public string Description { get; } public OptionValueType OptionValueType { get; } public int MaxValueCount { get; } public bool Hidden { get; } internal string[] Names { get; } internal string[] ValueSeparators { get; set; } public string[] GetNames() { return (string[]) Names.Clone(); } public string[] GetValueSeparators() { if (ValueSeparators == null) return new string[0]; return (string[]) ValueSeparators.Clone(); } protected static T Parse<T>(string value, OptionContext c) { Type tt = typeof (T); bool nullable = tt.IsValueType && tt.IsGenericType && !tt.IsGenericTypeDefinition && tt.GetGenericTypeDefinition() == typeof (Nullable<>); Type targetType = nullable ? tt.GetGenericArguments()[0] : typeof (T); TypeConverter conv = TypeDescriptor.GetConverter(targetType); T t = default(T); try { if (value != null) t = (T) conv.ConvertFromString(value); } catch (Exception e) { throw new OptionException( string.Format( c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."), value, targetType.Name, c.OptionName), c.OptionName, e); } return t; } OptionValueType ParsePrototype() { char type = '\0'; List<string> seps = new List<string>(); for (int i = 0; i < Names.Length; ++i) { string name = Names[i]; if (name.Length == 0) throw new ArgumentException("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny(NameTerminator); if (end == -1) continue; Names[i] = name.Substring(0, end); if (type == '\0' || type == name[end]) type = name[end]; else throw new ArgumentException( string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]), "prototype"); AddSeparators(name, end, seps); } if (type == '\0') return OptionValueType.None; if (MaxValueCount <= 1 && seps.Count != 0) throw new ArgumentException( string.Format("Cannot provide key/value separators for Options taking {0} value(s).", MaxValueCount), "prototype"); if (MaxValueCount > 1) { if (seps.Count == 0) ValueSeparators = new[] {":", "="}; else if (seps.Count == 1 && seps[0].Length == 0) ValueSeparators = null; else ValueSeparators = seps.ToArray(); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } static void AddSeparators(string name, int end, ICollection<string> seps) { int start = -1; for (int i = end + 1; i < name.Length; ++i) { switch (name[i]) { case '{': if (start != -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i + 1; break; case '}': if (start == -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add(name.Substring(start, i - start)); start = -1; break; default: if (start == -1) seps.Add(name[i].ToString()); break; } } if (start != -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke(OptionContext c) { OnParseComplete(c); c.OptionName = null; c.Option = null; c.OptionValues.Clear(); } protected abstract void OnParseComplete(OptionContext c); public override string ToString() { return Prototype; } } public abstract class ArgumentSource { public abstract string Description { get; } public abstract string[] GetNames(); public abstract bool GetArguments(string value, out IEnumerable<string> replacement); public static IEnumerable<string> GetArgumentsFromFile(string file) { return GetArguments(File.OpenText(file), true); } public static IEnumerable<string> GetArguments(TextReader reader) { return GetArguments(reader, false); } // Cribbed from mcs/driver.cs:LoadArgs(string) static IEnumerable<string> GetArguments(TextReader reader, bool close) { try { StringBuilder arg = new StringBuilder(); string line; while ((line = reader.ReadLine()) != null) { int t = line.Length; for (int i = 0; i < t; i++) { char c = line[i]; if (c == '"' || c == '\'') { char end = c; for (i++; i < t; i++) { c = line[i]; if (c == end) break; arg.Append(c); } } else if (c == ' ') { if (arg.Length > 0) { yield return arg.ToString(); arg.Length = 0; } } else arg.Append(c); } if (arg.Length > 0) { yield return arg.ToString(); arg.Length = 0; } } } finally { if (close) reader.Close(); } } } public class ResponseFileSource : ArgumentSource { public override string Description { get { return "Read response file for more options."; } } public override string[] GetNames() { return new[] {"@file"}; } public override bool GetArguments(string value, out IEnumerable<string> replacement) { if (string.IsNullOrEmpty(value) || !value.StartsWith("@")) { replacement = null; return false; } replacement = GetArgumentsFromFile(value.Substring(1)); return true; } } [Serializable] public class OptionException : Exception { public OptionException() { } public OptionException(string message, string optionName) : base(message) { OptionName = optionName; } public OptionException(string message, string optionName, Exception innerException) : base(message, innerException) { OptionName = optionName; } protected OptionException(SerializationInfo info, StreamingContext context) : base(info, context) { OptionName = info.GetString("OptionName"); } public string OptionName { get; } #pragma warning disable 618 // SecurityPermissionAttribute is obsolete [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] #pragma warning restore 618 public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("OptionName", OptionName); } } public delegate void OptionAction<TKey, TValue>(TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { const int OptionWidth = 29; const int Description_FirstWidth = 80 - OptionWidth; const int Description_RemWidth = 80 - OptionWidth - 2; readonly List<ArgumentSource> sources = new List<ArgumentSource>(); readonly Regex ValueOption = new Regex( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); public OptionSet() : this(delegate(string f) { return f; }) { } public OptionSet(Converter<string, string> localizer) { MessageLocalizer = localizer; ArgumentSources = new ReadOnlyCollection<ArgumentSource>(sources); } public Converter<string, string> MessageLocalizer { get; } public ReadOnlyCollection<ArgumentSource> ArgumentSources { get; } protected override string GetKeyForItem(Option item) { if (item == null) throw new ArgumentNullException("option"); if (item.Names != null && item.Names.Length > 0) return item.Names[0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException("Option has no names!"); } [Obsolete("Use KeyedCollection.this[string]")] protected Option GetOptionForName(string option) { if (option == null) throw new ArgumentNullException("option"); try { return base[option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem(int index, Option item) { base.InsertItem(index, item); AddImpl(item); } protected override void RemoveItem(int index) { Option p = Items[index]; base.RemoveItem(index); // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove(p.Names[i]); } } protected override void SetItem(int index, Option item) { base.SetItem(index, item); AddImpl(item); } void AddImpl(Option option) { if (option == null) throw new ArgumentNullException("option"); List<string> added = new List<string>(option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add(option.Names[i], option); added.Add(option.Names[i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove(name); throw; } } public OptionSet Add(string header) { if (header == null) throw new ArgumentNullException("header"); Add(new Category(header)); return this; } public new OptionSet Add(Option option) { base.Add(option); return this; } public OptionSet Add(string prototype, Action<string> action) { return Add(prototype, null, action); } public OptionSet Add(string prototype, string description, Action<string> action) { return Add(prototype, description, action, false); } public OptionSet Add(string prototype, string description, Action<string> action, bool hidden) { if (action == null) throw new ArgumentNullException("action"); Option p = new ActionOption(prototype, description, 1, delegate(OptionValueCollection v) { action(v[0]); }, hidden); base.Add(p); return this; } public OptionSet Add(string prototype, OptionAction<string, string> action) { return Add(prototype, null, action); } public OptionSet Add(string prototype, string description, OptionAction<string, string> action) { return Add(prototype, description, action, false); } public OptionSet Add(string prototype, string description, OptionAction<string, string> action, bool hidden) { if (action == null) throw new ArgumentNullException("action"); Option p = new ActionOption(prototype, description, 2, delegate(OptionValueCollection v) { action(v[0], v[1]); }, hidden); base.Add(p); return this; } public OptionSet Add<T>(string prototype, Action<T> action) { return Add(prototype, null, action); } public OptionSet Add<T>(string prototype, string description, Action<T> action) { return Add(new ActionOption<T>(prototype, description, action)); } public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action) { return Add(prototype, null, action); } public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action) { return Add(new ActionOption<TKey, TValue>(prototype, description, action)); } public OptionSet Add(ArgumentSource source) { if (source == null) throw new ArgumentNullException("source"); sources.Add(source); return this; } protected virtual OptionContext CreateOptionContext() { return new OptionContext(this); } public List<string> Parse(IEnumerable<string> arguments) { if (arguments == null) throw new ArgumentNullException("arguments"); OptionContext c = CreateOptionContext(); c.OptionIndex = -1; bool process = true; List<string> unprocessed = new List<string>(); Option def = Contains("<>") ? this["<>"] : null; ArgumentEnumerator ae = new ArgumentEnumerator(arguments); foreach (string argument in ae) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed(unprocessed, def, c, argument); continue; } if (AddSource(ae, argument)) continue; if (!Parse(argument, c)) Unprocessed(unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke(c); return unprocessed; } bool AddSource(ArgumentEnumerator ae, string argument) { foreach (ArgumentSource source in sources) { IEnumerable<string> replacement; if (!source.GetArguments(argument, out replacement)) continue; ae.Add(replacement); return true; } return false; } static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add(argument); return false; } c.OptionValues.Add(argument); c.Option = def; c.Option.Invoke(c); return false; } protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException("argument"); flag = name = sep = value = null; Match m = ValueOption.Match(argument); if (!m.Success) { return false; } flag = m.Groups["flag"].Value; name = m.Groups["name"].Value; if (m.Groups["sep"].Success && m.Groups["value"].Success) { sep = m.Groups["sep"].Value; value = m.Groups["value"].Value; } return true; } protected virtual bool Parse(string argument, OptionContext c) { if (c.Option != null) { ParseValue(argument, c); return true; } string f, n, s, v; if (!GetOptionParts(argument, out f, out n, out s, out v)) return false; Option p; if (Contains(n)) { p = this[n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add(n); c.Option.Invoke(c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue(v, c); break; } return true; } // no match; is it a bool option? if (ParseBool(argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue(f, string.Concat(n + s + v), c)) return true; return false; } void ParseValue(string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split(c.Option.ValueSeparators, c.Option.MaxValueCount - c.OptionValues.Count, StringSplitOptions.None) : new[] {option}) { c.OptionValues.Add(o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke(c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException(MessageLocalizer(string.Format( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } bool ParseBool(string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') && Contains((rn = n.Substring(0, n.Length - 1)))) { p = this[rn]; string v = n[n.Length - 1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add(v); p.Invoke(c); return true; } return false; } bool ParseBundledValue(string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n[i]; string rn = n[i].ToString(); if (!Contains(rn)) { if (i == 0) return false; throw new OptionException(string.Format(MessageLocalizer( "Cannot use unregistered option '{0}' in bundle '{1}'."), rn, f + n), null); } p = this[rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke(c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring(i + 1); c.Option = p; c.OptionName = opt; ParseValue(v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType); } } return true; } static void Invoke(OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add(value); option.Invoke(c); } public void WriteOptionDescriptions(TextWriter o) { foreach (Option p in this) { int written = 0; if (p.Hidden) continue; Category c = p as Category; if (c != null) { WriteDescription(o, p.Description, "", 80, 80); continue; } if (!WriteOptionPrototype(o, p, ref written)) continue; if (written < OptionWidth) o.Write(new string(' ', OptionWidth - written)); else { o.WriteLine(); o.Write(new string(' ', OptionWidth)); } WriteDescription(o, p.Description, new string(' ', OptionWidth + 2), Description_FirstWidth, Description_RemWidth); } foreach (ArgumentSource s in sources) { string[] names = s.GetNames(); if (names == null || names.Length == 0) continue; int written = 0; Write(o, ref written, " "); Write(o, ref written, names[0]); for (int i = 1; i < names.Length; ++i) { Write(o, ref written, ", "); Write(o, ref written, names[i]); } if (written < OptionWidth) o.Write(new string(' ', OptionWidth - written)); else { o.WriteLine(); o.Write(new string(' ', OptionWidth)); } WriteDescription(o, s.Description, new string(' ', OptionWidth + 2), Description_FirstWidth, Description_RemWidth); } } void WriteDescription(TextWriter o, string value, string prefix, int firstWidth, int remWidth) { bool indent = false; foreach (string line in GetLines(MessageLocalizer(GetDescription(value)), firstWidth, remWidth)) { if (indent) o.Write(prefix); o.WriteLine(line); indent = true; } } bool WriteOptionPrototype(TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex(names, 0); if (i == names.Length) return false; if (names[i].Length == 1) { Write(o, ref written, " -"); Write(o, ref written, names[0]); } else { Write(o, ref written, " --"); Write(o, ref written, names[0]); } for (i = GetNextOptionIndex(names, i + 1); i < names.Length; i = GetNextOptionIndex(names, i + 1)) { Write(o, ref written, ", "); Write(o, ref written, names[i].Length == 1 ? "-" : "--"); Write(o, ref written, names[i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write(o, ref written, MessageLocalizer("[")); } Write(o, ref written, MessageLocalizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators[0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write(o, ref written, MessageLocalizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write(o, ref written, MessageLocalizer("]")); } } return true; } static int GetNextOptionIndex(string[] names, int i) { while (i < names.Length && names[i] == "<>") { ++i; } return i; } static void Write(TextWriter o, ref int n, string s) { n += s.Length; o.Write(s); } static string GetArgumentName(int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new[] {"{0:", "{"}; else nameStart = new[] {"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf(nameStart[i], j); } while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf("}", start); if (end == -1) continue; return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } static string GetDescription(string description) { if (description == null) return string.Empty; StringBuilder sb = new StringBuilder(description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description[i]) { case '{': if (i == start) { sb.Append('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i + 1) == description.Length || description[i + 1] != '}') throw new InvalidOperationException("Invalid option description: " + description); ++i; sb.Append("}"); } else { sb.Append(description.Substring(start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append(description[i]); break; } } return sb.ToString(); } static IEnumerable<string> GetLines(string description, int firstWidth, int remWidth) { return StringCoda.WrappedLines(description, firstWidth, remWidth); } internal sealed class Category : Option { // Prototype starts with '=' because this is an invalid prototype // (see Option.ParsePrototype(), and thus it'll prevent Category // instances from being accidentally used as normal options. public Category(string description) : base("=:Category:= " + description, description) { } protected override void OnParseComplete(OptionContext c) { throw new NotSupportedException("Category.OnParseComplete should not be invoked."); } } sealed class ActionOption : Option { readonly Action<OptionValueCollection> action; public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action) : this(prototype, description, count, action, false) { } public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action, bool hidden) : base(prototype, description, count, hidden) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action(c.OptionValues); } } sealed class ActionOption<T> : Option { readonly Action<T> action; public ActionOption(string prototype, string description, Action<T> action) : base(prototype, description, 1) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action(Parse<T>(c.OptionValues[0], c)); } } sealed class ActionOption<TKey, TValue> : Option { readonly OptionAction<TKey, TValue> action; public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action) : base(prototype, description, 2) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action( Parse<TKey>(c.OptionValues[0], c), Parse<TValue>(c.OptionValues[1], c)); } } class ArgumentEnumerator : IEnumerable<string> { readonly List<IEnumerator<string>> sources = new List<IEnumerator<string>>(); public ArgumentEnumerator(IEnumerable<string> arguments) { sources.Add(arguments.GetEnumerator()); } public IEnumerator<string> GetEnumerator() { do { IEnumerator<string> c = sources[sources.Count - 1]; if (c.MoveNext()) yield return c.Current; else { c.Dispose(); sources.RemoveAt(sources.Count - 1); } } while (sources.Count > 0); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(IEnumerable<string> arguments) { sources.Add(arguments.GetEnumerator()); } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using LRWarehouse.Business; using LearningRegistryCache2.App_Code.Classes; using Isle.BizServices; namespace LearningRegistryCache2 { public class BaseDataController { private List<ProhibitedKeyword> prohibitedKeywords; protected ImportServices importManager; public ResourceBizService resourceBizService; private AuditReportingServices auditReportingManager; public static List<ManualResetEvent> doneEvents = new List<ManualResetEvent>(1000); public BaseDataController() { importManager = new ImportServices(); resourceBizService = new ResourceBizService(); auditReportingManager = new AuditReportingServices(); string status = "successful"; prohibitedKeywords = importManager.GetProhibitedKeywordRules(ref status); } #region === Keyword Helper Methods === /// <summary> /// Adds one or more keywords to a resource /// </summary> /// <param name="resource"></param> /// <param name="record"></param> /// <param name="tagName"></param> public void AddKeywords(Resource resource, XmlDocument record, string tagName, ref string message) { message = ""; int nbrKeywords = 0; int maxKeywords = int.Parse(ConfigurationManager.AppSettings["maxKeywordsToProcess"].ToString()); // Speed processing - some people are submitting hundreds of keywords!!! bool isProhibitedKeyword = false; XmlNodeList list = record.GetElementsByTagName(tagName); List<string> keywordSubstrings = prohibitedKeywords.Where(x => x.IsRegex == false).Select(x => x.Keyword).ToList(); List<string> keywordExpressionStrings = prohibitedKeywords.Where(x => x.IsRegex == true).Select(x => x.Keyword).ToList(); foreach (XmlNode node in list) { string keyword = node.InnerText.Trim(); if (keywordSubstrings.Any(x => keyword.IndexOf(x) > -1)) { isProhibitedKeyword = true; } if (!isProhibitedKeyword) { foreach (string keywordExpression in keywordExpressionStrings) { Regex rex = new Regex(keywordExpression, RegexOptions.IgnoreCase); if (rex.IsMatch(keyword)) { isProhibitedKeyword = true; break; } } } if (!isProhibitedKeyword) { nbrKeywords++; if (maxKeywords > 0 && nbrKeywords > maxKeywords) { message += string.Format("Number of keywords exceeds {0}. First {0}/{1} keywords processed, remainder ignored. ", maxKeywords, list.Count); break; } AddKeyword(resource, keyword); } } } /// <summary> /// Adds a single keyword to the database /// </summary> /// <param name="resource"></param> /// <param name="keyword"></param> public void AddKeyword(Resource resource, string keyword) { string status = "successful"; int amp = keyword.IndexOf("&"); int scolon = keyword.IndexOf(";"); if (scolon > -1 && amp == -1) { // key contains ";" but does not contain "&" (ie contains semicolon but no HTML entities), so split by semicolon string[] keyList = keyword.Split(';'); foreach (string keyItem in keyList) { if (!SkipKey(keyItem)) { string key = ApplyKeyEditRules(keyItem); ResourceChildItem keys = new ResourceChildItem(); //keys.ResourceId = resource.RowId; keys.ResourceIntId = resource.Id; keys.OriginalValue = key; importManager.CreateKeyword(keys, ref status); if (status != "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, "", resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } } } else if (!SkipKey(keyword)) { keyword = ApplyKeyEditRules(keyword); ResourceChildItem keys = new ResourceChildItem(); //keys.ResourceId = resource.RowId; keys.ResourceIntId = resource.Id; keys.OriginalValue = keyword; importManager.CreateKeyword(keys, ref status); if (status != "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, "", resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } }// AddKeyword /// <summary> /// Checks to see if a keyword should be skipped. Returns true if keyword should be skipped. /// </summary> /// <param name="keyword"></param> /// <returns></returns> private bool SkipKey(string keyword) { bool retVal = false; if (keyword.Length > 2 && keyword.Substring(0, 1) == "\"" && keyword.Substring(keyword.Length - 1, 1) == "\"") { // keyword begins and ends with a quotation mark. Check for internal quotes. Note that stripping quotes requires the string to be at least 2 characters long. string tKey = keyword.Substring(1, keyword.Length - 2); if (tKey.IndexOf("\"") == -1) { // no internal quotes found, strip quotes keyword = keyword.Replace("\"", ""); } } if (keyword.Length == 0) { retVal = true; } if (keyword.IndexOf("http:") > -1 || keyword.IndexOf("https:") > -1) { retVal = true; } if (keyword == "LRE" || keyword == "LRE4" || keyword == "learning resource exchange" || keyword == "LRE metadata application profile" || keyword == "LOM" || keyword == "EUN" || keyword == "ilox" || keyword == "needs" || keyword == "lr-test-data" || keyword.IndexOf("ncs-NSDL-COLLECTION") > -1) { retVal = true; } try { float f = float.Parse(keyword); retVal = true; } catch { // Do nothing, just checking to see if key is numeric. It isn't so keep it. } return retVal; }// SkipKey /// <summary> /// Applies key edit rules to keyword /// </summary> /// <param name="keyword"></param> /// <returns></returns> private string ApplyKeyEditRules(string keyword) { if (keyword.Length > 2 && keyword.Substring(0, 1) == "\"" && keyword.Substring(keyword.Length - 1, 1) == "\"") { // keyword begins and ends with a quotation mark. Check for internal quotes. Note that stripping quotes requires the string to be at least 2 characters long. string tKey = keyword.Substring(1, keyword.Length - 2); if (tKey.IndexOf("\"") == -1) { // no internal quotes found, strip quotes keyword = keyword.Replace("\"", ""); } } return keyword; } #endregion #region === Career Cluster Helpers === public void AddCareerClusters(Resource resource, XmlDocument payload) { string status = ""; XmlNodeList list = payload.GetElementsByTagName("careerCluster"); foreach (XmlNode node in list) { ResourceCluster cluster = new ResourceCluster(); cluster.ResourceIntId = resource.Id; cluster.ClusterId = 0; cluster.Title = TrimWhitespace(node.InnerText); status = importManager.ImportCluster(cluster); if (status != "successful") { auditReportingManager.LogMessage(LearningRegistry.reportId, LearningRegistry.fileName, resource.Version.LRDocId, resource.ResourceUrl, ErrorType.Error, ErrorRouting.Technical, status); } } } //AddCareerClusters #endregion #region Helper Methods private bool IsNumeric(string param) { try { double dbl = double.Parse(param); } catch (Exception ex) { return false; } return true; } private bool IsDate(string param) { try { DateTime dt = DateTime.Parse(param); } catch (Exception ex) { return false; } return true; } protected bool IsGoodTitle(string title, ref string message) { bool retVal = true; StringBuilder sb = new StringBuilder(); if (IsNumeric(title)) { retVal = false; sb.Append(" Title is numeric;"); } if (title.Length <= 10 && IsDate(title)) { retVal = false; sb.Append(" Title is a date;"); } if (title.Length < 6) { retVal = false; sb.Append(" Title does not meet minimum length requirements;"); } if (sb.ToString().Length > 0) { message = "Title does not meet requirements:" + sb.ToString(); } else { message = "OK"; } return retVal; } /// <summary> /// Returns the signer field of an LR document /// </summary> /// <param name="xdoc"></param> /// <returns></returns> public string GetSigner(XmlDocument xdoc) { string retVal = ""; XmlNodeList list; list = xdoc.GetElementsByTagName("signer"); if (list == null || list.Count == 0) { list = xdoc.GetElementsByTagName("submitter"); } if (list != null && list.Count != 0) { retVal = list[0].InnerText; int pos = retVal.ToLower().IndexOf("on behalf of"); if (pos > -1) { retVal = retVal.Substring(0, pos); } } retVal = TrimWhitespace(retVal); return retVal; } /// <summary> /// Regular "Trim()" does not handle \r and \n. This handles it. /// </summary> /// <param name="str"></param> /// <returns></returns> public string TrimWhitespace(string str) { Regex leadingWhitespace = new Regex(@"^\s+"); Regex trailingWhitespace = new Regex(@"\s+$"); str = leadingWhitespace.Replace(str, ""); str = trailingWhitespace.Replace(str, ""); return str; } public static bool DoesDataSetHaveRows(DataSet ds) { if (ds == null) return false; if (ds.Tables == null || ds.Tables.Count == 0) return false; if (ds.Tables[0].Rows == null || ds.Tables[0].Rows.Count == 0) return false; return true; } public static int GetRowColumn(DataRow dr, string columnName, int defaultValue) { int retVal = defaultValue; try { retVal = int.Parse(dr[columnName].ToString()); } catch { // do nothing } return retVal; } public static int GetRowColumn(SqlDataReader dr, string columnName, int defaultValue) { int retVal = defaultValue; try { retVal = int.Parse(dr[columnName].ToString()); } catch { // do nothing } return retVal; } public static DateTime GetRowColumn(SqlDataReader dr, string columnName, DateTime defaultValue) { DateTime retVal = defaultValue; try { retVal = DateTime.Parse(dr[columnName].ToString()); } catch { // do nothing } return retVal; } public static DateTime GetRowColumn(DataRow dr, string columnName, DateTime defaultValue) { DateTime retVal = defaultValue; try { retVal = DateTime.Parse(dr[columnName].ToString()); } catch { // do nothing } return retVal; } public static string GetRowColumn(DataRow dr, string columnName, string defaultValue) { string retVal = defaultValue; try { retVal = dr[columnName].ToString(); } catch { // do nothing } return retVal; } public static string GetRowColumn(SqlDataReader dr, string columnName, string defaultValue) { string retVal = defaultValue; try { retVal = dr[columnName].ToString(); } catch { // do nothing } return retVal; } protected string StripTrailingPeriod(string input) { Regex trailingPeriod = new Regex(@"\.+$"); // backslash escapes the period so that it is interpreted as an actual period, + makes it greedy, $ asserts end of string if (input == null) { return null; } string output = trailingPeriod.Replace(input, ""); return output; } protected string FixPlusesInUrl(string input) { string retVal = ""; if (input.IndexOf("+") == -1) { // There are no + signs, return what was input return input; } int posQuestionMark = input.IndexOf("?"); if (posQuestionMark == -1) { retVal = input.Replace("+", "%20"); } else { string originalPage = input.Substring(0, posQuestionMark); string newPage = originalPage.Replace("+", "%20"); retVal = input.Replace(originalPage, newPage); } return retVal; } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type uint with 2 columns and 2 rows. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct umat2 : IEnumerable<uint>, IEquatable<umat2> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> public uint m00; /// <summary> /// Column 0, Rows 1 /// </summary> public uint m01; /// <summary> /// Column 1, Rows 0 /// </summary> public uint m10; /// <summary> /// Column 1, Rows 1 /// </summary> public uint m11; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public umat2(uint m00, uint m01, uint m10, uint m11) { this.m00 = m00; this.m01 = m01; this.m10 = m10; this.m11 = m11; } /// <summary> /// Constructs this matrix from a umat2. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a umat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a umat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a umat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a umat3. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a umat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a umat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a umat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a umat4. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(umat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m10 = m.m10; this.m11 = m.m11; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public umat2(uvec2 c0, uvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m10 = c1.x; this.m11 = c1.y; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public uint[,] Values => new[,] { { m00, m01 }, { m10, m11 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public uint[] Values1D => new[] { m00, m01, m10, m11 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public uvec2 Column0 { get { return new uvec2(m00, m01); } set { m00 = value.x; m01 = value.y; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public uvec2 Column1 { get { return new uvec2(m10, m11); } set { m10 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public uvec2 Row0 { get { return new uvec2(m00, m10); } set { m00 = value.x; m10 = value.y; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public uvec2 Row1 { get { return new uvec2(m01, m11); } set { m01 = value.x; m11 = value.y; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static umat2 Zero { get; } = new umat2(0u, 0u, 0u, 0u); /// <summary> /// Predefined all-ones matrix /// </summary> public static umat2 Ones { get; } = new umat2(1u, 1u, 1u, 1u); /// <summary> /// Predefined identity matrix /// </summary> public static umat2 Identity { get; } = new umat2(1u, 0u, 0u, 1u); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static umat2 AllMaxValue { get; } = new umat2(uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static umat2 DiagonalMaxValue { get; } = new umat2(uint.MaxValue, 0u, 0u, uint.MaxValue); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static umat2 AllMinValue { get; } = new umat2(uint.MinValue, uint.MinValue, uint.MinValue, uint.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static umat2 DiagonalMinValue { get; } = new umat2(uint.MinValue, 0u, 0u, uint.MinValue); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<uint> GetEnumerator() { yield return m00; yield return m01; yield return m10; yield return m11; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (2 x 2 = 4). /// </summary> public int Count => 4; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public uint this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m10; case 3: return m11; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m10 = value; break; case 3: this.m11 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public uint this[int col, int row] { get { return this[col * 2 + row]; } set { this[col * 2 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(umat2 rhs) => ((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is umat2 && Equals((umat2) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(umat2 lhs, umat2 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(umat2 lhs, umat2 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public umat2 Transposed => new umat2(m00, m10, m01, m11); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public uint MinElement => Math.Min(Math.Min(Math.Min(m00, m01), m10), m11); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public uint MaxElement => Math.Max(Math.Max(Math.Max(m00, m01), m10), m11); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public float Length => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public float LengthSqr => ((m00*m00 + m01*m01) + (m10*m10 + m11*m11)); /// <summary> /// Returns the sum of all fields. /// </summary> public uint Sum => ((m00 + m01) + (m10 + m11)); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public float Norm => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public float Norm1 => ((m00 + m01) + (m10 + m11)); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public float Norm2 => (float)Math.Sqrt(((m00*m00 + m01*m01) + (m10*m10 + m11*m11))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public uint NormMax => Math.Max(Math.Max(Math.Max(m00, m01), m10), m11); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow(((Math.Pow((double)m00, p) + Math.Pow((double)m01, p)) + (Math.Pow((double)m10, p) + Math.Pow((double)m11, p))), 1 / p); /// <summary> /// Returns determinant of this matrix. /// </summary> public uint Determinant => m00 * m11 - m10 * m01; /// <summary> /// Executes a matrix-matrix-multiplication umat2 * umat2 -> umat2. /// </summary> public static umat2 operator*(umat2 lhs, umat2 rhs) => new umat2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11)); /// <summary> /// Executes a matrix-matrix-multiplication umat2 * umat3x2 -> umat3x2. /// </summary> public static umat3x2 operator*(umat2 lhs, umat3x2 rhs) => new umat3x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21)); /// <summary> /// Executes a matrix-matrix-multiplication umat2 * umat4x2 -> umat4x2. /// </summary> public static umat4x2 operator*(umat2 lhs, umat4x2 rhs) => new umat4x2((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static uvec2 operator*(umat2 m, uvec2 v) => new uvec2((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y)); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static umat2 CompMul(umat2 A, umat2 B) => new umat2(A.m00 * B.m00, A.m01 * B.m01, A.m10 * B.m10, A.m11 * B.m11); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static umat2 CompDiv(umat2 A, umat2 B) => new umat2(A.m00 / B.m00, A.m01 / B.m01, A.m10 / B.m10, A.m11 / B.m11); /// <summary> /// Executes a component-wise + (add). /// </summary> public static umat2 CompAdd(umat2 A, umat2 B) => new umat2(A.m00 + B.m00, A.m01 + B.m01, A.m10 + B.m10, A.m11 + B.m11); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static umat2 CompSub(umat2 A, umat2 B) => new umat2(A.m00 - B.m00, A.m01 - B.m01, A.m10 - B.m10, A.m11 - B.m11); /// <summary> /// Executes a component-wise + (add). /// </summary> public static umat2 operator+(umat2 lhs, umat2 rhs) => new umat2(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static umat2 operator+(umat2 lhs, uint rhs) => new umat2(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m10 + rhs, lhs.m11 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static umat2 operator+(uint lhs, umat2 rhs) => new umat2(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m10, lhs + rhs.m11); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static umat2 operator-(umat2 lhs, umat2 rhs) => new umat2(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static umat2 operator-(umat2 lhs, uint rhs) => new umat2(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m10 - rhs, lhs.m11 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static umat2 operator-(uint lhs, umat2 rhs) => new umat2(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m10, lhs - rhs.m11); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static umat2 operator/(umat2 lhs, uint rhs) => new umat2(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m10 / rhs, lhs.m11 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static umat2 operator/(uint lhs, umat2 rhs) => new umat2(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m10, lhs / rhs.m11); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static umat2 operator*(umat2 lhs, uint rhs) => new umat2(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m10 * rhs, lhs.m11 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static umat2 operator*(uint lhs, umat2 rhs) => new umat2(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m10, lhs * rhs.m11); /// <summary> /// Executes a component-wise % (modulo). /// </summary> public static umat2 operator%(umat2 lhs, umat2 rhs) => new umat2(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static umat2 operator%(umat2 lhs, uint rhs) => new umat2(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m10 % rhs, lhs.m11 % rhs); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static umat2 operator%(uint lhs, umat2 rhs) => new umat2(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m10, lhs % rhs.m11); /// <summary> /// Executes a component-wise ^ (xor). /// </summary> public static umat2 operator^(umat2 lhs, umat2 rhs) => new umat2(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static umat2 operator^(umat2 lhs, uint rhs) => new umat2(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static umat2 operator^(uint lhs, umat2 rhs) => new umat2(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m10, lhs ^ rhs.m11); /// <summary> /// Executes a component-wise | (bitwise-or). /// </summary> public static umat2 operator|(umat2 lhs, umat2 rhs) => new umat2(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static umat2 operator|(umat2 lhs, uint rhs) => new umat2(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m10 | rhs, lhs.m11 | rhs); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static umat2 operator|(uint lhs, umat2 rhs) => new umat2(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m10, lhs | rhs.m11); /// <summary> /// Executes a component-wise &amp; (bitwise-and). /// </summary> public static umat2 operator&(umat2 lhs, umat2 rhs) => new umat2(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static umat2 operator&(umat2 lhs, uint rhs) => new umat2(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m10 & rhs, lhs.m11 & rhs); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static umat2 operator&(uint lhs, umat2 rhs) => new umat2(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m10, lhs & rhs.m11); /// <summary> /// Executes a component-wise left-shift with a scalar. /// </summary> public static umat2 operator<<(umat2 lhs, int rhs) => new umat2(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m10 << rhs, lhs.m11 << rhs); /// <summary> /// Executes a component-wise right-shift with a scalar. /// </summary> public static umat2 operator>>(umat2 lhs, int rhs) => new umat2(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat2 operator<(umat2 lhs, umat2 rhs) => new bmat2(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2 operator<(umat2 lhs, uint rhs) => new bmat2(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m10 < rhs, lhs.m11 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2 operator<(uint lhs, umat2 rhs) => new bmat2(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m10, lhs < rhs.m11); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat2 operator<=(umat2 lhs, umat2 rhs) => new bmat2(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2 operator<=(umat2 lhs, uint rhs) => new bmat2(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2 operator<=(uint lhs, umat2 rhs) => new bmat2(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m10, lhs <= rhs.m11); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat2 operator>(umat2 lhs, umat2 rhs) => new bmat2(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2 operator>(umat2 lhs, uint rhs) => new bmat2(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m10 > rhs, lhs.m11 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2 operator>(uint lhs, umat2 rhs) => new bmat2(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m10, lhs > rhs.m11); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat2 operator>=(umat2 lhs, umat2 rhs) => new bmat2(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2 operator>=(umat2 lhs, uint rhs) => new bmat2(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2 operator>=(uint lhs, umat2 rhs) => new bmat2(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m10, lhs >= rhs.m11); } }
// 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.Diagnostics; namespace System.Data { internal sealed class Merger { private readonly DataSet _dataSet = null; private readonly DataTable _dataTable = null; private readonly bool _preserveChanges; private readonly MissingSchemaAction _missingSchemaAction; private readonly bool _isStandAlonetable = false; private bool _IgnoreNSforTableLookup = false; // Everett Behavior : SQL BU DT 370850 internal Merger(DataSet dataSet, bool preserveChanges, MissingSchemaAction missingSchemaAction) { _dataSet = dataSet; _preserveChanges = preserveChanges; // map AddWithKey -> Add _missingSchemaAction = missingSchemaAction == MissingSchemaAction.AddWithKey ? MissingSchemaAction.Add : missingSchemaAction; } internal Merger(DataTable dataTable, bool preserveChanges, MissingSchemaAction missingSchemaAction) { _isStandAlonetable = true; _dataTable = dataTable; _preserveChanges = preserveChanges; // map AddWithKey -> Add _missingSchemaAction = missingSchemaAction == MissingSchemaAction.AddWithKey ? MissingSchemaAction.Add : missingSchemaAction; } internal void MergeDataSet(DataSet source) { if (source == _dataSet) return; //somebody is doing an 'automerge' bool fEnforce = _dataSet.EnforceConstraints; _dataSet.EnforceConstraints = false; _IgnoreNSforTableLookup = (_dataSet._namespaceURI != source._namespaceURI); // if two DataSets have different // Namespaces, ignore NS for table lookups as we won't be able to find the right tables which inherits its NS List<DataColumn> existingColumns = null; // need to cache existing columns if (MissingSchemaAction.Add == _missingSchemaAction) { existingColumns = new List<DataColumn>(); // need to cache existing columns foreach (DataTable dt in _dataSet.Tables) { foreach (DataColumn dc in dt.Columns) { existingColumns.Add(dc); } } } for (int i = 0; i < source.Tables.Count; i++) { MergeTableData(source.Tables[i]); // since column expression might have dependency on relation, we do not set //column expression at this point. We need to set it after adding relations } if (MissingSchemaAction.Ignore != _missingSchemaAction) { // Add all independent constraints MergeConstraints(source); // Add all relationships for (int i = 0; i < source.Relations.Count; i++) { MergeRelation(source.Relations[i]); } } if (MissingSchemaAction.Add == _missingSchemaAction) { // for which other options we should add expressions also? foreach (DataTable sourceTable in source.Tables) { DataTable targetTable; if (_IgnoreNSforTableLookup) { targetTable = _dataSet.Tables[sourceTable.TableName]; } else { targetTable = _dataSet.Tables[sourceTable.TableName, sourceTable.Namespace]; // we know that target table won't be null since MissingSchemaAction is Add , we have already added it! } foreach (DataColumn dc in sourceTable.Columns) { // Should we overwrite the previous expression column? No, refer to spec, if it is new column we need to add the schema if (dc.Computed) { DataColumn targetColumn = targetTable.Columns[dc.ColumnName]; if (!existingColumns.Contains(targetColumn)) { targetColumn.Expression = dc.Expression; } } } } } MergeExtendedProperties(source.ExtendedProperties, _dataSet.ExtendedProperties); foreach (DataTable dt in _dataSet.Tables) { dt.EvaluateExpressions(); } _dataSet.EnforceConstraints = fEnforce; } internal void MergeTable(DataTable src) { bool fEnforce = false; if (!_isStandAlonetable) { if (src.DataSet == _dataSet) return; //somebody is doing an 'automerge' fEnforce = _dataSet.EnforceConstraints; _dataSet.EnforceConstraints = false; } else { if (src == _dataTable) return; //somebody is doing an 'automerge' _dataTable.SuspendEnforceConstraints = true; } if (_dataSet != null) { // this is ds.Merge // if source does not have a DS, or if NS of both DS does not match, ignore the NS if (src.DataSet == null || src.DataSet._namespaceURI != _dataSet._namespaceURI) { _IgnoreNSforTableLookup = true; } } else { // this is dt.Merge if (_dataTable.DataSet == null || src.DataSet == null || src.DataSet._namespaceURI != _dataTable.DataSet._namespaceURI) { _IgnoreNSforTableLookup = true; } } MergeTableData(src); DataTable dt = _dataTable; if (dt == null && _dataSet != null) { dt = _IgnoreNSforTableLookup ? _dataSet.Tables[src.TableName] : _dataSet.Tables[src.TableName, src.Namespace]; } if (dt != null) { dt.EvaluateExpressions(); } if (!_isStandAlonetable) { _dataSet.EnforceConstraints = fEnforce; } else { _dataTable.SuspendEnforceConstraints = false; try { if (_dataTable.EnforceConstraints) { _dataTable.EnableConstraints(); } } catch (ConstraintException) { if (_dataTable.DataSet != null) { _dataTable.DataSet.EnforceConstraints = false; } throw; } } } private void MergeTable(DataTable src, DataTable dst) { int rowsCount = src.Rows.Count; bool wasEmpty = dst.Rows.Count == 0; if (0 < rowsCount) { Index ndxSearch = null; DataKey key = default(DataKey); dst.SuspendIndexEvents(); try { if (!wasEmpty && dst._primaryKey != null) { key = GetSrcKey(src, dst); if (key.HasValue) { ndxSearch = dst._primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added); } } // this improves performance by iterating over the rows instead of computing their position foreach (DataRow sourceRow in src.Rows) { DataRow targetRow = null; if (ndxSearch != null) { targetRow = dst.FindMergeTarget(sourceRow, key, ndxSearch); } dst.MergeRow(sourceRow, targetRow, _preserveChanges, ndxSearch); } } finally { dst.RestoreIndexEvents(true); } } MergeExtendedProperties(src.ExtendedProperties, dst.ExtendedProperties); } internal void MergeRows(DataRow[] rows) { DataTable src = null; DataTable dst = null; DataKey key = default(DataKey); Index ndxSearch = null; bool fEnforce = _dataSet.EnforceConstraints; _dataSet.EnforceConstraints = false; for (int i = 0; i < rows.Length; i++) { DataRow row = rows[i]; if (row == null) { throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}]"); } if (row.Table == null) { throw ExceptionBuilder.ArgumentNull($"{nameof(rows)}[{i}].{nameof(DataRow.Table)}"); } //somebody is doing an 'automerge' if (row.Table.DataSet == _dataSet) { continue; } if (src != row.Table) { // row.Table changed from prev. row. src = row.Table; dst = MergeSchema(row.Table); if (dst == null) { Debug.Assert(MissingSchemaAction.Ignore == _missingSchemaAction, "MergeSchema failed"); _dataSet.EnforceConstraints = fEnforce; return; } if (dst._primaryKey != null) { key = GetSrcKey(src, dst); } if (key.HasValue) { // Getting our own copy instead. ndxSearch = dst.primaryKey.Key.GetSortIndex(); // IMO, Better would be to reuse index // ndxSearch = dst.primaryKey.Key.GetSortIndex(DataViewRowState.OriginalRows | DataViewRowState.Added ); if (null != ndxSearch) { ndxSearch.RemoveRef(); ndxSearch = null; } ndxSearch = new Index(dst, dst._primaryKey.Key.GetIndexDesc(), DataViewRowState.OriginalRows | DataViewRowState.Added, null); ndxSearch.AddRef(); // need to addref twice, otherwise it will be collected ndxSearch.AddRef(); // in past first adref was done in const } } if (row._newRecord == -1 && row._oldRecord == -1) { continue; } DataRow targetRow = null; if (0 < dst.Rows.Count && ndxSearch != null) { targetRow = dst.FindMergeTarget(row, key, ndxSearch); } targetRow = dst.MergeRow(row, targetRow, _preserveChanges, ndxSearch); if (targetRow.Table._dependentColumns != null && targetRow.Table._dependentColumns.Count > 0) { targetRow.Table.EvaluateExpressions(targetRow, DataRowAction.Change, null); } } if (null != ndxSearch) { ndxSearch.RemoveRef(); ndxSearch = null; } _dataSet.EnforceConstraints = fEnforce; } private DataTable MergeSchema(DataTable table) { DataTable targetTable = null; if (!_isStandAlonetable) { if (_dataSet.Tables.Contains(table.TableName, true)) { if (_IgnoreNSforTableLookup) { targetTable = _dataSet.Tables[table.TableName]; } else { targetTable = _dataSet.Tables[table.TableName, table.Namespace]; } } } else { targetTable = _dataTable; } if (targetTable == null) { // in case of standalone table, we make sure that targetTable is not null, so if this check passes, it will be when it is called via detaset if (MissingSchemaAction.Add == _missingSchemaAction) { targetTable = table.Clone(table.DataSet); // if we are here mainly we are called from DataSet.Merge at this point we don't set //expression columns, since it might have refer to other columns via relation, so it won't find the table and we get exception; // do it after adding relations. _dataSet.Tables.Add(targetTable); } else if (MissingSchemaAction.Error == _missingSchemaAction) { throw ExceptionBuilder.MergeMissingDefinition(table.TableName); } } else { if (MissingSchemaAction.Ignore != _missingSchemaAction) { // Do the columns int oldCount = targetTable.Columns.Count; for (int i = 0; i < table.Columns.Count; i++) { DataColumn src = table.Columns[i]; DataColumn dest = (targetTable.Columns.Contains(src.ColumnName, true)) ? targetTable.Columns[src.ColumnName] : null; if (dest == null) { if (MissingSchemaAction.Add == _missingSchemaAction) { dest = src.Clone(); targetTable.Columns.Add(dest); } else { if (!_isStandAlonetable) { _dataSet.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName), _missingSchemaAction); } else { throw ExceptionBuilder.MergeFailed(SR.Format(SR.DataMerge_MissingColumnDefinition, table.TableName, src.ColumnName)); } } } else { if (dest.DataType != src.DataType || ((dest.DataType == typeof(DateTime)) && (dest.DateTimeMode != src.DateTimeMode) && ((dest.DateTimeMode & src.DateTimeMode) != DataSetDateTime.Unspecified))) { if (!_isStandAlonetable) _dataSet.RaiseMergeFailed(targetTable, SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName), MissingSchemaAction.Error); else throw ExceptionBuilder.MergeFailed(SR.Format(SR.DataMerge_DataTypeMismatch, src.ColumnName)); } MergeExtendedProperties(src.ExtendedProperties, dest.ExtendedProperties); } } // Set DataExpression if (_isStandAlonetable) { for (int i = oldCount; i < targetTable.Columns.Count; i++) { targetTable.Columns[i].Expression = table.Columns[targetTable.Columns[i].ColumnName].Expression; } } // check the PrimaryKey DataColumn[] targetPKey = targetTable.PrimaryKey; DataColumn[] tablePKey = table.PrimaryKey; if (targetPKey.Length != tablePKey.Length) { // special case when the target table does not have the PrimaryKey if (targetPKey.Length == 0) { DataColumn[] key = new DataColumn[tablePKey.Length]; for (int i = 0; i < tablePKey.Length; i++) { key[i] = targetTable.Columns[tablePKey[i].ColumnName]; } targetTable.PrimaryKey = key; } else if (tablePKey.Length != 0) { _dataSet.RaiseMergeFailed(targetTable, SR.DataMerge_PrimaryKeyMismatch, _missingSchemaAction); } } else { for (int i = 0; i < targetPKey.Length; i++) { if (string.Compare(targetPKey[i].ColumnName, tablePKey[i].ColumnName, false, targetTable.Locale) != 0) { _dataSet.RaiseMergeFailed(table, SR.Format(SR.DataMerge_PrimaryKeyColumnsMismatch, targetPKey[i].ColumnName, tablePKey[i].ColumnName), _missingSchemaAction); } } } } MergeExtendedProperties(table.ExtendedProperties, targetTable.ExtendedProperties); } return targetTable; } private void MergeTableData(DataTable src) { DataTable dest = MergeSchema(src); if (dest == null) return; dest.MergingData = true; try { MergeTable(src, dest); } finally { dest.MergingData = false; } } private void MergeConstraints(DataSet source) { for (int i = 0; i < source.Tables.Count; i++) { MergeConstraints(source.Tables[i]); } } private void MergeConstraints(DataTable table) { // Merge constraints for (int i = 0; i < table.Constraints.Count; i++) { Constraint src = table.Constraints[i]; Constraint dest = src.Clone(_dataSet, _IgnoreNSforTableLookup); if (dest == null) { _dataSet.RaiseMergeFailed(table, SR.Format(SR.DataMerge_MissingConstraint, src.GetType().FullName, src.ConstraintName), _missingSchemaAction ); } else { Constraint cons = dest.Table.Constraints.FindConstraint(dest); if (cons == null) { if (MissingSchemaAction.Add == _missingSchemaAction) { try { // try to keep the original name dest.Table.Constraints.Add(dest); } catch (DuplicateNameException) { // if fail, assume default name dest.ConstraintName = string.Empty; dest.Table.Constraints.Add(dest); } } else if (MissingSchemaAction.Error == _missingSchemaAction) { _dataSet.RaiseMergeFailed(table, SR.Format(SR.DataMerge_MissingConstraint, src.GetType().FullName, src.ConstraintName), _missingSchemaAction ); } } else { MergeExtendedProperties(src.ExtendedProperties, cons.ExtendedProperties); } } } } private void MergeRelation(DataRelation relation) { Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction || MissingSchemaAction.Add == _missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString()); DataRelation destRelation = null; // try to find given relation in this dataSet int iDest = _dataSet.Relations.InternalIndexOf(relation.RelationName); if (iDest >= 0) { // check the columns and Relation properties.. destRelation = _dataSet.Relations[iDest]; if (relation.ParentKey.ColumnsReference.Length != destRelation.ParentKey.ColumnsReference.Length) { _dataSet.RaiseMergeFailed(null, SR.Format(SR.DataMerge_MissingDefinition, relation.RelationName), _missingSchemaAction); } for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++) { DataColumn dest = destRelation.ParentKey.ColumnsReference[i]; DataColumn src = relation.ParentKey.ColumnsReference[i]; if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale)) { _dataSet.RaiseMergeFailed(null, SR.Format(SR.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName), _missingSchemaAction); } dest = destRelation.ChildKey.ColumnsReference[i]; src = relation.ChildKey.ColumnsReference[i]; if (0 != string.Compare(dest.ColumnName, src.ColumnName, false, dest.Table.Locale)) { _dataSet.RaiseMergeFailed(null, SR.Format(SR.DataMerge_ReltionKeyColumnsMismatch, relation.RelationName), _missingSchemaAction); } } } else { if (MissingSchemaAction.Add == _missingSchemaAction) { // create identical realtion in the current dataset DataTable parent = _IgnoreNSforTableLookup ? _dataSet.Tables[relation.ParentTable.TableName] : _dataSet.Tables[relation.ParentTable.TableName, relation.ParentTable.Namespace]; DataTable child = _IgnoreNSforTableLookup ? _dataSet.Tables[relation.ChildTable.TableName] : _dataSet.Tables[relation.ChildTable.TableName, relation.ChildTable.Namespace]; DataColumn[] parentColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length]; DataColumn[] childColumns = new DataColumn[relation.ParentKey.ColumnsReference.Length]; for (int i = 0; i < relation.ParentKey.ColumnsReference.Length; i++) { parentColumns[i] = parent.Columns[relation.ParentKey.ColumnsReference[i].ColumnName]; childColumns[i] = child.Columns[relation.ChildKey.ColumnsReference[i].ColumnName]; } try { destRelation = new DataRelation(relation.RelationName, parentColumns, childColumns, relation._createConstraints); destRelation.Nested = relation.Nested; _dataSet.Relations.Add(destRelation); } catch (Exception e) when (Common.ADP.IsCatchableExceptionType(e)) { ExceptionBuilder.TraceExceptionForCapture(e); _dataSet.RaiseMergeFailed(null, e.Message, _missingSchemaAction); } } else { Debug.Assert(MissingSchemaAction.Error == _missingSchemaAction, "Unexpected value of MissingSchemaAction parameter : " + _missingSchemaAction.ToString()); throw ExceptionBuilder.MergeMissingDefinition(relation.RelationName); } } MergeExtendedProperties(relation.ExtendedProperties, destRelation.ExtendedProperties); return; } private void MergeExtendedProperties(PropertyCollection src, PropertyCollection dst) { if (MissingSchemaAction.Ignore == _missingSchemaAction) { return; } IDictionaryEnumerator srcDE = src.GetEnumerator(); while (srcDE.MoveNext()) { if (!_preserveChanges || dst[srcDE.Key] == null) { dst[srcDE.Key] = srcDE.Value; } } } private DataKey GetSrcKey(DataTable src, DataTable dst) { if (src._primaryKey != null) { return src._primaryKey.Key; } DataKey key = default(DataKey); if (dst._primaryKey != null) { DataColumn[] dstColumns = dst._primaryKey.Key.ColumnsReference; DataColumn[] srcColumns = new DataColumn[dstColumns.Length]; for (int j = 0; j < dstColumns.Length; j++) { srcColumns[j] = src.Columns[dstColumns[j].ColumnName]; } key = new DataKey(srcColumns, false); // DataKey will take ownership of srcColumns } return key; } } }
using UnityEngine; using System.Collections.Generic; [System.Serializable] public class MOMVert { public int id; public float w; public Vector3 start; public Vector3 delta; } [System.Serializable] public class MegaMomVertMap { public int[] indices; } [AddComponentMenu("Modifiers/Morph-O-Matic")] public class MegaMorphOMatic : MegaMorphBase { public bool UseLimit; public float Max; public float Min; public float importScale = 1.0f; public bool flipyz = false; public bool negx = false; public bool glUseLimit = false; public float glMin = 0.0f; public float glMax = 1.0f; public float tolerance = 0.0001f; public bool animate = false; public float atime = 0.0f; public float animtime = 0.0f; public float looptime = 0.0f; public MegaRepeatMode repeatMode = MegaRepeatMode.Loop; public float speed = 1.0f; public Vector3[] oPoints; // Base points public MegaMomVertMap[] mapping; public override string ModName() { return "Morph-O-Matic"; } public override string GetHelpURL() { return "?page_id=1521"; } public override bool ModLateUpdate(MegaModContext mc) { if ( animate ) { animtime += Time.deltaTime * speed; switch ( repeatMode ) { case MegaRepeatMode.Loop: animtime = Mathf.Repeat(animtime, looptime); break; case MegaRepeatMode.Clamp: animtime = Mathf.Clamp(animtime, 0.0f, looptime); break; } SetAnim(animtime); } return Prepare(mc); } public override bool Prepare(MegaModContext mc) { if ( chanBank != null && chanBank.Count > 0 ) return true; return false; } Vector3 Cubic(MegaMorphTarget t, int pointnum, float alpha) { // Linear for now, will have coefs in here for cubic Vector3 v = t.mompoints[pointnum].delta; v.x *= alpha; v.y *= alpha; v.z *= alpha; return v; } static public void Bez3D(out Vector3 b, ref Vector3[] p, float u) { Vector3 t01 = p[0] + (p[1] - p[0]) * u; Vector3 t12 = p[1] + (p[2] - p[1]) * u; Vector3 t02 = t01 + (t12 - t01) * u; t01 = p[2] + (p[3] - p[2]) * u; Vector3 t13 = t12 + (t01 - t12) * u; b = t02 + (t13 - t02) * u; } // We should just modify the internal points then map them out at the end public override void Modify(MegaModifiers mc) { verts.CopyTo(sverts, 0); // This should only blit totally untouched verts for ( int i = 0; i < chanBank.Count; i++ ) { MegaMorphChan chan = chanBank[i]; chan.UpdatePercent(); float fChannelPercent = chan.Percent; // check for change since last frame on percent, if none just add in diff // Can we keep each chan delta then if not changed can just add it in if ( fChannelPercent == chan.fChannelPercent ) { MegaMorphTarget trg = chan.mTargetCache[chan.targ]; for ( int pointnum = 0; pointnum < trg.mompoints.Length; pointnum++ ) { int p = trg.mompoints[pointnum].id; int c = mapping[p].indices.Length; Vector3 df = chan.diff[pointnum]; for ( int m = 0; m < c; m++ ) { int index = mapping[p].indices[m]; sverts[index].x += df.x; sverts[index].y += df.y; sverts[index].z += df.z; } } } else { chan.fChannelPercent = fChannelPercent; if ( chan.mTargetCache != null && chan.mTargetCache.Count > 0 && chan.mActiveOverride ) { if ( chan.mUseLimit || glUseLimit ) { if ( glUseLimit ) fChannelPercent = Mathf.Clamp(fChannelPercent, glMin, glMax); else fChannelPercent = Mathf.Clamp(fChannelPercent, chan.mSpinmin, chan.mSpinmax); } int targ = 0; float alpha = 0.0f; if ( fChannelPercent < chan.mTargetCache[0].percent ) { targ = 0; //alpha = 0.0f; alpha = (fChannelPercent - chan.mTargetCache[targ].percent) / (chan.mTargetCache[targ + 1].percent - chan.mTargetCache[targ].percent); //Debug.Log("alpha " + alpha + " percent " + fChannelPercent); } else { int last = chan.mTargetCache.Count - 1; if ( fChannelPercent >= chan.mTargetCache[last].percent ) { targ = last - 1; //alpha = 1.0f; alpha = (fChannelPercent - chan.mTargetCache[targ].percent) / (chan.mTargetCache[targ + 1].percent - chan.mTargetCache[targ].percent); } else { for ( int t = 1; t < chan.mTargetCache.Count; t++ ) { if ( fChannelPercent < chan.mTargetCache[t].percent ) { targ = t - 1; alpha = (fChannelPercent - chan.mTargetCache[targ].percent) / (chan.mTargetCache[t].percent - chan.mTargetCache[targ].percent); //Debug.Log("alpha1 " + alpha + " percent1 " + fChannelPercent); break; } } } } MegaMorphTarget trg = chan.mTargetCache[targ]; chan.targ = targ; for ( int pointnum = 0; pointnum < trg.mompoints.Length; pointnum++ ) { int p = trg.mompoints[pointnum].id; // Save so if chan doesnt change we dont need to recalc Vector3 df = trg.mompoints[pointnum].start; df.x += trg.mompoints[pointnum].delta.x * alpha; df.y += trg.mompoints[pointnum].delta.y * alpha; df.z += trg.mompoints[pointnum].delta.z * alpha; chan.diff[pointnum] = df; for ( int m = 0; m < mapping[p].indices.Length; m++ ) { int index = mapping[p].indices[m]; sverts[index].x += df.x; sverts[index].y += df.y; sverts[index].z += df.z; } } } } } } // Threaded version public override void PrepareMT(MegaModifiers mc, int cores) { } public override void DoWork(MegaModifiers mc, int index, int start, int end, int cores) { if ( index == 0 ) Modify(mc); } }
// 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.IO; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { internal class SslState { // // The public Client and Server classes enforce the parameters rules before // calling into this .ctor. // internal SslState(Stream innerStream, RemoteCertValidationCallback certValidationCallback, LocalCertSelectionCallback certSelectionCallback, EncryptionPolicy encryptionPolicy) { } // // // internal void ValidateCreateContext(bool isServer, string targetHost, SslProtocols enabledSslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertRevocationStatus) { } internal bool IsAuthenticated { get { return false; } } internal bool IsMutuallyAuthenticated { get { return false; } } internal bool RemoteCertRequired { get { return false; } } internal bool IsServer { get { return false; } } // // This will return selected local cert for both client/server streams // internal X509Certificate LocalCertificate { get { return null; } } internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) { return null; } internal bool CheckCertRevocationStatus { get { return false; } } internal CipherAlgorithmType CipherAlgorithm { get { return CipherAlgorithmType.Null; } } internal int CipherStrength { get { return 0; } } internal HashAlgorithmType HashAlgorithm { get { return HashAlgorithmType.None; } } internal int HashStrength { get { return 0; } } internal ExchangeAlgorithmType KeyExchangeAlgorithm { get { return ExchangeAlgorithmType.None; } } internal int KeyExchangeStrength { get { return 0; } } internal SslProtocols SslProtocol { get { return SslProtocols.None; } } internal _SslStream SecureStream { get { return null; } } internal void CheckThrow(bool authSucessCheck) { } internal void Flush() { } // // This is to not depend on GC&SafeHandle class if the context is not needed anymore. // internal void Close() { } // // This method assumes that a SSPI context is already in a good shape. // For example it is either a fresh context or already authenticated context that needs renegotiation. // internal void ProcessAuthentication(LazyAsyncResult lazyResult) { } internal void EndProcessAuthentication(IAsyncResult result) { } } internal class _SslStream : Stream { public override bool CanRead { get { throw new NotImplementedException(); } } public override bool CanSeek { get { throw new NotImplementedException(); } } public override bool CanWrite { get { throw new NotImplementedException(); } } public override long Length { get { throw new NotImplementedException(); } } public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public override void Flush() { throw new NotImplementedException(); } public override int Read(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { throw new NotImplementedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotImplementedException(); } internal IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { throw new NotImplementedException(); } internal int EndRead(IAsyncResult asyncResult) { throw new NotImplementedException(); } internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { throw new NotImplementedException(); } internal void EndWrite(IAsyncResult asyncResult) { throw new NotImplementedException(); } } }
// 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; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Venus { internal static class ContainedLanguageCodeSupport { public static bool IsValidId(Document document, string identifier) { var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); return syntaxFacts.IsValidIdentifier(identifier); } public static bool TryGetBaseClassName(Document document, string className, CancellationToken cancellationToken, out string baseClassName) { baseClassName = null; var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className); if (type == null || type.BaseType == null) { return false; } baseClassName = type.BaseType.ToDisplayString(); return true; } public static string CreateUniqueEventName( Document document, string className, string objectName, string nameOfEvent, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className); var name = objectName + "_" + nameOfEvent; var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var tree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken); var typeNode = type.DeclaringSyntaxReferences.Where(r => r.SyntaxTree == tree).Select(r => r.GetSyntax(cancellationToken)).First(); var codeModel = document.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var point = codeModel.GetStartPoint(typeNode, EnvDTE.vsCMPart.vsCMPartBody); var reservedNames = semanticModel.LookupSymbols(point.Value.Position, type).Select(m => m.Name); return NameGenerator.EnsureUniqueness(name, reservedNames, document.Project.LanguageServices.GetService<ISyntaxFactsService>().IsCaseSensitive); } /// <summary> /// Determine what methods of <paramref name=" className"/> could possibly be used as event /// handlers. /// </summary> /// <param name="document">The document containing <paramref name="className"/>.</param> /// <param name="className">The name of the type whose methods should be considered.</param> /// <param name="objectTypeName">The fully qualified name of the type containing a member /// that is an event. (E.g. "System.Web.Forms.Button")</param> /// <param name="nameOfEvent">The name of the member in <paramref name="objectTypeName"/> /// that is the event (E.g. "Clicked")</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>The display name of the method, and a unique to for the method.</returns> public static IEnumerable<Tuple<string, string>> GetCompatibleEventHandlers( Document document, string className, string objectTypeName, string nameOfEvent, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var type = compilation.GetTypeByMetadataName(className); if (type == null) { throw new InvalidOperationException(); } var eventMember = GetEventSymbol(document, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType) { throw new InvalidOperationException(ServicesVSResources.EventTypeIsInvalid); } var methods = type.GetMembers().OfType<IMethodSymbol>().Where(m => m.CompatibleSignatureToDelegate((INamedTypeSymbol)eventType)); return methods.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } public static string GetEventHandlerMemberId(Document document, string className, string objectTypeName, string nameOfEvent, string eventHandlerName, CancellationToken cancellationToken) { var nameAndId = GetCompatibleEventHandlers(document, className, objectTypeName, nameOfEvent, cancellationToken).SingleOrDefault(pair => pair.Item1 == eventHandlerName); return nameAndId == null ? null : nameAndId.Item2; } /// <summary> /// Ensure that an event handler exists for a given event. /// </summary> /// <param name="thisDocument">The document corresponding to this operation.</param> /// <param name="targetDocument">The document to generate the event handler in if it doesn't /// exist.</param> /// <param name="className">The name of the type to generate the event handler in.</param> /// <param name="objectName">The name of the event member (if <paramref /// name="useHandlesClause"/> is true)</param> /// <param name="objectTypeName">The name of the type containing the event.</param> /// <param name="nameOfEvent">The name of the event member in <paramref /// name="objectTypeName"/></param> /// <param name="eventHandlerName">The name of the method to be hooked up to the /// event.</param> /// <param name="itemidInsertionPoint">The VS itemid of the file to generate the event /// handler in.</param> /// <param name="useHandlesClause">If true, a vb "Handles" clause will be generated for the /// handler.</param> /// <param name="additionalFormattingRule">An additional formatting rule that can be used to /// format the newly inserted method</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>Either the unique id of the method if it already exists, or the unique id of /// the to be generated method, the text of the to be generated method, and the position in /// <paramref name="itemidInsertionPoint"/> where the text should be inserted.</returns> public static Tuple<string, string, VsTextSpan> EnsureEventHandler( Document thisDocument, Document targetDocument, string className, string objectName, string objectTypeName, string nameOfEvent, string eventHandlerName, uint itemidInsertionPoint, bool useHandlesClause, IFormattingRule additionalFormattingRule, CancellationToken cancellationToken) { var thisCompilation = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var type = thisCompilation.GetTypeByMetadataName(className); var existingEventHandlers = GetCompatibleEventHandlers(targetDocument, className, objectTypeName, nameOfEvent, cancellationToken); var existingHandler = existingEventHandlers.SingleOrDefault(e => e.Item1 == eventHandlerName); if (existingHandler != null) { return Tuple.Create(existingHandler.Item2, (string)null, default(VsTextSpan)); } // Okay, it doesn't exist yet. Let's create it. var codeGenerationService = targetDocument.GetLanguageService<ICodeGenerationService>(); var syntaxFactory = targetDocument.GetLanguageService<SyntaxGenerator>(); var eventMember = GetEventSymbol(thisDocument, objectTypeName, nameOfEvent, type, cancellationToken); if (eventMember == null) { throw new InvalidOperationException(); } var eventType = ((IEventSymbol)eventMember).Type; if (eventType.Kind != SymbolKind.NamedType || ((INamedTypeSymbol)eventType).DelegateInvokeMethod == null) { throw new InvalidOperationException(ServicesVSResources.EventTypeIsInvalid); } var handlesExpressions = useHandlesClause ? new[] { syntaxFactory.MemberAccessExpression( objectName != null ? syntaxFactory.IdentifierName(objectName) : syntaxFactory.ThisExpression(), syntaxFactory.IdentifierName(nameOfEvent)) } : null; var invokeMethod = ((INamedTypeSymbol)eventType).DelegateInvokeMethod; var newMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: null, accessibility: Accessibility.Protected, modifiers: new DeclarationModifiers(), returnType: targetDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetSpecialType(SpecialType.System_Void), explicitInterfaceSymbol: null, name: eventHandlerName, typeParameters: null, parameters: invokeMethod.Parameters.ToArray(), statements: null, handlesExpressions: handlesExpressions); var annotation = new SyntaxAnnotation(); newMethod = annotation.AddAnnotationToSymbol(newMethod); var codeModel = targetDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var syntaxFacts = targetDocument.Project.LanguageServices.GetService<ISyntaxFactsService>(); var targetSyntaxTree = targetDocument.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken); var position = type.Locations.First(loc => loc.SourceTree == targetSyntaxTree).SourceSpan.Start; var destinationType = syntaxFacts.GetContainingTypeDeclaration(targetSyntaxTree.GetRoot(cancellationToken), position); var insertionPoint = codeModel.GetEndPoint(destinationType, EnvDTE.vsCMPart.vsCMPartBody); if (insertionPoint == null) { throw new InvalidOperationException(ServicesVSResources.MemberInsertionFailed); } var newType = codeGenerationService.AddMethod(destinationType, newMethod, new CodeGenerationOptions(autoInsertionLocation: false), cancellationToken); var newRoot = targetSyntaxTree.GetRoot(cancellationToken).ReplaceNode(destinationType, newType); newRoot = Simplifier.ReduceAsync(targetDocument.WithSyntaxRoot(newRoot), Simplifier.Annotation, null, cancellationToken).WaitAndGetResult(cancellationToken).GetSyntaxRootAsync(cancellationToken).WaitAndGetResult(cancellationToken); var formattingRules = additionalFormattingRule.Concat(Formatter.GetDefaultFormattingRules(targetDocument)); var workspace = targetDocument.Project.Solution.Workspace; newRoot = Formatter.Format(newRoot, Formatter.Annotation, workspace, workspace.Options, formattingRules, cancellationToken); var newMember = newRoot.GetAnnotatedNodesAndTokens(annotation).Single(); var newMemberText = newMember.ToFullString(); // In VB, the final newline is likely a statement terminator in the parent - just add // one on so that things don't get messed. if (!newMemberText.EndsWith(Environment.NewLine, StringComparison.Ordinal)) { newMemberText += Environment.NewLine; } return Tuple.Create(ConstructMemberId(newMethod), newMemberText, insertionPoint.Value.ToVsTextSpan()); } public static bool TryGetMemberNavigationPoint( Document thisDocument, string className, string uniqueMemberID, out VsTextSpan textSpan, out Document targetDocument, CancellationToken cancellationToken) { targetDocument = null; textSpan = default(VsTextSpan); var type = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className); var member = LookupMemberId(type, uniqueMemberID); if (member == null) { return false; } var codeModel = thisDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>(); var memberNode = member.DeclaringSyntaxReferences.Select(r => r.GetSyntax(cancellationToken)).FirstOrDefault(); if (memberNode != null) { var navigationPoint = codeModel.GetStartPoint(memberNode, EnvDTE.vsCMPart.vsCMPartNavigate); if (navigationPoint != null) { targetDocument = thisDocument.Project.Solution.GetDocument(memberNode.SyntaxTree); textSpan = navigationPoint.Value.ToVsTextSpan(); return true; } } return false; } /// <summary> /// Get the display names and unique ids of all the members of the given type in <paramref /// name="className"/>. /// </summary> public static IEnumerable<Tuple<string, string>> GetMembers( Document document, string className, CODEMEMBERTYPE codeMemberType, CancellationToken cancellationToken) { var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(className); var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var allMembers = codeMemberType == CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS ? semanticModel.LookupSymbols(position: type.Locations[0].SourceSpan.Start, container: type, name: null) : type.GetMembers(); var members = allMembers.Where(m => IncludeMember(m, codeMemberType, compilation)); return members.Select(m => Tuple.Create(m.Name, ConstructMemberId(m))); } /// <summary> /// Try to do a symbolic rename the specified symbol. /// </summary> /// <returns>False ONLY if it can't resolve the name. Other errors result in the normal /// exception being propagated.</returns> public static bool TryRenameElement( Document document, ContainedLanguageRenameType clrt, string oldFullyQualifiedName, string newFullyQualifiedName, IEnumerable<IRefactorNotifyService> refactorNotifyServices, CancellationToken cancellationToken) { var symbol = FindSymbol(document, clrt, oldFullyQualifiedName, cancellationToken); if (symbol == null) { return false; } Workspace workspace; if (Workspace.TryGetWorkspace(document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).Container, out workspace)) { var newName = newFullyQualifiedName.Substring(newFullyQualifiedName.LastIndexOf('.') + 1); var optionSet = document.Project.Solution.Workspace.Options; var newSolution = Renamer.RenameSymbolAsync(document.Project.Solution, symbol, newName, optionSet, cancellationToken).WaitAndGetResult(cancellationToken); var changedDocuments = newSolution.GetChangedDocuments(document.Project.Solution); var undoTitle = string.Format(EditorFeaturesResources.RenameTo, symbol.Name, newName); using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoTitle)) { // Notify third parties about the coming rename operation on the workspace, and let // any exceptions propagate through refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); if (!workspace.TryApplyChanges(newSolution)) { Exceptions.ThrowEFail(); } // Notify third parties about the completed rename operation on the workspace, and // let any exceptions propagate through refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true); workspaceUndoTransaction.Commit(); } RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); return true; } else { return false; } } private static bool IncludeMember(ISymbol member, CODEMEMBERTYPE memberType, Compilation compilation) { if (!member.CanBeReferencedByName) { return false; } switch (memberType) { case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS: // NOTE: the Dev10 C# codebase just returned if (member.Kind != SymbolKind.Method) { return false; } var method = (IMethodSymbol)member; if (!method.ReturnsVoid) { return false; } if (method.Parameters.Length != 2) { return false; } if (!method.Parameters[0].Type.Equals(compilation.ObjectType)) { return false; } if (!method.Parameters[1].Type.InheritsFromOrEquals(compilation.EventArgsType())) { return false; } return true; case CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS: return member.Kind == SymbolKind.Event; case CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS: return member.Kind == SymbolKind.Method; default: throw new ArgumentException("InvalidValue", "memberType"); } } private static ISymbol FindSymbol( Document document, ContainedLanguageRenameType renameType, string fullyQualifiedName, CancellationToken cancellationToken) { switch (renameType) { case ContainedLanguageRenameType.CLRT_CLASS: return document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(fullyQualifiedName); case ContainedLanguageRenameType.CLRT_CLASSMEMBER: var lastDot = fullyQualifiedName.LastIndexOf('.'); var typeName = fullyQualifiedName.Substring(0, lastDot); var memberName = fullyQualifiedName.Substring(lastDot + 1, fullyQualifiedName.Length - lastDot - 1); var type = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetTypeByMetadataName(typeName); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var membersOfName = type.GetMembers(memberName); return membersOfName.SingleOrDefault(); case ContainedLanguageRenameType.CLRT_NAMESPACE: var ns = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GlobalNamespace; var parts = fullyQualifiedName.Split('.'); for (int i = 0; i < parts.Length && ns != null; i++) { ns = ns.GetNamespaceMembers().SingleOrDefault(n => n.Name == parts[i]); } return ns; case ContainedLanguageRenameType.CLRT_OTHER: throw new NotSupportedException(ServicesVSResources.ElementRenameFailed); default: throw new InvalidOperationException(ServicesVSResources.UnknownRenameType); } } internal static string ConstructMemberId(ISymbol member) { if (member.Kind == SymbolKind.Method) { return string.Format("{0}({1})", member.Name, string.Join(",", ((IMethodSymbol)member).Parameters.Select(p => p.Type.ToDisplayString()))); } else if (member.Kind == SymbolKind.Event) { return member.Name + "(EVENT)"; } else { throw new NotSupportedException(ServicesVSResources.SymbolTypeIdInvalid); } } internal static ISymbol LookupMemberId(INamedTypeSymbol type, string uniqueMemberID) { var memberName = uniqueMemberID.Substring(0, uniqueMemberID.IndexOf('(')); var members = type.GetMembers(memberName).Where(m => m.Kind == SymbolKind.Method); foreach (var m in members) { if (ConstructMemberId(m) == uniqueMemberID) { return m; } } return null; } private static ISymbol GetEventSymbol( Document document, string objectTypeName, string nameOfEvent, INamedTypeSymbol type, CancellationToken cancellationToken) { var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken); var semanticModel = document.GetSemanticModelAsync(cancellationToken).WaitAndGetResult(cancellationToken); var objectType = compilation.GetTypeByMetadataName(objectTypeName); if (objectType == null) { throw new InvalidOperationException(); } var containingTree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken); var typeLocation = type.Locations.FirstOrDefault(d => d.SourceTree == containingTree); if (typeLocation == null) { throw new InvalidOperationException(); } return semanticModel.LookupSymbols(typeLocation.SourceSpan.Start, objectType, nameOfEvent).SingleOrDefault(m => m.Kind == SymbolKind.Event); } } }
// Copyright (c) 2014-2018 The Khronos Group Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and/or associated documentation files (the "Materials"), // to deal in the Materials without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Materials, and to permit persons to whom the // Materials are 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 Materials. // // MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS // STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND // HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/ // // THE MATERIALS ARE 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 MATERIALS OR THE USE OR OTHER DEALINGS // IN THE MATERIALS. // This header is automatically generated by the same tool that creates // the Binary Section of the SPIR-V specification. // Enumeration tokens for SPIR-V, in various styles: // C, C++, C++11, JSON, Lua, Python, C# // // - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL // - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL // - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL // - Lua will use tables, e.g.: spv.SourceLanguage.GLSL // - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL'] // - C# will use enum classes in the Specification class located in the "Spv" namespace, e.g.: Spv.Specification.SourceLanguage.GLSL // // Some tokens act like mask values, which can be OR'd together, // while others are mutually exclusive. The mask-like ones have // "Mask" in their name, and a parallel enum that has the shift // amount (1 << x) for each corresponding enumerant. namespace Spv { public static class Specification { public const uint MagicNumber = 0x07230203; public const uint Version = 0x00010200; public const uint Revision = 2; public const uint OpCodeMask = 0xffff; public const uint WordCountShift = 16; public enum SourceLanguage { Unknown = 0, ESSL = 1, GLSL = 2, OpenCL_C = 3, OpenCL_CPP = 4, HLSL = 5, } public enum ExecutionModel { Vertex = 0, TessellationControl = 1, TessellationEvaluation = 2, Geometry = 3, Fragment = 4, GLCompute = 5, Kernel = 6, } public enum AddressingModel { Logical = 0, Physical32 = 1, Physical64 = 2, } public enum MemoryModel { Simple = 0, GLSL450 = 1, OpenCL = 2, } public enum ExecutionMode { Invocations = 0, SpacingEqual = 1, SpacingFractionalEven = 2, SpacingFractionalOdd = 3, VertexOrderCw = 4, VertexOrderCcw = 5, PixelCenterInteger = 6, OriginUpperLeft = 7, OriginLowerLeft = 8, EarlyFragmentTests = 9, PointMode = 10, Xfb = 11, DepthReplacing = 12, DepthGreater = 14, DepthLess = 15, DepthUnchanged = 16, LocalSize = 17, LocalSizeHint = 18, InputPoints = 19, InputLines = 20, InputLinesAdjacency = 21, Triangles = 22, InputTrianglesAdjacency = 23, Quads = 24, Isolines = 25, OutputVertices = 26, OutputPoints = 27, OutputLineStrip = 28, OutputTriangleStrip = 29, VecTypeHint = 30, ContractionOff = 31, Initializer = 33, Finalizer = 34, SubgroupSize = 35, SubgroupsPerWorkgroup = 36, SubgroupsPerWorkgroupId = 37, LocalSizeId = 38, LocalSizeHintId = 39, PostDepthCoverage = 4446, StencilRefReplacingEXT = 5027, } public enum StorageClass { UniformConstant = 0, Input = 1, Uniform = 2, Output = 3, Workgroup = 4, CrossWorkgroup = 5, Private = 6, Function = 7, Generic = 8, PushConstant = 9, AtomicCounter = 10, Image = 11, StorageBuffer = 12, } public enum Dim { Dim1D = 0, Dim2D = 1, Dim3D = 2, Cube = 3, Rect = 4, Buffer = 5, SubpassData = 6, } public enum SamplerAddressingMode { None = 0, ClampToEdge = 1, Clamp = 2, Repeat = 3, RepeatMirrored = 4, } public enum SamplerFilterMode { Nearest = 0, Linear = 1, } public enum ImageFormat { Unknown = 0, Rgba32f = 1, Rgba16f = 2, R32f = 3, Rgba8 = 4, Rgba8Snorm = 5, Rg32f = 6, Rg16f = 7, R11fG11fB10f = 8, R16f = 9, Rgba16 = 10, Rgb10A2 = 11, Rg16 = 12, Rg8 = 13, R16 = 14, R8 = 15, Rgba16Snorm = 16, Rg16Snorm = 17, Rg8Snorm = 18, R16Snorm = 19, R8Snorm = 20, Rgba32i = 21, Rgba16i = 22, Rgba8i = 23, R32i = 24, Rg32i = 25, Rg16i = 26, Rg8i = 27, R16i = 28, R8i = 29, Rgba32ui = 30, Rgba16ui = 31, Rgba8ui = 32, R32ui = 33, Rgb10a2ui = 34, Rg32ui = 35, Rg16ui = 36, Rg8ui = 37, R16ui = 38, R8ui = 39, } public enum ImageChannelOrder { R = 0, A = 1, RG = 2, RA = 3, RGB = 4, RGBA = 5, BGRA = 6, ARGB = 7, Intensity = 8, Luminance = 9, Rx = 10, RGx = 11, RGBx = 12, Depth = 13, DepthStencil = 14, sRGB = 15, sRGBx = 16, sRGBA = 17, sBGRA = 18, ABGR = 19, } public enum ImageChannelDataType { SnormInt8 = 0, SnormInt16 = 1, UnormInt8 = 2, UnormInt16 = 3, UnormShort565 = 4, UnormShort555 = 5, UnormInt101010 = 6, SignedInt8 = 7, SignedInt16 = 8, SignedInt32 = 9, UnsignedInt8 = 10, UnsignedInt16 = 11, UnsignedInt32 = 12, HalfFloat = 13, Float = 14, UnormInt24 = 15, UnormInt101010_2 = 16, } public enum ImageOperandsShift { Bias = 0, Lod = 1, Grad = 2, ConstOffset = 3, Offset = 4, ConstOffsets = 5, Sample = 6, MinLod = 7, } public enum ImageOperandsMask { MaskNone = 0, Bias = 0x00000001, Lod = 0x00000002, Grad = 0x00000004, ConstOffset = 0x00000008, Offset = 0x00000010, ConstOffsets = 0x00000020, Sample = 0x00000040, MinLod = 0x00000080, } public enum FPFastMathModeShift { NotNaN = 0, NotInf = 1, NSZ = 2, AllowRecip = 3, Fast = 4, } public enum FPFastMathModeMask { MaskNone = 0, NotNaN = 0x00000001, NotInf = 0x00000002, NSZ = 0x00000004, AllowRecip = 0x00000008, Fast = 0x00000010, } public enum FPRoundingMode { RTE = 0, RTZ = 1, RTP = 2, RTN = 3, } public enum LinkageType { Export = 0, Import = 1, } public enum AccessQualifier { ReadOnly = 0, WriteOnly = 1, ReadWrite = 2, } public enum FunctionParameterAttribute { Zext = 0, Sext = 1, ByVal = 2, Sret = 3, NoAlias = 4, NoCapture = 5, NoWrite = 6, NoReadWrite = 7, } public enum Decoration { RelaxedPrecision = 0, SpecId = 1, Block = 2, BufferBlock = 3, RowMajor = 4, ColMajor = 5, ArrayStride = 6, MatrixStride = 7, GLSLShared = 8, GLSLPacked = 9, CPacked = 10, BuiltIn = 11, NoPerspective = 13, Flat = 14, Patch = 15, Centroid = 16, Sample = 17, Invariant = 18, Restrict = 19, Aliased = 20, Volatile = 21, Constant = 22, Coherent = 23, NonWritable = 24, NonReadable = 25, Uniform = 26, SaturatedConversion = 28, Stream = 29, Location = 30, Component = 31, Index = 32, Binding = 33, DescriptorSet = 34, Offset = 35, XfbBuffer = 36, XfbStride = 37, FuncParamAttr = 38, FPRoundingMode = 39, FPFastMathMode = 40, LinkageAttributes = 41, NoContraction = 42, InputAttachmentIndex = 43, Alignment = 44, MaxByteOffset = 45, AlignmentId = 46, MaxByteOffsetId = 47, ExplicitInterpAMD = 4999, OverrideCoverageNV = 5248, PassthroughNV = 5250, ViewportRelativeNV = 5252, SecondaryViewportRelativeNV = 5256, HlslCounterBufferGOOGLE = 5634, HlslSemanticGOOGLE = 5635, } public enum BuiltIn { Position = 0, PointSize = 1, ClipDistance = 3, CullDistance = 4, VertexId = 5, InstanceId = 6, PrimitiveId = 7, InvocationId = 8, Layer = 9, ViewportIndex = 10, TessLevelOuter = 11, TessLevelInner = 12, TessCoord = 13, PatchVertices = 14, FragCoord = 15, PointCoord = 16, FrontFacing = 17, SampleId = 18, SamplePosition = 19, SampleMask = 20, FragDepth = 22, HelperInvocation = 23, NumWorkgroups = 24, WorkgroupSize = 25, WorkgroupId = 26, LocalInvocationId = 27, GlobalInvocationId = 28, LocalInvocationIndex = 29, WorkDim = 30, GlobalSize = 31, EnqueuedWorkgroupSize = 32, GlobalOffset = 33, GlobalLinearId = 34, SubgroupSize = 36, SubgroupMaxSize = 37, NumSubgroups = 38, NumEnqueuedSubgroups = 39, SubgroupId = 40, SubgroupLocalInvocationId = 41, VertexIndex = 42, InstanceIndex = 43, SubgroupEqMaskKHR = 4416, SubgroupGeMaskKHR = 4417, SubgroupGtMaskKHR = 4418, SubgroupLeMaskKHR = 4419, SubgroupLtMaskKHR = 4420, BaseVertex = 4424, BaseInstance = 4425, DrawIndex = 4426, DeviceIndex = 4438, ViewIndex = 4440, BaryCoordNoPerspAMD = 4992, BaryCoordNoPerspCentroidAMD = 4993, BaryCoordNoPerspSampleAMD = 4994, BaryCoordSmoothAMD = 4995, BaryCoordSmoothCentroidAMD = 4996, BaryCoordSmoothSampleAMD = 4997, BaryCoordPullModelAMD = 4998, FragStencilRefEXT = 5014, ViewportMaskNV = 5253, SecondaryPositionNV = 5257, SecondaryViewportMaskNV = 5258, PositionPerViewNV = 5261, ViewportMaskPerViewNV = 5262, } public enum SelectionControlShift { Flatten = 0, DontFlatten = 1, } public enum SelectionControlMask { MaskNone = 0, Flatten = 0x00000001, DontFlatten = 0x00000002, } public enum LoopControlShift { Unroll = 0, DontUnroll = 1, DependencyInfinite = 2, DependencyLength = 3, } public enum LoopControlMask { MaskNone = 0, Unroll = 0x00000001, DontUnroll = 0x00000002, DependencyInfinite = 0x00000004, DependencyLength = 0x00000008, } public enum FunctionControlShift { Inline = 0, DontInline = 1, Pure = 2, Const = 3, } public enum FunctionControlMask { MaskNone = 0, Inline = 0x00000001, DontInline = 0x00000002, Pure = 0x00000004, Const = 0x00000008, } public enum MemorySemanticsShift { Acquire = 1, Release = 2, AcquireRelease = 3, SequentiallyConsistent = 4, UniformMemory = 6, SubgroupMemory = 7, WorkgroupMemory = 8, CrossWorkgroupMemory = 9, AtomicCounterMemory = 10, ImageMemory = 11, } public enum MemorySemanticsMask { MaskNone = 0, Acquire = 0x00000002, Release = 0x00000004, AcquireRelease = 0x00000008, SequentiallyConsistent = 0x00000010, UniformMemory = 0x00000040, SubgroupMemory = 0x00000080, WorkgroupMemory = 0x00000100, CrossWorkgroupMemory = 0x00000200, AtomicCounterMemory = 0x00000400, ImageMemory = 0x00000800, } public enum MemoryAccessShift { Volatile = 0, Aligned = 1, Nontemporal = 2, } public enum MemoryAccessMask { MaskNone = 0, Volatile = 0x00000001, Aligned = 0x00000002, Nontemporal = 0x00000004, } public enum Scope { CrossDevice = 0, Device = 1, Workgroup = 2, Subgroup = 3, Invocation = 4, } public enum GroupOperation { Reduce = 0, InclusiveScan = 1, ExclusiveScan = 2, } public enum KernelEnqueueFlags { NoWait = 0, WaitKernel = 1, WaitWorkGroup = 2, } public enum KernelProfilingInfoShift { CmdExecTime = 0, } public enum KernelProfilingInfoMask { MaskNone = 0, CmdExecTime = 0x00000001, } public enum Capability { Matrix = 0, Shader = 1, Geometry = 2, Tessellation = 3, Addresses = 4, Linkage = 5, Kernel = 6, Vector16 = 7, Float16Buffer = 8, Float16 = 9, Float64 = 10, Int64 = 11, Int64Atomics = 12, ImageBasic = 13, ImageReadWrite = 14, ImageMipmap = 15, Pipes = 17, Groups = 18, DeviceEnqueue = 19, LiteralSampler = 20, AtomicStorage = 21, Int16 = 22, TessellationPointSize = 23, GeometryPointSize = 24, ImageGatherExtended = 25, StorageImageMultisample = 27, UniformBufferArrayDynamicIndexing = 28, SampledImageArrayDynamicIndexing = 29, StorageBufferArrayDynamicIndexing = 30, StorageImageArrayDynamicIndexing = 31, ClipDistance = 32, CullDistance = 33, ImageCubeArray = 34, SampleRateShading = 35, ImageRect = 36, SampledRect = 37, GenericPointer = 38, Int8 = 39, InputAttachment = 40, SparseResidency = 41, MinLod = 42, Sampled1D = 43, Image1D = 44, SampledCubeArray = 45, SampledBuffer = 46, ImageBuffer = 47, ImageMSArray = 48, StorageImageExtendedFormats = 49, ImageQuery = 50, DerivativeControl = 51, InterpolationFunction = 52, TransformFeedback = 53, GeometryStreams = 54, StorageImageReadWithoutFormat = 55, StorageImageWriteWithoutFormat = 56, MultiViewport = 57, SubgroupDispatch = 58, NamedBarrier = 59, PipeStorage = 60, SubgroupBallotKHR = 4423, DrawParameters = 4427, SubgroupVoteKHR = 4431, StorageBuffer16BitAccess = 4433, StorageUniformBufferBlock16 = 4433, StorageUniform16 = 4434, UniformAndStorageBuffer16BitAccess = 4434, StoragePushConstant16 = 4435, StorageInputOutput16 = 4436, DeviceGroup = 4437, MultiView = 4439, VariablePointersStorageBuffer = 4441, VariablePointers = 4442, AtomicStorageOps = 4445, SampleMaskPostDepthCoverage = 4447, ImageGatherBiasLodAMD = 5009, FragmentMaskAMD = 5010, StencilExportEXT = 5013, ImageReadWriteLodAMD = 5015, SampleMaskOverrideCoverageNV = 5249, GeometryShaderPassthroughNV = 5251, ShaderViewportIndexLayerEXT = 5254, ShaderViewportIndexLayerNV = 5254, ShaderViewportMaskNV = 5255, ShaderStereoViewNV = 5259, PerViewAttributesNV = 5260, SubgroupShuffleINTEL = 5568, SubgroupBufferBlockIOINTEL = 5569, SubgroupImageBlockIOINTEL = 5570, } public enum Op { OpNop = 0, OpUndef = 1, OpSourceContinued = 2, OpSource = 3, OpSourceExtension = 4, OpName = 5, OpMemberName = 6, OpString = 7, OpLine = 8, OpExtension = 10, OpExtInstImport = 11, OpExtInst = 12, OpMemoryModel = 14, OpEntryPoint = 15, OpExecutionMode = 16, OpCapability = 17, OpTypeVoid = 19, OpTypeBool = 20, OpTypeInt = 21, OpTypeFloat = 22, OpTypeVector = 23, OpTypeMatrix = 24, OpTypeImage = 25, OpTypeSampler = 26, OpTypeSampledImage = 27, OpTypeArray = 28, OpTypeRuntimeArray = 29, OpTypeStruct = 30, OpTypeOpaque = 31, OpTypePointer = 32, OpTypeFunction = 33, OpTypeEvent = 34, OpTypeDeviceEvent = 35, OpTypeReserveId = 36, OpTypeQueue = 37, OpTypePipe = 38, OpTypeForwardPointer = 39, OpConstantTrue = 41, OpConstantFalse = 42, OpConstant = 43, OpConstantComposite = 44, OpConstantSampler = 45, OpConstantNull = 46, OpSpecConstantTrue = 48, OpSpecConstantFalse = 49, OpSpecConstant = 50, OpSpecConstantComposite = 51, OpSpecConstantOp = 52, OpFunction = 54, OpFunctionParameter = 55, OpFunctionEnd = 56, OpFunctionCall = 57, OpVariable = 59, OpImageTexelPointer = 60, OpLoad = 61, OpStore = 62, OpCopyMemory = 63, OpCopyMemorySized = 64, OpAccessChain = 65, OpInBoundsAccessChain = 66, OpPtrAccessChain = 67, OpArrayLength = 68, OpGenericPtrMemSemantics = 69, OpInBoundsPtrAccessChain = 70, OpDecorate = 71, OpMemberDecorate = 72, OpDecorationGroup = 73, OpGroupDecorate = 74, OpGroupMemberDecorate = 75, OpVectorExtractDynamic = 77, OpVectorInsertDynamic = 78, OpVectorShuffle = 79, OpCompositeConstruct = 80, OpCompositeExtract = 81, OpCompositeInsert = 82, OpCopyObject = 83, OpTranspose = 84, OpSampledImage = 86, OpImageSampleImplicitLod = 87, OpImageSampleExplicitLod = 88, OpImageSampleDrefImplicitLod = 89, OpImageSampleDrefExplicitLod = 90, OpImageSampleProjImplicitLod = 91, OpImageSampleProjExplicitLod = 92, OpImageSampleProjDrefImplicitLod = 93, OpImageSampleProjDrefExplicitLod = 94, OpImageFetch = 95, OpImageGather = 96, OpImageDrefGather = 97, OpImageRead = 98, OpImageWrite = 99, OpImage = 100, OpImageQueryFormat = 101, OpImageQueryOrder = 102, OpImageQuerySizeLod = 103, OpImageQuerySize = 104, OpImageQueryLod = 105, OpImageQueryLevels = 106, OpImageQuerySamples = 107, OpConvertFToU = 109, OpConvertFToS = 110, OpConvertSToF = 111, OpConvertUToF = 112, OpUConvert = 113, OpSConvert = 114, OpFConvert = 115, OpQuantizeToF16 = 116, OpConvertPtrToU = 117, OpSatConvertSToU = 118, OpSatConvertUToS = 119, OpConvertUToPtr = 120, OpPtrCastToGeneric = 121, OpGenericCastToPtr = 122, OpGenericCastToPtrExplicit = 123, OpBitcast = 124, OpSNegate = 126, OpFNegate = 127, OpIAdd = 128, OpFAdd = 129, OpISub = 130, OpFSub = 131, OpIMul = 132, OpFMul = 133, OpUDiv = 134, OpSDiv = 135, OpFDiv = 136, OpUMod = 137, OpSRem = 138, OpSMod = 139, OpFRem = 140, OpFMod = 141, OpVectorTimesScalar = 142, OpMatrixTimesScalar = 143, OpVectorTimesMatrix = 144, OpMatrixTimesVector = 145, OpMatrixTimesMatrix = 146, OpOuterProduct = 147, OpDot = 148, OpIAddCarry = 149, OpISubBorrow = 150, OpUMulExtended = 151, OpSMulExtended = 152, OpAny = 154, OpAll = 155, OpIsNan = 156, OpIsInf = 157, OpIsFinite = 158, OpIsNormal = 159, OpSignBitSet = 160, OpLessOrGreater = 161, OpOrdered = 162, OpUnordered = 163, OpLogicalEqual = 164, OpLogicalNotEqual = 165, OpLogicalOr = 166, OpLogicalAnd = 167, OpLogicalNot = 168, OpSelect = 169, OpIEqual = 170, OpINotEqual = 171, OpUGreaterThan = 172, OpSGreaterThan = 173, OpUGreaterThanEqual = 174, OpSGreaterThanEqual = 175, OpULessThan = 176, OpSLessThan = 177, OpULessThanEqual = 178, OpSLessThanEqual = 179, OpFOrdEqual = 180, OpFUnordEqual = 181, OpFOrdNotEqual = 182, OpFUnordNotEqual = 183, OpFOrdLessThan = 184, OpFUnordLessThan = 185, OpFOrdGreaterThan = 186, OpFUnordGreaterThan = 187, OpFOrdLessThanEqual = 188, OpFUnordLessThanEqual = 189, OpFOrdGreaterThanEqual = 190, OpFUnordGreaterThanEqual = 191, OpShiftRightLogical = 194, OpShiftRightArithmetic = 195, OpShiftLeftLogical = 196, OpBitwiseOr = 197, OpBitwiseXor = 198, OpBitwiseAnd = 199, OpNot = 200, OpBitFieldInsert = 201, OpBitFieldSExtract = 202, OpBitFieldUExtract = 203, OpBitReverse = 204, OpBitCount = 205, OpDPdx = 207, OpDPdy = 208, OpFwidth = 209, OpDPdxFine = 210, OpDPdyFine = 211, OpFwidthFine = 212, OpDPdxCoarse = 213, OpDPdyCoarse = 214, OpFwidthCoarse = 215, OpEmitVertex = 218, OpEndPrimitive = 219, OpEmitStreamVertex = 220, OpEndStreamPrimitive = 221, OpControlBarrier = 224, OpMemoryBarrier = 225, OpAtomicLoad = 227, OpAtomicStore = 228, OpAtomicExchange = 229, OpAtomicCompareExchange = 230, OpAtomicCompareExchangeWeak = 231, OpAtomicIIncrement = 232, OpAtomicIDecrement = 233, OpAtomicIAdd = 234, OpAtomicISub = 235, OpAtomicSMin = 236, OpAtomicUMin = 237, OpAtomicSMax = 238, OpAtomicUMax = 239, OpAtomicAnd = 240, OpAtomicOr = 241, OpAtomicXor = 242, OpPhi = 245, OpLoopMerge = 246, OpSelectionMerge = 247, OpLabel = 248, OpBranch = 249, OpBranchConditional = 250, OpSwitch = 251, OpKill = 252, OpReturn = 253, OpReturnValue = 254, OpUnreachable = 255, OpLifetimeStart = 256, OpLifetimeStop = 257, OpGroupAsyncCopy = 259, OpGroupWaitEvents = 260, OpGroupAll = 261, OpGroupAny = 262, OpGroupBroadcast = 263, OpGroupIAdd = 264, OpGroupFAdd = 265, OpGroupFMin = 266, OpGroupUMin = 267, OpGroupSMin = 268, OpGroupFMax = 269, OpGroupUMax = 270, OpGroupSMax = 271, OpReadPipe = 274, OpWritePipe = 275, OpReservedReadPipe = 276, OpReservedWritePipe = 277, OpReserveReadPipePackets = 278, OpReserveWritePipePackets = 279, OpCommitReadPipe = 280, OpCommitWritePipe = 281, OpIsValidReserveId = 282, OpGetNumPipePackets = 283, OpGetMaxPipePackets = 284, OpGroupReserveReadPipePackets = 285, OpGroupReserveWritePipePackets = 286, OpGroupCommitReadPipe = 287, OpGroupCommitWritePipe = 288, OpEnqueueMarker = 291, OpEnqueueKernel = 292, OpGetKernelNDrangeSubGroupCount = 293, OpGetKernelNDrangeMaxSubGroupSize = 294, OpGetKernelWorkGroupSize = 295, OpGetKernelPreferredWorkGroupSizeMultiple = 296, OpRetainEvent = 297, OpReleaseEvent = 298, OpCreateUserEvent = 299, OpIsValidEvent = 300, OpSetUserEventStatus = 301, OpCaptureEventProfilingInfo = 302, OpGetDefaultQueue = 303, OpBuildNDRange = 304, OpImageSparseSampleImplicitLod = 305, OpImageSparseSampleExplicitLod = 306, OpImageSparseSampleDrefImplicitLod = 307, OpImageSparseSampleDrefExplicitLod = 308, OpImageSparseSampleProjImplicitLod = 309, OpImageSparseSampleProjExplicitLod = 310, OpImageSparseSampleProjDrefImplicitLod = 311, OpImageSparseSampleProjDrefExplicitLod = 312, OpImageSparseFetch = 313, OpImageSparseGather = 314, OpImageSparseDrefGather = 315, OpImageSparseTexelsResident = 316, OpNoLine = 317, OpAtomicFlagTestAndSet = 318, OpAtomicFlagClear = 319, OpImageSparseRead = 320, OpSizeOf = 321, OpTypePipeStorage = 322, OpConstantPipeStorage = 323, OpCreatePipeFromPipeStorage = 324, OpGetKernelLocalSizeForSubgroupCount = 325, OpGetKernelMaxNumSubgroups = 326, OpTypeNamedBarrier = 327, OpNamedBarrierInitialize = 328, OpMemoryNamedBarrier = 329, OpModuleProcessed = 330, OpExecutionModeId = 331, OpDecorateId = 332, OpSubgroupBallotKHR = 4421, OpSubgroupFirstInvocationKHR = 4422, OpSubgroupAllKHR = 4428, OpSubgroupAnyKHR = 4429, OpSubgroupAllEqualKHR = 4430, OpSubgroupReadInvocationKHR = 4432, OpGroupIAddNonUniformAMD = 5000, OpGroupFAddNonUniformAMD = 5001, OpGroupFMinNonUniformAMD = 5002, OpGroupUMinNonUniformAMD = 5003, OpGroupSMinNonUniformAMD = 5004, OpGroupFMaxNonUniformAMD = 5005, OpGroupUMaxNonUniformAMD = 5006, OpGroupSMaxNonUniformAMD = 5007, OpFragmentMaskFetchAMD = 5011, OpFragmentFetchAMD = 5012, OpSubgroupShuffleINTEL = 5571, OpSubgroupShuffleDownINTEL = 5572, OpSubgroupShuffleUpINTEL = 5573, OpSubgroupShuffleXorINTEL = 5574, OpSubgroupBlockReadINTEL = 5575, OpSubgroupBlockWriteINTEL = 5576, OpSubgroupImageBlockReadINTEL = 5577, OpSubgroupImageBlockWriteINTEL = 5578, OpDecorateStringGOOGLE = 5632, OpMemberDecorateStringGOOGLE = 5633, } } }
using UnityEngine; using System; using AppodealAds.Unity.Api; using AppodealAds.Unity.Common; using AOT; #if UNITY_IPHONE namespace AppodealAds.Unity.iOS { public class AppodealAdsClient : IAppodealAdsClient { private const int AppodealAdTypeInterstitial = 1 << 0; private const int AppodealAdTypeSkippableVideo = 1 << 1; private const int AppodealAdTypeBanner = 1 << 2; private const int AppodealAdTypeRewardedVideo = 1 << 4; private const int AppodealAdTypeNonSkippableVideo = 1 << 6; private const int AppodealAdTypeAll = AppodealAdTypeInterstitial | AppodealAdTypeSkippableVideo | AppodealAdTypeBanner | AppodealAdTypeNonSkippableVideo | AppodealAdTypeRewardedVideo; private const int AppodealShowStyleInterstitial = 1; private const int AppodealShowStyleVideo = 2; private const int AppodealShowStyleVideoOrInterstitial = 3; private const int AppodealShowStyleBannerTop = 4; private const int AppodealShowStyleBannerBottom = 5; private const int AppodealShowStyleRewardedVideo = 6; private const int AppodealShowStyleNonSkippableVideo = 7; #region Singleton private AppodealAdsClient(){} private static readonly AppodealAdsClient instance = new AppodealAdsClient(); public static AppodealAdsClient Instance { get { return instance; } } #endregion public void requestAndroidMPermissions(IPermissionGrantedListener listener) { // not supported on ios } private static IInterstitialAdListener interstitialListener; private static ISkippableVideoAdListener skippableVideoListener; private static INonSkippableVideoAdListener nonSkippableVideoListener; private static IRewardedVideoAdListener rewardedVideoListener; private static IBannerAdListener bannerListener; #region Interstitial Delegate [MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))] private static void interstitialDidLoad () { if (AppodealAdsClient.interstitialListener != null) { AppodealAdsClient.interstitialListener.onInterstitialLoaded(); } } [MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))] private static void interstitialDidFailToLoad () { if (AppodealAdsClient.interstitialListener != null) { AppodealAdsClient.interstitialListener.onInterstitialFailedToLoad(); } } [MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))] private static void interstitialDidClick () { if (AppodealAdsClient.interstitialListener != null) { AppodealAdsClient.interstitialListener.onInterstitialClicked(); } } [MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))] private static void interstitialDidDismiss () { if (AppodealAdsClient.interstitialListener != null) { AppodealAdsClient.interstitialListener.onInterstitialClosed(); } } [MonoPInvokeCallback (typeof (AppodealInterstitialCallbacks))] private static void interstitialWillPresent () { if (AppodealAdsClient.interstitialListener != null) { AppodealAdsClient.interstitialListener.onInterstitialShown(); } } public void setInterstitialCallbacks(IInterstitialAdListener listener) { AppodealAdsClient.interstitialListener = listener; AppodealObjCBridge.AppodealSetInterstitialDelegate( AppodealAdsClient.interstitialDidLoad, AppodealAdsClient.interstitialDidFailToLoad, AppodealAdsClient.interstitialDidClick, AppodealAdsClient.interstitialDidDismiss, AppodealAdsClient.interstitialWillPresent ); } #endregion #region Skippable Video Delegate [MonoPInvokeCallback (typeof (AppodealSkippableVideoCallbacks))] private static void skippableVideoDidLoadAd() { if (AppodealAdsClient.skippableVideoListener != null) { AppodealAdsClient.skippableVideoListener.onSkippableVideoLoaded(); } } [MonoPInvokeCallback (typeof (AppodealSkippableVideoCallbacks))] private static void skippableVideoDidFailToLoadAd() { if (AppodealAdsClient.skippableVideoListener != null) { AppodealAdsClient.skippableVideoListener.onSkippableVideoFailedToLoad(); } } [MonoPInvokeCallback (typeof (AppodealSkippableVideoCallbacks))] private static void skippableVideoWillDismiss() { if (AppodealAdsClient.skippableVideoListener != null) { AppodealAdsClient.skippableVideoListener.onSkippableVideoClosed(); } } [MonoPInvokeCallback (typeof (AppodealSkippableVideoCallbacks))] private static void skippableVideoDidFinish() { if (AppodealAdsClient.skippableVideoListener != null) { AppodealAdsClient.skippableVideoListener.onSkippableVideoFinished(); } } [MonoPInvokeCallback (typeof (AppodealSkippableVideoCallbacks))] private static void skippableVideoDidPresent() { if (AppodealAdsClient.skippableVideoListener != null) { AppodealAdsClient.skippableVideoListener.onSkippableVideoShown(); } } public void setSkippableVideoCallbacks(ISkippableVideoAdListener listener) { AppodealAdsClient.skippableVideoListener = listener; AppodealObjCBridge.AppodealSetSkippableVideoDelegate( AppodealAdsClient.skippableVideoDidLoadAd, AppodealAdsClient.skippableVideoDidFailToLoadAd, AppodealAdsClient.skippableVideoWillDismiss, AppodealAdsClient.skippableVideoDidFinish, AppodealAdsClient.skippableVideoDidPresent ); } #endregion #region Non Skippable Video Delegate [MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))] private static void nonSkippableVideoDidLoadAd() { if (AppodealAdsClient.nonSkippableVideoListener != null) { AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoLoaded(); } } [MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))] private static void nonSkippableVideoDidFailToLoadAd() { if (AppodealAdsClient.nonSkippableVideoListener != null) { AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoFailedToLoad(); } } [MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))] private static void nonSkippableVideoWillDismiss() { if (AppodealAdsClient.nonSkippableVideoListener != null) { AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoClosed(); } } [MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))] private static void nonSkippableVideoDidFinish() { if (AppodealAdsClient.nonSkippableVideoListener != null) { AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoFinished(); } } [MonoPInvokeCallback (typeof (AppodealNonSkippableVideoCallbacks))] private static void nonSkippableVideoDidPresent() { if (AppodealAdsClient.nonSkippableVideoListener != null) { AppodealAdsClient.nonSkippableVideoListener.onNonSkippableVideoShown(); } } public void setNonSkippableVideoCallbacks(INonSkippableVideoAdListener listener) { AppodealAdsClient.nonSkippableVideoListener = listener; AppodealObjCBridge.AppodealSetNonSkippableVideoDelegate( AppodealAdsClient.nonSkippableVideoDidLoadAd, AppodealAdsClient.nonSkippableVideoDidFailToLoadAd, AppodealAdsClient.nonSkippableVideoWillDismiss, AppodealAdsClient.nonSkippableVideoDidFinish, AppodealAdsClient.nonSkippableVideoDidPresent ); } #endregion #region Rewarded Video Delegate [MonoPInvokeCallback (typeof (AppodealRewardedVideoCallbacks))] private static void rewardedVideoDidLoadAd() { if (AppodealAdsClient.rewardedVideoListener != null) { AppodealAdsClient.rewardedVideoListener.onRewardedVideoLoaded(); } } [MonoPInvokeCallback (typeof (AppodealRewardedVideoCallbacks))] private static void rewardedVideoDidFailToLoadAd() { if (AppodealAdsClient.rewardedVideoListener != null) { AppodealAdsClient.rewardedVideoListener.onRewardedVideoFailedToLoad(); } } [MonoPInvokeCallback (typeof (AppodealRewardedVideoCallbacks))] private static void rewardedVideoWillDismiss() { if (AppodealAdsClient.rewardedVideoListener != null) { AppodealAdsClient.rewardedVideoListener.onRewardedVideoClosed(); } } [MonoPInvokeCallback (typeof (AppodealRewardedVideoDidFinishCallback))] private static void rewardedVideoDidFinish(int amount, string name) { if (AppodealAdsClient.rewardedVideoListener != null) { AppodealAdsClient.rewardedVideoListener.onRewardedVideoFinished(amount, name); } } [MonoPInvokeCallback (typeof (AppodealRewardedVideoCallbacks))] private static void rewardedVideoDidPresent() { if (AppodealAdsClient.rewardedVideoListener != null) { AppodealAdsClient.rewardedVideoListener.onRewardedVideoShown(); } } public void setRewardedVideoCallbacks(IRewardedVideoAdListener listener) { AppodealAdsClient.rewardedVideoListener = listener; AppodealObjCBridge.AppodealSetRewardedVideoDelegate( AppodealAdsClient.rewardedVideoDidLoadAd, AppodealAdsClient.rewardedVideoDidFailToLoadAd, AppodealAdsClient.rewardedVideoWillDismiss, AppodealAdsClient.rewardedVideoDidFinish, AppodealAdsClient.rewardedVideoDidPresent ); } #endregion #region Banner Delegate [MonoPInvokeCallback (typeof (AppodealBannerCallbacks))] private static void bannerDidLoadAd() { if (AppodealAdsClient.bannerListener != null) { AppodealAdsClient.bannerListener.onBannerLoaded(); } } [MonoPInvokeCallback (typeof (AppodealBannerCallbacks))] private static void bannerDidFailToLoadAd() { if (AppodealAdsClient.bannerListener != null) { AppodealAdsClient.bannerListener.onBannerFailedToLoad(); } } [MonoPInvokeCallback (typeof (AppodealBannerCallbacks))] private static void bannerDidClick () { if (AppodealAdsClient.bannerListener != null) { AppodealAdsClient.bannerListener.onBannerClicked(); } } [MonoPInvokeCallback (typeof (AppodealBannerCallbacks))] private static void bannerDidShow () { if (AppodealAdsClient.bannerListener != null) { AppodealAdsClient.bannerListener.onBannerShown(); } } public void setBannerCallbacks(IBannerAdListener listener) { AppodealAdsClient.bannerListener = listener; AppodealObjCBridge.AppodealSetBannerDelegate( AppodealAdsClient.bannerDidLoadAd, AppodealAdsClient.bannerDidFailToLoadAd, AppodealAdsClient.bannerDidClick, AppodealAdsClient.bannerDidShow); } #endregion private int nativeAdTypesForType(int adTypes) { int nativeAdTypes = 0; if ((adTypes & Appodeal.INTERSTITIAL) > 0) { nativeAdTypes |= AppodealAdTypeInterstitial; } if ((adTypes & Appodeal.SKIPPABLE_VIDEO) > 0) { nativeAdTypes |= AppodealAdTypeSkippableVideo; } if ((adTypes & Appodeal.BANNER) > 0 || (adTypes & Appodeal.BANNER_TOP) > 0 || (adTypes & Appodeal.BANNER_BOTTOM) > 0) { nativeAdTypes |= AppodealAdTypeBanner; } if ((adTypes & Appodeal.REWARDED_VIDEO) > 0) { nativeAdTypes |= AppodealAdTypeRewardedVideo; } if ((adTypes & Appodeal.NON_SKIPPABLE_VIDEO) > 0) { nativeAdTypes |= AppodealAdTypeNonSkippableVideo; } return nativeAdTypes; } private int nativeShowStyleForType(int adTypes) { bool isInterstitial = (adTypes & Appodeal.INTERSTITIAL) > 0; bool isVideo = (adTypes & Appodeal.SKIPPABLE_VIDEO) > 0; if (isInterstitial && isVideo) { return AppodealShowStyleVideoOrInterstitial; } else if (isVideo) { return AppodealShowStyleVideo; } else if (isInterstitial) { return AppodealShowStyleInterstitial; } if ((adTypes & Appodeal.BANNER_TOP) > 0) { return AppodealShowStyleBannerTop; } if ((adTypes & Appodeal.BANNER_BOTTOM) > 0) { return AppodealShowStyleBannerBottom; } if ((adTypes & Appodeal.REWARDED_VIDEO) > 0) { return AppodealShowStyleRewardedVideo; } if ((adTypes & Appodeal.NON_SKIPPABLE_VIDEO) > 0) { return AppodealShowStyleNonSkippableVideo; } return 0; } public void initialize(string appKey, int adTypes) { AppodealObjCBridge.AppodealInitializeWithTypes(appKey, nativeAdTypesForType(adTypes)); } public void cache(int adTypes) { AppodealObjCBridge.AppodealCacheAd(nativeAdTypesForType(adTypes)); } public void cache(int adTypes, string placement) { AppodealObjCBridge.AppodealCacheAdWithPlacement(nativeAdTypesForType(adTypes), placement); } public Boolean isLoaded(int adTypes) { int style = nativeShowStyleForType(adTypes); bool isBanner = style == AppodealShowStyleBannerTop || style == AppodealShowStyleBannerBottom; return isBanner ? true : AppodealObjCBridge.AppodealIsReadyWithStyle(style); } public Boolean isPrecache(int adTypes) { return false; } public Boolean show(int adTypes) { return AppodealObjCBridge.AppodealShowAd(nativeShowStyleForType(adTypes)); } public Boolean show(int adTypes, string placement) { return AppodealObjCBridge.AppodealShowAdforPlacement(nativeShowStyleForType(adTypes), placement); } public void hide(int adTypes) { if ((nativeAdTypesForType(adTypes) & AppodealAdTypeBanner) > 0) { AppodealObjCBridge.AppodealHideBanner(); } } public void setAutoCache(int adTypes, Boolean autoCache) { AppodealObjCBridge.AppodealSetAutocache(autoCache, nativeAdTypesForType(adTypes)); } public void setTesting(Boolean test) { AppodealObjCBridge.AppodealSetTestingEnabled(test); } public void setLogging(Boolean logging) { AppodealObjCBridge.AppodealSetDebugEnabled(logging); } public void setOnLoadedTriggerBoth(int adTypes, Boolean onLoadedTriggerBoth) { // Not supported for iOS SDK } public void confirm(int adTypes) { AppodealObjCBridge.AppodealConfirmUsage(adTypes); } public void disableWriteExternalStoragePermissionCheck() { // Not supported for iOS SDK } public void disableNetwork(String network) { AppodealObjCBridge.AppodealDisableNetwork(network); } public void disableNetwork(String network, int adTypes) { AppodealObjCBridge.AppodealDisableNetworkForAdTypes(network, adTypes); } public void disableLocationPermissionCheck() { AppodealObjCBridge.AppodealDisableLocationPermissionCheck(); } public void orientationChange() { } // handled by SDK public string getVersion() { return AppodealObjCBridge.AppodealGetVersion(); } //User Settings public void getUserSettings() { // No additional state change required on iOS } public void setUserId(string id) { AppodealObjCBridge.AppodealSetUserId(id); } public void setAge(int age) { AppodealObjCBridge.AppodealSetUserAge(age); } public void setBirthday(string bDay) { AppodealObjCBridge.AppodealSetUserBirthday(bDay); } public void setEmail(String email) { AppodealObjCBridge.AppodealSetUserEmail(email); } public void setGender(int gender) { AppodealObjCBridge.AppodealSetUserGender(gender - 1); // iOS Enum starts from 0 } public void setInterests(String interests) { AppodealObjCBridge.AppodealSetUserInterests(interests); } public void setOccupation(int occupation) { AppodealObjCBridge.AppodealSetUserOccupation(occupation - 1); } public void setRelation(int relation) { AppodealObjCBridge.AppodealSetUserRelationship(relation - 1); } public void setAlcohol(int alcohol) { AppodealObjCBridge.AppodealSetUserAlcoholAttitude(alcohol); } public void setSmoking(int smoking) { AppodealObjCBridge.AppodealSetUserSmokingAttitude(smoking); } public void trackInAppPurchase(double amount, string currency) { //TODO; } public void setCustomRule(string name, bool value) { AppodealObjCBridge.setCustomSegmentBool(name, value); } public void setCustomRule(string name, int value) { AppodealObjCBridge.setCustomSegmentInt(name, value); } public void setCustomRule(string name, double value) { AppodealObjCBridge.setCustomSegmentDouble(name, value); } public void setCustomRule(string name, string value) { AppodealObjCBridge.setCustomSegmentString(name, value); } public void setSmartBanners(Boolean value) { AppodealObjCBridge.setSmartBanners(value); } public void setBannerAnimation(bool value) { AppodealObjCBridge.setBannerAnimation(value); } public void setBannerBackground(bool value) { AppodealObjCBridge.setBannerBackground(value); } } } #endif
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Reflection; #if CustomDLR using DLR = Microsoft.Scripting.Ast; #else using DLR = System.Linq.Expressions; #endif #if CLR_35 using CobaltAHK.v35Compat; #endif using CobaltAHK.Expressions; namespace CobaltAHK.ExpressionTree { public class Generator { internal static readonly DLR.Expression NULL = DLR.Expression.Constant(null); internal static readonly DLR.Expression TRUE = DLR.Expression.Constant(true); internal static readonly DLR.Expression FALSE = DLR.Expression.Constant(false); internal static readonly DLR.Expression EMPTY_STRING = DLR.Expression.Constant(""); public Generator(ScriptSettings config) { settings = config; } private readonly ScriptSettings settings; public DLR.Expression Generate(Expression expr, Scope scope) { if (expr is FunctionCallExpression) { return GenerateFunctionCall((FunctionCallExpression)expr, scope); } else if (expr is FunctionDefinitionExpression) { return GenerateFunctionDefinition((FunctionDefinitionExpression)expr, scope); } else if (expr is ClassDefinitionExpression) { return GenerateClassDefinition((ClassDefinitionExpression)expr, scope); } else if (expr is CustomVariableExpression) { return scope.ResolveVariable(((CustomVariableExpression)expr).Name); } else if (expr is BuiltinVariableExpression) { return scope.ResolveBuiltinVariable(((BuiltinVariableExpression)expr).Variable); } else if (expr is ValueKeywordExpression) { switch (((ValueKeywordExpression)expr).Keyword) { case Syntax.ValueKeyword.False: return FALSE; case Syntax.ValueKeyword.True: return TRUE; case Syntax.ValueKeyword.Null: return NULL; } } else if (expr is UnaryExpression) { return GenerateUnaryExpression((UnaryExpression)expr, scope); } else if (expr is BinaryExpression) { return GenerateBinaryExpression((BinaryExpression)expr, scope); } else if (expr is TernaryExpression) { return GenerateTernaryExpression((TernaryExpression)expr, scope); } else if (expr is MemberAccessExpression) { return GenerateMemberAccess((MemberAccessExpression)expr, scope); } else if (expr is StringLiteralExpression) { return DLR.Expression.Constant(((StringLiteralExpression)expr).Value); } else if (expr is NumberLiteralExpression) { return DLR.Expression.Constant(((NumberLiteralExpression)expr).GetValue()); } else if (expr is ObjectLiteralExpression) { return GenerateObjectLiteral((ObjectLiteralExpression)expr, scope); } else if (expr is ArrayLiteralExpression) { return GenerateArrayLiteral((ArrayLiteralExpression)expr, scope); } else if (expr is BlockExpression) { return GenerateIfElse((BlockExpression)expr, scope); } else if (expr is ThrowExpression) { return GenerateThrow((ThrowExpression)expr, scope); } else if (expr is ReturnExpression) { return GenerateReturnExpression((ReturnExpression)expr, scope); } throw new NotImplementedException(); } private static readonly ConstructorInfo ObjConstructor = typeof(CobaltAHKObject) .GetConstructor(BindingFlags.NonPublic|BindingFlags.Instance, null, new[] { typeof(IEnumerable<object>), typeof(IEnumerable<object>) }, null); private DLR.Expression GenerateObjectLiteral(ObjectLiteralExpression obj, Scope scope) { var keys = ExpressionArray(obj.Value.Keys, scope); var values = ExpressionArray(obj.Value.Values, scope); return DLR.Expression.New(ObjConstructor, keys, values); } private DLR.Expression GenerateArrayLiteral(ArrayLiteralExpression arr, Scope scope) { var create = DLR.Expression.New(typeof(List<object>)); if (arr.Value.Length == 0) { return create; } return DLR.Expression.ListInit( create, arr.Value.Select(e => Converter.ConvertToObject(Generate(e, scope))) ); } [Obsolete] private DLR.Expression ExpressionArray(IEnumerable<ValueExpression> exprs, Scope scope) { return DLR.Expression.NewArrayInit(typeof(object), exprs.Select(e => Converter.ConvertToObject(Generate(e, scope)))); } private DLR.Expression GenerateIfElse(BlockExpression block, Scope scope) { return GenerateIfElse(block.Branches, scope); } private DLR.Expression GenerateIfElse(ControlFlowExpression[] branches, Scope scope) { if (!(branches[0] is IfExpression)) { throw new InvalidOperationException(); } var ifExpr = (IfExpression)branches[0]; var ifCond = Converter.ConvertToBoolean(Generate(ifExpr.Condition, scope)); var ifBlock = DLR.Expression.Block(ifExpr.Body.Select(e => Generate(e, scope)).Append(DLR.Expression.Empty())); if (branches.Length == 1) { return DLR.Expression.IfThen(ifCond, ifBlock); } else if (branches[1] is ElseExpression) { var elseExpr = (ElseExpression)branches[1]; return DLR.Expression.IfThenElse(ifCond, ifBlock, DLR.Expression.Block(elseExpr.Body.Select(e => Generate(e, scope)))); } else { return DLR.Expression.IfThenElse(ifCond, ifBlock, GenerateIfElse(branches.Except(new[] { ifExpr }).ToArray(), scope)); } } private DLR.Expression GenerateFunctionCall(FunctionCallExpression func, Scope scope) { if (!scope.FunctionExists(func.Name)) { throw new Exception("Unknown function: " + func.Name); // todo } else if (!scope.IsFunctionDefined(func.Name)) { return GenerateDynamicFunctionCall(func, scope); } var lambda = scope.ResolveFunction(func.Name); var prms = GenerateParams(func, scope); if (lambda.Parameters.Count != prms.Count()) { throw new Exception(); // todo } return DLR.Expression.Invoke(lambda, prms); } private DLR.Expression GenerateDynamicFunctionCall(FunctionCallExpression func, Scope scope) { var args = new List<DLR.Expression>(func.Parameters.Length + 1); args.Add(DLR.Expression.Constant(func.Name)); args.AddRange(GenerateParams(func, scope)); // todo: store param count in scope and validate? var binder = new FunctionCallBinder(new CallInfo(func.Parameters.Length), scope); // todo: cache instances? return DLR.Expression.Dynamic(binder, typeof(object), args); } private IEnumerable<DLR.Expression> GenerateParams(FunctionCallExpression func, Scope scope) { return func.Parameters.Select(p => Generate(p, scope)); // todo: convert param types } private DLR.Expression GenerateFunctionDefinition(FunctionDefinitionExpression func, Scope scope) { var funcScope = scope.GetScope(func); // get the scope created by the preprocessor var prms = new List<DLR.ParameterExpression>(); var types = new List<Type>(prms.Count + 1); foreach (var p in func.Parameters) { var param = DLR.Expression.Parameter(typeof(object), p.Name); prms.Add(param); funcScope.AddVariable(p.Name, param); /*if (p.DefaultValue != null) { // todo: init: `if (!param) { param := default }` // todo: this conflicts with intentionally-passed NULL // todo: instead, add overloads // todo: however, especially with named parameter support, there's endless possibilities and thus endless overloads // todo: instead, store default values and detect them on function call }*/ var type = typeof(object); if (p.Modifier.HasFlag(Syntax.ParameterModifier.ByRef)) { type = type.MakeByRefType(); } types.Add(type); } types.Add(typeof(object)); // return value var funcBody = func.Body.Select(e => Generate(e, funcScope)).Append( DLR.Expression.Label(funcScope.Return, NULL) // default return value is null ); var function = DLR.Expression.Lambda( DLR.Expression.GetFuncType(types.ToArray()), DLR.Expression.Block(funcScope.GetVariables().Except(prms), funcBody), func.Name, prms ); scope.AddFunction(func.Name, function); return function; } #region return private DLR.Expression GenerateReturnExpression(ReturnExpression expr, Scope scope) { if (expr.OtherExpressions.Count() > 0) { var blockBody = expr.OtherExpressions.Select(e => Generate(e, scope)).Append( MakeReturn(expr, scope) ); return DLR.Expression.Block(blockBody); // todo: vars? } return MakeReturn(expr, scope); } private DLR.Expression MakeReturn(ReturnExpression expr, Scope scope) { var target = GetScopeReturn(scope); if (expr.Value == null) { return DLR.Expression.Return(target, NULL); } return DLR.Expression.Return(target, Converter.ConvertToObject(Generate(expr.Value, scope))); } private DLR.LabelTarget GetScopeReturn(Scope scope) { while (scope.Return == null && !scope.IsRoot) { scope = scope.Parent; } if (scope.Return == null) { throw new InvalidOperationException(); } return scope.Return; } #endregion private DLR.Expression GenerateClassDefinition(ClassDefinitionExpression expr, Scope scope) { var obj = DLR.Expression.Parameter(typeof(CobaltAHKObject), expr.Name); scope.AddVariable(expr.Name, obj); var exprs = new List<DLR.Expression>() { DLR.Expression.Assign(obj, DLR.Expression.New(typeof(CobaltAHKObject))) }; foreach (var method in expr.Methods) { exprs.Add( GenerateMemberAssign(obj, method.Name, Generate(method, scope) ) ); } return DLR.Expression.Block(typeof(void), exprs); } private static ConstructorInfo exceptionConstructor = typeof(ScriptException).GetConstructor(new[] { typeof(object) }); private DLR.Expression GenerateThrow(ThrowExpression expr, Scope scope) { var val = Generate(expr.Value, scope); return DLR.Expression.Throw( DLR.Expression.Condition( DLR.Expression.TypeIs(val, typeof(Exception)), DLR.Expression.Convert(DLR.Expression.Convert(val, typeof(object)), typeof(Exception)), DLR.Expression.Convert(DLR.Expression.New(exceptionConstructor, val), typeof(Exception)) ) ); } private DLR.Expression GenerateMemberAccess(MemberAccessExpression expr, Scope scope) { return DLR.Expression.Dynamic(BinderCache.GetGetMemberBinder(expr.Member), typeof(object), Generate(expr.Object, scope) ); } private DLR.Expression GenerateMemberAssign(MemberAccessExpression expr, DLR.Expression value, Scope scope) { return GenerateMemberAssign(Generate(expr.Object, scope), expr.Member, value ); } private DLR.Expression GenerateMemberAssign(DLR.Expression obj, string member, DLR.Expression value) { return DLR.Expression.Dynamic(BinderCache.GetSetMemberBinder(member), typeof(object), obj, value); } private DLR.Expression GenerateTernaryExpression(TernaryExpression expr, Scope scope) { var cond = Generate(expr.Expressions[0], scope); var ifTrue = Generate(expr.Expressions[1], scope); var ifFalse = Generate(expr.Expressions[2], scope); return DLR.Expression.Condition(Converter.ConvertToBoolean(cond), ifTrue, ifFalse); } #region unary operations private DLR.Expression GenerateUnaryExpression(UnaryExpression expr, Scope scope) { if (expr.Operator == Operator.LogicalNot || expr.Operator == Operator.WordLogicalNot) { return DLR.Expression.Not(Converter.ConvertToBoolean(Generate(expr.Expressions[0], scope))); } throw new NotImplementedException(); } #endregion #region binary operations private DLR.Expression GenerateBinaryExpression(BinaryExpression expr, Scope scope) { var op = (BinaryOperator)expr.Operator; if (op == Operator.Concatenate) { return GenerateStringConcat(expr, scope); } var member = expr.Expressions[0] as MemberAccessExpression; var right = Generate(expr.Expressions[1], scope); if (member != null) { if (expr.Operator == Operator.Assign) { return GenerateMemberAssign(member, right, scope); } else if (Operator.IsCompoundAssignment(op)) { return MemberCompoundAssignment(member, op, right, scope); } } return GenerateBinaryExpression(Generate(expr.Expressions[0], scope), op, right, scope); } private DLR.Expression GenerateBinaryExpression(DLR.Expression left, BinaryOperator op, DLR.Expression right, Scope scope) { if (op.Is(BinaryOperationType.Arithmetic)) { return GenerateArithmeticExpression(left, op, right, scope); } else if (op.Is(BinaryOperationType.Comparison)) { return GenerateComparisonExpression(left, op, right); } else if (op == Operator.Concatenate) { // keep here for compound assignments return GenerateStringConcat(Converter.ConvertToString(left), Converter.ConvertToString(right)); } else if (Operator.IsCompoundAssignment(op)) { return CompoundAssigment((DLR.ParameterExpression)left, left, op, right, scope); } else if (op == Operator.Assign) { if (left is DLR.ParameterExpression) { left = RetypeVariable((DLR.ParameterExpression)left, right.Type, scope); } return DLR.Expression.Assign(left, right); } throw new NotImplementedException(); } private DLR.Expression CompoundAssigment(DLR.ParameterExpression variable, DLR.Expression left, BinaryOperator op, DLR.Expression right, Scope scope) { return GenerateBinaryExpression(variable, (BinaryOperator)Operator.Assign, GenerateBinaryExpression(left, Operator.CompoundGetUnderlyingOperator(op), right, scope), scope); } private DLR.Expression MemberCompoundAssignment(MemberAccessExpression member, BinaryOperator op, DLR.Expression right, Scope scope) { return GenerateMemberAssign(member, GenerateBinaryExpression( Generate(member, scope), Operator.CompoundGetUnderlyingOperator(op), right, scope ), scope ); } #region comparison private DLR.Expression GenerateComparisonExpression(DLR.Expression left, Operator op, DLR.Expression right) { // todo: changes types (numeric, string, ...) if (op == Operator.Less) { return DLR.Expression.LessThan(left, right); } else if (op == Operator.LessOrEqual) { return DLR.Expression.LessThanOrEqual(left, right); } else if (op == Operator.Greater) { return DLR.Expression.GreaterThan(left, right); } else if (op == Operator.GreaterOrEqual) { return DLR.Expression.GreaterThanOrEqual(left, right); } else if (op == Operator.Equal) { return DLR.Expression.Equal(left, right); // todo: special for strings } else if (op == Operator.CaseEqual) { return DLR.Expression.Equal(left, right); } else if (op == Operator.NotEqual) { return DLR.Expression.NotEqual(left, right); } else if (op == Operator.RegexMatch) { // todo } throw new NotImplementedException(); } #endregion #region optimized string concat private static readonly MethodInfo concat = typeof(String).GetMethod("Concat", new[] { typeof(string[]) }); private DLR.Expression GenerateStringConcat(BinaryExpression expr, Scope scope) { var operands = OptimizeConcat(ExtractConcats(expr)); if (operands.Count() == 0) { return EMPTY_STRING; } else if (operands.Count() == 1) { return GenerateString(operands.ElementAt(0), scope); } return GenerateStringConcat( operands.Select(e => GenerateString(e, scope)).ToArray() ); } private DLR.Expression GenerateStringConcat(params DLR.Expression[] exprs) { return DLR.Expression.Call(concat, DLR.Expression.NewArrayInit(typeof(string), exprs)); } private IEnumerable<Expression> ExtractConcats(Expression expr) { var binary = expr as BinaryExpression; if (binary != null && binary.Operator == Operator.Concatenate) { return ExtractConcats(binary.Expressions[0]).Concat( ExtractConcats(binary.Expressions[1]) ); } return new[] { expr }; } private IEnumerable<Expression> OptimizeConcat(IEnumerable<Expression> exprs) { return exprs.Where(expr => !IsEmptyString(expr)); } private bool IsEmptyString(Expression expr) { return expr is StringLiteralExpression && ((StringLiteralExpression)expr).Value == ""; } private DLR.Expression GenerateString(Expression expr, Scope scope) { return Converter.ConvertToString(Generate(expr, scope)); } #endregion #region arithmetic private DLR.Expression GenerateArithmeticExpression(DLR.Expression left, BinaryOperator op, DLR.Expression right, Scope scope) { Type leftType = left.Type, rightType = right.Type; DLR.ParameterExpression variable = null; if (NegotiateArithmeticTypes(ref leftType, ref rightType)) { if (leftType != left.Type) { if (left is DLR.ParameterExpression && Operator.IsCompoundAssignment(op)) { variable = RetypeVariable((DLR.ParameterExpression)left, leftType, scope); } left = DLR.Expression.Convert(left, leftType); // todo: see below } if (rightType != right.Type) { right = DLR.Expression.Convert(right, rightType); // todo: conversion from non-arithmetic types like string, object, ... } } if (Operator.IsCompoundAssignment(op)) { return CompoundAssigment(variable, left, op, right, scope); } else if (op == Operator.Add) { return DLR.Expression.Add(left, right); } else if (op == Operator.Subtract) { return DLR.Expression.Subtract(left, right); } else if (op == Operator.Multiply) { return DLR.Expression.Multiply(left, right); } else if (op == Operator.TrueDivide) { return DLR.Expression.Divide(left, right); } else if (op == Operator.FloorDivide) { var floor = typeof(Math).GetMethod("Floor", new[] { typeof(double) }); return DLR.Expression.Call(floor, GenerateArithmeticExpression(left, (BinaryOperator)Operator.TrueDivide, right, scope)); } else if (op == Operator.Power) { return DLR.Expression.Power(DLR.Expression.Convert(left, typeof(double)), DLR.Expression.Convert(right, typeof(double))); } throw new InvalidOperationException(); // todo } private bool NegotiateArithmeticTypes(ref Type left, ref Type right) { Type _left = left, _right = right; if (!IsArithmeticType(left) && !IsArithmeticType(right)) { left = right = arithmeticTypes.First(); } else { left = right = HigherArithmeticType(left, right); } return _left != left || _right != right; } private static readonly Type[] arithmeticTypes = { typeof(double), typeof(int), typeof(uint) }; private Type HigherArithmeticType(Type one, Type two) { return arithmeticTypes.First(t => t == one || t == two); } private bool IsArithmeticType(Type type) { return arithmeticTypes.Contains(type); } #endregion #endregion private DLR.ParameterExpression RetypeVariable(DLR.ParameterExpression variable, Type type, Scope scope) { if (variable.Type != type) { Func<DLR.ParameterExpression, bool> match = v => v.Name == variable.Name && v.Type == type; if (scope.GetVariables().Any(match)) { variable = scope.GetVariables().First(match); } else { variable = DLR.Expression.Parameter(type, variable.Name); } scope.AddVariable(variable.Name, variable); } return variable; } } }
// 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. #pragma warning disable 0184 using System; using System.Runtime.InteropServices; internal class Program { private static void Eval(int testCase, bool b1, bool b2) { if (b1 != b2) throw new Exception(string.Format("case {0:000} failed: v1 {1} v2 {2}", testCase, b1, b2)); } private static void TestCase0001() { { IntE v = default(IntE); Enum o = v; Eval(0001, o is IntE, true); Eval(0002, o is IntE[], false); Eval(0003, o is IntE?, true); Eval(0004, o is IntE?[], false); Eval(0005, o is ByteE, false); Eval(0006, o is ByteE[], false); Eval(0007, o is ByteE?, false); Eval(0008, o is ByteE?[], false); Eval(0009, o is LongE, false); Eval(0010, o is LongE[], false); Eval(0011, o is LongE?, false); Eval(0012, o is LongE?[], false); Eval(0013, o is object, true); Eval(0014, o is object[], false); Eval(0015, o is string, false); Eval(0016, o is string[], false); Eval(0017, o is ValueType, true); Eval(0018, o is ValueType[], false); Eval(0019, o is Array, false); Eval(0020, o is Array[], false); Eval(0021, o is Enum, true); Eval(0022, o is Enum[], false); Eval(0023, o is Delegate, false); Eval(0024, o is Delegate[], false); Eval(0025, o is MulticastDelegate, false); Eval(0026, o is MulticastDelegate[], false); Eval(0027, o is IEmpty, false); Eval(0028, o is IEmpty[], false); Eval(0029, o is INotEmpty, false); Eval(0030, o is INotEmpty[], false); Eval(0031, o is IEmptyGen<int>, false); Eval(0032, o is IEmptyGen<int>[], false); Eval(0033, o is INotEmptyGen<int>, false); Eval(0034, o is INotEmptyGen<int>[], false); Eval(0035, o is SimpleDelegate, false); Eval(0036, o is SimpleDelegate[], false); Eval(0037, o is GenericDelegate<int>, false); Eval(0038, o is GenericDelegate<int>[], false); Eval(0039, o is EmptyClass, false); Eval(0040, o is EmptyClass[], false); Eval(0041, o is NotEmptyClass, false); Eval(0042, o is NotEmptyClass[], false); Eval(0043, o is EmptyClassGen<int>, false); Eval(0044, o is EmptyClassGen<int>[], false); Eval(0045, o is NotEmptyClassGen<Guid>, false); Eval(0046, o is NotEmptyClassGen<Guid>[], false); Eval(0047, o is NotEmptyClassConstrainedGen<object>, false); Eval(0048, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0049, o is NestedClass, false); Eval(0050, o is NestedClass[], false); Eval(0051, o is NestedClassGen<Decimal>, false); Eval(0052, o is NestedClassGen<Decimal>[], false); Eval(0053, o is ImplementOneInterfaceC, false); Eval(0054, o is ImplementOneInterfaceC[], false); Eval(0055, o is ImplementTwoInterfaceC, false); Eval(0056, o is ImplementTwoInterfaceC[], false); Eval(0057, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0058, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0059, o is ImplementTwoInterfaceGenC<int>, false); Eval(0060, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0061, o is ImplementAllInterfaceC<int>, false); Eval(0062, o is ImplementAllInterfaceC<int>[], false); Eval(0063, o is SealedClass, false); Eval(0064, o is SealedClass[], false); } { IntE? v = default(IntE); Enum o = v; Eval(0065, o is IntE, true); Eval(0066, o is IntE[], false); Eval(0067, o is IntE?, true); Eval(0068, o is IntE?[], false); Eval(0069, o is ByteE, false); Eval(0070, o is ByteE[], false); Eval(0071, o is ByteE?, false); Eval(0072, o is ByteE?[], false); Eval(0073, o is LongE, false); Eval(0074, o is LongE[], false); Eval(0075, o is LongE?, false); Eval(0076, o is LongE?[], false); Eval(0077, o is object, true); Eval(0078, o is object[], false); Eval(0079, o is string, false); Eval(0080, o is string[], false); Eval(0081, o is ValueType, true); Eval(0082, o is ValueType[], false); Eval(0083, o is Array, false); Eval(0084, o is Array[], false); Eval(0085, o is Enum, true); Eval(0086, o is Enum[], false); Eval(0087, o is Delegate, false); Eval(0088, o is Delegate[], false); Eval(0089, o is MulticastDelegate, false); Eval(0090, o is MulticastDelegate[], false); Eval(0091, o is IEmpty, false); Eval(0092, o is IEmpty[], false); Eval(0093, o is INotEmpty, false); Eval(0094, o is INotEmpty[], false); Eval(0095, o is IEmptyGen<int>, false); Eval(0096, o is IEmptyGen<int>[], false); Eval(0097, o is INotEmptyGen<int>, false); Eval(0098, o is INotEmptyGen<int>[], false); Eval(0099, o is SimpleDelegate, false); Eval(0100, o is SimpleDelegate[], false); Eval(0101, o is GenericDelegate<int>, false); Eval(0102, o is GenericDelegate<int>[], false); Eval(0103, o is EmptyClass, false); Eval(0104, o is EmptyClass[], false); Eval(0105, o is NotEmptyClass, false); Eval(0106, o is NotEmptyClass[], false); Eval(0107, o is EmptyClassGen<int>, false); Eval(0108, o is EmptyClassGen<int>[], false); Eval(0109, o is NotEmptyClassGen<Guid>, false); Eval(0110, o is NotEmptyClassGen<Guid>[], false); Eval(0111, o is NotEmptyClassConstrainedGen<object>, false); Eval(0112, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0113, o is NestedClass, false); Eval(0114, o is NestedClass[], false); Eval(0115, o is NestedClassGen<Decimal>, false); Eval(0116, o is NestedClassGen<Decimal>[], false); Eval(0117, o is ImplementOneInterfaceC, false); Eval(0118, o is ImplementOneInterfaceC[], false); Eval(0119, o is ImplementTwoInterfaceC, false); Eval(0120, o is ImplementTwoInterfaceC[], false); Eval(0121, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0122, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0123, o is ImplementTwoInterfaceGenC<int>, false); Eval(0124, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0125, o is ImplementAllInterfaceC<int>, false); Eval(0126, o is ImplementAllInterfaceC<int>[], false); Eval(0127, o is SealedClass, false); Eval(0128, o is SealedClass[], false); } { IntE? v = default(IntE?); Enum o = v; Eval(0129, o is IntE, false); Eval(0130, o is IntE[], false); Eval(0131, o is IntE?, false); Eval(0132, o is IntE?[], false); Eval(0133, o is ByteE, false); Eval(0134, o is ByteE[], false); Eval(0135, o is ByteE?, false); Eval(0136, o is ByteE?[], false); Eval(0137, o is LongE, false); Eval(0138, o is LongE[], false); Eval(0139, o is LongE?, false); Eval(0140, o is LongE?[], false); Eval(0141, o is object, false); Eval(0142, o is object[], false); Eval(0143, o is string, false); Eval(0144, o is string[], false); Eval(0145, o is ValueType, false); Eval(0146, o is ValueType[], false); Eval(0147, o is Array, false); Eval(0148, o is Array[], false); Eval(0149, o is Enum, false); Eval(0150, o is Enum[], false); Eval(0151, o is Delegate, false); Eval(0152, o is Delegate[], false); Eval(0153, o is MulticastDelegate, false); Eval(0154, o is MulticastDelegate[], false); Eval(0155, o is IEmpty, false); Eval(0156, o is IEmpty[], false); Eval(0157, o is INotEmpty, false); Eval(0158, o is INotEmpty[], false); Eval(0159, o is IEmptyGen<int>, false); Eval(0160, o is IEmptyGen<int>[], false); Eval(0161, o is INotEmptyGen<int>, false); Eval(0162, o is INotEmptyGen<int>[], false); Eval(0163, o is SimpleDelegate, false); Eval(0164, o is SimpleDelegate[], false); Eval(0165, o is GenericDelegate<int>, false); Eval(0166, o is GenericDelegate<int>[], false); Eval(0167, o is EmptyClass, false); Eval(0168, o is EmptyClass[], false); Eval(0169, o is NotEmptyClass, false); Eval(0170, o is NotEmptyClass[], false); Eval(0171, o is EmptyClassGen<int>, false); Eval(0172, o is EmptyClassGen<int>[], false); Eval(0173, o is NotEmptyClassGen<Guid>, false); Eval(0174, o is NotEmptyClassGen<Guid>[], false); Eval(0175, o is NotEmptyClassConstrainedGen<object>, false); Eval(0176, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0177, o is NestedClass, false); Eval(0178, o is NestedClass[], false); Eval(0179, o is NestedClassGen<Decimal>, false); Eval(0180, o is NestedClassGen<Decimal>[], false); Eval(0181, o is ImplementOneInterfaceC, false); Eval(0182, o is ImplementOneInterfaceC[], false); Eval(0183, o is ImplementTwoInterfaceC, false); Eval(0184, o is ImplementTwoInterfaceC[], false); Eval(0185, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0186, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0187, o is ImplementTwoInterfaceGenC<int>, false); Eval(0188, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0189, o is ImplementAllInterfaceC<int>, false); Eval(0190, o is ImplementAllInterfaceC<int>[], false); Eval(0191, o is SealedClass, false); Eval(0192, o is SealedClass[], false); } } // end of test case 0001 private static void TestCase0002() { { ByteE v = default(ByteE); Enum o = v; Eval(0193, o is IntE, false); Eval(0194, o is IntE[], false); Eval(0195, o is IntE?, false); Eval(0196, o is IntE?[], false); Eval(0197, o is ByteE, true); Eval(0198, o is ByteE[], false); Eval(0199, o is ByteE?, true); Eval(0200, o is ByteE?[], false); Eval(0201, o is LongE, false); Eval(0202, o is LongE[], false); Eval(0203, o is LongE?, false); Eval(0204, o is LongE?[], false); Eval(0205, o is object, true); Eval(0206, o is object[], false); Eval(0207, o is string, false); Eval(0208, o is string[], false); Eval(0209, o is ValueType, true); Eval(0210, o is ValueType[], false); Eval(0211, o is Array, false); Eval(0212, o is Array[], false); Eval(0213, o is Enum, true); Eval(0214, o is Enum[], false); Eval(0215, o is Delegate, false); Eval(0216, o is Delegate[], false); Eval(0217, o is MulticastDelegate, false); Eval(0218, o is MulticastDelegate[], false); Eval(0219, o is IEmpty, false); Eval(0220, o is IEmpty[], false); Eval(0221, o is INotEmpty, false); Eval(0222, o is INotEmpty[], false); Eval(0223, o is IEmptyGen<int>, false); Eval(0224, o is IEmptyGen<int>[], false); Eval(0225, o is INotEmptyGen<int>, false); Eval(0226, o is INotEmptyGen<int>[], false); Eval(0227, o is SimpleDelegate, false); Eval(0228, o is SimpleDelegate[], false); Eval(0229, o is GenericDelegate<int>, false); Eval(0230, o is GenericDelegate<int>[], false); Eval(0231, o is EmptyClass, false); Eval(0232, o is EmptyClass[], false); Eval(0233, o is NotEmptyClass, false); Eval(0234, o is NotEmptyClass[], false); Eval(0235, o is EmptyClassGen<int>, false); Eval(0236, o is EmptyClassGen<int>[], false); Eval(0237, o is NotEmptyClassGen<Guid>, false); Eval(0238, o is NotEmptyClassGen<Guid>[], false); Eval(0239, o is NotEmptyClassConstrainedGen<object>, false); Eval(0240, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0241, o is NestedClass, false); Eval(0242, o is NestedClass[], false); Eval(0243, o is NestedClassGen<Decimal>, false); Eval(0244, o is NestedClassGen<Decimal>[], false); Eval(0245, o is ImplementOneInterfaceC, false); Eval(0246, o is ImplementOneInterfaceC[], false); Eval(0247, o is ImplementTwoInterfaceC, false); Eval(0248, o is ImplementTwoInterfaceC[], false); Eval(0249, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0250, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0251, o is ImplementTwoInterfaceGenC<int>, false); Eval(0252, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0253, o is ImplementAllInterfaceC<int>, false); Eval(0254, o is ImplementAllInterfaceC<int>[], false); Eval(0255, o is SealedClass, false); Eval(0256, o is SealedClass[], false); } { ByteE? v = default(ByteE); Enum o = v; Eval(0257, o is IntE, false); Eval(0258, o is IntE[], false); Eval(0259, o is IntE?, false); Eval(0260, o is IntE?[], false); Eval(0261, o is ByteE, true); Eval(0262, o is ByteE[], false); Eval(0263, o is ByteE?, true); Eval(0264, o is ByteE?[], false); Eval(0265, o is LongE, false); Eval(0266, o is LongE[], false); Eval(0267, o is LongE?, false); Eval(0268, o is LongE?[], false); Eval(0269, o is object, true); Eval(0270, o is object[], false); Eval(0271, o is string, false); Eval(0272, o is string[], false); Eval(0273, o is ValueType, true); Eval(0274, o is ValueType[], false); Eval(0275, o is Array, false); Eval(0276, o is Array[], false); Eval(0277, o is Enum, true); Eval(0278, o is Enum[], false); Eval(0279, o is Delegate, false); Eval(0280, o is Delegate[], false); Eval(0281, o is MulticastDelegate, false); Eval(0282, o is MulticastDelegate[], false); Eval(0283, o is IEmpty, false); Eval(0284, o is IEmpty[], false); Eval(0285, o is INotEmpty, false); Eval(0286, o is INotEmpty[], false); Eval(0287, o is IEmptyGen<int>, false); Eval(0288, o is IEmptyGen<int>[], false); Eval(0289, o is INotEmptyGen<int>, false); Eval(0290, o is INotEmptyGen<int>[], false); Eval(0291, o is SimpleDelegate, false); Eval(0292, o is SimpleDelegate[], false); Eval(0293, o is GenericDelegate<int>, false); Eval(0294, o is GenericDelegate<int>[], false); Eval(0295, o is EmptyClass, false); Eval(0296, o is EmptyClass[], false); Eval(0297, o is NotEmptyClass, false); Eval(0298, o is NotEmptyClass[], false); Eval(0299, o is EmptyClassGen<int>, false); Eval(0300, o is EmptyClassGen<int>[], false); Eval(0301, o is NotEmptyClassGen<Guid>, false); Eval(0302, o is NotEmptyClassGen<Guid>[], false); Eval(0303, o is NotEmptyClassConstrainedGen<object>, false); Eval(0304, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0305, o is NestedClass, false); Eval(0306, o is NestedClass[], false); Eval(0307, o is NestedClassGen<Decimal>, false); Eval(0308, o is NestedClassGen<Decimal>[], false); Eval(0309, o is ImplementOneInterfaceC, false); Eval(0310, o is ImplementOneInterfaceC[], false); Eval(0311, o is ImplementTwoInterfaceC, false); Eval(0312, o is ImplementTwoInterfaceC[], false); Eval(0313, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0314, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0315, o is ImplementTwoInterfaceGenC<int>, false); Eval(0316, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0317, o is ImplementAllInterfaceC<int>, false); Eval(0318, o is ImplementAllInterfaceC<int>[], false); Eval(0319, o is SealedClass, false); Eval(0320, o is SealedClass[], false); } { ByteE? v = default(ByteE?); Enum o = v; Eval(0321, o is IntE, false); Eval(0322, o is IntE[], false); Eval(0323, o is IntE?, false); Eval(0324, o is IntE?[], false); Eval(0325, o is ByteE, false); Eval(0326, o is ByteE[], false); Eval(0327, o is ByteE?, false); Eval(0328, o is ByteE?[], false); Eval(0329, o is LongE, false); Eval(0330, o is LongE[], false); Eval(0331, o is LongE?, false); Eval(0332, o is LongE?[], false); Eval(0333, o is object, false); Eval(0334, o is object[], false); Eval(0335, o is string, false); Eval(0336, o is string[], false); Eval(0337, o is ValueType, false); Eval(0338, o is ValueType[], false); Eval(0339, o is Array, false); Eval(0340, o is Array[], false); Eval(0341, o is Enum, false); Eval(0342, o is Enum[], false); Eval(0343, o is Delegate, false); Eval(0344, o is Delegate[], false); Eval(0345, o is MulticastDelegate, false); Eval(0346, o is MulticastDelegate[], false); Eval(0347, o is IEmpty, false); Eval(0348, o is IEmpty[], false); Eval(0349, o is INotEmpty, false); Eval(0350, o is INotEmpty[], false); Eval(0351, o is IEmptyGen<int>, false); Eval(0352, o is IEmptyGen<int>[], false); Eval(0353, o is INotEmptyGen<int>, false); Eval(0354, o is INotEmptyGen<int>[], false); Eval(0355, o is SimpleDelegate, false); Eval(0356, o is SimpleDelegate[], false); Eval(0357, o is GenericDelegate<int>, false); Eval(0358, o is GenericDelegate<int>[], false); Eval(0359, o is EmptyClass, false); Eval(0360, o is EmptyClass[], false); Eval(0361, o is NotEmptyClass, false); Eval(0362, o is NotEmptyClass[], false); Eval(0363, o is EmptyClassGen<int>, false); Eval(0364, o is EmptyClassGen<int>[], false); Eval(0365, o is NotEmptyClassGen<Guid>, false); Eval(0366, o is NotEmptyClassGen<Guid>[], false); Eval(0367, o is NotEmptyClassConstrainedGen<object>, false); Eval(0368, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0369, o is NestedClass, false); Eval(0370, o is NestedClass[], false); Eval(0371, o is NestedClassGen<Decimal>, false); Eval(0372, o is NestedClassGen<Decimal>[], false); Eval(0373, o is ImplementOneInterfaceC, false); Eval(0374, o is ImplementOneInterfaceC[], false); Eval(0375, o is ImplementTwoInterfaceC, false); Eval(0376, o is ImplementTwoInterfaceC[], false); Eval(0377, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0378, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0379, o is ImplementTwoInterfaceGenC<int>, false); Eval(0380, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0381, o is ImplementAllInterfaceC<int>, false); Eval(0382, o is ImplementAllInterfaceC<int>[], false); Eval(0383, o is SealedClass, false); Eval(0384, o is SealedClass[], false); } } // end of test case 0002 private static void TestCase0003() { { LongE v = default(LongE); Enum o = v; Eval(0385, o is IntE, false); Eval(0386, o is IntE[], false); Eval(0387, o is IntE?, false); Eval(0388, o is IntE?[], false); Eval(0389, o is ByteE, false); Eval(0390, o is ByteE[], false); Eval(0391, o is ByteE?, false); Eval(0392, o is ByteE?[], false); Eval(0393, o is LongE, true); Eval(0394, o is LongE[], false); Eval(0395, o is LongE?, true); Eval(0396, o is LongE?[], false); Eval(0397, o is object, true); Eval(0398, o is object[], false); Eval(0399, o is string, false); Eval(0400, o is string[], false); Eval(0401, o is ValueType, true); Eval(0402, o is ValueType[], false); Eval(0403, o is Array, false); Eval(0404, o is Array[], false); Eval(0405, o is Enum, true); Eval(0406, o is Enum[], false); Eval(0407, o is Delegate, false); Eval(0408, o is Delegate[], false); Eval(0409, o is MulticastDelegate, false); Eval(0410, o is MulticastDelegate[], false); Eval(0411, o is IEmpty, false); Eval(0412, o is IEmpty[], false); Eval(0413, o is INotEmpty, false); Eval(0414, o is INotEmpty[], false); Eval(0415, o is IEmptyGen<int>, false); Eval(0416, o is IEmptyGen<int>[], false); Eval(0417, o is INotEmptyGen<int>, false); Eval(0418, o is INotEmptyGen<int>[], false); Eval(0419, o is SimpleDelegate, false); Eval(0420, o is SimpleDelegate[], false); Eval(0421, o is GenericDelegate<int>, false); Eval(0422, o is GenericDelegate<int>[], false); Eval(0423, o is EmptyClass, false); Eval(0424, o is EmptyClass[], false); Eval(0425, o is NotEmptyClass, false); Eval(0426, o is NotEmptyClass[], false); Eval(0427, o is EmptyClassGen<int>, false); Eval(0428, o is EmptyClassGen<int>[], false); Eval(0429, o is NotEmptyClassGen<Guid>, false); Eval(0430, o is NotEmptyClassGen<Guid>[], false); Eval(0431, o is NotEmptyClassConstrainedGen<object>, false); Eval(0432, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0433, o is NestedClass, false); Eval(0434, o is NestedClass[], false); Eval(0435, o is NestedClassGen<Decimal>, false); Eval(0436, o is NestedClassGen<Decimal>[], false); Eval(0437, o is ImplementOneInterfaceC, false); Eval(0438, o is ImplementOneInterfaceC[], false); Eval(0439, o is ImplementTwoInterfaceC, false); Eval(0440, o is ImplementTwoInterfaceC[], false); Eval(0441, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0442, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0443, o is ImplementTwoInterfaceGenC<int>, false); Eval(0444, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0445, o is ImplementAllInterfaceC<int>, false); Eval(0446, o is ImplementAllInterfaceC<int>[], false); Eval(0447, o is SealedClass, false); Eval(0448, o is SealedClass[], false); } { LongE? v = default(LongE); Enum o = v; Eval(0449, o is IntE, false); Eval(0450, o is IntE[], false); Eval(0451, o is IntE?, false); Eval(0452, o is IntE?[], false); Eval(0453, o is ByteE, false); Eval(0454, o is ByteE[], false); Eval(0455, o is ByteE?, false); Eval(0456, o is ByteE?[], false); Eval(0457, o is LongE, true); Eval(0458, o is LongE[], false); Eval(0459, o is LongE?, true); Eval(0460, o is LongE?[], false); Eval(0461, o is object, true); Eval(0462, o is object[], false); Eval(0463, o is string, false); Eval(0464, o is string[], false); Eval(0465, o is ValueType, true); Eval(0466, o is ValueType[], false); Eval(0467, o is Array, false); Eval(0468, o is Array[], false); Eval(0469, o is Enum, true); Eval(0470, o is Enum[], false); Eval(0471, o is Delegate, false); Eval(0472, o is Delegate[], false); Eval(0473, o is MulticastDelegate, false); Eval(0474, o is MulticastDelegate[], false); Eval(0475, o is IEmpty, false); Eval(0476, o is IEmpty[], false); Eval(0477, o is INotEmpty, false); Eval(0478, o is INotEmpty[], false); Eval(0479, o is IEmptyGen<int>, false); Eval(0480, o is IEmptyGen<int>[], false); Eval(0481, o is INotEmptyGen<int>, false); Eval(0482, o is INotEmptyGen<int>[], false); Eval(0483, o is SimpleDelegate, false); Eval(0484, o is SimpleDelegate[], false); Eval(0485, o is GenericDelegate<int>, false); Eval(0486, o is GenericDelegate<int>[], false); Eval(0487, o is EmptyClass, false); Eval(0488, o is EmptyClass[], false); Eval(0489, o is NotEmptyClass, false); Eval(0490, o is NotEmptyClass[], false); Eval(0491, o is EmptyClassGen<int>, false); Eval(0492, o is EmptyClassGen<int>[], false); Eval(0493, o is NotEmptyClassGen<Guid>, false); Eval(0494, o is NotEmptyClassGen<Guid>[], false); Eval(0495, o is NotEmptyClassConstrainedGen<object>, false); Eval(0496, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0497, o is NestedClass, false); Eval(0498, o is NestedClass[], false); Eval(0499, o is NestedClassGen<Decimal>, false); Eval(0500, o is NestedClassGen<Decimal>[], false); Eval(0501, o is ImplementOneInterfaceC, false); Eval(0502, o is ImplementOneInterfaceC[], false); Eval(0503, o is ImplementTwoInterfaceC, false); Eval(0504, o is ImplementTwoInterfaceC[], false); Eval(0505, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0506, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0507, o is ImplementTwoInterfaceGenC<int>, false); Eval(0508, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0509, o is ImplementAllInterfaceC<int>, false); Eval(0510, o is ImplementAllInterfaceC<int>[], false); Eval(0511, o is SealedClass, false); Eval(0512, o is SealedClass[], false); } { LongE? v = default(LongE?); Enum o = v; Eval(0513, o is IntE, false); Eval(0514, o is IntE[], false); Eval(0515, o is IntE?, false); Eval(0516, o is IntE?[], false); Eval(0517, o is ByteE, false); Eval(0518, o is ByteE[], false); Eval(0519, o is ByteE?, false); Eval(0520, o is ByteE?[], false); Eval(0521, o is LongE, false); Eval(0522, o is LongE[], false); Eval(0523, o is LongE?, false); Eval(0524, o is LongE?[], false); Eval(0525, o is object, false); Eval(0526, o is object[], false); Eval(0527, o is string, false); Eval(0528, o is string[], false); Eval(0529, o is ValueType, false); Eval(0530, o is ValueType[], false); Eval(0531, o is Array, false); Eval(0532, o is Array[], false); Eval(0533, o is Enum, false); Eval(0534, o is Enum[], false); Eval(0535, o is Delegate, false); Eval(0536, o is Delegate[], false); Eval(0537, o is MulticastDelegate, false); Eval(0538, o is MulticastDelegate[], false); Eval(0539, o is IEmpty, false); Eval(0540, o is IEmpty[], false); Eval(0541, o is INotEmpty, false); Eval(0542, o is INotEmpty[], false); Eval(0543, o is IEmptyGen<int>, false); Eval(0544, o is IEmptyGen<int>[], false); Eval(0545, o is INotEmptyGen<int>, false); Eval(0546, o is INotEmptyGen<int>[], false); Eval(0547, o is SimpleDelegate, false); Eval(0548, o is SimpleDelegate[], false); Eval(0549, o is GenericDelegate<int>, false); Eval(0550, o is GenericDelegate<int>[], false); Eval(0551, o is EmptyClass, false); Eval(0552, o is EmptyClass[], false); Eval(0553, o is NotEmptyClass, false); Eval(0554, o is NotEmptyClass[], false); Eval(0555, o is EmptyClassGen<int>, false); Eval(0556, o is EmptyClassGen<int>[], false); Eval(0557, o is NotEmptyClassGen<Guid>, false); Eval(0558, o is NotEmptyClassGen<Guid>[], false); Eval(0559, o is NotEmptyClassConstrainedGen<object>, false); Eval(0560, o is NotEmptyClassConstrainedGen<object>[], false); Eval(0561, o is NestedClass, false); Eval(0562, o is NestedClass[], false); Eval(0563, o is NestedClassGen<Decimal>, false); Eval(0564, o is NestedClassGen<Decimal>[], false); Eval(0565, o is ImplementOneInterfaceC, false); Eval(0566, o is ImplementOneInterfaceC[], false); Eval(0567, o is ImplementTwoInterfaceC, false); Eval(0568, o is ImplementTwoInterfaceC[], false); Eval(0569, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>, false); Eval(0570, o is ImplementOneInterfaceGenC<EmptyStructGen<int>>[], false); Eval(0571, o is ImplementTwoInterfaceGenC<int>, false); Eval(0572, o is ImplementTwoInterfaceGenC<int>[], false); Eval(0573, o is ImplementAllInterfaceC<int>, false); Eval(0574, o is ImplementAllInterfaceC<int>[], false); Eval(0575, o is SealedClass, false); Eval(0576, o is SealedClass[], false); } } // end of test case 0003 private static int Main() { try { TestCase0001(); TestCase0002(); TestCase0003(); } catch (Exception e) { System.Console.WriteLine(e.Message); Console.WriteLine("Test FAILED"); return 666; } Console.WriteLine("Test SUCCESS"); return 100; } }
// 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.Runtime.CompilerServices; namespace System.Collections.Generic { // The SortedDictionary class implements a generic sorted list of keys // and values. Entries in a sorted list are sorted by their keys and // are accessible both by key and by index. The keys of a sorted dictionary // can be ordered either according to a specific IComparer // implementation given when the sorted dictionary is instantiated, or // according to the IComparable implementation provided by the keys // themselves. In either case, a sorted dictionary does not allow entries // with duplicate or null keys. // // A sorted list internally maintains two arrays that store the keys and // values of the entries. The capacity of a sorted list is the allocated // length of these internal arrays. As elements are added to a sorted list, the // capacity of the sorted list is automatically increased as required by // reallocating the internal arrays. The capacity is never automatically // decreased, but users can call either TrimExcess or // Capacity explicitly. // // The GetKeyList and GetValueList methods of a sorted list // provides access to the keys and values of the sorted list in the form of // List implementations. The List objects returned by these // methods are aliases for the underlying sorted list, so modifications // made to those lists are directly reflected in the sorted list, and vice // versa. // // The SortedList class provides a convenient way to create a sorted // copy of another dictionary, such as a Hashtable. For example: // // Hashtable h = new Hashtable(); // h.Add(...); // h.Add(...); // ... // SortedList s = new SortedList(h); // // The last line above creates a sorted list that contains a copy of the keys // and values stored in the hashtable. In this particular example, the keys // will be ordered according to the IComparable interface, which they // all must implement. To impose a different ordering, SortedList also // has a constructor that allows a specific IComparer implementation to // be specified. // [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> { private TKey[] keys; // Do not rename (binary serialization) private TValue[] values; // Do not rename (binary serialization) private int _size; // Do not rename (binary serialization) private int version; // Do not rename (binary serialization) private IComparer<TKey> comparer; // Do not rename (binary serialization) private KeyList keyList; // Do not rename (binary serialization) private ValueList valueList; // Do not rename (binary serialization) private const int DefaultCapacity = 4; // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to DefaultCapacity, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. public SortedList() { keys = Array.Empty<TKey>(); values = Array.Empty<TValue>(); _size = 0; comparer = Comparer<TKey>.Default; } // Constructs a new sorted list. The sorted list is initially empty and has // a capacity of zero. Upon adding the first element to the sorted list the // capacity is increased to 16, and then increased in multiples of two as // required. The elements of the sorted list are ordered according to the // IComparable interface, which must be implemented by the keys of // all entries added to the sorted list. // public SortedList(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity), capacity, SR.ArgumentOutOfRange_NeedNonNegNum); keys = new TKey[capacity]; values = new TValue[capacity]; comparer = Comparer<TKey>.Default; } // Constructs a new sorted list with a given IComparer // implementation. The sorted list is initially empty and has a capacity of // zero. Upon adding the first element to the sorted list the capacity is // increased to 16, and then increased in multiples of two as required. The // elements of the sorted list are ordered according to the given // IComparer implementation. If comparer is null, the // elements are compared to each other using the IComparable // interface, which in that case must be implemented by the keys of all // entries added to the sorted list. // public SortedList(IComparer<TKey> comparer) : this() { if (comparer != null) { this.comparer = comparer; } } // Constructs a new sorted dictionary with a given IComparer // implementation and a given initial capacity. The sorted list is // initially empty, but will have room for the given number of elements // before any reallocations are required. The elements of the sorted list // are ordered according to the given IComparer implementation. If // comparer is null, the elements are compared to each other using // the IComparable interface, which in that case must be implemented // by the keys of all entries added to the sorted list. // public SortedList(int capacity, IComparer<TKey> comparer) : this(comparer) { Capacity = capacity; } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the IComparable interface, which must be implemented by the // keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } // Constructs a new sorted list containing a copy of the entries in the // given dictionary. The elements of the sorted list are ordered according // to the given IComparer implementation. If comparer is // null, the elements are compared to each other using the // IComparable interface, which in that case must be implemented // by the keys of all entries in the given dictionary as well as keys // subsequently added to the sorted list. // public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) : this((dictionary != null ? dictionary.Count : 0), comparer) { if (dictionary == null) throw new ArgumentNullException(nameof(dictionary)); int count = dictionary.Count; if (count != 0) { TKey[] keys = this.keys; dictionary.Keys.CopyTo(keys, 0); dictionary.Values.CopyTo(values, 0); Debug.Assert(count == this.keys.Length); if (count > 1) { comparer = Comparer; // obtain default if this is null. Array.Sort<TKey, TValue>(keys, values, comparer); for (int i = 1; i != keys.Length; ++i) { if (comparer.Compare(keys[i - 1], keys[i]) == 0) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, keys[i])); } } } } _size = count; } // Adds an entry with the given key and value to this sorted list. An // ArgumentException is thrown if the key is already present in the sorted list. // public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer); if (i >= 0) throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, key), nameof(key)); Insert(~i, key, value); } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { Add(keyValuePair.Key, keyValuePair.Value); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { int index = IndexOfKey(keyValuePair.Key); if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value)) { return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { int index = IndexOfKey(keyValuePair.Key); if (index >= 0 && EqualityComparer<TValue>.Default.Equals(values[index], keyValuePair.Value)) { RemoveAt(index); return true; } return false; } // Returns the capacity of this sorted list. The capacity of a sorted list // represents the allocated length of the internal arrays used to store the // keys and values of the list, and thus also indicates the maximum number // of entries the list can contain before a reallocation of the internal // arrays is required. // public int Capacity { get { return keys.Length; } set { if (value != keys.Length) { if (value < _size) { throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_SmallCapacity); } if (value > 0) { TKey[] newKeys = new TKey[value]; TValue[] newValues = new TValue[value]; if (_size > 0) { Array.Copy(keys, 0, newKeys, 0, _size); Array.Copy(values, 0, newValues, 0, _size); } keys = newKeys; values = newValues; } else { keys = Array.Empty<TKey>(); values = Array.Empty<TValue>(); } } } } public IComparer<TKey> Comparer { get { return comparer; } } void IDictionary.Add(object key, object value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null && !(default(TValue) == null)) // null is an invalid value for Value types throw new ArgumentNullException(nameof(value)); if (!(key is TKey)) throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); if (!(value is TValue) && value != null) // null is a valid value for Reference Types throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); Add((TKey)key, (TValue)value); } // Returns the number of entries in this sorted list. public int Count { get { return _size; } } // Returns a collection representing the keys of this sorted list. This // method returns the same object as GetKeyList, but typed as an // ICollection instead of an IList. public IList<TKey> Keys { get { return GetKeyListHelper(); } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return GetKeyListHelper(); } } ICollection IDictionary.Keys { get { return GetKeyListHelper(); } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return GetKeyListHelper(); } } // Returns a collection representing the values of this sorted list. This // method returns the same object as GetValueList, but typed as an // ICollection instead of an IList. // public IList<TValue> Values { get { return GetValueListHelper(); } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return GetValueListHelper(); } } ICollection IDictionary.Values { get { return GetValueListHelper(); } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return GetValueListHelper(); } } private KeyList GetKeyListHelper() { if (keyList == null) keyList = new KeyList(this); return keyList; } private ValueList GetValueListHelper() { if (valueList == null) valueList = new ValueList(this); return valueList; } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } bool IDictionary.IsFixedSize { get { return false; } } bool ICollection.IsSynchronized { get { return false; } } // Synchronization root for this object. object ICollection.SyncRoot => this; // Removes all entries from this sorted list. public void Clear() { // clear does not change the capacity version++; // Don't need to doc this but we clear the elements so that the gc can reclaim the references. if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { Array.Clear(keys, 0, _size); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { Array.Clear(values, 0, _size); } _size = 0; } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } // Checks if this sorted list contains an entry with the given key. public bool ContainsKey(TKey key) { return IndexOfKey(key) >= 0; } // Checks if this sorted list contains an entry with the given value. The // values of the entries of the sorted list are compared to the given value // using the Object.Equals method. This method performs a linear // search and is substantially slower than the Contains // method. public bool ContainsValue(TValue value) { return IndexOfValue(value) >= 0; } // Copies the values in this SortedList to an array. void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), arrayIndex, SR.ArgumentOutOfRange_Index); } if (array.Length - arrayIndex < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } for (int i = 0; i < Count; i++) { KeyValuePair<TKey, TValue> entry = new KeyValuePair<TKey, TValue>(keys[i], values[i]); array[arrayIndex + i] = entry; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (index < 0 || index > array.Length) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } KeyValuePair<TKey, TValue>[] keyValuePairArray = array as KeyValuePair<TKey, TValue>[]; if (keyValuePairArray != null) { for (int i = 0; i < Count; i++) { keyValuePairArray[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]); } } else { object[] objects = array as object[]; if (objects == null) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } try { for (int i = 0; i < Count; i++) { objects[i + index] = new KeyValuePair<TKey, TValue>(keys[i], values[i]); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } } private const int MaxArrayLength = 0X7FEFFFFF; // Ensures that the capacity of this sorted list is at least the given // minimum value. If the current capacity of the list is less than // min, the capacity is increased to twice the current capacity or // to min, whichever is larger. private void EnsureCapacity(int min) { int newCapacity = keys.Length == 0 ? DefaultCapacity : keys.Length * 2; // Allow the list to grow to maximum possible capacity (~2G elements) before encountering overflow. // Note that this check works even when _items.Length overflowed thanks to the (uint) cast if ((uint)newCapacity > MaxArrayLength) newCapacity = MaxArrayLength; if (newCapacity < min) newCapacity = min; Capacity = newCapacity; } // Returns the value of the entry at the given index. private TValue GetByIndex(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); return values[index]; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } // Returns the key of the entry at the given index. private TKey GetKey(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); return keys[index]; } // Returns the value associated with the given key. If an entry with the // given key is not found, the returned value is null. public TValue this[TKey key] { get { int i = IndexOfKey(key); if (i >= 0) return values[i]; throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString())); } set { if (((object)key) == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer); if (i >= 0) { values[i] = value; version++; return; } Insert(~i, key, value); } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { int i = IndexOfKey((TKey)key); if (i >= 0) { return values[i]; } } return null; } set { if (!IsCompatibleKey(key)) { throw new ArgumentNullException(nameof(key)); } if (value == null && !(default(TValue) == null)) throw new ArgumentNullException(nameof(value)); TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); } } } // Returns the index of the entry with a given key in this sorted list. The // key is located through a binary search, and thus the average execution // time of this method is proportional to Log2(size), where // size is the size of this sorted list. The returned value is -1 if // the given key does not occur in this sorted list. Null is an invalid // key value. public int IndexOfKey(TKey key) { if (key == null) throw new ArgumentNullException(nameof(key)); int ret = Array.BinarySearch<TKey>(keys, 0, _size, key, comparer); return ret >= 0 ? ret : -1; } // Returns the index of the first occurrence of an entry with a given value // in this sorted list. The entry is located through a linear search, and // thus the average execution time of this method is proportional to the // size of this sorted list. The elements of the list are compared to the // given value using the Object.Equals method. public int IndexOfValue(TValue value) { return Array.IndexOf(values, value, 0, _size); } // Inserts an entry with a given key and value at a given index. private void Insert(int index, TKey key, TValue value) { if (_size == keys.Length) EnsureCapacity(_size + 1); if (index < _size) { Array.Copy(keys, index, keys, index + 1, _size - index); Array.Copy(values, index, values, index + 1, _size - index); } keys[index] = key; values[index] = value; _size++; version++; } public bool TryGetValue(TKey key, out TValue value) { int i = IndexOfKey(key); if (i >= 0) { value = values[i]; return true; } value = default(TValue); return false; } // Removes the entry at the given index. The size of the sorted list is // decreased by one. public void RemoveAt(int index) { if (index < 0 || index >= _size) throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index); _size--; if (index < _size) { Array.Copy(keys, index + 1, keys, index, _size - index); Array.Copy(values, index + 1, values, index, _size - index); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TKey>()) { keys[_size] = default(TKey); } if (RuntimeHelpers.IsReferenceOrContainsReferences<TValue>()) { values[_size] = default(TValue); } version++; } // Removes an entry from this sorted list. If an entry with the specified // key exists in the sorted list, it is removed. An ArgumentException is // thrown if the key is null. public bool Remove(TKey key) { int i = IndexOfKey(key); if (i >= 0) RemoveAt(i); return i >= 0; } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } // Sets the capacity of this sorted list to the size of the sorted list. // This method can be used to minimize a sorted list's memory overhead once // it is known that no new elements will be added to the sorted list. To // completely clear a sorted list and release all memory referenced by the // sorted list, execute the following statements: // // SortedList.Clear(); // SortedList.TrimExcess(); public void TrimExcess() { int threshold = (int)(((double)keys.Length) * 0.9); if (_size < threshold) { Capacity = _size; } } private static bool IsCompatibleKey(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return (key is TKey); } private struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private SortedList<TKey, TValue> _sortedList; private TKey _key; private TValue _value; private int _index; private int _version; private int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int KeyValuePair = 1; internal const int DictEntry = 2; internal Enumerator(SortedList<TKey, TValue> sortedList, int getEnumeratorRetType) { _sortedList = sortedList; _index = 0; _version = _sortedList.version; _getEnumeratorRetType = getEnumeratorRetType; _key = default(TKey); _value = default(TValue); } public void Dispose() { _index = 0; _key = default(TKey); _value = default(TValue); } object IDictionaryEnumerator.Key { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _key; } } public bool MoveNext() { if (_version != _sortedList.version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if ((uint)_index < (uint)_sortedList.Count) { _key = _sortedList.keys[_index]; _value = _sortedList.values[_index]; _index++; return true; } _index = _sortedList.Count + 1; _key = default(TKey); _value = default(TValue); return false; } DictionaryEntry IDictionaryEnumerator.Entry { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(_key, _value); } } public KeyValuePair<TKey, TValue> Current { get { return new KeyValuePair<TKey, TValue>(_key, _value); } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_getEnumeratorRetType == DictEntry) { return new DictionaryEntry(_key, _value); } else { return new KeyValuePair<TKey, TValue>(_key, _value); } } } object IDictionaryEnumerator.Value { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _value; } } void IEnumerator.Reset() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _key = default(TKey); _value = default(TValue); } } private sealed class SortedListKeyEnumerator : IEnumerator<TKey>, IEnumerator { private SortedList<TKey, TValue> _sortedList; private int _index; private int _version; private TKey _currentKey; internal SortedListKeyEnumerator(SortedList<TKey, TValue> sortedList) { _sortedList = sortedList; _version = sortedList.version; } public void Dispose() { _index = 0; _currentKey = default(TKey); } public bool MoveNext() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if ((uint)_index < (uint)_sortedList.Count) { _currentKey = _sortedList.keys[_index]; _index++; return true; } _index = _sortedList.Count + 1; _currentKey = default(TKey); return false; } public TKey Current { get { return _currentKey; } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentKey; } } void IEnumerator.Reset() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _currentKey = default(TKey); } } private sealed class SortedListValueEnumerator : IEnumerator<TValue>, IEnumerator { private SortedList<TKey, TValue> _sortedList; private int _index; private int _version; private TValue _currentValue; internal SortedListValueEnumerator(SortedList<TKey, TValue> sortedList) { _sortedList = sortedList; _version = sortedList.version; } public void Dispose() { _index = 0; _currentValue = default(TValue); } public bool MoveNext() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } if ((uint)_index < (uint)_sortedList.Count) { _currentValue = _sortedList.values[_index]; _index++; return true; } _index = _sortedList.Count + 1; _currentValue = default(TValue); return false; } public TValue Current { get { return _currentValue; } } object IEnumerator.Current { get { if (_index == 0 || (_index == _sortedList.Count + 1)) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return _currentValue; } } void IEnumerator.Reset() { if (_version != _sortedList.version) { throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); } _index = 0; _currentValue = default(TValue); } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class KeyList : IList<TKey>, ICollection { private SortedList<TKey, TValue> _dict; // Do not rename (binary serialization) internal KeyList(SortedList<TKey, TValue> dictionary) { _dict = dictionary; } public int Count { get { return _dict._size; } } public bool IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dict).SyncRoot; } } public void Add(TKey key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public bool Contains(TKey key) { return _dict.ContainsKey(key); } public void CopyTo(TKey[] array, int arrayIndex) { // defer error checking to Array.Copy Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count); } void ICollection.CopyTo(Array array, int arrayIndex) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try { // defer error checking to Array.Copy Array.Copy(_dict.keys, 0, array, arrayIndex, _dict.Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } public void Insert(int index, TKey value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public TKey this[int index] { get { return _dict.GetKey(index); } set { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } } public IEnumerator<TKey> GetEnumerator() { return new SortedListKeyEnumerator(_dict); } IEnumerator IEnumerable.GetEnumerator() { return new SortedListKeyEnumerator(_dict); } public int IndexOf(TKey key) { if (((object)key) == null) throw new ArgumentNullException(nameof(key)); int i = Array.BinarySearch<TKey>(_dict.keys, 0, _dict.Count, key, _dict.comparer); if (i >= 0) return i; return -1; } public bool Remove(TKey key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return false; } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] [Serializable] public sealed class ValueList : IList<TValue>, ICollection { private SortedList<TKey, TValue> _dict; // Do not rename (binary serialization) internal ValueList(SortedList<TKey, TValue> dictionary) { _dict = dictionary; } public int Count { get { return _dict._size; } } public bool IsReadOnly { get { return true; } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dict).SyncRoot; } } public void Add(TValue key) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public void Clear() { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public bool Contains(TValue value) { return _dict.ContainsValue(value); } public void CopyTo(TValue[] array, int arrayIndex) { // defer error checking to Array.Copy Array.Copy(_dict.values, 0, array, arrayIndex, _dict.Count); } void ICollection.CopyTo(Array array, int index) { if (array != null && array.Rank != 1) throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); try { // defer error checking to Array.Copy Array.Copy(_dict.values, 0, array, index, _dict.Count); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } public void Insert(int index, TValue value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } public TValue this[int index] { get { return _dict.GetByIndex(index); } set { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } public IEnumerator<TValue> GetEnumerator() { return new SortedListValueEnumerator(_dict); } IEnumerator IEnumerable.GetEnumerator() { return new SortedListValueEnumerator(_dict); } public int IndexOf(TValue value) { return Array.IndexOf(_dict.values, value, 0, _dict.Count); } public bool Remove(TValue value) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); // return false; } public void RemoveAt(int index) { throw new NotSupportedException(SR.NotSupported_SortedListNestedWrite); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace System.Xml.Linq { internal class XNodeBuilder : XmlWriter { private List<object> _content; private XContainer _parent; private XName _attrName; private string _attrValue; private XContainer _root; public XNodeBuilder(XContainer container) { _root = container; } public override XmlWriterSettings Settings { get { XmlWriterSettings settings = new XmlWriterSettings(); settings.ConformanceLevel = ConformanceLevel.Auto; return settings; } } public override WriteState WriteState { get { throw new NotSupportedException(); } // nop } protected override void Dispose(bool disposing) { if (disposing) { Close(); } } private void Close() { _root.Add(_content); } public override void Flush() { } public override string LookupPrefix(string namespaceName) { throw new NotSupportedException(); // nop } public override void WriteBase64(byte[] buffer, int index, int count) { throw new NotSupportedException(SR.NotSupported_WriteBase64); } public override void WriteCData(string text) { AddNode(new XCData(text)); } public override void WriteCharEntity(char ch) { AddString(new string(ch, 1)); } public override void WriteChars(char[] buffer, int index, int count) { AddString(new string(buffer, index, count)); } public override void WriteComment(string text) { AddNode(new XComment(text)); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { AddNode(new XDocumentType(name, pubid, sysid, subset)); } public override void WriteEndAttribute() { XAttribute a = new XAttribute(_attrName, _attrValue); _attrName = null; _attrValue = null; if (_parent != null) { _parent.Add(a); } else { Add(a); } } public override void WriteEndDocument() { } public override void WriteEndElement() { _parent = ((XElement)_parent).parent; } public override void WriteEntityRef(string name) { switch (name) { case "amp": AddString("&"); break; case "apos": AddString("'"); break; case "gt": AddString(">"); break; case "lt": AddString("<"); break; case "quot": AddString("\""); break; default: throw new NotSupportedException(SR.NotSupported_WriteEntityRef); } } public override void WriteFullEndElement() { XElement e = (XElement)_parent; if (e.IsEmpty) { e.Add(string.Empty); } _parent = e.parent; } public override void WriteProcessingInstruction(string name, string text) { if (name == "xml") { return; } AddNode(new XProcessingInstruction(name, text)); } public override void WriteRaw(char[] buffer, int index, int count) { AddString(new string(buffer, index, count)); } public override void WriteRaw(string data) { AddString(data); } public override void WriteStartAttribute(string prefix, string localName, string namespaceName) { if (prefix == null) throw new ArgumentNullException("prefix"); _attrName = XNamespace.Get(prefix.Length == 0 ? string.Empty : namespaceName).GetName(localName); _attrValue = string.Empty; } public override void WriteStartDocument() { } public override void WriteStartDocument(bool standalone) { } public override void WriteStartElement(string prefix, string localName, string namespaceName) { AddNode(new XElement(XNamespace.Get(namespaceName).GetName(localName))); } public override void WriteString(string text) { AddString(text); } public override void WriteSurrogateCharEntity(char lowCh, char highCh) { AddString(new string(new char[] { highCh, lowCh })); } public override void WriteValue(DateTimeOffset value) { // For compatibility with custom writers, XmlWriter writes DateTimeOffset as DateTime. // Our internal writers should use the DateTimeOffset-String conversion from XmlConvert. WriteString(XmlConvert.ToString(value)); } public override void WriteWhitespace(string ws) { AddString(ws); } private void Add(object o) { if (_content == null) { _content = new List<object>(); } _content.Add(o); } private void AddNode(XNode n) { if (_parent != null) { _parent.Add(n); } else { Add(n); } XContainer c = n as XContainer; if (c != null) { _parent = c; } } private void AddString(string s) { if (s == null) { return; } if (_attrValue != null) { _attrValue += s; } else if (_parent != null) { _parent.Add(s); } else { Add(s); } } } }
// 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; using System; using System.IO; using System.Text; namespace System.IO.Tests { public class BinaryWriter_WriteByteCharTests { protected virtual Stream CreateStream() { return new MemoryStream(); } /// <summary> /// Cases Tested: /// 1) Tests that BinaryWriter properly writes chars into a stream. /// 2) Tests that if someone writes surrogate characters, an argument exception is thrown /// 3) Casting an int to char and writing it, works. /// </summary> [Fact] public void BinaryWriter_WriteCharTest() { Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); BinaryReader dr2 = new BinaryReader(mstr); char[] chArr = new char[0]; int ii = 0; // [] Write a series of characters to a MemoryStream and read them back chArr = new char[] { 'A', 'c', '\0', '\u2701', '$', '.', '1', 'l', '\u00FF', '\n', '\t', '\v' }; for (ii = 0; ii < chArr.Length; ii++) dw2.Write(chArr[ii]); dw2.Flush(); mstr.Position = 0; for (ii = 0; ii < chArr.Length; ii++) { char c = dr2.ReadChar(); Assert.Equal(chArr[ii], c); } Assert.Throws<EndOfStreamException>(() => dr2.ReadChar()); dw2.Dispose(); dr2.Dispose(); mstr.Dispose(); //If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in. //They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int). //A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF char ch; Stream mem = CreateStream(); BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode); //between 1 <= x < 255 int[] randomNumbers = new int[] { 1, 254, 210, 200, 105, 135, 98, 54 }; for (int i = 0; i < randomNumbers.Length; i++) { ch = (char)randomNumbers[i]; writer.Write(ch); } mem.Position = 0; writer.Dispose(); mem.Dispose(); } [Fact] public void BinaryWriter_WriteCharTest_Negative() { //If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in. //They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int). //A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF char ch; Stream mem = CreateStream(); BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode); // between 55296 <= x < 56319 int[] randomNumbers = new int[] { 55296, 56318, 55305, 56019, 55888, 55900, 56251 }; for (int i = 0; i < randomNumbers.Length; i++) { ch = (char)randomNumbers[i]; Assert.Throws<ArgumentException>(() => writer.Write(ch)); } // between 56320 <= x < 57343 randomNumbers = new int[] { 56320, 57342, 56431, 57001, 56453, 57245, 57111 }; for (int i = 0; i < randomNumbers.Length; i++) { ch = (char)randomNumbers[i]; Assert.Throws<ArgumentException>(() => writer.Write(ch)); } writer.Dispose(); mem.Dispose(); } /// <summary> /// Cases Tested: /// Writing bytes casted to chars and using a different encoding; iso-2022-jp. /// </summary> [Fact] public void BinaryWriter_WriteCharTest2() { // BinaryReader/BinaryWriter don't do well when mixing char or char[] data and binary data. // This behavior remains for compat. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Stream stream = CreateStream(); // string name = iso-2022-jp, codepage = 50220 (original test used a code page number). // taken from http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx string codepageName = "iso-2022-jp"; BinaryWriter writer = new BinaryWriter(stream, Encoding.GetEncoding(codepageName)); byte[] bytes = { 0x01, 0x02, 0x03, 0x04, 0x05 }; writer.Write((char)0x30ca); writer.Write(bytes); writer.Flush(); writer.Write('\0'); stream.Seek(0, SeekOrigin.Begin); BinaryReader reader = new BinaryReader(stream, Encoding.GetEncoding(codepageName)); char japanese = reader.ReadChar(); Assert.Equal(0x30ca, (int)japanese); byte[] readBytes = reader.ReadBytes(5); for (int i = 0; i < 5; i++) { //We pretty much dont expect this to work Assert.NotEqual(readBytes[i], bytes[i]); } stream.Dispose(); writer.Dispose(); reader.Dispose(); } /// <summary> /// Testing that bytes can be written to a stream with BinaryWriter. /// </summary> [Fact] public void BinaryWriter_WriteByteTest() { int ii = 0; byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 100, 1, 10, byte.MaxValue / 2, byte.MaxValue - 100 }; // [] read/Write with Memorystream Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); for (ii = 0; ii < bytArr.Length; ii++) dw2.Write(bytArr[ii]); dw2.Flush(); mstr.Position = 0; BinaryReader dr2 = new BinaryReader(mstr); for (ii = 0; ii < bytArr.Length; ii++) { Assert.Equal(bytArr[ii], dr2.ReadByte()); } // [] Check End Of Stream Assert.Throws<EndOfStreamException>(() => dr2.ReadByte()); dr2.Dispose(); dw2.Dispose(); mstr.Dispose(); } /// <summary> /// Testing that SBytes can be written to a stream with BinaryWriter. /// </summary> [Fact] public void BinaryWriter_WriteSByteTest() { int ii = 0; sbyte[] sbArr = new sbyte[] { sbyte.MinValue, sbyte.MaxValue, -100, 100, 0, sbyte.MinValue / 2, sbyte.MaxValue / 2, 10, 20, 30, -10, -20, -30, sbyte.MaxValue - 100 }; // [] read/Write with Memorystream Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); for (ii = 0; ii < sbArr.Length; ii++) dw2.Write(sbArr[ii]); dw2.Flush(); mstr.Position = 0; BinaryReader dr2 = new BinaryReader(mstr); for (ii = 0; ii < sbArr.Length; ii++) { Assert.Equal(sbArr[ii], dr2.ReadSByte()); } dr2.Dispose(); dw2.Dispose(); mstr.Dispose(); } /// <summary> /// Testing that an ArgumentException is thrown when Sbytes are written to a stream /// and read past the end of that stream. /// </summary> [Fact] public void BinaryWriter_WriteSByteTest_NegativeCase() { int ii = 0; sbyte[] sbArr = new sbyte[] { sbyte.MinValue, sbyte.MaxValue, -100, 100, 0, sbyte.MinValue / 2, sbyte.MaxValue / 2, 10, 20, 30, -10, -20, -30, sbyte.MaxValue - 100 }; Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); for (ii = 0; ii < sbArr.Length; ii++) dw2.Write(sbArr[ii]); dw2.Flush(); BinaryReader dr2 = new BinaryReader(mstr); // [] Check End Of Stream Assert.Throws<EndOfStreamException>(() => dr2.ReadSByte()); dr2.Dispose(); dw2.Dispose(); mstr.Dispose(); } /// <summary> /// Testing that a byte[] can be written to a stream with BinaryWriter. /// </summary> [Fact] public void BinaryWriter_WriteBArrayTest() { int ii = 0; byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 1, 5, 10, 100, 200 }; // [] read/Write with Memorystream Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); dw2.Write(bytArr); dw2.Flush(); mstr.Position = 0; BinaryReader dr2 = new BinaryReader(mstr); for (ii = 0; ii < bytArr.Length; ii++) { Assert.Equal(bytArr[ii], dr2.ReadByte()); } // [] Check End Of Stream Assert.Throws<EndOfStreamException>(() => dr2.ReadByte()); mstr.Dispose(); dw2.Dispose(); dr2.Dispose(); } [Fact] public void BinaryWriter_WriteBArrayTest_Negative() { int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue, short.MinValue }; int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 }; byte[] bArr = new byte[0]; // [] ArgumentNullException for null argument Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); Assert.Throws<ArgumentNullException>(() => dw2.Write((byte[])null)); mstr.Dispose(); dw2.Dispose(); // [] ArgumentNullException for null argument mstr = CreateStream(); dw2 = new BinaryWriter(mstr); Assert.Throws<ArgumentNullException>(() => dw2.Write((byte[])null, 0, 0)); dw2.Dispose(); mstr.Dispose(); mstr = CreateStream(); dw2 = new BinaryWriter(mstr); for (int iLoop = 0; iLoop < iArrInvalidValues.Length; iLoop++) { // [] ArgumentOutOfRange for negative offset Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(bArr, iArrInvalidValues[iLoop], 0)); // [] ArgumentOutOfRangeException for negative count Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(bArr, 0, iArrInvalidValues[iLoop])); } dw2.Dispose(); mstr.Dispose(); mstr = CreateStream(); dw2 = new BinaryWriter(mstr); for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++) { // [] Offset out of range Assert.Throws<ArgumentException>(() => dw2.Write(bArr, iArrLargeValues[iLoop], 0)); // [] Invalid count value Assert.Throws<ArgumentException>(() => dw2.Write(bArr, 0, iArrLargeValues[iLoop])); } dw2.Dispose(); mstr.Dispose(); } /// <summary> /// Cases Tested: /// 1) Testing that bytes can be written to a stream with BinaryWriter. /// 2) Tests exceptional scenarios. /// </summary> [Fact] public void BinaryWriter_WriteBArrayTest2() { BinaryWriter dw2 = null; BinaryReader dr2 = null; Stream mstr = null; byte[] bArr = new byte[0]; int ii = 0; byte[] bReadArr = new byte[0]; int ReturnValue; bArr = new byte[1000]; bArr[0] = byte.MinValue; bArr[1] = byte.MaxValue; for (ii = 2; ii < 1000; ii++) bArr[ii] = (byte)(ii % 255); // []read/ Write character values 0-1000 with Memorystream mstr = CreateStream(); dw2 = new BinaryWriter(mstr); dw2.Write(bArr, 0, bArr.Length); dw2.Flush(); mstr.Position = 0; dr2 = new BinaryReader(mstr); bReadArr = new byte[bArr.Length]; ReturnValue = dr2.Read(bReadArr, 0, bArr.Length); Assert.Equal(bArr.Length, ReturnValue); for (ii = 0; ii < bArr.Length; ii++) { Assert.Equal(bArr[ii], bReadArr[ii]); } dw2.Dispose(); dr2.Dispose(); mstr.Dispose(); } /// <summary> /// Cases Tested: /// 1) Testing that char[] can be written to a stream with BinaryWriter. /// 2) Tests exceptional scenarios. /// </summary> [Fact] public void BinaryWriter_WriteCharArrayTest() { int ii = 0; char[] chArr = new char[1000]; chArr[0] = char.MinValue; chArr[1] = char.MaxValue; chArr[2] = '1'; chArr[3] = 'A'; chArr[4] = '\0'; chArr[5] = '#'; chArr[6] = '\t'; for (ii = 7; ii < 1000; ii++) chArr[ii] = (char)ii; // [] read/Write with Memorystream Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); dw2.Write(chArr); dw2.Flush(); mstr.Position = 0; BinaryReader dr2 = new BinaryReader(mstr); for (ii = 0; ii < chArr.Length; ii++) { Assert.Equal(chArr[ii], dr2.ReadChar()); } // [] Check End Of Stream Assert.Throws<EndOfStreamException>(() => dr2.ReadChar()); dw2.Dispose(); dr2.Dispose(); mstr.Dispose(); } [Fact] public void BinaryWriter_WriteCharArrayTest_Negative() { int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue, short.MinValue }; int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 }; char[] chArr = new char[1000]; // [] ArgumentNullException for null argument Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); Assert.Throws<ArgumentNullException>(() => dw2.Write((char[])null)); dw2.Dispose(); mstr.Dispose(); // [] ArgumentNullException for null argument mstr = CreateStream(); dw2 = new BinaryWriter(mstr); Assert.Throws<ArgumentNullException>(() => dw2.Write((char[])null, 0, 0)); mstr.Dispose(); dw2.Dispose(); mstr = CreateStream(); dw2 = new BinaryWriter(mstr); for (int iLoop = 0; iLoop < iArrInvalidValues.Length; iLoop++) { // [] ArgumentOutOfRange for negative offset Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, iArrInvalidValues[iLoop], 0)); // [] negative count. Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, 0, iArrInvalidValues[iLoop])); } mstr.Dispose(); dw2.Dispose(); mstr = CreateStream(); dw2 = new BinaryWriter(mstr); for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++) { // [] Offset out of range Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, iArrLargeValues[iLoop], 0)); // [] Invalid count value Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, 0, iArrLargeValues[iLoop])); } mstr.Dispose(); dw2.Dispose(); } /// <summary> /// Cases Tested: /// If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in. /// They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int). /// A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF /// /// We dont throw on the second read but then throws continuously - note the loop count difference in the 2 loops /// /// BinaryReader was reverting to its original location instead of advancing. This was changed to skip past the char in the surrogate range. /// The affected method is InternalReadOneChar (IROC). Note that the work here is slightly complicated by the way surrogates are handled by /// the decoding classes. When IROC calls decoder.GetChars(), if the bytes passed in are surrogates, UnicodeEncoding doesn't report it. /// charsRead would end up being one value, and since BinaryReader doesn't have the logic telling it exactly how many bytes total to expect, /// it calls GetChars in a second loop. In that loop, UnicodeEncoding matches up a surrogate pair. If it realizes it's too big for the encoding, /// then it throws an ArgumentException (chars overflow). This meant that BinaryReader.IROC is advancing past two chars in the surrogate /// range, which is why the position actually needs to be moved back (but not past the first surrogate char). /// /// Note that UnicodeEncoding doesn't always throw when it encounters two successive chars in the surrogate range. The exception /// encountered here happens if it finds a valid pair but then determines it's too long. If the pair isn't valid (a low then a high), /// then it returns 0xfffd, which is why BinaryReader.ReadChar needs to do an explicit check. (It always throws when it encounters a surrogate) /// </summary> [Fact] public void BinaryWriter_WriteCharArrayTest2() { Stream mem = CreateStream(); BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode); // between 55296 <= x < 56319 // between 56320 <= x < 57343 char[] randomChars = new char[] { (char)55296, (char)57297, (char)55513, (char)56624, (char)55334, (char)56957, (char)55857, (char)56355, (char)56095, (char)56887, (char) 56126, (char) 56735, (char)55748, (char)56405, (char)55787, (char)56707, (char) 56300, (char)56417, (char)55465, (char)56944 }; writer.Write(randomChars); mem.Position = 0; BinaryReader reader = new BinaryReader(mem, Encoding.Unicode); for (int i = 0; i < 50; i++) { try { reader.ReadChar(); Assert.Equal(1, i); } catch (ArgumentException) { // ArgumentException is sometimes thrown on ReadChar() due to the // behavior outlined in the method summary. } } char[] chars = reader.ReadChars(randomChars.Length); for (int i = 0; i < randomChars.Length; i++) Assert.Equal(randomChars[i], chars[i]); reader.Dispose(); writer.Dispose(); } /// <summary> /// Cases Tested: /// 1) Tests that char[] can be written to a stream with BinaryWriter. /// 2) Tests Exceptional cases. /// </summary> [Fact] public void BinaryWriter_WriteCharArrayTest3() { char[] chArr = new char[1000]; chArr[0] = char.MinValue; chArr[1] = char.MaxValue; chArr[2] = '1'; chArr[3] = 'A'; chArr[4] = '\0'; chArr[5] = '#'; chArr[6] = '\t'; for (int ii = 7; ii < 1000; ii++) chArr[ii] = (char)ii; // []read/ Write character values 0-1000 with Memorystream Stream mstr = CreateStream(); BinaryWriter dw2 = new BinaryWriter(mstr); dw2.Write(chArr, 0, chArr.Length); dw2.Flush(); mstr.Position = 0; BinaryReader dr2 = new BinaryReader(mstr); char[] chReadArr = new char[chArr.Length]; int charsRead = dr2.Read(chReadArr, 0, chArr.Length); Assert.Equal(chArr.Length, charsRead); for (int ii = 0; ii < chArr.Length; ii++) { Assert.Equal(chArr[ii], chReadArr[ii]); } mstr.Dispose(); dw2.Dispose(); } } }
// 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.IO; using System.Linq; using System.Net.Test.Common; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class UnixDomainSocketTest { private readonly ITestOutputHelper _log; public UnixDomainSocketTest(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void Socket_CreateUnixDomainSocket_Throws_OnWindows() { SocketException e = Assert.Throws<SocketException>(() => new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)); Assert.Equal(SocketError.AddressFamilyNotSupported, e.SocketErrorCode); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_Success() { string path = null; SocketTestServer server = null; UnixDomainSocketEndPoint endPoint = null; for (int attempt = 0; attempt < 5; attempt++) { path = GetRandomNonExistingFilePath(); endPoint = new UnixDomainSocketEndPoint(path); try { server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, endPoint, ProtocolType.Unspecified); break; } catch (SocketException) { //Path selection is contingent on a successful Bind(). //If it fails, the next iteration will try another path. } } try { Assert.NotNull(server); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = endPoint; args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true); var complete = new TaskCompletionSource<bool>(); args.UserToken = complete; using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { Assert.True(sock.ConnectAsync(args)); await complete.Task; Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); } } finally { server.Dispose(); try { File.Delete(path); } catch { } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = endPoint; args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true); var complete = new TaskCompletionSource<bool>(); args.UserToken = complete; using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { await complete.Task; } Assert.Equal(SocketError.AddressNotAvailable, args.SocketError); } } finally { try { File.Delete(path); } catch { } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void Socket_SendReceive_Success() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { server.Bind(endPoint); server.Listen(1); client.Connect(endPoint); using (Socket accepted = server.Accept()) { var data = new byte[1]; for (int i = 0; i < 10; i++) { data[0] = (byte)i; accepted.Send(data); data[0] = 0; Assert.Equal(1, client.Receive(data)); Assert.Equal(i, data[0]); } } } } finally { try { File.Delete(path); } catch { } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public async Task Socket_SendReceiveAsync_Success() { string path = GetRandomNonExistingFilePath(); var endPoint = new UnixDomainSocketEndPoint(path); try { using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { server.Bind(endPoint); server.Listen(1); await client.ConnectAsync(endPoint); using (Socket accepted = await server.AcceptAsync()) { var data = new byte[1]; for (int i = 0; i < 10; i++) { data[0] = (byte)i; await accepted.SendAsync(new ArraySegment<byte>(data), SocketFlags.None); data[0] = 0; Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(data), SocketFlags.None)); Assert.Equal(i, data[0]); } } } } finally { try { File.Delete(path); } catch { } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void ConcurrentSendReceive() { using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified)) { const int Iters = 2048; byte[] sendData = new byte[Iters]; byte[] receiveData = new byte[sendData.Length]; new Random().NextBytes(sendData); string path = GetRandomNonExistingFilePath(); server.Bind(new UnixDomainSocketEndPoint(path)); server.Listen(1); Task<Socket> acceptTask = server.AcceptAsync(); client.Connect(new UnixDomainSocketEndPoint(path)); acceptTask.Wait(); Socket accepted = acceptTask.Result; Task[] writes = new Task[Iters]; Task<int>[] reads = new Task<int>[Iters]; for (int i = 0; i < Iters; i++) { writes[i] = client.SendAsync(new ArraySegment<byte>(sendData, i, 1), SocketFlags.None); } for (int i = 0; i < Iters; i++) { reads[i] = accepted.ReceiveAsync(new ArraySegment<byte>(receiveData, i, 1), SocketFlags.None); } Task.WaitAll(writes); Task.WaitAll(reads); Assert.Equal(sendData, receiveData); } } private static string GetRandomNonExistingFilePath() { string result; do { result = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); } while (File.Exists(result)); return result; } private sealed class UnixDomainSocketEndPoint : EndPoint { private const AddressFamily EndPointAddressFamily = AddressFamily.Unix; private static readonly Encoding s_pathEncoding = Encoding.UTF8; private static readonly int s_nativePathOffset = 2; // = offsetof(struct sockaddr_un, sun_path). It's the same on Linux and OSX private static readonly int s_nativePathLength = 91; // sockaddr_un.sun_path at http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_un.h.html, -1 for terminator private static readonly int s_nativeAddressSize = s_nativePathOffset + s_nativePathLength; private readonly string _path; private readonly byte[] _encodedPath; public UnixDomainSocketEndPoint(string path) { if (path == null) { throw new ArgumentNullException(nameof(path)); } _path = path; _encodedPath = s_pathEncoding.GetBytes(_path); if (path.Length == 0 || _encodedPath.Length > s_nativePathLength) { throw new ArgumentOutOfRangeException(nameof(path)); } } internal UnixDomainSocketEndPoint(SocketAddress socketAddress) { if (socketAddress == null) { throw new ArgumentNullException(nameof(socketAddress)); } if (socketAddress.Family != EndPointAddressFamily || socketAddress.Size > s_nativeAddressSize) { throw new ArgumentOutOfRangeException(nameof(socketAddress)); } if (socketAddress.Size > s_nativePathOffset) { _encodedPath = new byte[socketAddress.Size - s_nativePathOffset]; for (int i = 0; i < _encodedPath.Length; i++) { _encodedPath[i] = socketAddress[s_nativePathOffset + i]; } _path = s_pathEncoding.GetString(_encodedPath, 0, _encodedPath.Length); } else { _encodedPath = Array.Empty<byte>(); _path = string.Empty; } } public override SocketAddress Serialize() { var result = new SocketAddress(AddressFamily.Unix, s_nativeAddressSize); Debug.Assert(_encodedPath.Length + s_nativePathOffset <= result.Size, "Expected path to fit in address"); for (int index = 0; index < _encodedPath.Length; index++) { result[s_nativePathOffset + index] = _encodedPath[index]; } result[s_nativePathOffset + _encodedPath.Length] = 0; // path must be null-terminated return result; } public override EndPoint Create(SocketAddress socketAddress) => new UnixDomainSocketEndPoint(socketAddress); public override AddressFamily AddressFamily => EndPointAddressFamily; public override string ToString() => _path; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.IO; using System.Text; using System.Collections.ObjectModel; using System.Management.Automation.Runspaces; using Microsoft.PowerShell.Commands; using System.Collections.Generic; using System.Management.Automation.Language; using System.Management.Automation.Security; namespace System.Management.Automation { /// <summary> /// Provides information for MSH scripts that are directly executable by MSH /// but are not built into the runspace configuration. /// </summary> public class ExternalScriptInfo : CommandInfo, IScriptCommandInfo { #region ctor /// <summary> /// Creates an instance of the ExternalScriptInfo class with the specified name, and path. /// </summary> /// <param name="name"> /// The name of the script. /// </param> /// <param name="path"> /// The path to the script /// </param> /// <param name="context"> /// The context of the currently running engine. /// </param> /// <exception cref="ArgumentNullException"> /// If <paramref name="context"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="path"/> is null or empty. /// </exception> internal ExternalScriptInfo(string name, string path, ExecutionContext context) : base(name, CommandTypes.ExternalScript, context) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } Diagnostics.Assert(IO.Path.IsPathRooted(path), "Caller makes sure that 'path' is already resolved."); // Path might contain short-name syntax such as 'DOCUME~1'. Use Path.GetFullPath to expand the short name _path = IO.Path.GetFullPath(path); CommonInitialization(); } /// <summary> /// Creates an instance of ExternalScriptInfo that has no ExecutionContext. /// This is used exclusively to pass it to the AuthorizationManager that just uses the path parameter. /// </summary> /// <param name="name"> /// The name of the script. /// </param> /// <param name="path"> /// The path to the script /// </param> /// <exception cref="ArgumentException"> /// If <paramref name="path"/> is null or empty. /// </exception> internal ExternalScriptInfo(string name, string path) : base(name, CommandTypes.ExternalScript) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } Diagnostics.Assert(IO.Path.IsPathRooted(path), "Caller makes sure that 'path' is already resolved."); // Path might contain short-name syntax such as 'DOCUME~1'. Use Path.GetFullPath to expand the short name _path = IO.Path.GetFullPath(path); CommonInitialization(); } /// <summary> /// This is a copy constructor, used primarily for get-command. /// </summary> internal ExternalScriptInfo(ExternalScriptInfo other) : base(other) { _path = other._path; CommonInitialization(); } /// <summary> /// Common initialization for all constructors. /// </summary> private void CommonInitialization() { // Assume external scripts are untrusted by default (for Get-Command, etc) // until we've actually parsed their script block. if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None) { // Get the lock down policy with no handle. This only impacts command discovery, // as the real language mode assignment will be done when we read the script // contents. SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, null); if (scriptSpecificPolicy != SystemEnforcementMode.Enforce) { this.DefiningLanguageMode = PSLanguageMode.FullLanguage; } else { this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; } } } /// <summary> /// Create a copy of commandInfo for GetCommandCommand so that we can generate parameter /// sets based on an argument list (so we can get the dynamic parameters.) /// </summary> internal override CommandInfo CreateGetCommandCopy(object[] argumentList) { ExternalScriptInfo copy = new ExternalScriptInfo(this) { IsGetCommandCopy = true, Arguments = argumentList }; return copy; } #endregion ctor internal override HelpCategory HelpCategory { get { return HelpCategory.ExternalScript; } } /// <summary> /// Gets the path to the script file. /// </summary> public string Path { get { return _path; } } private readonly string _path = string.Empty; /// <summary> /// Gets the path to the script file. /// </summary> public override string Definition { get { return Path; } } /// <summary> /// Gets the source of this command. /// </summary> public override string Source { get { return this.Definition; } } /// <summary> /// Returns the syntax of a command. /// </summary> internal override string Syntax { get { StringBuilder synopsis = new StringBuilder(); foreach (CommandParameterSetInfo parameterSet in ParameterSets) { synopsis.AppendLine( string.Format( Globalization.CultureInfo.CurrentCulture, "{0} {1}", Name, parameterSet)); } return synopsis.ToString(); } } /// <summary> /// Determine the visibility for this script... /// </summary> public override SessionStateEntryVisibility Visibility { get { if (Context == null) return SessionStateEntryVisibility.Public; return Context.EngineSessionState.CheckScriptVisibility(_path); } set { throw PSTraceSource.NewNotImplementedException(); } } /// <summary> /// The script block that represents the external script. /// </summary> public ScriptBlock ScriptBlock { get { if (_scriptBlock == null) { // Skip ShouldRun check for .psd1 files. // Use ValidateScriptInfo() for explicitly validating the checkpolicy for psd1 file. // if (!_path.EndsWith(".psd1", StringComparison.OrdinalIgnoreCase)) { ValidateScriptInfo(null); } // parse the script into an expression tree... ScriptBlock newScriptBlock = ParseScriptContents(new Parser(), _path, ScriptContents, DefiningLanguageMode); this.ScriptBlock = newScriptBlock; } return _scriptBlock; } private set { _scriptBlock = value; if (value != null) { _scriptBlock.LanguageMode = this.DefiningLanguageMode; } } } private ScriptBlock _scriptBlock; private ScriptBlockAst _scriptBlockAst; private static ScriptBlock ParseScriptContents(Parser parser, string fileName, string fileContents, PSLanguageMode? definingLanguageMode) { // If we are in ConstrainedLanguage mode but the defining language mode is FullLanguage, then we need // to parse the script contents in FullLanguage mode context. Otherwise we will get bogus parsing errors // such as "Configuration keyword not allowed". if (definingLanguageMode.HasValue && (definingLanguageMode == PSLanguageMode.FullLanguage)) { var context = LocalPipeline.GetExecutionContextFromTLS(); if ((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) { context.LanguageMode = PSLanguageMode.FullLanguage; try { return ScriptBlock.Create(parser, fileName, fileContents); } finally { context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } } } return ScriptBlock.Create(parser, fileName, fileContents); } internal ScriptBlockAst GetScriptBlockAst() { var scriptContents = ScriptContents; if (_scriptBlock == null) { this.ScriptBlock = ScriptBlock.TryGetCachedScriptBlock(_path, scriptContents); } if (_scriptBlock != null) { return (ScriptBlockAst)_scriptBlock.Ast; } if (_scriptBlockAst == null) { ParseError[] errors; Parser parser = new Parser(); // If we are in ConstrainedLanguage mode but the defining language mode is FullLanguage, then we need // to parse the script contents in FullLanguage mode context. Otherwise we will get bogus parsing errors // such as "Configuration or Class keyword not allowed". var context = LocalPipeline.GetExecutionContextFromTLS(); if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage && DefiningLanguageMode == PSLanguageMode.FullLanguage) { context.LanguageMode = PSLanguageMode.FullLanguage; try { _scriptBlockAst = parser.Parse(_path, ScriptContents, null, out errors, ParseMode.Default); } finally { context.LanguageMode = PSLanguageMode.ConstrainedLanguage; } } else { _scriptBlockAst = parser.Parse(_path, ScriptContents, null, out errors, ParseMode.Default); } if (errors.Length == 0) { this.ScriptBlock = new ScriptBlock(_scriptBlockAst, isFilter: false); ScriptBlock.CacheScriptBlock(_scriptBlock.Clone(), _path, scriptContents); } } return _scriptBlockAst; } /// <summary> /// Validates the external script info. /// </summary> /// <param name="host"></param> public void ValidateScriptInfo(Host.PSHost host) { if (!_signatureChecked) { ExecutionContext context = Context ?? LocalPipeline.GetExecutionContextFromTLS(); ReadScriptContents(); // We have no way to check the signature w/o context because we don't have // an AuthorizationManager. This can happen during initialization when trying // to get the CommandMetadata for a script (either to prepopulate the metadata // or creating a proxy). If context can be null under any other circumstances, // we need to make sure it's acceptable if the parser is invoked on unsigned scripts. if (context != null) { CommandDiscovery.ShouldRun(context, host, this, CommandOrigin.Internal); _signatureChecked = true; } } } /// <summary> /// The output type(s) is specified in the script block. /// </summary> public override ReadOnlyCollection<PSTypeName> OutputType { get { return ScriptBlock.OutputType; } } internal bool SignatureChecked { set { _signatureChecked = value; } } private bool _signatureChecked; #region Internal /// <summary> /// The command metadata for the script. /// </summary> internal override CommandMetadata CommandMetadata { get { return _commandMetadata ?? (_commandMetadata = new CommandMetadata(this.ScriptBlock, this.Name, LocalPipeline.GetExecutionContextFromTLS())); } } private CommandMetadata _commandMetadata; /// <summary> /// True if the command has dynamic parameters, false otherwise. /// </summary> internal override bool ImplementsDynamicParameters { get { try { return ScriptBlock.HasDynamicParameters; } catch (ParseException) { } catch (ScriptRequiresException) { } // If we got here, there was some sort of parsing exception. We'll just // ignore it and assume the script does not implement dynamic parameters. // Futhermore, we'll clear out the fields so that the next attempt to // access ScriptBlock will result in an exception that doesn't get ignored. _scriptBlock = null; _scriptContents = null; return false; } } #endregion Internal private ScriptRequirements GetRequiresData() { return GetScriptBlockAst().ScriptRequirements; } internal string RequiresApplicationID { get { var data = GetRequiresData(); return data == null ? null : data.RequiredApplicationId; } } internal uint ApplicationIDLineNumber { get { return 0; } } internal Version RequiresPSVersion { get { var data = GetRequiresData(); return data == null ? null : data.RequiredPSVersion; } } internal IEnumerable<string> RequiresPSEditions { get { var data = GetRequiresData(); return data == null ? null : data.RequiredPSEditions; } } internal IEnumerable<ModuleSpecification> RequiresModules { get { var data = GetRequiresData(); return data == null ? null : data.RequiredModules; } } internal bool RequiresElevation { get { var data = GetRequiresData(); return data == null ? false : data.IsElevationRequired; } } internal uint PSVersionLineNumber { get { return 0; } } internal IEnumerable<PSSnapInSpecification> RequiresPSSnapIns { get { var data = GetRequiresData(); return data == null ? null : data.RequiresPSSnapIns; } } /// <summary> /// Gets the original contents of the script. /// </summary> public string ScriptContents { get { if (_scriptContents == null) { ReadScriptContents(); } return _scriptContents; } } private string _scriptContents; /// <summary> /// Gets the original encoding of the script. /// </summary> public Encoding OriginalEncoding { get { if (_scriptContents == null) { ReadScriptContents(); } return _originalEncoding; } } private Encoding _originalEncoding; private void ReadScriptContents() { if (_scriptContents == null) { // make sure we can actually load the script and that it's non-empty // before we call it. // Note, although we are passing ASCII as the encoding, the StreamReader // class still obeys the byte order marks at the beginning of the file // if present. If not present, then ASCII is used as the default encoding. try { using (FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read)) { Encoding defaultEncoding = ClrFacade.GetDefaultEncoding(); Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle; using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding)) { _scriptContents = scriptReader.ReadToEnd(); _originalEncoding = scriptReader.CurrentEncoding; // Check if this came from a trusted path. If so, set its language mode to FullLanguage. if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None) { SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, safeFileHandle); if (scriptSpecificPolicy != SystemEnforcementMode.Enforce) { this.DefiningLanguageMode = PSLanguageMode.FullLanguage; } else { this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; } } else { if (this.Context != null) { this.DefiningLanguageMode = this.Context.LanguageMode; } } } } } catch (ArgumentException e) { // This catches PSArgumentException as well. ThrowCommandNotFoundException(e); } catch (IOException e) { ThrowCommandNotFoundException(e); } catch (NotSupportedException e) { ThrowCommandNotFoundException(e); } catch (UnauthorizedAccessException e) { // this is unadvertised exception thrown by the StreamReader ctor when // no permission to read the script file ThrowCommandNotFoundException(e); } } } private static void ThrowCommandNotFoundException(Exception innerException) { CommandNotFoundException cmdE = new CommandNotFoundException(innerException.Message, innerException); throw cmdE; } } /// <summary> /// Thrown when fail to parse #requires statements. Caught by CommandDiscovery. /// </summary> internal class ScriptRequiresSyntaxException : ScriptRequiresException { internal ScriptRequiresSyntaxException(string message) : base(message) { } } /// <summary> /// Defines the name and version tuple of a PSSnapin. /// </summary> [Serializable] public class PSSnapInSpecification { internal PSSnapInSpecification(string psSnapinName) { PSSnapInInfo.VerifyPSSnapInFormatThrowIfError(psSnapinName); Name = psSnapinName; Version = null; } /// <summary> /// The name of the snapin. /// </summary> public string Name { get; internal set; } /// <summary> /// The version of the snapin. /// </summary> public Version Version { get; internal set; } } }
// 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; using System.Threading; using Alachisoft.NGroups.Util; using Alachisoft.NCache.Common.Threading; using Alachisoft.NCache.Common.Net; namespace Alachisoft.NGroups.Stack { /// <summary> Maintains a pool of sequence numbers of messages that need to be retransmitted. Messages /// are aged and retransmission requests sent according to age (linear backoff used). If a /// TimeScheduler instance is given to the constructor, it will be used, otherwise Reransmitter /// will create its own. The retransmit timeouts have to be set first thing after creating an instance. /// The <code>add()</code> method adds a range of sequence numbers of messages to be retransmitted. The /// <code>remove()</code> method removes a sequence number again, cancelling retransmission requests for it. /// Whenever a message needs to be retransmitted, the <code>RetransmitCommand.retransmit()</code> method is called. /// It can be used e.g. by an ack-based scheme (e.g. AckSenderWindow) to retransmit a message to the receiver, or /// by a nak-based scheme to send a retransmission request to the sender of the missing message. /// /// </summary> /// <author> John Giorgiadis /// </author> /// <author> Bela Ban /// </author> /// <version> $Revision: 1.4 $ /// </version> internal class Retransmitter { virtual public long[] RetransmitTimeouts { set { if (value != null) RETRANSMIT_TIMEOUTS = value; } } private const long SEC = 1000; /// <summary>Default retransmit intervals (ms) - exponential approx. </summary> private static long[] RETRANSMIT_TIMEOUTS = new long[]{2 * SEC, 3 * SEC, 5 * SEC, 8 * SEC}; /// <summary>Default retransmit thread suspend timeout (ms) </summary> private const long SUSPEND_TIMEOUT = 2000; private Address sender = null; private System.Collections.ArrayList msgs = new System.Collections.ArrayList(); private Retransmitter.RetransmitCommand cmd = null; private bool retransmitter_owned; private TimeScheduler retransmitter = null; /// <summary>Retransmit command (see Gamma et al.) used to retrieve missing messages </summary> internal interface RetransmitCommand { /// <summary> Get the missing messages between sequence numbers /// <code>first_seqno</code> and <code>last_seqno</code>. This can either be done by sending a /// retransmit message to destination <code>sender</code> (nak-based scheme), or by /// retransmitting the missing message(s) to <code>sender</code> (ack-based scheme). /// </summary> /// <param name="first_seqno">The sequence number of the first missing message /// </param> /// <param name="last_seqno"> The sequence number of the last missing message /// </param> /// <param name="sender">The destination of the member to which the retransmit request will be sent /// (nak-based scheme), or to which the message will be retransmitted (ack-based scheme). /// </param> void retransmit(long first_seqno, long last_seqno, Address sender); } /// <summary> Create a new Retransmitter associated with the given sender address</summary> /// <param name="sender">the address from which retransmissions are expected or to which retransmissions are sent /// </param> /// <param name="cmd">the retransmission callback reference /// </param> /// <param name="sched">retransmissions scheduler /// </param> public Retransmitter(Address sender, Retransmitter.RetransmitCommand cmd, TimeScheduler sched) { init(sender, cmd, sched, false); } /// <summary> Create a new Retransmitter associated with the given sender address</summary> /// <param name="sender">the address from which retransmissions are expected or to which retransmissions are sent /// </param> /// <param name="cmd">the retransmission callback reference /// </param> public Retransmitter(Address sender, Retransmitter.RetransmitCommand cmd) { init(sender, cmd, new TimeScheduler(30 * 1000), true); } /// <summary> Add the given range [first_seqno, last_seqno] in the list of /// entries eligible for retransmission. If first_seqno > last_seqno, /// then the range [last_seqno, first_seqno] is added instead /// <p> /// If retransmitter thread is suspended, wake it up /// TODO: /// Does not check for duplicates ! /// </summary> public virtual void add(long first_seqno, long last_seqno) { Entry e; if (first_seqno > last_seqno) { long tmp = first_seqno; first_seqno = last_seqno; last_seqno = tmp; } lock (msgs.SyncRoot) { e = new Entry(this, first_seqno, last_seqno, RETRANSMIT_TIMEOUTS); msgs.Add(e); retransmitter.AddTask(e); } } /// <summary> Remove the given sequence number from the list of seqnos eligible /// for retransmission. If there are no more seqno intervals in the /// respective entry, cancel the entry from the retransmission /// scheduler and remove it from the pending entries /// </summary> public virtual void remove(long seqno) { lock (msgs.SyncRoot) { for (int index = 0; index < msgs.Count; index++) { Entry e = (Entry) msgs[index]; lock (e) { if (seqno < e.low || seqno > e.high) continue; e.remove(seqno); if (e.low > e.high) { e.cancel(); msgs.RemoveAt(index); } } break; } } } /// <summary> Reset the retransmitter: clear all msgs and cancel all the /// respective tasks /// </summary> public virtual void reset() { lock (msgs.SyncRoot) { for (int index = 0; index < msgs.Count; index++) { Entry entry = (Entry) msgs[index]; entry.cancel(); } msgs.Clear(); } } /// <summary> Stop the rentransmition and clear all pending msgs. /// <p> /// If this retransmitter has been provided an externally managed /// scheduler, then just clear all msgs and the associated tasks, else /// stop the scheduler. In this case the method blocks until the /// scheduler's thread is dead. Only the owner of the scheduler should /// stop it. /// </summary> public virtual void stop() { // i. If retransmitter is owned, stop it else cancel all tasks // ii. Clear all pending msgs lock (msgs.SyncRoot) { if (retransmitter_owned) { try { retransmitter.Dispose(); } catch (System.Threading.ThreadInterruptedException ex) { } } else { for (int index = 0; index < msgs.Count; index++) { Entry e = (Entry) msgs[index]; e.cancel(); } } msgs.Clear(); } } public override string ToString() { return (msgs.Count + " messages to retransmit: (" + Global.CollectionToString(msgs) + ')'); } /* ------------------------------- Private Methods -------------------------------------- */ /// <summary> Init this object /// /// </summary> /// <param name="sender">the address from which retransmissions are expected /// </param> /// <param name="cmd">the retransmission callback reference /// </param> /// <param name="sched">retransmissions scheduler /// </param> /// <param name="sched_owned">whether the scheduler parameter is owned by this /// object or is externally provided /// </param> private void init(Address sender, Retransmitter.RetransmitCommand cmd, TimeScheduler sched, bool sched_owned) { this.sender = sender; this.cmd = cmd; retransmitter_owned = sched_owned; retransmitter = sched; } /* ---------------------------- End of Private Methods ------------------------------------ */ /// <summary> The retransmit task executed by the scheduler in regular intervals</summary> private abstract class Task : TimeScheduler.Task { private Interval intervals; private bool isCancelled; protected internal Task(long[] intervals) { this.intervals = new Interval(intervals); this.isCancelled = false; } public override long GetNextInterval() { return (intervals.next()); } public override bool IsCancelled() { return (isCancelled); } public virtual void cancel() { isCancelled = true; } public override void Run() { } } /// <summary> The entry associated with an initial group of missing messages /// with contiguous sequence numbers and with all its subgroups.<br> /// E.g. /// - initial group: [5-34] /// - msg 12 is acknowledged, now the groups are: [5-11], [13-34] /// <p> /// Groups are stored in a list as long[2] arrays of the each group's /// bounds. For speed and convenience, the lowest & highest bounds of /// all the groups in this entry are also stored separately /// </summary> private class Entry:Task { private Retransmitter enclosingInstance; public System.Collections.ArrayList list; public long low; public long high; public Entry(Retransmitter enclosingInstance, long low, long high, long[] intervals):base(intervals) { this.enclosingInstance = enclosingInstance; this.low = low; this.high = high; list = new System.Collections.ArrayList(); list.Add(low); list.Add(high); } /// <summary> Remove the given seqno and resize or partition groups as /// necessary. The algorithm is as follows:<br> /// i. Find the group with low <= seqno <= high /// ii. If seqno == low, /// a. if low == high, then remove the group /// Adjust global low. If global low was pointing to the group /// deleted in the previous step, set it to point to the next group. /// If there is no next group, set global low to be higher than /// global high. This way the entry is invalidated and will be removed /// all together from the pending msgs and the task scheduler /// iii. If seqno == high, adjust high, adjust global high if this is /// the group at the tail of the list /// iv. Else low < seqno < high, break [low,high] into [low,seqno-1] /// and [seqno+1,high] /// /// </summary> /// <param name="seqno">the sequence number to remove /// </param> public virtual void remove(long seqno) { int i; long loBound = -1; long hiBound = -1; lock (this) { for (i = 0; i < list.Count; i+=2) { loBound = (long) list[i]; hiBound = (long) list[i+1]; if (seqno < loBound || seqno > hiBound) continue; break; } if (i == list.Count) return ; if (seqno == loBound) { if (loBound == hiBound) { list.RemoveAt(i); list.RemoveAt(i); } else list[i] = ++loBound; if (i == 0) low = list.Count == 0 ? high + 1:loBound; } else if (seqno == hiBound) { list[i+1] = --hiBound; if (i == list.Count - 1) high = hiBound; } else { list[i+1] = seqno - 1; list.Insert(i + 2, hiBound); list.Insert(i + 2, seqno + 1); } } } /// <summary> Retransmission task:<br> /// For each interval, call the retransmission callback command /// </summary> public override void Run() { ArrayList cloned; lock (this) { cloned = (ArrayList) list.Clone(); } for (int i = 0; i < cloned.Count; i+=2) { long loBound = (long) cloned[i]; long hiBound = (long) cloned[i+1]; enclosingInstance.cmd.retransmit(loBound, hiBound, enclosingInstance.sender); } } public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); if (low == high) sb.Append(low); else sb.Append(low).Append(':').Append(high); return sb.ToString(); } } // end class Entry internal static void sleep(long timeout) { Util.Util.sleep(timeout); } } }
// /* // * Copyright (c) 2016, Alachisoft. 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. // */ #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Alachisoft.NosDB.Common.Protobuf { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Response { #region EXTENSION registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NosDB_Common_Protobuf_Response__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.Response, global::Alachisoft.NosDB.Common.Protobuf.Response.Builder> internal__static_Alachisoft_NosDB_Common_Protobuf_Response__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static Response() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cg5SZXNwb25zZS5wcm90bxIgQWxhY2hpc29mdC5Ob3NEQi5Db21tb24uUHJv", "dG9idWYaHUluc2VydERvY3VtZW50c1Jlc3BvbnNlLnByb3RvGh1EZWxldGVE", "b2N1bWVudHNSZXNwb25zZS5wcm90bxoaR2V0RG9jdW1lbnRzUmVzcG9uc2Uu", "cHJvdG8aFFVwZGF0ZVJlc3BvbnNlLnByb3RvGhhXcml0ZVF1ZXJ5UmVzcG9u", "c2UucHJvdG8aF1JlYWRRdWVyeVJlc3BvbnNlLnByb3RvGhtDcmVhdGVTZXNz", "aW9uUmVzcG9uc2UucHJvdG8aFkdldENodW5rUmVzcG9uc2UucHJvdG8aHlJl", "cGxhY2VEb2N1bWVudHNSZXNwb25zZS5wcm90bxocQXV0aGVudGljYXRpb25S", "ZXNwb25zZS5wcm90bxoaSW5pdERhdGFiYXNlUmVzcG9uc2UucHJvdG8ikgsK", "CFJlc3BvbnNlEj0KBHR5cGUYASABKA4yLy5BbGFjaGlzb2Z0Lk5vc0RCLkNv", "bW1vbi5Qcm90b2J1Zi5SZXNwb25zZS5UeXBlEhEKCXJlcXVlc3RJZBgCIAEo", "AxIUCgxpc1N1Y2Nlc3NmdWwYAyABKAgSEQoJZXJyb3JDb2RlGAQgASgFEhMK", "C2Vycm9yUGFyYW1zGAUgAygJEloKF2luc2VydERvY3VtZW50c1Jlc3BvbnNl", "GAYgASgLMjkuQWxhY2hpc29mdC5Ob3NEQi5Db21tb24uUHJvdG9idWYuSW5z", "ZXJ0RG9jdW1lbnRzUmVzcG9uc2USWgoXZGVsZXRlRG9jdW1lbnRzUmVzcG9u", "c2UYByABKAsyOS5BbGFjaGlzb2Z0Lk5vc0RCLkNvbW1vbi5Qcm90b2J1Zi5E", "ZWxldGVEb2N1bWVudHNSZXNwb25zZRJUChRnZXREb2N1bWVudHNSZXNwb25z", "ZRgIIAEoCzI2LkFsYWNoaXNvZnQuTm9zREIuQ29tbW9uLlByb3RvYnVmLkdl", "dERvY3VtZW50c1Jlc3BvbnNlEkgKDnVwZGF0ZVJlc3BvbnNlGAkgASgLMjAu", "QWxhY2hpc29mdC5Ob3NEQi5Db21tb24uUHJvdG9idWYuVXBkYXRlUmVzcG9u", "c2USUAoSd3JpdGVRdWVyeVJlc3BvbnNlGAogASgLMjQuQWxhY2hpc29mdC5O", "b3NEQi5Db21tb24uUHJvdG9idWYuV3JpdGVRdWVyeVJlc3BvbnNlEk4KEXJl", "YWRRdWVyeVJlc3BvbnNlGAsgASgLMjMuQWxhY2hpc29mdC5Ob3NEQi5Db21t", "b24uUHJvdG9idWYuUmVhZFF1ZXJ5UmVzcG9uc2USVgoVQ3JlYXRlU2Vzc2lv", "blJlc3BvbnNlGAwgASgLMjcuQWxhY2hpc29mdC5Ob3NEQi5Db21tb24uUHJv", "dG9idWYuQ3JlYXRlU2Vzc2lvblJlc3BvbnNlEkwKEGdldENodW5rUmVzcG9u", "c2UYDSABKAsyMi5BbGFjaGlzb2Z0Lk5vc0RCLkNvbW1vbi5Qcm90b2J1Zi5H", "ZXRDaHVua1Jlc3BvbnNlElwKGHJlcGxhY2VEb2N1bWVudHNSZXNwb25zZRgO", "IAEoCzI6LkFsYWNoaXNvZnQuTm9zREIuQ29tbW9uLlByb3RvYnVmLlJlcGxh", "Y2VEb2N1bWVudHNSZXNwb25zZRJYChZhdXRoZW50aWNhdGlvblJlc3BvbnNl", "GA8gASgLMjguQWxhY2hpc29mdC5Ob3NEQi5Db21tb24uUHJvdG9idWYuQXV0", "aGVudGljYXRpb25SZXNwb25zZRJUChRpbml0RGF0YWJhc2VSZXNwb25zZRgQ", "IAEoCzI2LkFsYWNoaXNvZnQuTm9zREIuQ29tbW9uLlByb3RvYnVmLkluaXRE", "YXRhYmFzZVJlc3BvbnNlIscCCgRUeXBlEhQKEElOU0VSVF9ET0NVTUVOVFMQ", "ARIUChBERUxFVEVfRE9DVU1FTlRTEAISEQoNR0VUX0RPQ1VNRU5UUxADEgoK", "BlVQREFURRAEEg8KC1dSSVRFX1FVRVJZEAUSDgoKUkVBRF9RVUVSWRAGEhUK", "EUNSRUFURV9DT0xMRUNUSU9OEAcSEwoPRFJPUF9DT0xMRUNUSU9OEAgSEgoO", "Q1JFQVRFX1NFU1NJT04QCRIQCgxEUk9QX1NFU1NJT04QChIQCgxDUkVBVEVf", "SU5ERVgQCxIOCgpEUk9QX0lOREVYEAwSDQoJR0VUX0NIVU5LEA0SEgoORElT", "UE9TRV9SRUFERVIQDhIVChFSRVBMQUNFX0RPQ1VNRU5UUxAPEhIKDkFVVEhF", "TlRJQ0FUSU9OEBASEQoNSU5JVF9EQVRBQkFTRRARQjgKJGNvbS5hbGFjaGlz", "b2Z0Lm5vc2RiLmNvbW1vbi5wcm90b2J1ZkIQUmVzcG9uc2VQcm90b2NvbA==")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NosDB_Common_Protobuf_Response__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NosDB_Common_Protobuf_Response__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NosDB.Common.Protobuf.Response, global::Alachisoft.NosDB.Common.Protobuf.Response.Builder>(internal__static_Alachisoft_NosDB_Common_Protobuf_Response__Descriptor, new string[] { "Type", "RequestId", "IsSuccessful", "ErrorCode", "ErrorParams", "InsertDocumentsResponse", "DeleteDocumentsResponse", "GetDocumentsResponse", "UpdateResponse", "WriteQueryResponse", "ReadQueryResponse", "CreateSessionResponse", "GetChunkResponse", "ReplaceDocumentsResponse", "AuthenticationResponse", "InitDatabaseResponse", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { global::Alachisoft.NosDB.Common.Protobuf.Proto.InsertDocumentsResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.DeleteDocumentsResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.GetDocumentsResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.UpdateResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.WriteQueryResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.ReadQueryResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.CreateSessionResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.GetChunkResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.ReplaceDocumentsResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.AuthenticationResponse.Descriptor, global::Alachisoft.NosDB.Common.Protobuf.Proto.InitDatabaseResponse.Descriptor, }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Response : pb::GeneratedMessage<Response, Response.Builder> { private Response() { } private static readonly Response defaultInstance = new Response().MakeReadOnly(); private static readonly string[] _responseFieldNames = new string[] { "CreateSessionResponse", "authenticationResponse", "deleteDocumentsResponse", "errorCode", "errorParams", "getChunkResponse", "getDocumentsResponse", "initDatabaseResponse", "insertDocumentsResponse", "isSuccessful", "readQueryResponse", "replaceDocumentsResponse", "requestId", "type", "updateResponse", "writeQueryResponse" }; private static readonly uint[] _responseFieldTags = new uint[] { 98, 122, 58, 32, 42, 106, 66, 130, 50, 24, 90, 114, 16, 8, 74, 82 }; public static Response DefaultInstance { get { return defaultInstance; } } public override Response DefaultInstanceForType { get { return DefaultInstance; } } protected override Response ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.Response.internal__static_Alachisoft_NosDB_Common_Protobuf_Response__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<Response, Response.Builder> InternalFieldAccessors { get { return global::Alachisoft.NosDB.Common.Protobuf.Proto.Response.internal__static_Alachisoft_NosDB_Common_Protobuf_Response__FieldAccessorTable; } } #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum Type { INSERT_DOCUMENTS = 1, DELETE_DOCUMENTS = 2, GET_DOCUMENTS = 3, UPDATE = 4, WRITE_QUERY = 5, READ_QUERY = 6, CREATE_COLLECTION = 7, DROP_COLLECTION = 8, CREATE_SESSION = 9, DROP_SESSION = 10, CREATE_INDEX = 11, DROP_INDEX = 12, GET_CHUNK = 13, DISPOSE_READER = 14, REPLACE_DOCUMENTS = 15, AUTHENTICATION = 16, INIT_DATABASE = 17, } } #endregion public const int TypeFieldNumber = 1; private bool hasType; private global::Alachisoft.NosDB.Common.Protobuf.Response.Types.Type type_ = global::Alachisoft.NosDB.Common.Protobuf.Response.Types.Type.INSERT_DOCUMENTS; public bool HasType { get { return hasType; } } public global::Alachisoft.NosDB.Common.Protobuf.Response.Types.Type Type { get { return type_; } } public const int RequestIdFieldNumber = 2; private bool hasRequestId; private long requestId_; public bool HasRequestId { get { return hasRequestId; } } public long RequestId { get { return requestId_; } } public const int IsSuccessfulFieldNumber = 3; private bool hasIsSuccessful; private bool isSuccessful_; public bool HasIsSuccessful { get { return hasIsSuccessful; } } public bool IsSuccessful { get { return isSuccessful_; } } public const int ErrorCodeFieldNumber = 4; private bool hasErrorCode; private int errorCode_; public bool HasErrorCode { get { return hasErrorCode; } } public int ErrorCode { get { return errorCode_; } } public const int ErrorParamsFieldNumber = 5; private pbc::PopsicleList<string> errorParams_ = new pbc::PopsicleList<string>(); public scg::IList<string> ErrorParamsList { get { return pbc::Lists.AsReadOnly(errorParams_); } } public int ErrorParamsCount { get { return errorParams_.Count; } } public string GetErrorParams(int index) { return errorParams_[index]; } public const int InsertDocumentsResponseFieldNumber = 6; private bool hasInsertDocumentsResponse; private global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse insertDocumentsResponse_; public bool HasInsertDocumentsResponse { get { return hasInsertDocumentsResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse InsertDocumentsResponse { get { return insertDocumentsResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse.DefaultInstance; } } public const int DeleteDocumentsResponseFieldNumber = 7; private bool hasDeleteDocumentsResponse; private global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse deleteDocumentsResponse_; public bool HasDeleteDocumentsResponse { get { return hasDeleteDocumentsResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse DeleteDocumentsResponse { get { return deleteDocumentsResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse.DefaultInstance; } } public const int GetDocumentsResponseFieldNumber = 8; private bool hasGetDocumentsResponse; private global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse getDocumentsResponse_; public bool HasGetDocumentsResponse { get { return hasGetDocumentsResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse GetDocumentsResponse { get { return getDocumentsResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse.DefaultInstance; } } public const int UpdateResponseFieldNumber = 9; private bool hasUpdateResponse; private global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse updateResponse_; public bool HasUpdateResponse { get { return hasUpdateResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse UpdateResponse { get { return updateResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse.DefaultInstance; } } public const int WriteQueryResponseFieldNumber = 10; private bool hasWriteQueryResponse; private global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse writeQueryResponse_; public bool HasWriteQueryResponse { get { return hasWriteQueryResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse WriteQueryResponse { get { return writeQueryResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.DefaultInstance; } } public const int ReadQueryResponseFieldNumber = 11; private bool hasReadQueryResponse; private global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse readQueryResponse_; public bool HasReadQueryResponse { get { return hasReadQueryResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse ReadQueryResponse { get { return readQueryResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.DefaultInstance; } } public const int CreateSessionResponseFieldNumber = 12; private bool hasCreateSessionResponse; private global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse createSessionResponse_; public bool HasCreateSessionResponse { get { return hasCreateSessionResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse CreateSessionResponse { get { return createSessionResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse.DefaultInstance; } } public const int GetChunkResponseFieldNumber = 13; private bool hasGetChunkResponse; private global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse getChunkResponse_; public bool HasGetChunkResponse { get { return hasGetChunkResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse GetChunkResponse { get { return getChunkResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.DefaultInstance; } } public const int ReplaceDocumentsResponseFieldNumber = 14; private bool hasReplaceDocumentsResponse; private global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse replaceDocumentsResponse_; public bool HasReplaceDocumentsResponse { get { return hasReplaceDocumentsResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse ReplaceDocumentsResponse { get { return replaceDocumentsResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse.DefaultInstance; } } public const int AuthenticationResponseFieldNumber = 15; private bool hasAuthenticationResponse; private global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse authenticationResponse_; public bool HasAuthenticationResponse { get { return hasAuthenticationResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse AuthenticationResponse { get { return authenticationResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.DefaultInstance; } } public const int InitDatabaseResponseFieldNumber = 16; private bool hasInitDatabaseResponse; private global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse initDatabaseResponse_; public bool HasInitDatabaseResponse { get { return hasInitDatabaseResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse InitDatabaseResponse { get { return initDatabaseResponse_ ?? global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse.DefaultInstance; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _responseFieldNames; if (hasType) { output.WriteEnum(1, field_names[13], (int) Type, Type); } if (hasRequestId) { output.WriteInt64(2, field_names[12], RequestId); } if (hasIsSuccessful) { output.WriteBool(3, field_names[9], IsSuccessful); } if (hasErrorCode) { output.WriteInt32(4, field_names[3], ErrorCode); } if (errorParams_.Count > 0) { output.WriteStringArray(5, field_names[4], errorParams_); } if (hasInsertDocumentsResponse) { output.WriteMessage(6, field_names[8], InsertDocumentsResponse); } if (hasDeleteDocumentsResponse) { output.WriteMessage(7, field_names[2], DeleteDocumentsResponse); } if (hasGetDocumentsResponse) { output.WriteMessage(8, field_names[6], GetDocumentsResponse); } if (hasUpdateResponse) { output.WriteMessage(9, field_names[14], UpdateResponse); } if (hasWriteQueryResponse) { output.WriteMessage(10, field_names[15], WriteQueryResponse); } if (hasReadQueryResponse) { output.WriteMessage(11, field_names[10], ReadQueryResponse); } if (hasCreateSessionResponse) { output.WriteMessage(12, field_names[0], CreateSessionResponse); } if (hasGetChunkResponse) { output.WriteMessage(13, field_names[5], GetChunkResponse); } if (hasReplaceDocumentsResponse) { output.WriteMessage(14, field_names[11], ReplaceDocumentsResponse); } if (hasAuthenticationResponse) { output.WriteMessage(15, field_names[1], AuthenticationResponse); } if (hasInitDatabaseResponse) { output.WriteMessage(16, field_names[7], InitDatabaseResponse); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasType) { size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Type); } if (hasRequestId) { size += pb::CodedOutputStream.ComputeInt64Size(2, RequestId); } if (hasIsSuccessful) { size += pb::CodedOutputStream.ComputeBoolSize(3, IsSuccessful); } if (hasErrorCode) { size += pb::CodedOutputStream.ComputeInt32Size(4, ErrorCode); } { int dataSize = 0; foreach (string element in ErrorParamsList) { dataSize += pb::CodedOutputStream.ComputeStringSizeNoTag(element); } size += dataSize; size += 1 * errorParams_.Count; } if (hasInsertDocumentsResponse) { size += pb::CodedOutputStream.ComputeMessageSize(6, InsertDocumentsResponse); } if (hasDeleteDocumentsResponse) { size += pb::CodedOutputStream.ComputeMessageSize(7, DeleteDocumentsResponse); } if (hasGetDocumentsResponse) { size += pb::CodedOutputStream.ComputeMessageSize(8, GetDocumentsResponse); } if (hasUpdateResponse) { size += pb::CodedOutputStream.ComputeMessageSize(9, UpdateResponse); } if (hasWriteQueryResponse) { size += pb::CodedOutputStream.ComputeMessageSize(10, WriteQueryResponse); } if (hasReadQueryResponse) { size += pb::CodedOutputStream.ComputeMessageSize(11, ReadQueryResponse); } if (hasCreateSessionResponse) { size += pb::CodedOutputStream.ComputeMessageSize(12, CreateSessionResponse); } if (hasGetChunkResponse) { size += pb::CodedOutputStream.ComputeMessageSize(13, GetChunkResponse); } if (hasReplaceDocumentsResponse) { size += pb::CodedOutputStream.ComputeMessageSize(14, ReplaceDocumentsResponse); } if (hasAuthenticationResponse) { size += pb::CodedOutputStream.ComputeMessageSize(15, AuthenticationResponse); } if (hasInitDatabaseResponse) { size += pb::CodedOutputStream.ComputeMessageSize(16, InitDatabaseResponse); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static Response ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static Response ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static Response ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static Response ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static Response ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static Response ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static Response ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static Response ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static Response ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static Response ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private Response MakeReadOnly() { errorParams_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(Response prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<Response, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(Response cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private Response result; private Response PrepareBuilder() { if (resultIsReadOnly) { Response original = result; result = new Response(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override Response MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Alachisoft.NosDB.Common.Protobuf.Response.Descriptor; } } public override Response DefaultInstanceForType { get { return global::Alachisoft.NosDB.Common.Protobuf.Response.DefaultInstance; } } public override Response BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is Response) { return MergeFrom((Response) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(Response other) { if (other == global::Alachisoft.NosDB.Common.Protobuf.Response.DefaultInstance) return this; PrepareBuilder(); if (other.HasType) { Type = other.Type; } if (other.HasRequestId) { RequestId = other.RequestId; } if (other.HasIsSuccessful) { IsSuccessful = other.IsSuccessful; } if (other.HasErrorCode) { ErrorCode = other.ErrorCode; } if (other.errorParams_.Count != 0) { result.errorParams_.Add(other.errorParams_); } if (other.HasInsertDocumentsResponse) { MergeInsertDocumentsResponse(other.InsertDocumentsResponse); } if (other.HasDeleteDocumentsResponse) { MergeDeleteDocumentsResponse(other.DeleteDocumentsResponse); } if (other.HasGetDocumentsResponse) { MergeGetDocumentsResponse(other.GetDocumentsResponse); } if (other.HasUpdateResponse) { MergeUpdateResponse(other.UpdateResponse); } if (other.HasWriteQueryResponse) { MergeWriteQueryResponse(other.WriteQueryResponse); } if (other.HasReadQueryResponse) { MergeReadQueryResponse(other.ReadQueryResponse); } if (other.HasCreateSessionResponse) { MergeCreateSessionResponse(other.CreateSessionResponse); } if (other.HasGetChunkResponse) { MergeGetChunkResponse(other.GetChunkResponse); } if (other.HasReplaceDocumentsResponse) { MergeReplaceDocumentsResponse(other.ReplaceDocumentsResponse); } if (other.HasAuthenticationResponse) { MergeAuthenticationResponse(other.AuthenticationResponse); } if (other.HasInitDatabaseResponse) { MergeInitDatabaseResponse(other.InitDatabaseResponse); } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_responseFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _responseFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 8: { object unknown; if(input.ReadEnum(ref result.type_, out unknown)) { result.hasType = true; } else if(unknown is int) { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } unknownFields.MergeVarintField(1, (ulong)(int)unknown); } break; } case 16: { result.hasRequestId = input.ReadInt64(ref result.requestId_); break; } case 24: { result.hasIsSuccessful = input.ReadBool(ref result.isSuccessful_); break; } case 32: { result.hasErrorCode = input.ReadInt32(ref result.errorCode_); break; } case 42: { input.ReadStringArray(tag, field_name, result.errorParams_); break; } case 50: { global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse.CreateBuilder(); if (result.hasInsertDocumentsResponse) { subBuilder.MergeFrom(InsertDocumentsResponse); } input.ReadMessage(subBuilder, extensionRegistry); InsertDocumentsResponse = subBuilder.BuildPartial(); break; } case 58: { global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse.CreateBuilder(); if (result.hasDeleteDocumentsResponse) { subBuilder.MergeFrom(DeleteDocumentsResponse); } input.ReadMessage(subBuilder, extensionRegistry); DeleteDocumentsResponse = subBuilder.BuildPartial(); break; } case 66: { global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse.CreateBuilder(); if (result.hasGetDocumentsResponse) { subBuilder.MergeFrom(GetDocumentsResponse); } input.ReadMessage(subBuilder, extensionRegistry); GetDocumentsResponse = subBuilder.BuildPartial(); break; } case 74: { global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse.CreateBuilder(); if (result.hasUpdateResponse) { subBuilder.MergeFrom(UpdateResponse); } input.ReadMessage(subBuilder, extensionRegistry); UpdateResponse = subBuilder.BuildPartial(); break; } case 82: { global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.CreateBuilder(); if (result.hasWriteQueryResponse) { subBuilder.MergeFrom(WriteQueryResponse); } input.ReadMessage(subBuilder, extensionRegistry); WriteQueryResponse = subBuilder.BuildPartial(); break; } case 90: { global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.CreateBuilder(); if (result.hasReadQueryResponse) { subBuilder.MergeFrom(ReadQueryResponse); } input.ReadMessage(subBuilder, extensionRegistry); ReadQueryResponse = subBuilder.BuildPartial(); break; } case 98: { global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse.CreateBuilder(); if (result.hasCreateSessionResponse) { subBuilder.MergeFrom(CreateSessionResponse); } input.ReadMessage(subBuilder, extensionRegistry); CreateSessionResponse = subBuilder.BuildPartial(); break; } case 106: { global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.CreateBuilder(); if (result.hasGetChunkResponse) { subBuilder.MergeFrom(GetChunkResponse); } input.ReadMessage(subBuilder, extensionRegistry); GetChunkResponse = subBuilder.BuildPartial(); break; } case 114: { global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse.CreateBuilder(); if (result.hasReplaceDocumentsResponse) { subBuilder.MergeFrom(ReplaceDocumentsResponse); } input.ReadMessage(subBuilder, extensionRegistry); ReplaceDocumentsResponse = subBuilder.BuildPartial(); break; } case 122: { global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.CreateBuilder(); if (result.hasAuthenticationResponse) { subBuilder.MergeFrom(AuthenticationResponse); } input.ReadMessage(subBuilder, extensionRegistry); AuthenticationResponse = subBuilder.BuildPartial(); break; } case 130: { global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse.Builder subBuilder = global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse.CreateBuilder(); if (result.hasInitDatabaseResponse) { subBuilder.MergeFrom(InitDatabaseResponse); } input.ReadMessage(subBuilder, extensionRegistry); InitDatabaseResponse = subBuilder.BuildPartial(); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasType { get { return result.hasType; } } public global::Alachisoft.NosDB.Common.Protobuf.Response.Types.Type Type { get { return result.Type; } set { SetType(value); } } public Builder SetType(global::Alachisoft.NosDB.Common.Protobuf.Response.Types.Type value) { PrepareBuilder(); result.hasType = true; result.type_ = value; return this; } public Builder ClearType() { PrepareBuilder(); result.hasType = false; result.type_ = global::Alachisoft.NosDB.Common.Protobuf.Response.Types.Type.INSERT_DOCUMENTS; return this; } public bool HasRequestId { get { return result.hasRequestId; } } public long RequestId { get { return result.RequestId; } set { SetRequestId(value); } } public Builder SetRequestId(long value) { PrepareBuilder(); result.hasRequestId = true; result.requestId_ = value; return this; } public Builder ClearRequestId() { PrepareBuilder(); result.hasRequestId = false; result.requestId_ = 0L; return this; } public bool HasIsSuccessful { get { return result.hasIsSuccessful; } } public bool IsSuccessful { get { return result.IsSuccessful; } set { SetIsSuccessful(value); } } public Builder SetIsSuccessful(bool value) { PrepareBuilder(); result.hasIsSuccessful = true; result.isSuccessful_ = value; return this; } public Builder ClearIsSuccessful() { PrepareBuilder(); result.hasIsSuccessful = false; result.isSuccessful_ = false; return this; } public bool HasErrorCode { get { return result.hasErrorCode; } } public int ErrorCode { get { return result.ErrorCode; } set { SetErrorCode(value); } } public Builder SetErrorCode(int value) { PrepareBuilder(); result.hasErrorCode = true; result.errorCode_ = value; return this; } public Builder ClearErrorCode() { PrepareBuilder(); result.hasErrorCode = false; result.errorCode_ = 0; return this; } public pbc::IPopsicleList<string> ErrorParamsList { get { return PrepareBuilder().errorParams_; } } public int ErrorParamsCount { get { return result.ErrorParamsCount; } } public string GetErrorParams(int index) { return result.GetErrorParams(index); } public Builder SetErrorParams(int index, string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.errorParams_[index] = value; return this; } public Builder AddErrorParams(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.errorParams_.Add(value); return this; } public Builder AddRangeErrorParams(scg::IEnumerable<string> values) { PrepareBuilder(); result.errorParams_.Add(values); return this; } public Builder ClearErrorParams() { PrepareBuilder(); result.errorParams_.Clear(); return this; } public bool HasInsertDocumentsResponse { get { return result.hasInsertDocumentsResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse InsertDocumentsResponse { get { return result.InsertDocumentsResponse; } set { SetInsertDocumentsResponse(value); } } public Builder SetInsertDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasInsertDocumentsResponse = true; result.insertDocumentsResponse_ = value; return this; } public Builder SetInsertDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasInsertDocumentsResponse = true; result.insertDocumentsResponse_ = builderForValue.Build(); return this; } public Builder MergeInsertDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasInsertDocumentsResponse && result.insertDocumentsResponse_ != global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse.DefaultInstance) { result.insertDocumentsResponse_ = global::Alachisoft.NosDB.Common.Protobuf.InsertDocumentsResponse.CreateBuilder(result.insertDocumentsResponse_).MergeFrom(value).BuildPartial(); } else { result.insertDocumentsResponse_ = value; } result.hasInsertDocumentsResponse = true; return this; } public Builder ClearInsertDocumentsResponse() { PrepareBuilder(); result.hasInsertDocumentsResponse = false; result.insertDocumentsResponse_ = null; return this; } public bool HasDeleteDocumentsResponse { get { return result.hasDeleteDocumentsResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse DeleteDocumentsResponse { get { return result.DeleteDocumentsResponse; } set { SetDeleteDocumentsResponse(value); } } public Builder SetDeleteDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasDeleteDocumentsResponse = true; result.deleteDocumentsResponse_ = value; return this; } public Builder SetDeleteDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasDeleteDocumentsResponse = true; result.deleteDocumentsResponse_ = builderForValue.Build(); return this; } public Builder MergeDeleteDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasDeleteDocumentsResponse && result.deleteDocumentsResponse_ != global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse.DefaultInstance) { result.deleteDocumentsResponse_ = global::Alachisoft.NosDB.Common.Protobuf.DeleteDocumentsResponse.CreateBuilder(result.deleteDocumentsResponse_).MergeFrom(value).BuildPartial(); } else { result.deleteDocumentsResponse_ = value; } result.hasDeleteDocumentsResponse = true; return this; } public Builder ClearDeleteDocumentsResponse() { PrepareBuilder(); result.hasDeleteDocumentsResponse = false; result.deleteDocumentsResponse_ = null; return this; } public bool HasGetDocumentsResponse { get { return result.hasGetDocumentsResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse GetDocumentsResponse { get { return result.GetDocumentsResponse; } set { SetGetDocumentsResponse(value); } } public Builder SetGetDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasGetDocumentsResponse = true; result.getDocumentsResponse_ = value; return this; } public Builder SetGetDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasGetDocumentsResponse = true; result.getDocumentsResponse_ = builderForValue.Build(); return this; } public Builder MergeGetDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasGetDocumentsResponse && result.getDocumentsResponse_ != global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse.DefaultInstance) { result.getDocumentsResponse_ = global::Alachisoft.NosDB.Common.Protobuf.GetDocumentsResponse.CreateBuilder(result.getDocumentsResponse_).MergeFrom(value).BuildPartial(); } else { result.getDocumentsResponse_ = value; } result.hasGetDocumentsResponse = true; return this; } public Builder ClearGetDocumentsResponse() { PrepareBuilder(); result.hasGetDocumentsResponse = false; result.getDocumentsResponse_ = null; return this; } public bool HasUpdateResponse { get { return result.hasUpdateResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse UpdateResponse { get { return result.UpdateResponse; } set { SetUpdateResponse(value); } } public Builder SetUpdateResponse(global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasUpdateResponse = true; result.updateResponse_ = value; return this; } public Builder SetUpdateResponse(global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasUpdateResponse = true; result.updateResponse_ = builderForValue.Build(); return this; } public Builder MergeUpdateResponse(global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasUpdateResponse && result.updateResponse_ != global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse.DefaultInstance) { result.updateResponse_ = global::Alachisoft.NosDB.Common.Protobuf.UpdateResponse.CreateBuilder(result.updateResponse_).MergeFrom(value).BuildPartial(); } else { result.updateResponse_ = value; } result.hasUpdateResponse = true; return this; } public Builder ClearUpdateResponse() { PrepareBuilder(); result.hasUpdateResponse = false; result.updateResponse_ = null; return this; } public bool HasWriteQueryResponse { get { return result.hasWriteQueryResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse WriteQueryResponse { get { return result.WriteQueryResponse; } set { SetWriteQueryResponse(value); } } public Builder SetWriteQueryResponse(global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasWriteQueryResponse = true; result.writeQueryResponse_ = value; return this; } public Builder SetWriteQueryResponse(global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasWriteQueryResponse = true; result.writeQueryResponse_ = builderForValue.Build(); return this; } public Builder MergeWriteQueryResponse(global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasWriteQueryResponse && result.writeQueryResponse_ != global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.DefaultInstance) { result.writeQueryResponse_ = global::Alachisoft.NosDB.Common.Protobuf.WriteQueryResponse.CreateBuilder(result.writeQueryResponse_).MergeFrom(value).BuildPartial(); } else { result.writeQueryResponse_ = value; } result.hasWriteQueryResponse = true; return this; } public Builder ClearWriteQueryResponse() { PrepareBuilder(); result.hasWriteQueryResponse = false; result.writeQueryResponse_ = null; return this; } public bool HasReadQueryResponse { get { return result.hasReadQueryResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse ReadQueryResponse { get { return result.ReadQueryResponse; } set { SetReadQueryResponse(value); } } public Builder SetReadQueryResponse(global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasReadQueryResponse = true; result.readQueryResponse_ = value; return this; } public Builder SetReadQueryResponse(global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasReadQueryResponse = true; result.readQueryResponse_ = builderForValue.Build(); return this; } public Builder MergeReadQueryResponse(global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasReadQueryResponse && result.readQueryResponse_ != global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.DefaultInstance) { result.readQueryResponse_ = global::Alachisoft.NosDB.Common.Protobuf.ReadQueryResponse.CreateBuilder(result.readQueryResponse_).MergeFrom(value).BuildPartial(); } else { result.readQueryResponse_ = value; } result.hasReadQueryResponse = true; return this; } public Builder ClearReadQueryResponse() { PrepareBuilder(); result.hasReadQueryResponse = false; result.readQueryResponse_ = null; return this; } public bool HasCreateSessionResponse { get { return result.hasCreateSessionResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse CreateSessionResponse { get { return result.CreateSessionResponse; } set { SetCreateSessionResponse(value); } } public Builder SetCreateSessionResponse(global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasCreateSessionResponse = true; result.createSessionResponse_ = value; return this; } public Builder SetCreateSessionResponse(global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasCreateSessionResponse = true; result.createSessionResponse_ = builderForValue.Build(); return this; } public Builder MergeCreateSessionResponse(global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasCreateSessionResponse && result.createSessionResponse_ != global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse.DefaultInstance) { result.createSessionResponse_ = global::Alachisoft.NosDB.Common.Protobuf.CreateSessionResponse.CreateBuilder(result.createSessionResponse_).MergeFrom(value).BuildPartial(); } else { result.createSessionResponse_ = value; } result.hasCreateSessionResponse = true; return this; } public Builder ClearCreateSessionResponse() { PrepareBuilder(); result.hasCreateSessionResponse = false; result.createSessionResponse_ = null; return this; } public bool HasGetChunkResponse { get { return result.hasGetChunkResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse GetChunkResponse { get { return result.GetChunkResponse; } set { SetGetChunkResponse(value); } } public Builder SetGetChunkResponse(global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasGetChunkResponse = true; result.getChunkResponse_ = value; return this; } public Builder SetGetChunkResponse(global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasGetChunkResponse = true; result.getChunkResponse_ = builderForValue.Build(); return this; } public Builder MergeGetChunkResponse(global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasGetChunkResponse && result.getChunkResponse_ != global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.DefaultInstance) { result.getChunkResponse_ = global::Alachisoft.NosDB.Common.Protobuf.GetChunkResponse.CreateBuilder(result.getChunkResponse_).MergeFrom(value).BuildPartial(); } else { result.getChunkResponse_ = value; } result.hasGetChunkResponse = true; return this; } public Builder ClearGetChunkResponse() { PrepareBuilder(); result.hasGetChunkResponse = false; result.getChunkResponse_ = null; return this; } public bool HasReplaceDocumentsResponse { get { return result.hasReplaceDocumentsResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse ReplaceDocumentsResponse { get { return result.ReplaceDocumentsResponse; } set { SetReplaceDocumentsResponse(value); } } public Builder SetReplaceDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasReplaceDocumentsResponse = true; result.replaceDocumentsResponse_ = value; return this; } public Builder SetReplaceDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasReplaceDocumentsResponse = true; result.replaceDocumentsResponse_ = builderForValue.Build(); return this; } public Builder MergeReplaceDocumentsResponse(global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasReplaceDocumentsResponse && result.replaceDocumentsResponse_ != global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse.DefaultInstance) { result.replaceDocumentsResponse_ = global::Alachisoft.NosDB.Common.Protobuf.ReplaceDocumentsResponse.CreateBuilder(result.replaceDocumentsResponse_).MergeFrom(value).BuildPartial(); } else { result.replaceDocumentsResponse_ = value; } result.hasReplaceDocumentsResponse = true; return this; } public Builder ClearReplaceDocumentsResponse() { PrepareBuilder(); result.hasReplaceDocumentsResponse = false; result.replaceDocumentsResponse_ = null; return this; } public bool HasAuthenticationResponse { get { return result.hasAuthenticationResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse AuthenticationResponse { get { return result.AuthenticationResponse; } set { SetAuthenticationResponse(value); } } public Builder SetAuthenticationResponse(global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasAuthenticationResponse = true; result.authenticationResponse_ = value; return this; } public Builder SetAuthenticationResponse(global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasAuthenticationResponse = true; result.authenticationResponse_ = builderForValue.Build(); return this; } public Builder MergeAuthenticationResponse(global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasAuthenticationResponse && result.authenticationResponse_ != global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.DefaultInstance) { result.authenticationResponse_ = global::Alachisoft.NosDB.Common.Protobuf.AuthenticationResponse.CreateBuilder(result.authenticationResponse_).MergeFrom(value).BuildPartial(); } else { result.authenticationResponse_ = value; } result.hasAuthenticationResponse = true; return this; } public Builder ClearAuthenticationResponse() { PrepareBuilder(); result.hasAuthenticationResponse = false; result.authenticationResponse_ = null; return this; } public bool HasInitDatabaseResponse { get { return result.hasInitDatabaseResponse; } } public global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse InitDatabaseResponse { get { return result.InitDatabaseResponse; } set { SetInitDatabaseResponse(value); } } public Builder SetInitDatabaseResponse(global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasInitDatabaseResponse = true; result.initDatabaseResponse_ = value; return this; } public Builder SetInitDatabaseResponse(global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.hasInitDatabaseResponse = true; result.initDatabaseResponse_ = builderForValue.Build(); return this; } public Builder MergeInitDatabaseResponse(global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); if (result.hasInitDatabaseResponse && result.initDatabaseResponse_ != global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse.DefaultInstance) { result.initDatabaseResponse_ = global::Alachisoft.NosDB.Common.Protobuf.InitDatabaseResponse.CreateBuilder(result.initDatabaseResponse_).MergeFrom(value).BuildPartial(); } else { result.initDatabaseResponse_ = value; } result.hasInitDatabaseResponse = true; return this; } public Builder ClearInitDatabaseResponse() { PrepareBuilder(); result.hasInitDatabaseResponse = false; result.initDatabaseResponse_ = null; return this; } } static Response() { object.ReferenceEquals(global::Alachisoft.NosDB.Common.Protobuf.Proto.Response.Descriptor, null); } } #endregion } #endregion Designer generated code
using System; using System.Collections; using System.Diagnostics; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.IO; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; using Org.BouncyCastle.Security.Certificates; using Org.BouncyCastle.Utilities; using Org.BouncyCastle.Utilities.Collections; using Org.BouncyCastle.Utilities.IO; using Org.BouncyCastle.X509; namespace Org.BouncyCastle.Cms { /** * General class for generating a pkcs7-signature message stream. * <p> * A simple example of usage. * </p> * <pre> * IX509Store certs... * CmsSignedDataStreamGenerator gen = new CmsSignedDataStreamGenerator(); * * gen.AddSigner(privateKey, cert, CmsSignedDataStreamGenerator.DIGEST_SHA1); * * gen.AddCertificates(certs); * * Stream sigOut = gen.Open(bOut); * * sigOut.Write(Encoding.UTF8.GetBytes("Hello World!")); * * sigOut.Close(); * </pre> */ public class CmsSignedDataStreamGenerator : CmsSignedGenerator { private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance; private readonly IList _signerInfs = Platform.CreateArrayList(); private readonly ISet _messageDigestOids = new HashSet(); private readonly IDictionary _messageDigests = Platform.CreateHashtable(); private readonly IDictionary _messageHashes = Platform.CreateHashtable(); private bool _messageDigestsLocked; private int _bufferSize; private class DigestAndSignerInfoGeneratorHolder { internal readonly SignerInfoGenerator signerInf; internal readonly string digestOID; internal DigestAndSignerInfoGeneratorHolder(SignerInfoGenerator signerInf, String digestOID) { this.signerInf = signerInf; this.digestOID = digestOID; } internal AlgorithmIdentifier DigestAlgorithm { get { return new AlgorithmIdentifier(new DerObjectIdentifier(this.digestOID), DerNull.Instance); } } } private class SignerInfoGeneratorImpl : SignerInfoGenerator { private readonly CmsSignedDataStreamGenerator outer; private readonly SignerIdentifier _signerIdentifier; private readonly string _digestOID; private readonly string _encOID; private readonly CmsAttributeTableGenerator _sAttr; private readonly CmsAttributeTableGenerator _unsAttr; private readonly string _encName; private readonly ISigner _sig; internal SignerInfoGeneratorImpl( CmsSignedDataStreamGenerator outer, IAsymmetricKeyParameter key, SignerIdentifier signerIdentifier, string digestOID, string encOID, CmsAttributeTableGenerator sAttr, CmsAttributeTableGenerator unsAttr) { this.outer = outer; _signerIdentifier = signerIdentifier; _digestOID = digestOID; _encOID = encOID; _sAttr = sAttr; _unsAttr = unsAttr; _encName = Helper.GetEncryptionAlgName(_encOID); string digestName = Helper.GetDigestAlgName(_digestOID); string signatureName = digestName + "with" + _encName; if (_sAttr != null) { _sig = Helper.GetSignatureInstance(signatureName); } else { // Note: Need to use raw signatures here since we have already calculated the digest if (_encName.Equals("RSA")) { _sig = Helper.GetSignatureInstance("RSA"); } else if (_encName.Equals("DSA")) { _sig = Helper.GetSignatureInstance("NONEwithDSA"); } // TODO Add support for raw PSS // else if (_encName.equals("RSAandMGF1")) // { // _sig = CMSSignedHelper.INSTANCE.getSignatureInstance("NONEWITHRSAPSS", _sigProvider); // try // { // // Init the params this way to avoid having a 'raw' version of each PSS algorithm // Signature sig2 = CMSSignedHelper.INSTANCE.getSignatureInstance(signatureName, _sigProvider); // PSSParameterSpec spec = (PSSParameterSpec)sig2.getParameters().getParameterSpec(PSSParameterSpec.class); // _sig.setParameter(spec); // } // catch (Exception e) // { // throw new SignatureException("algorithm: " + _encName + " could not be configured."); // } // } else { throw new SignatureException("algorithm: " + _encName + " not supported in base signatures."); } } _sig.Init(true, new ParametersWithRandom(key, outer.rand)); } public SignerInfo Generate(DerObjectIdentifier contentType, AlgorithmIdentifier digestAlgorithm, byte[] calculatedDigest) { try { string digestName = Helper.GetDigestAlgName(_digestOID); string signatureName = digestName + "with" + _encName; // AlgorithmIdentifier digAlgId = DigestAlgorithmID; // // byte[] hash = (byte[])outer._messageHashes[Helper.GetDigestAlgName(this._digestOID)]; // outer._digests[_digestOID] = hash.Clone(); byte[] bytesToSign = calculatedDigest; /* RFC 3852 5.4 * The result of the message digest calculation process depends on * whether the signedAttrs field is present. When the field is absent, * the result is just the message digest of the content as described * * above. When the field is present, however, the result is the message * digest of the complete DER encoding of the SignedAttrs value * contained in the signedAttrs field. */ Asn1Set signedAttr = null; if (_sAttr != null) { IDictionary parameters = outer.GetBaseParameters(contentType, digestAlgorithm, calculatedDigest); // Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable signed = _sAttr.GetAttributes(parameters); if (contentType == null) //counter signature { if (signed != null && signed[CmsAttributes.ContentType] != null) { IDictionary tmpSigned = signed.ToDictionary(); tmpSigned.Remove(CmsAttributes.ContentType); signed = new Asn1.Cms.AttributeTable(tmpSigned); } } signedAttr = outer.GetAttributeSet(signed); // sig must be composed from the DER encoding. bytesToSign = signedAttr.GetEncoded(Asn1Encodable.Der); } else { // Note: Need to use raw signatures here since we have already calculated the digest if (_encName.Equals("RSA")) { DigestInfo dInfo = new DigestInfo(digestAlgorithm, calculatedDigest); bytesToSign = dInfo.GetEncoded(Asn1Encodable.Der); } } _sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length); byte[] sigBytes = _sig.GenerateSignature(); Asn1Set unsignedAttr = null; if (_unsAttr != null) { IDictionary parameters = outer.GetBaseParameters( contentType, digestAlgorithm, calculatedDigest); parameters[CmsAttributeTableParameter.Signature] = sigBytes.Clone(); // Asn1.Cms.AttributeTable unsigned = _unsAttr.getAttributes(Collections.unmodifiableMap(parameters)); Asn1.Cms.AttributeTable unsigned = _unsAttr.GetAttributes(parameters); unsignedAttr = outer.GetAttributeSet(unsigned); } // TODO[RSAPSS] Need the ability to specify non-default parameters Asn1Encodable sigX509Parameters = SignerUtilities.GetDefaultX509Parameters(signatureName); AlgorithmIdentifier digestEncryptionAlgorithm = CmsSignedGenerator.GetEncAlgorithmIdentifier( new DerObjectIdentifier(_encOID), sigX509Parameters); return new SignerInfo(_signerIdentifier, digestAlgorithm, signedAttr, digestEncryptionAlgorithm, new DerOctetString(sigBytes), unsignedAttr); } catch (IOException e) { throw new CmsStreamException("encoding error.", e); } catch (SignatureException e) { throw new CmsStreamException("error creating signature.", e); } } } public CmsSignedDataStreamGenerator() { } /// <summary>Constructor allowing specific source of randomness</summary> /// <param name="rand">Instance of <c>SecureRandom</c> to use.</param> public CmsSignedDataStreamGenerator( SecureRandom rand) : base(rand) { } /** * Set the underlying string size for encapsulated data * * @param bufferSize length of octet strings to buffer the data. */ public void SetBufferSize( int bufferSize) { _bufferSize = bufferSize; } public void AddDigests( params string[] digestOids) { AddDigests((IEnumerable)digestOids); } public void AddDigests( IEnumerable digestOids) { foreach (string digestOid in digestOids) { ConfigureDigest(digestOid); } } /** * add a signer - no attributes other than the default ones will be * provided here. * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ public void AddSigner( IAsymmetricKeyParameter privateKey, X509Certificate cert, string digestOid) { AddSigner(privateKey, cert, digestOid, new DefaultSignedAttributeTableGenerator(), null); } /** * add a signer, specifying the digest encryption algorithm - no attributes other than the default ones will be * provided here. * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ public void AddSigner( IAsymmetricKeyParameter privateKey, X509Certificate cert, string encryptionOid, string digestOid) { AddSigner(privateKey, cert, encryptionOid, digestOid, new DefaultSignedAttributeTableGenerator(), (CmsAttributeTableGenerator)null); } /** * add a signer with extra signed/unsigned attributes. * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ public void AddSigner( IAsymmetricKeyParameter privateKey, X509Certificate cert, string digestOid, Asn1.Cms.AttributeTable signedAttr, Asn1.Cms.AttributeTable unsignedAttr) { AddSigner(privateKey, cert, digestOid, new DefaultSignedAttributeTableGenerator(signedAttr), new SimpleAttributeTableGenerator(unsignedAttr)); } /** * add a signer with extra signed/unsigned attributes - specifying digest * encryption algorithm. * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ public void AddSigner( IAsymmetricKeyParameter privateKey, X509Certificate cert, string encryptionOid, string digestOid, Asn1.Cms.AttributeTable signedAttr, Asn1.Cms.AttributeTable unsignedAttr) { AddSigner(privateKey, cert, encryptionOid, digestOid, new DefaultSignedAttributeTableGenerator(signedAttr), new SimpleAttributeTableGenerator(unsignedAttr)); } public void AddSigner( IAsymmetricKeyParameter privateKey, X509Certificate cert, string digestOid, CmsAttributeTableGenerator signedAttrGenerator, CmsAttributeTableGenerator unsignedAttrGenerator) { AddSigner(privateKey, cert, GetEncOid(privateKey, digestOid), digestOid, signedAttrGenerator, unsignedAttrGenerator); } public void AddSigner( IAsymmetricKeyParameter privateKey, X509Certificate cert, string encryptionOid, string digestOid, CmsAttributeTableGenerator signedAttrGenerator, CmsAttributeTableGenerator unsignedAttrGenerator) { DoAddSigner(privateKey, GetSignerIdentifier(cert), encryptionOid, digestOid, signedAttrGenerator, unsignedAttrGenerator); } /** * add a signer - no attributes other than the default ones will be * provided here. * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ public void AddSigner( IAsymmetricKeyParameter privateKey, byte[] subjectKeyID, string digestOid) { AddSigner(privateKey, subjectKeyID, digestOid, new DefaultSignedAttributeTableGenerator(), (CmsAttributeTableGenerator)null); } /** * add a signer - no attributes other than the default ones will be * provided here. * @throws NoSuchProviderException * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ public void AddSigner( IAsymmetricKeyParameter privateKey, byte[] subjectKeyID, string encryptionOid, string digestOid) { AddSigner(privateKey, subjectKeyID, encryptionOid, digestOid, new DefaultSignedAttributeTableGenerator(), (CmsAttributeTableGenerator)null); } /** * add a signer with extra signed/unsigned attributes. * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ public void AddSigner( IAsymmetricKeyParameter privateKey, byte[] subjectKeyID, string digestOid, Asn1.Cms.AttributeTable signedAttr, Asn1.Cms.AttributeTable unsignedAttr) { AddSigner(privateKey, subjectKeyID, digestOid, new DefaultSignedAttributeTableGenerator(signedAttr), new SimpleAttributeTableGenerator(unsignedAttr)); } public void AddSigner( IAsymmetricKeyParameter privateKey, byte[] subjectKeyID, string digestOid, CmsAttributeTableGenerator signedAttrGenerator, CmsAttributeTableGenerator unsignedAttrGenerator) { AddSigner(privateKey, subjectKeyID, GetEncOid(privateKey, digestOid), digestOid, signedAttrGenerator, unsignedAttrGenerator); } public void AddSigner( IAsymmetricKeyParameter privateKey, byte[] subjectKeyID, string encryptionOid, string digestOid, CmsAttributeTableGenerator signedAttrGenerator, CmsAttributeTableGenerator unsignedAttrGenerator) { DoAddSigner(privateKey, GetSignerIdentifier(subjectKeyID), encryptionOid, digestOid, signedAttrGenerator, unsignedAttrGenerator); } private void DoAddSigner( IAsymmetricKeyParameter privateKey, SignerIdentifier signerIdentifier, string encryptionOid, string digestOid, CmsAttributeTableGenerator signedAttrGenerator, CmsAttributeTableGenerator unsignedAttrGenerator) { ConfigureDigest(digestOid); SignerInfoGeneratorImpl signerInf = new SignerInfoGeneratorImpl(this, privateKey, signerIdentifier, digestOid, encryptionOid, signedAttrGenerator, unsignedAttrGenerator); _signerInfs.Add(new DigestAndSignerInfoGeneratorHolder(signerInf, digestOid)); } internal override void AddSignerCallback( SignerInformation si) { // FIXME If there were parameters in si.DigestAlgorithmID.Parameters, they are lost // NB: Would need to call FixAlgID on the DigestAlgorithmID // For precalculated signers, just need to register the algorithm, not configure a digest RegisterDigestOid(si.DigestAlgorithmID.ObjectID.Id); } /** * generate a signed object that for a CMS Signed Data object */ public Stream Open( Stream outStream) { return Open(outStream, false); } /** * generate a signed object that for a CMS Signed Data * object - if encapsulate is true a copy * of the message will be included in the signature with the * default content type "data". */ public Stream Open( Stream outStream, bool encapsulate) { return Open(outStream, Data, encapsulate); } /** * generate a signed object that for a CMS Signed Data * object using the given provider - if encapsulate is true a copy * of the message will be included in the signature with the * default content type "data". If dataOutputStream is non null the data * being signed will be written to the stream as it is processed. * @param out stream the CMS object is to be written to. * @param encapsulate true if data should be encapsulated. * @param dataOutputStream output stream to copy the data being signed to. */ public Stream Open( Stream outStream, bool encapsulate, Stream dataOutputStream) { return Open(outStream, Data, encapsulate, dataOutputStream); } /** * generate a signed object that for a CMS Signed Data * object - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. */ public Stream Open( Stream outStream, string signedContentType, bool encapsulate) { return Open(outStream, signedContentType, encapsulate, null); } /** * generate a signed object that for a CMS Signed Data * object using the given provider - if encapsulate is true a copy * of the message will be included in the signature. The content type * is set according to the OID represented by the string signedContentType. * @param out stream the CMS object is to be written to. * @param signedContentType OID for data to be signed. * @param encapsulate true if data should be encapsulated. * @param dataOutputStream output stream to copy the data being signed to. */ public Stream Open( Stream outStream, string signedContentType, bool encapsulate, Stream dataOutputStream) { if (outStream == null) throw new ArgumentNullException("outStream"); if (!outStream.CanWrite) throw new ArgumentException(@"Expected writeable stream", "outStream"); if (dataOutputStream != null && !dataOutputStream.CanWrite) throw new ArgumentException(@"Expected writeable stream", "dataOutputStream"); _messageDigestsLocked = true; // // ContentInfo // BerSequenceGenerator sGen = new BerSequenceGenerator(outStream); sGen.AddObject(CmsObjectIdentifiers.SignedData); // // Signed Data // BerSequenceGenerator sigGen = new BerSequenceGenerator( sGen.GetRawOutputStream(), 0, true); bool isCounterSignature = (signedContentType == null); DerObjectIdentifier contentTypeOid = isCounterSignature ? null : new DerObjectIdentifier(signedContentType); sigGen.AddObject(CalculateVersion(contentTypeOid)); Asn1EncodableVector digestAlgs = new Asn1EncodableVector(); foreach (string digestOid in _messageDigestOids) { digestAlgs.Add( new AlgorithmIdentifier(new DerObjectIdentifier(digestOid), DerNull.Instance)); } { byte[] tmp = new DerSet(digestAlgs).GetEncoded(); sigGen.GetRawOutputStream().Write(tmp, 0, tmp.Length); } BerSequenceGenerator eiGen = new BerSequenceGenerator(sigGen.GetRawOutputStream()); eiGen.AddObject(contentTypeOid); // If encapsulating, add the data as an octet string in the sequence Stream encapStream = encapsulate ? CmsUtilities.CreateBerOctetOutputStream(eiGen.GetRawOutputStream(), 0, true, _bufferSize) : null; // Also send the data to 'dataOutputStream' if necessary Stream teeStream = GetSafeTeeOutputStream(dataOutputStream, encapStream); // Let all the digests see the data as it is written Stream digStream = AttachDigestsToOutputStream(_messageDigests.Values, teeStream); return new CmsSignedDataOutputStream(this, digStream, signedContentType, sGen, sigGen, eiGen); } private void RegisterDigestOid( string digestOid) { if (_messageDigestsLocked) { if (!_messageDigestOids.Contains(digestOid)) throw new InvalidOperationException("Cannot register new digest OIDs after the data stream is opened"); } else { _messageDigestOids.Add(digestOid); } } private void ConfigureDigest( string digestOid) { RegisterDigestOid(digestOid); string digestName = Helper.GetDigestAlgName(digestOid); IDigest dig = (IDigest)_messageDigests[digestName]; if (dig == null) { if (_messageDigestsLocked) throw new InvalidOperationException("Cannot configure new digests after the data stream is opened"); dig = Helper.GetDigestInstance(digestName); _messageDigests[digestName] = dig; } } // TODO Make public? internal void Generate( Stream outStream, string eContentType, bool encapsulate, Stream dataOutputStream, CmsProcessable content) { Stream signedOut = Open(outStream, eContentType, encapsulate, dataOutputStream); if (content != null) { content.Write(signedOut); } #if !NETFX_CORE signedOut.Close(); #else signedOut.Dispose(); #endif } // RFC3852, section 5.1: // IF ((certificates is present) AND // (any certificates with a type of other are present)) OR // ((crls is present) AND // (any crls with a type of other are present)) // THEN version MUST be 5 // ELSE // IF (certificates is present) AND // (any version 2 attribute certificates are present) // THEN version MUST be 4 // ELSE // IF ((certificates is present) AND // (any version 1 attribute certificates are present)) OR // (any SignerInfo structures are version 3) OR // (encapContentInfo eContentType is other than id-data) // THEN version MUST be 3 // ELSE version MUST be 1 // private DerInteger CalculateVersion( DerObjectIdentifier contentOid) { bool otherCert = false; bool otherCrl = false; bool attrCertV1Found = false; bool attrCertV2Found = false; if (_certs != null) { foreach (object obj in _certs) { if (obj is Asn1TaggedObject) { Asn1TaggedObject tagged = (Asn1TaggedObject)obj; if (tagged.TagNo == 1) { attrCertV1Found = true; } else if (tagged.TagNo == 2) { attrCertV2Found = true; } else if (tagged.TagNo == 3) { otherCert = true; break; } } } } if (otherCert) { return new DerInteger(5); } if (_crls != null) { foreach (object obj in _crls) { if (obj is Asn1TaggedObject) { otherCrl = true; break; } } } if (otherCrl) { return new DerInteger(5); } if (attrCertV2Found) { return new DerInteger(4); } if (attrCertV1Found || !CmsObjectIdentifiers.Data.Equals(contentOid) || CheckForVersion3(_signers)) { return new DerInteger(3); } return new DerInteger(1); } private bool CheckForVersion3( IList signerInfos) { foreach (SignerInformation si in signerInfos) { SignerInfo s = SignerInfo.GetInstance(si.ToSignerInfo()); if (s.Version.Value.IntValue == 3) { return true; } } return false; } private static Stream AttachDigestsToOutputStream(ICollection digests, Stream s) { Stream result = s; foreach (IDigest digest in digests) { result = GetSafeTeeOutputStream(result, new DigOutputStream(digest)); } return result; } private static Stream GetSafeOutputStream(Stream s) { if (s == null) return new NullOutputStream(); return s; } private static Stream GetSafeTeeOutputStream(Stream s1, Stream s2) { if (s1 == null) return GetSafeOutputStream(s2); if (s2 == null) return GetSafeOutputStream(s1); return new TeeOutputStream(s1, s2); } private class CmsSignedDataOutputStream : BaseOutputStream { private readonly CmsSignedDataStreamGenerator outer; private Stream _out; private DerObjectIdentifier _contentOID; private BerSequenceGenerator _sGen; private BerSequenceGenerator _sigGen; private BerSequenceGenerator _eiGen; public CmsSignedDataOutputStream( CmsSignedDataStreamGenerator outer, Stream outStream, string contentOID, BerSequenceGenerator sGen, BerSequenceGenerator sigGen, BerSequenceGenerator eiGen) { this.outer = outer; _out = outStream; _contentOID = new DerObjectIdentifier(contentOID); _sGen = sGen; _sigGen = sigGen; _eiGen = eiGen; } public override void WriteByte( byte b) { _out.WriteByte(b); } public override void Write( byte[] bytes, int off, int len) { _out.Write(bytes, off, len); } private void CloseParentContext() { // TODO Parent context(s) should really be be closed explicitly _eiGen.Close(); outer._digests.Clear(); // clear the current preserved digest state if (outer._certs.Count > 0) { Asn1Set certs = CmsUtilities.CreateBerSetFromList(outer._certs); WriteToGenerator(_sigGen, new BerTaggedObject(false, 0, certs)); } if (outer._crls.Count > 0) { Asn1Set crls = CmsUtilities.CreateBerSetFromList(outer._crls); WriteToGenerator(_sigGen, new BerTaggedObject(false, 1, crls)); } // // Calculate the digest hashes // foreach (DictionaryEntry de in outer._messageDigests) { outer._messageHashes.Add(de.Key, DigestUtilities.DoFinal((IDigest)de.Value)); } // TODO If the digest OIDs for precalculated signers weren't mixed in with // the others, we could fill in outer._digests here, instead of SignerInfoGenerator.Generate // // collect all the SignerInfo objects // Asn1EncodableVector signerInfos = new Asn1EncodableVector(); // // add the generated SignerInfo objects // { foreach (DigestAndSignerInfoGeneratorHolder holder in outer._signerInfs) { AlgorithmIdentifier digestAlgorithm = holder.DigestAlgorithm; byte[] calculatedDigest = (byte[])outer._messageHashes[ Helper.GetDigestAlgName(holder.digestOID)]; outer._digests[holder.digestOID] = calculatedDigest.Clone(); signerInfos.Add(holder.signerInf.Generate(_contentOID, digestAlgorithm, calculatedDigest)); } } // // add the precalculated SignerInfo objects. // { foreach (SignerInformation signer in outer._signers) { // TODO Verify the content type and calculated digest match the precalculated SignerInfo // if (!signer.ContentType.Equals(_contentOID)) // { // // TODO The precalculated content type did not match - error? // } // // byte[] calculatedDigest = (byte[])outer._digests[signer.DigestAlgOid]; // if (calculatedDigest == null) // { // // TODO We can't confirm this digest because we didn't calculate it - error? // } // else // { // if (!Arrays.AreEqual(signer.GetContentDigest(), calculatedDigest)) // { // // TODO The precalculated digest did not match - error? // } // } signerInfos.Add(signer.ToSignerInfo()); } } WriteToGenerator(_sigGen, new DerSet(signerInfos)); _sigGen.Close(); _sGen.Close(); } #if !NETFX_CORE public override void Close() { _out.Close(); this.CloseParentContext(); base.Close(); } #else protected override void Dispose(bool disposing) { _out.Dispose(); this.CloseParentContext(); base.Dispose(disposing); } #endif private static void WriteToGenerator( Asn1Generator ag, Asn1Encodable ae) { byte[] encoded = ae.GetEncoded(); ag.GetRawOutputStream().Write(encoded, 0, encoded.Length); } } } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://github.com/jskeet/dotnet-protobufs/ // Original C++/Java/Python code: // http://code.google.com/p/protobuf/ // // 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 Google Inc. 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. #endregion using System; using Google.ProtocolBuffers.DescriptorProtos; using Google.ProtocolBuffers.Descriptors; namespace Google.ProtocolBuffers.ProtoGen { internal class ServiceGenerator : SourceGeneratorBase<ServiceDescriptor>, ISourceGenerator { private readonly CSharpServiceType svcType; private ISourceGenerator _generator; internal ServiceGenerator(ServiceDescriptor descriptor) : base(descriptor) { svcType = descriptor.File.CSharpOptions.ServiceGeneratorType; switch (svcType) { case CSharpServiceType.NONE: _generator = new NoServicesGenerator(descriptor); break; case CSharpServiceType.GENERIC: _generator = new GenericServiceGenerator(descriptor); break; case CSharpServiceType.INTERFACE: _generator = new ServiceInterfaceGenerator(descriptor); break; case CSharpServiceType.IRPCDISPATCH: _generator = new RpcServiceGenerator(descriptor); break; default: throw new ApplicationException("Unknown ServiceGeneratorType = " + svcType.ToString()); } } public void Generate(TextGenerator writer) { _generator.Generate(writer); } private class NoServicesGenerator : SourceGeneratorBase<ServiceDescriptor>, ISourceGenerator { public NoServicesGenerator(ServiceDescriptor descriptor) : base(descriptor) { } public virtual void Generate(TextGenerator writer) { writer.WriteLine("/*"); writer.WriteLine("* Service generation is now disabled by default, use the following option to enable:"); writer.WriteLine("* option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;"); writer.WriteLine("*/"); } } private class ServiceInterfaceGenerator : SourceGeneratorBase<ServiceDescriptor>, ISourceGenerator { public ServiceInterfaceGenerator(ServiceDescriptor descriptor) : base(descriptor) { } public virtual void Generate(TextGenerator writer) { CSharpServiceOptions options = Descriptor.Options.GetExtension(CSharpOptions.CsharpServiceOptions); if (options != null && options.HasInterfaceId) { writer.WriteLine("[global::System.Runtime.InteropServices.GuidAttribute(\"{0}\")]", new Guid(options.InterfaceId)); } WriteGeneratedCodeAttributes(writer); writer.WriteLine("{0} partial interface I{1} {{", ClassAccessLevel, Descriptor.Name); writer.Indent(); foreach (MethodDescriptor method in Descriptor.Methods) { CSharpMethodOptions mth = method.Options.GetExtension(CSharpOptions.CsharpMethodOptions); if (mth.HasDispatchId) { writer.WriteLine("[global::System.Runtime.InteropServices.DispId({0})]", mth.DispatchId); } writer.WriteLine("{0} {1}({2} {3});", GetClassName(method.OutputType), NameHelpers.UnderscoresToPascalCase(method.Name), GetClassName(method.InputType), NameHelpers.UnderscoresToCamelCase(method.InputType.Name)); } writer.Outdent(); writer.WriteLine("}"); } } private class RpcServiceGenerator : ServiceInterfaceGenerator { public RpcServiceGenerator(ServiceDescriptor descriptor) : base(descriptor) { } public override void Generate(TextGenerator writer) { base.Generate(writer); writer.WriteLine(); // CLIENT Proxy { if (Descriptor.File.CSharpOptions.ClsCompliance) { writer.WriteLine("[global::System.CLSCompliant(false)]"); } writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine("{0} partial class {1} : I{1}, pb::IRpcDispatch, global::System.IDisposable {{", ClassAccessLevel, Descriptor.Name); writer.Indent(); writer.WriteLine("private readonly bool dispose;"); writer.WriteLine("private readonly pb::IRpcDispatch dispatch;"); writer.WriteLine("public {0}(pb::IRpcDispatch dispatch) : this(dispatch, true) {{", Descriptor.Name); writer.WriteLine("}"); writer.WriteLine("public {0}(pb::IRpcDispatch dispatch, bool dispose) {{", Descriptor.Name); writer.WriteLine(" pb::ThrowHelper.ThrowIfNull(this.dispatch = dispatch, \"dispatch\");"); writer.WriteLine(" this.dispose = dispose && dispatch is global::System.IDisposable;"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("public void Dispose() {"); writer.WriteLine(" if (dispose) ((global::System.IDisposable)dispatch).Dispose();"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine( "TMessage pb::IRpcDispatch.CallMethod<TMessage, TBuilder>(string method, pb::IMessageLite request, pb::IBuilderLite<TMessage, TBuilder> response) {"); writer.WriteLine(" return dispatch.CallMethod(method, request, response);"); writer.WriteLine("}"); writer.WriteLine(); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine("public {0} {1}({2} {3}) {{", GetClassName(method.OutputType), NameHelpers.UnderscoresToPascalCase(method.Name), GetClassName(method.InputType), NameHelpers.UnderscoresToCamelCase(method.InputType.Name)); writer.WriteLine(" return dispatch.CallMethod(\"{0}\", {1}, {2}.CreateBuilder());", method.Name, NameHelpers.UnderscoresToCamelCase(method.InputType.Name), GetClassName(method.OutputType) ); writer.WriteLine("}"); writer.WriteLine(); } } // SERVER - DISPATCH { if (Descriptor.File.CSharpOptions.ClsCompliance) { writer.WriteLine("[global::System.CLSCompliant(false)]"); } writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine("public partial class Dispatch : pb::IRpcDispatch, global::System.IDisposable {"); writer.Indent(); writer.WriteLine("private readonly bool dispose;"); writer.WriteLine("private readonly I{0} implementation;", Descriptor.Name); writer.WriteLine("public Dispatch(I{0} implementation) : this(implementation, true) {{", Descriptor.Name); writer.WriteLine("}"); writer.WriteLine("public Dispatch(I{0} implementation, bool dispose) {{", Descriptor.Name); writer.WriteLine(" pb::ThrowHelper.ThrowIfNull(this.implementation = implementation, \"implementation\");"); writer.WriteLine(" this.dispose = dispose && implementation is global::System.IDisposable;"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("public void Dispose() {"); writer.WriteLine(" if (dispose) ((global::System.IDisposable)implementation).Dispose();"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine( "public TMessage CallMethod<TMessage, TBuilder>(string methodName, pb::IMessageLite request, pb::IBuilderLite<TMessage, TBuilder> response)"); writer.WriteLine(" where TMessage : pb::IMessageLite<TMessage, TBuilder>"); writer.WriteLine(" where TBuilder : pb::IBuilderLite<TMessage, TBuilder> {"); writer.Indent(); writer.WriteLine("switch(methodName) {"); writer.Indent(); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine( "case \"{0}\": return response.MergeFrom(implementation.{1}(({2})request)).Build();", method.Name, NameHelpers.UnderscoresToPascalCase(method.Name), GetClassName(method.InputType)); } writer.WriteLine("default: throw pb::ThrowHelper.CreateMissingMethod(typeof(I{0}), methodName);", Descriptor.Name); writer.Outdent(); writer.WriteLine("}"); //end switch writer.Outdent(); writer.WriteLine("}"); //end invoke writer.Outdent(); writer.WriteLine("}"); //end server } // SERVER - STUB { if (Descriptor.File.CSharpOptions.ClsCompliance) { writer.WriteLine("[global::System.CLSCompliant(false)]"); } writer.WriteLine("[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]"); WriteGeneratedCodeAttributes(writer); writer.WriteLine( "public partial class ServerStub : pb::IRpcServerStub, global::System.IDisposable {"); writer.Indent(); writer.WriteLine("private readonly bool dispose;"); writer.WriteLine("private readonly pb::IRpcDispatch implementation;", Descriptor.Name); writer.WriteLine("public ServerStub(I{0} implementation) : this(implementation, true) {{", Descriptor.Name); writer.WriteLine("}"); writer.WriteLine( "public ServerStub(I{0} implementation, bool dispose) : this(new Dispatch(implementation, dispose), dispose) {{", Descriptor.Name); writer.WriteLine("}"); writer.WriteLine("public ServerStub(pb::IRpcDispatch implementation) : this(implementation, true) {"); writer.WriteLine("}"); writer.WriteLine("public ServerStub(pb::IRpcDispatch implementation, bool dispose) {"); writer.WriteLine(" pb::ThrowHelper.ThrowIfNull(this.implementation = implementation, \"implementation\");"); writer.WriteLine(" this.dispose = dispose && implementation is global::System.IDisposable;"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine("public void Dispose() {"); writer.WriteLine(" if (dispose) ((global::System.IDisposable)implementation).Dispose();"); writer.WriteLine("}"); writer.WriteLine(); writer.WriteLine( "public pb::IMessageLite CallMethod(string methodName, pb::ICodedInputStream input, pb::ExtensionRegistry registry) {{", Descriptor.Name); writer.Indent(); writer.WriteLine("switch(methodName) {"); writer.Indent(); foreach (MethodDescriptor method in Descriptor.Methods) { writer.WriteLine( "case \"{0}\": return implementation.CallMethod(methodName, {1}.ParseFrom(input, registry), {2}.CreateBuilder());", method.Name, GetClassName(method.InputType), GetClassName(method.OutputType)); } writer.WriteLine("default: throw pb::ThrowHelper.CreateMissingMethod(typeof(I{0}), methodName);", Descriptor.Name); writer.Outdent(); writer.WriteLine("}"); //end switch writer.Outdent(); writer.WriteLine("}"); //end invoke writer.Outdent(); writer.WriteLine("}"); //end server } writer.Outdent(); writer.WriteLine("}"); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace TerribleWebApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// 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.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Text; using System.Threading; public static class TieredVtableMethodTests { private const int CallCountPerIteration = 8; private static StringBuilder s_expectedCallSequence = new StringBuilder(); private static StringBuilder s_actualCallSequence = new StringBuilder(); private static int Main() { const int Pass = 100, Fail = 101; var baseObj = new Base(); var derivedObj = new Derived(); var derivedForDevirtualizationObj = new DerivedForDevirtualization(); PromoteToTier1( () => CallVirtualMethod(baseObj), () => CallVirtualMethod(derivedObj), () => CallGenericVirtualMethodWithValueType(baseObj), () => CallGenericVirtualMethodWithValueType(derivedObj), () => CallGenericVirtualMethodWithReferenceType(baseObj), () => CallGenericVirtualMethodWithReferenceType(derivedObj), () => CallVirtualMethodForDevirtualization(derivedForDevirtualizationObj), () => CallInterfaceVirtualMethodPolymorhpic(baseObj), () => CallInterfaceVirtualMethodPolymorhpic(derivedObj)); for (int i = 0; i < 4; ++i) { CallVirtualMethod(baseObj, CallCountPerIteration); CallVirtualMethod(derivedObj, CallCountPerIteration); CallGenericVirtualMethodWithValueType(baseObj, CallCountPerIteration); CallGenericVirtualMethodWithValueType(derivedObj, CallCountPerIteration); CallGenericVirtualMethodWithReferenceType(baseObj, CallCountPerIteration); CallGenericVirtualMethodWithReferenceType(derivedObj, CallCountPerIteration); CallVirtualMethodForDevirtualization(derivedForDevirtualizationObj, CallCountPerIteration); CallInterfaceVirtualMethodMonomorphicOnBase(baseObj, CallCountPerIteration); CallInterfaceVirtualMethodMonomorphicOnDerived(derivedObj, CallCountPerIteration); CallInterfaceVirtualMethodPolymorhpic(baseObj, CallCountPerIteration); CallInterfaceVirtualMethodPolymorhpic(derivedObj, CallCountPerIteration); for (int j = 0; j < 2; ++j) { RunCollectibleIterations(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.WaitForPendingFinalizers(); } } if (s_actualCallSequence.Equals(s_expectedCallSequence)) { return Pass; } Console.WriteLine($"Expected: {s_expectedCallSequence}"); Console.WriteLine($"Actual: {s_actualCallSequence}"); return Fail; } /// Creates a collectible type deriving from <see cref="Base"/> similar to <see cref="Derived"/>. The collectible derived /// type inherits vtable slots from the base. After multiple iterations of the test, the collectible type will be collected /// and replaced with another new collectible type. This is used to cover vtable slot backpatching and cleanup of recorded /// slots in collectible types. [MethodImpl(MethodImplOptions.NoInlining)] private static void RunCollectibleIterations() { Base collectibleDerivedObj = CreateCollectibleDerived(); PromoteToTier1( () => CallVirtualMethod(collectibleDerivedObj), () => CallGenericVirtualMethodWithValueType(collectibleDerivedObj), () => CallGenericVirtualMethodWithReferenceType(collectibleDerivedObj), () => CallInterfaceVirtualMethodPolymorhpic(collectibleDerivedObj)); CallVirtualMethod(collectibleDerivedObj, CallCountPerIteration); CallGenericVirtualMethodWithValueType(collectibleDerivedObj, CallCountPerIteration); CallGenericVirtualMethodWithReferenceType(collectibleDerivedObj, CallCountPerIteration); CallInterfaceVirtualMethodPolymorhpic(collectibleDerivedObj, CallCountPerIteration); } public interface IBase { void InterfaceVirtualMethod(); } public class Base : IBase { [MethodImpl(MethodImplOptions.NoInlining)] public virtual void VirtualMethod() { s_actualCallSequence.Append("v "); } [MethodImpl(MethodImplOptions.NoInlining)] public virtual void GenericVirtualMethod<T>(T t) { s_actualCallSequence.Append(typeof(T).IsValueType ? "gvv " : "gvr "); } [MethodImpl(MethodImplOptions.NoInlining)] public virtual void VirtualMethodForDevirtualization() { s_actualCallSequence.Append("vd "); } [MethodImpl(MethodImplOptions.NoInlining)] public virtual void InterfaceVirtualMethod() { s_actualCallSequence.Append("iv "); } } private class Derived : Base { // Prevent this type from sharing the vtable chunk from the base public virtual void VirtualMethod2() { } } // Derived type that is sealed for testing devirtualization of calls to inherited virtual methods private sealed class DerivedForDevirtualization : Derived { // Prevent this type from sharing the vtable chunk from the base public override void VirtualMethod() { } } [MethodImpl(MethodImplOptions.NoInlining)] private static void CallVirtualMethod(Base obj, int count = 1) { for (int i = 0; i < count; ++i) { s_expectedCallSequence.Append("v "); obj.VirtualMethod(); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void CallGenericVirtualMethodWithValueType(Base obj, int count = 1) { for (int i = 0; i < count; ++i) { s_expectedCallSequence.Append("gvv "); obj.GenericVirtualMethod(0); } } [MethodImpl(MethodImplOptions.NoInlining)] private static void CallGenericVirtualMethodWithReferenceType(Base obj, int count = 1) { var objArg = new object(); for (int i = 0; i < count; ++i) { s_expectedCallSequence.Append("gvr "); obj.GenericVirtualMethod(objArg); } } /// The virtual call in this method may be devirtualized because <see cref="DerivedForDevirtualization"/> is sealed [MethodImpl(MethodImplOptions.NoInlining)] private static void CallVirtualMethodForDevirtualization(DerivedForDevirtualization obj, int count = 1) { for (int i = 0; i < count; ++i) { s_expectedCallSequence.Append("vd "); obj.VirtualMethodForDevirtualization(); } } /// The interface call site in this method is monomorphic on <see cref="Base"/> and is used to cover dispatch stub /// backpatching [MethodImpl(MethodImplOptions.NoInlining)] private static void CallInterfaceVirtualMethodMonomorphicOnBase(IBase obj, int count = 1) { for (int i = 0; i < count; ++i) { s_expectedCallSequence.Append("iv "); obj.InterfaceVirtualMethod(); } } /// The interface call site in this method is monomorphic on <see cref="Base"/> and is used to cover dispatch stub /// backpatching [MethodImpl(MethodImplOptions.NoInlining)] private static void CallInterfaceVirtualMethodMonomorphicOnDerived(IBase obj, int count = 1) { for (int i = 0; i < count; ++i) { s_expectedCallSequence.Append("iv "); obj.InterfaceVirtualMethod(); } } // The call site in this method is polymorphic and is used to cover resolve cache entry backpatching [MethodImpl(MethodImplOptions.NoInlining)] private static void CallInterfaceVirtualMethodPolymorhpic(IBase obj, int count = 1) { for (int i = 0; i < count; ++i) { s_expectedCallSequence.Append("iv "); obj.InterfaceVirtualMethod(); } } private static ulong s_collectibleIndex = 0; private static Base CreateCollectibleDerived() { ulong collectibleIndex = s_collectibleIndex++; var ab = AssemblyBuilder.DefineDynamicAssembly( new AssemblyName($"CollectibleDerivedAssembly{collectibleIndex}"), AssemblyBuilderAccess.RunAndCollect); var mob = ab.DefineDynamicModule($"CollectibleDerivedModule{collectibleIndex}"); var tb = mob.DefineType( $"CollectibleDerived{collectibleIndex}", TypeAttributes.Class | TypeAttributes.Public, typeof(Base)); /// Add a virtual method to prevent this type from sharing the vtable chunk from the base, similarly to what is done in /// <see cref="Derived"/> { var mb = tb.DefineMethod( "VirtualMethod2", MethodAttributes.Public | MethodAttributes.Virtual | MethodAttributes.NewSlot); var ilg = mb.GetILGenerator(); ilg.Emit(OpCodes.Ret); } return (Base)Activator.CreateInstance(tb.CreateTypeInfo()); } [MethodImpl(MethodImplOptions.NoInlining)] private static void PromoteToTier1(params Action[] actions) { // Call the methods once to register a call each for call counting foreach (Action action in actions) { action(); } // Allow time for call counting to begin Thread.Sleep(500); // Call the methods enough times to trigger tier 1 promotion for (int i = 0; i < 100; ++i) { foreach (Action action in actions) { action(); } } // Allow time for the methods to be jitted at tier 1 Thread.Sleep(Math.Max(500, 100 * actions.Length)); } }
// 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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class ReadOnlyKeywordRecommenderTests : KeywordRecommenderTests { [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AtRoot_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterClass_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"class C { } $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalStatement_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalVariableDeclaration_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"int i = 0; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInEmptyStatement() { VerifyAbsence(AddInsideMethod( @"$$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInCompilationUnit() { VerifyAbsence(SourceCodeKind.Regular, @"$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterExtern() { VerifyAbsence(SourceCodeKind.Regular, @"extern alias Foo; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterExtern_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"extern alias Foo; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterUsing() { VerifyAbsence(SourceCodeKind.Regular, @"using Foo; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterUsing_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"using Foo; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterNamespace() { VerifyAbsence(SourceCodeKind.Regular, @"namespace N {} $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterTypeDeclaration() { VerifyAbsence(SourceCodeKind.Regular, @"class C {} $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterDelegateDeclaration() { VerifyAbsence(SourceCodeKind.Regular, @"delegate void Foo(); $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethod() { VerifyKeyword( @"class C { void Foo() {} $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterField() { VerifyKeyword( @"class C { int i; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterProperty() { VerifyKeyword( @"class C { int i { get; } $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotBeforeUsing() { VerifyAbsence(SourceCodeKind.Regular, @"$$ using Foo;"); } [WpfFact(Skip = "528041"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotBeforeUsing_Interactive() { VerifyAbsence(SourceCodeKind.Script, @"$$ using Foo;"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterAssemblyAttribute() { VerifyAbsence(SourceCodeKind.Regular, @"[assembly: foo] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterAssemblyAttribute_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"[assembly: foo] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterRootAttribute() { VerifyAbsence(@"[foo] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAttribute() { VerifyKeyword( @"class C { [foo] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideStruct() { VerifyKeyword( @"struct S { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInsideInterface() { VerifyAbsence(@"interface I { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInsideEnum() { VerifyAbsence(@"enum E { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideClass() { VerifyKeyword( @"class C { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPartial() { VerifyAbsence(@"partial $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterAbstract() { VerifyAbsence(@"abstract $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterInternal() { VerifyAbsence(SourceCodeKind.Regular, @"internal $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterInternal_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"internal $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedInternal() { VerifyKeyword( @"class C { internal $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPublic() { VerifyAbsence(SourceCodeKind.Regular, @"public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPublic_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublic() { VerifyKeyword( @"class C { public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPrivate() { VerifyAbsence(SourceCodeKind.Regular, @"private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterPrivate_Script() { VerifyKeyword(SourceCodeKind.Script, @"private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPrivate() { VerifyKeyword( @"class C { private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterProtected() { VerifyAbsence( @"protected $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedProtected() { VerifyKeyword( @"class C { protected $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterSealed() { VerifyAbsence(@"sealed $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterNestedSealed() { VerifyAbsence( @"class C { sealed $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterStatic() { VerifyAbsence(SourceCodeKind.Regular, @"static $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterStatic_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"static $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStatic() { VerifyKeyword( @"class C { static $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterStaticPublic() { VerifyAbsence(SourceCodeKind.Regular, @"static public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterStaticPublic_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"static public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStaticPublic() { VerifyKeyword( @"class C { static public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterDelegate() { VerifyAbsence(@"delegate $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterEvent() { VerifyAbsence( @"class C { event $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterConst() { VerifyAbsence( @"class C { const $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterReadOnly() { VerifyAbsence( @"class C { readonly $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterVolatile() { VerifyAbsence( @"class C { volatile $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterNew() { VerifyAbsence( @"new $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedNew() { VerifyKeyword( @"class C { new $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInMethod() { VerifyAbsence( @"class C { void Foo() { $$"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Security.Claims; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Mvc; using Microsoft.Extensions.Logging; using portal.Models; using portal.Services; using portal.ViewModels.Manage; namespace portal.Controllers { [Authorize] public class ManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<ManageController>(); } // // GET: /Manage/Index [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } // // GET: /Manage/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var user = await GetCurrentUserAsync(); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // GET: /Manage/VerifyPhoneNumber [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } // // GET: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } //GET: /Manage/ManageLogins [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public IActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId()); return new ChallengeResult(provider, properties); } // // GET: /Manage/LinkLoginCallback [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId()); if (info == null) { return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); } var result = await _userManager.AddLoginAsync(user, info); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; return RedirectToAction(nameof(ManageLogins), new { Message = message }); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private async Task<ApplicationUser> GetCurrentUserAsync() { return await _userManager.FindByIdAsync(HttpContext.User.GetUserId()); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using OrchardCore.Documents; using OrchardCore.Modules; using OrchardCore.Roles.Models; using OrchardCore.Security; namespace OrchardCore.Roles.Services { public class RoleStore : IRoleClaimStore<IRole>, IQueryableRoleStore<IRole> { private readonly IServiceProvider _serviceProvider; private readonly IDocumentManager<RolesDocument> _documentManager; private readonly IStringLocalizer S; private readonly ILogger _logger; private bool _updating; public RoleStore( IServiceProvider serviceProvider, IDocumentManager<RolesDocument> documentManager, IStringLocalizer<RoleStore> stringLocalizer, ILogger<RoleStore> logger) { _serviceProvider = serviceProvider; _documentManager = documentManager; S = stringLocalizer; _logger = logger; } public IQueryable<IRole> Roles => GetRolesAsync().GetAwaiter().GetResult().Roles.AsQueryable(); /// <summary> /// Loads the roles document from the store for updating and that should not be cached. /// </summary> private Task<RolesDocument> LoadRolesAsync() => _documentManager.GetOrCreateMutableAsync(); /// <summary> /// Gets the roles document from the cache for sharing and that should not be updated. /// </summary> private Task<RolesDocument> GetRolesAsync() => _documentManager.GetOrCreateImmutableAsync(); /// <summary> /// Updates the store with the provided roles document and then updates the cache. /// </summary> private Task UpdateRolesAsync(RolesDocument roles) { _updating = true; return _documentManager.UpdateAsync(roles); } #region IRoleStore<IRole> public async Task<IdentityResult> CreateAsync(IRole role, CancellationToken cancellationToken) { if (role == null) { throw new ArgumentNullException(nameof(role)); } var roles = await LoadRolesAsync(); roles.Roles.Add((Role)role); await UpdateRolesAsync(roles); return IdentityResult.Success; } public async Task<IdentityResult> DeleteAsync(IRole role, CancellationToken cancellationToken) { if (role == null) { throw new ArgumentNullException(nameof(role)); } var roleToRemove = (Role)role; if (String.Equals(roleToRemove.NormalizedRoleName, "ANONYMOUS") || String.Equals(roleToRemove.NormalizedRoleName, "AUTHENTICATED")) { return IdentityResult.Failed(new IdentityError { Description = S["Can't delete system roles."] }); } var roleRemovedEventHandlers = _serviceProvider.GetRequiredService<IEnumerable<IRoleRemovedEventHandler>>(); await roleRemovedEventHandlers.InvokeAsync((handler, roleToRemove) => handler.RoleRemovedAsync(roleToRemove.RoleName), roleToRemove, _logger); var roles = await LoadRolesAsync(); roleToRemove = roles.Roles.FirstOrDefault(r => r.RoleName == roleToRemove.RoleName); roles.Roles.Remove(roleToRemove); await UpdateRolesAsync(roles); return IdentityResult.Success; } public async Task<IRole> FindByIdAsync(string roleId, CancellationToken cancellationToken) { // While updating find a role from the loaded document being mutated. var roles = _updating ? await LoadRolesAsync() : await GetRolesAsync(); var role = roles.Roles.FirstOrDefault(x => x.RoleName == roleId); if (role == null) { return null; } return _updating ? role : role.Clone(); } public async Task<IRole> FindByNameAsync(string normalizedRoleName, CancellationToken cancellationToken) { // While updating find a role from the loaded document being mutated. var roles = _updating ? await LoadRolesAsync() : await GetRolesAsync(); var role = roles.Roles.FirstOrDefault(x => x.NormalizedRoleName == normalizedRoleName); if (role == null) { return null; } return _updating ? role : role.Clone(); } public Task<string> GetNormalizedRoleNameAsync(IRole role, CancellationToken cancellationToken) { if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(((Role)role).NormalizedRoleName); } public Task<string> GetRoleIdAsync(IRole role, CancellationToken cancellationToken) { if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(role.RoleName.ToUpperInvariant()); } public Task<string> GetRoleNameAsync(IRole role, CancellationToken cancellationToken) { if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(role.RoleName); } public Task SetNormalizedRoleNameAsync(IRole role, string normalizedName, CancellationToken cancellationToken) { if (role == null) { throw new ArgumentNullException(nameof(role)); } ((Role)role).NormalizedRoleName = normalizedName; return Task.CompletedTask; } public Task SetRoleNameAsync(IRole role, string roleName, CancellationToken cancellationToken) { if (role == null) { throw new ArgumentNullException(nameof(role)); } ((Role)role).RoleName = roleName; return Task.CompletedTask; } public async Task<IdentityResult> UpdateAsync(IRole role, CancellationToken cancellationToken) { if (role == null) { throw new ArgumentNullException(nameof(role)); } var roles = await LoadRolesAsync(); var existingRole = roles.Roles.FirstOrDefault(x => x.RoleName == role.RoleName); roles.Roles.Remove(existingRole); roles.Roles.Add((Role)role); await UpdateRolesAsync(roles); return IdentityResult.Success; } #endregion IRoleStore<IRole> #region IRoleClaimStore<IRole> public Task AddClaimAsync(IRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { if (role == null) { throw new ArgumentNullException(nameof(role)); } if (claim == null) { throw new ArgumentNullException(nameof(claim)); } ((Role)role).RoleClaims.Add(new RoleClaim { ClaimType = claim.Type, ClaimValue = claim.Value }); return Task.CompletedTask; } public Task<IList<Claim>> GetClaimsAsync(IRole role, CancellationToken cancellationToken = default(CancellationToken)) { if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult<IList<Claim>>(((Role)role).RoleClaims.Select(x => x.ToClaim()).ToList()); } public Task RemoveClaimAsync(IRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { if (role == null) { throw new ArgumentNullException(nameof(role)); } if (claim == null) { throw new ArgumentNullException(nameof(claim)); } ((Role)role).RoleClaims.RemoveAll(x => x.ClaimType == claim.Type && x.ClaimValue == claim.Value); return Task.CompletedTask; } #endregion IRoleClaimStore<IRole> public void Dispose() { } } }
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 OutOfMemory.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 file="CollaborationHelperFunctions.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Security.Permissions; namespace System.Net.PeerToPeer.Collaboration { using System; using System.Collections.ObjectModel; using System.Runtime.InteropServices; using System.Net.Mail; using System.Security.Cryptography.X509Certificates; using System.Diagnostics; using System.Threading; /// <summary> /// This class contains some of the common functions needed for peer /// collaboration /// </summary> internal static class CollaborationHelperFunctions { private static volatile bool s_Initialized; private static object s_LockInitialized = new object(); private const short c_CollabVersion = 0x0001; // // Initialise windows collab. This has to be called before any collab operation // // <SecurityKernel Critical="True" Ring="0"> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabStartup(System.Int16):System.Int32" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static void Initialize() { if (!s_Initialized){ lock (s_LockInitialized){ if (!s_Initialized){ if(!PeerToPeerOSHelper.SupportsP2P) throw new PlatformNotSupportedException(SR.GetString(SR.P2P_NotAvailable)); int errorCode = UnsafeCollabNativeMethods.PeerCollabStartup(c_CollabVersion); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabStartup returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_StartupFailed), errorCode); } s_Initialized = true; } } } } // // Converts Guid class to GUID structure that we can pass into native // internal static GUID ConvertGuidToGUID(Guid guid) { GUID newGuid = new GUID(); if (guid != null){ byte[] guidBytes = guid.ToByteArray(); string guidString = guid.ToString(); int startVal = 0; int endVal = guidString.IndexOf('-'); newGuid.data1 = (uint)(Convert.ToUInt32(guidString.Substring(startVal, endVal - startVal), 16)); startVal = endVal + 1; endVal = guidString.IndexOf('-', endVal + 1); newGuid.data2 = (ushort)(Convert.ToUInt16(guidString.Substring(startVal, endVal - startVal), 16)); startVal = endVal + 1; endVal = guidString.IndexOf('-', endVal + 1); newGuid.data3 = (ushort)(Convert.ToUInt16(guidString.Substring(startVal, endVal - startVal), 16)); newGuid.data4 = guidBytes[8]; newGuid.data5 = guidBytes[9]; newGuid.data6 = guidBytes[10]; newGuid.data7 = guidBytes[11]; newGuid.data8 = guidBytes[12]; newGuid.data9 = guidBytes[13]; newGuid.data10 = guidBytes[14]; newGuid.data11 = guidBytes[15]; } return newGuid; } // // Converts native GUID structure to managed Guid class // internal static Guid ConvertGUIDToGuid(GUID guid) { byte[] bytes = new byte[8]; bytes[0] = guid.data4; bytes[1] = guid.data5; bytes[2] = guid.data6; bytes[3] = guid.data7; bytes[4] = guid.data8; bytes[5] = guid.data9; bytes[6] = guid.data10; bytes[7] = guid.data11; return new Guid((int)guid.data1, (short)guid.data2, (short)guid.data3, bytes); } // // Converts native PEER_CONTACT to PeerContact class // // <SecurityKernel Critical="True" Ring="1"> // <ReferencesCritical Name="Method: ConvertPEER_CONTACTToPeerContact(PEER_CONTACT, Boolean):PeerContact" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static PeerContact ConvertPEER_CONTACTToPeerContact(PEER_CONTACT pc) { return ConvertPEER_CONTACTToPeerContact(pc, false); } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="Marshal.Copy(System.IntPtr,System.Byte[],System.Int32,System.Int32):System.Void" /> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="Marshal.GetLastWin32Error():System.Int32" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="X509Store..ctor(System.IntPtr)" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.CertOpenStore(System.IntPtr,System.UInt32,System.IntPtr,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_DATA&):System.Net.PeerToPeer.Collaboration.SafeCertStore" /> // <ReferencesCritical Name="Local certHandle of type: SafeCertStore" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // <ReferencesCritical Name="Method: PeerContact..ctor()" Ring="2" /> // <ReferencesCritical Name="Method: MyContact..ctor()" Ring="3" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static PeerContact ConvertPEER_CONTACTToPeerContact(PEER_CONTACT pc, bool isMyContact) { PeerContact peerContact = (isMyContact ? new MyContact(): new PeerContact()); peerContact.PeerName = new PeerName(pc.pwzPeerName); peerContact.DisplayName = pc.pwzDisplayName; peerContact.Nickname = pc.pwzNickname; peerContact.EmailAddress = (pc.pwzEmailAddress != null) ? new MailAddress(pc.pwzEmailAddress) : null; if(!isMyContact) peerContact.SubscribeAllowed = pc.WatcherPermissions; peerContact.IsSubscribed = (isMyContact ? true : pc.fWatch); byte[] data = null; if (pc.credentials.cbData != 0){ data = new byte[pc.credentials.cbData]; Marshal.Copy(pc.credentials.pbData, data, 0, (int)pc.credentials.cbData); } if (data != null){ SafeCertStore certHandle = UnsafeCollabNativeMethods.CertOpenStore(new IntPtr(/*CERT_STORE_PROV_PKCS7*/ 5), 0x00000001/*X509_ASN_ENCODING*/| 0x00010000/*PKCS_7_ASN_ENCODING*/, IntPtr.Zero, 0x00000001/*CERT_STORE_NO_CRYPT_RELEASE_FLAG*/, ref pc.credentials); if (certHandle == null || certHandle.IsInvalid){ int win32ErrorCode = Marshal.GetLastWin32Error(); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_CredentialsError), win32ErrorCode); } try{ X509Store certStore = new X509Store(certHandle.DangerousGetHandle()); peerContact.Credentials = new X509Certificate2(certStore.Certificates[0]); } finally{ if(certHandle != null) certHandle.Dispose(); } } return peerContact; } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="Marshal.GetLastWin32Error():System.Int32" /> // <SatisfiesLinkDemand Name="SafeHandle.DangerousGetHandle():System.IntPtr" /> // <SatisfiesLinkDemand Name="X509Store..ctor(System.IntPtr)" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.CertOpenStore(System.IntPtr,System.UInt32,System.IntPtr,System.UInt32,System.IntPtr):System.Net.PeerToPeer.Collaboration.SafeCertStore" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.CertSaveStore(System.Net.PeerToPeer.Collaboration.SafeCertStore,System.UInt32,System.UInt32,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_DATA&,System.UInt32):System.Boolean" /> // <ReferencesCritical Name="Local certHandle of type: SafeCertStore" Ring="1" /> // <ReferencesCritical Name="Parameter safeCredentials of type: SafeCollabMemory" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // <ReferencesCritical Name="Method: SafeCollabMemory..ctor(System.Int32)" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static PEER_CONTACT ConvertPeerContactToPEER_CONTACT(PeerContact peerContact, ref SafeCollabMemory safeCredentials) { PEER_CONTACT pc = new PEER_CONTACT(); pc.pwzDisplayName = peerContact.DisplayName; pc.pwzEmailAddress = (peerContact.EmailAddress == null) ? null : peerContact.EmailAddress.ToString(); pc.pwzNickname = peerContact.Nickname; pc.pwzPeerName = peerContact.PeerName.ToString(); pc.fWatch = peerContact.IsSubscribed; pc.WatcherPermissions = peerContact.SubscribeAllowed; PEER_DATA pd = new PEER_DATA(); if (peerContact.Credentials != null){ SafeCertStore certHandle = UnsafeCollabNativeMethods.CertOpenStore(new IntPtr(/*CERT_STORE_PROV_MEMORY*/ 2), 0, IntPtr.Zero, 0x00002000/*CERT_STORE_CREATE_NEW_FLAG*/ | 0x00000001/*CERT_STORE_NO_CRYPT_RELEASE_FLAG*/, IntPtr.Zero); if (certHandle == null || certHandle.IsInvalid){ int win32ErrorCode = Marshal.GetLastWin32Error(); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_CredentialsError), win32ErrorCode); } try{ X509Store certStore = new X509Store(certHandle.DangerousGetHandle()); certStore.Add(peerContact.Credentials as X509Certificate2); bool returnCode = UnsafeCollabNativeMethods.CertSaveStore(certHandle, 0x00000001/*X509_ASN_ENCODING*/| 0x00010000/*PKCS_7_ASN_ENCODING*/, 2 /*CERT_STORE_SAVE_AS_STORE*/, 2, /*CERT_STORE_SAVE_TO_MEMORY*/ ref pd, 0); if ((pd.cbData != 0) && (returnCode)){ safeCredentials = new SafeCollabMemory((int)pd.cbData); pd.pbData = safeCredentials.DangerousGetHandle(); returnCode = UnsafeCollabNativeMethods.CertSaveStore(certHandle, 0x00000001/*X509_ASN_ENCODING*/| 0x00010000/*PKCS_7_ASN_ENCODING*/, 2 /*CERT_STORE_SAVE_AS_STORE*/, 2, /*CERT_STORE_SAVE_TO_MEMORY*/ ref pd,// Clean up memory from here; 0); } else{ pd.cbData = 0; pd.pbData = IntPtr.Zero; } } finally{ if (certHandle != null) certHandle.Dispose(); } } else{ pd.cbData = 0; pd.pbData = IntPtr.Zero; } pc.credentials = pd; return pc; } // // Converts address bytes to a SOCKADDR_IN6 that can be passed into // native // internal static void ByteArrayToSin6Addr(byte[] addrBytes, ref SOCKADDR_IN6 sin6) { sin6.sin6_addr0 = addrBytes[0]; sin6.sin6_addr1 = addrBytes[1]; sin6.sin6_addr2 = addrBytes[2]; sin6.sin6_addr3 = addrBytes[3]; sin6.sin6_addr4 = addrBytes[4]; sin6.sin6_addr5 = addrBytes[5]; sin6.sin6_addr6 = addrBytes[6]; sin6.sin6_addr7 = addrBytes[7]; sin6.sin6_addr8 = addrBytes[8]; sin6.sin6_addr9 = addrBytes[9]; sin6.sin6_addr10 = addrBytes[10]; sin6.sin6_addr11 = addrBytes[11]; sin6.sin6_addr12 = addrBytes[12]; sin6.sin6_addr13 = addrBytes[13]; sin6.sin6_addr14 = addrBytes[14]; sin6.sin6_addr15 = addrBytes[15]; } // // Converts native structure PEER_PEOPLE_NEAR_ME to managed PeerNearMe class // // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="Marshal.PtrToStringUni(System.IntPtr):System.String" /> // <ReferencesCritical Name="Method: ConvertPEER_ENDPOINTToPeerEndPoint(PEER_ENDPOINT):PeerEndPoint" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static PeerNearMe PEER_PEOPLE_NEAR_METoPeerNearMe(PEER_PEOPLE_NEAR_ME ppnm) { PeerNearMe peerNearMe = new PeerNearMe(); peerNearMe.Id = CollaborationHelperFunctions.ConvertGUIDToGuid(ppnm.id); peerNearMe.Nickname = Marshal.PtrToStringUni(ppnm.pwzNickname); ; PEER_ENDPOINT pe = ppnm.endpoint; PeerEndPoint peerEP = ConvertPEER_ENDPOINTToPeerEndPoint(pe); peerNearMe.PeerEndPoints.Add(peerEP); return peerNearMe; } // // Converts native PEER_OBJECT structure into PeerObject class // // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="Marshal.Copy(System.IntPtr,System.Byte[],System.Int32,System.Int32):System.Void" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static PeerObject ConvertPEER_OBJECTToPeerObject(PEER_OBJECT po) { byte[] data = null; if (po.data.cbData != 0){ data = new byte[po.data.cbData]; Marshal.Copy(po.data.pbData, data, 0, (int)po.data.cbData); } return new PeerObject(ConvertGUIDToGuid(po.guid), data, (PeerScope)po.dwPublicationScope); } // // Converts native PEER_APPLICATION structure into PeerApplication class // // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="Marshal.Copy(System.IntPtr,System.Byte[],System.Int32,System.Int32):System.Void" /> // <SatisfiesLinkDemand Name="Marshal.PtrToStringUni(System.IntPtr):System.String" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static PeerApplication ConvertPEER_APPLICATIONToPeerApplication(PEER_APPLICATION pa) { byte[] data = null; if (pa.data.cbData != 0){ data = new byte[pa.data.cbData]; Marshal.Copy(pa.data.pbData, data, 0, (int)pa.data.cbData); } return new PeerApplication( ConvertGUIDToGuid(pa.guid), Marshal.PtrToStringUni(pa.pwzDescription), data, null, null, PeerScope.None); } // // Converts native PEER_ENDPOINT structure into PeerEndPoint class // // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="Marshal.PtrToStringUni(System.IntPtr):System.String" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static PeerEndPoint ConvertPEER_ENDPOINTToPeerEndPoint(PEER_ENDPOINT pe) { byte[] addrBytes = new byte[]{ pe.peerAddress.sin6.sin6_addr0, pe.peerAddress.sin6.sin6_addr1, pe.peerAddress.sin6.sin6_addr2, pe.peerAddress.sin6.sin6_addr3, pe.peerAddress.sin6.sin6_addr4, pe.peerAddress.sin6.sin6_addr5, pe.peerAddress.sin6.sin6_addr6, pe.peerAddress.sin6.sin6_addr7, pe.peerAddress.sin6.sin6_addr8, pe.peerAddress.sin6.sin6_addr9, pe.peerAddress.sin6.sin6_addr10, pe.peerAddress.sin6.sin6_addr11, pe.peerAddress.sin6.sin6_addr12, pe.peerAddress.sin6.sin6_addr13, pe.peerAddress.sin6.sin6_addr14, pe.peerAddress.sin6.sin6_addr15}; IPAddress IPAddr = new IPAddress(addrBytes, (long)pe.peerAddress.sin6.sin6_scope_id); ushort port; unchecked{ port = (ushort)IPAddress.NetworkToHostOrder((short)pe.peerAddress.sin6.sin6_port); } IPEndPoint IPEndPt = new IPEndPoint(IPAddr, port); return new PeerEndPoint(IPEndPt, Marshal.PtrToStringUni(pe.pwzEndpointName)); } // // Converts IPEndpoint class into native PEER_ADDRESS structure // internal static PEER_ADDRESS ConvertIPEndpointToPEER_ADDRESS(IPEndPoint endPoint) { PEER_ADDRESS pa = new PEER_ADDRESS(); SOCKADDR_IN6 sin = new SOCKADDR_IN6(); sin.sin6_family = (ushort)endPoint.AddressFamily; sin.sin6_flowinfo = 0; // unchecked{ sin.sin6_port = (ushort)IPAddress.HostToNetworkOrder((short)endPoint.Port); } sin.sin6_scope_id = (uint)endPoint.Address.ScopeId; CollaborationHelperFunctions.ByteArrayToSin6Addr(endPoint.Address.GetAddressBytes(), ref sin); pa.dwSize = 32; pa.sin6 = sin; return pa; } // // Cleans up the registered handle and the wait event. Called under lock from events. // // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="SafeHandle.get_IsInvalid():System.Boolean" /> // <SatisfiesLinkDemand Name="SafeHandle.Dispose():System.Void" /> // <ReferencesCritical Name="Parameter safeEvent of type: SafeCollabEvent" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] [SecurityPermissionAttribute(SecurityAction.LinkDemand, UnmanagedCode = true)] internal static void CleanEventVars(ref RegisteredWaitHandle waitHandle, ref SafeCollabEvent safeEvent, ref AutoResetEvent firedEvent) { if (waitHandle != null){ waitHandle.Unregister(null); waitHandle = null; } if ((safeEvent != null) && (!safeEvent.IsInvalid)){ safeEvent.Dispose(); } if (firedEvent != null){ firedEvent.Close(); firedEvent = null; } } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <ReferencesCritical Name="Parameter safePresenceChangedEvent of type: SafeCollabEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static void AddMyPresenceChanged(EventHandler<PresenceChangedEventArgs> callback, ref EventHandler<PresenceChangedEventArgs> presenceChanged, object lockPresenceChangedEvent, ref RegisteredWaitHandle regPresenceChangedWaitHandle, ref AutoResetEvent presenceChangedEvent, ref SafeCollabEvent safePresenceChangedEvent, WaitOrTimerCallback PresenceChangedCallback) { // // Register a wait handle if one has not been registered already // lock (lockPresenceChangedEvent){ if (presenceChanged == null){ presenceChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // regPresenceChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(presenceChangedEvent, //Event that triggers the callback PresenceChangedCallback, //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.MyPresenceChanged; pcer.pInstance = IntPtr.Zero; // // Register event with collab // int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( presenceChangedEvent.SafeWaitHandle, 1, ref pcer, out safePresenceChangedEvent); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_PresenceChangedRegFailed), errorCode); } } presenceChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddMyPresenceChanged() successful."); } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <ReferencesCritical Name="Parameter safeAppChangedEvent of type: SafeCollabEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static void AddMyApplicationChanged(EventHandler<ApplicationChangedEventArgs> callback, ref EventHandler<ApplicationChangedEventArgs> applicationChanged, object lockAppChangedEvent, ref RegisteredWaitHandle regAppChangedWaitHandle, ref AutoResetEvent appChangedEvent, ref SafeCollabEvent safeAppChangedEvent, WaitOrTimerCallback ApplicationChangedCallback) { // // Register a wait handle if one has not been registered already // lock (lockAppChangedEvent){ if (applicationChanged == null){ appChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // regAppChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(appChangedEvent, //Event that triggers the callback ApplicationChangedCallback, //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.MyApplicationChanged; pcer.pInstance = IntPtr.Zero; // // Register event with collab // int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( appChangedEvent.SafeWaitHandle, 1, ref pcer, out safeAppChangedEvent); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_ApplicationChangedRegFailed), errorCode); } } applicationChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddApplicationChanged() successful."); } // <SecurityKernel Critical="True" Ring="0"> // <SatisfiesLinkDemand Name="WaitHandle.get_SafeWaitHandle():Microsoft.Win32.SafeHandles.SafeWaitHandle" /> // <CallsSuppressUnmanagedCode Name="UnsafeCollabNativeMethods.PeerCollabRegisterEvent(Microsoft.Win32.SafeHandles.SafeWaitHandle,System.UInt32,System.Net.PeerToPeer.Collaboration.PEER_COLLAB_EVENT_REGISTRATION&,System.Net.PeerToPeer.Collaboration.SafeCollabEvent&):System.Int32" /> // <ReferencesCritical Name="Parameter safeObjChangedEvent of type: SafeCollabEvent" Ring="1" /> // <ReferencesCritical Name="Method: PeerToPeerException.CreateFromHr(System.String,System.Int32):System.Net.PeerToPeer.PeerToPeerException" Ring="1" /> // </SecurityKernel> [System.Security.SecurityCritical] internal static void AddMyObjectChanged(EventHandler<ObjectChangedEventArgs> callback, ref EventHandler<ObjectChangedEventArgs> objectChanged, object lockObjChangedEvent, ref RegisteredWaitHandle regObjChangedWaitHandle, ref AutoResetEvent objChangedEvent, ref SafeCollabEvent safeObjChangedEvent, WaitOrTimerCallback ObjectChangedCallback) { // // Register a wait handle if one has not been registered already // lock (lockObjChangedEvent){ if (objectChanged == null){ objChangedEvent = new AutoResetEvent(false); // // Register callback with a wait handle // regObjChangedWaitHandle = ThreadPool.RegisterWaitForSingleObject(objChangedEvent, //Event that triggers the callback ObjectChangedCallback, //callback to be called null, //state to be passed -1, //Timeout - aplicable only for timers false //call us everytime the event is set ); PEER_COLLAB_EVENT_REGISTRATION pcer = new PEER_COLLAB_EVENT_REGISTRATION(); pcer.eventType = PeerCollabEventType.MyObjectChanged; pcer.pInstance = IntPtr.Zero; // // Register event with collab // int errorCode = UnsafeCollabNativeMethods.PeerCollabRegisterEvent( objChangedEvent.SafeWaitHandle, 1, ref pcer, out safeObjChangedEvent); if (errorCode != 0){ Logging.P2PTraceSource.TraceEvent(TraceEventType.Error, 0, "PeerCollabRegisterEvent returned with errorcode {0}", errorCode); throw PeerToPeerException.CreateFromHr(SR.GetString(SR.Collab_ObjectChangedRegFailed), errorCode); } } objectChanged += callback; } Logging.P2PTraceSource.TraceEvent(TraceEventType.Information, 0, "AddObjectChanged() successful."); } internal static void ThrowIfInvitationResponseInvalid(PeerInvitationResponse response) { // throw an exception if the response from the native API was PEER_INVITATION_RESPONSE_ERROR if (response.PeerInvitationResponseType < PeerInvitationResponseType.Declined || response.PeerInvitationResponseType > PeerInvitationResponseType.Expired) { throw new PeerToPeerException(SR.GetString(SR.Collab_InviteFailed)); } } } }
// 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.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.Implementation.F1Help; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.CSharp.LanguageService { [ExportLanguageService(typeof(IHelpContextService), LanguageNames.CSharp), Shared] internal class CSharpHelpContextService : AbstractHelpContextService { public override string Language { get { return "csharp"; } } public override string Product { get { return "csharp"; } } private static string Keyword(string text) { return text + "_CSharpKeyword"; } public override async Task<string> GetHelpTermAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); // For now, find the token under the start of the selection. var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var token = await syntaxTree.GetTouchingTokenAsync(span.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false); if (IsValid(token, span)) { var semanticModel = await document.GetSemanticModelForSpanAsync(span, cancellationToken).ConfigureAwait(false); var result = TryGetText(token, semanticModel, document, syntaxFacts, cancellationToken); if (string.IsNullOrEmpty(result)) { var previousToken = token.GetPreviousToken(); if (IsValid(previousToken, span)) { result = TryGetText(previousToken, semanticModel, document, syntaxFacts, cancellationToken); } } return result; } var trivia = root.FindTrivia(span.Start, findInsideTrivia: true); if (trivia.Span.IntersectsWith(span) && trivia.Kind() == SyntaxKind.PreprocessingMessageTrivia && trivia.Token.GetAncestor<RegionDirectiveTriviaSyntax>() != null) { return "#region"; } if (trivia.IsRegularOrDocComment()) { // just find the first "word" that intersects with our position var text = await syntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false); int start = span.Start; int end = span.Start; while (start > 0 && syntaxFacts.IsIdentifierPartCharacter(text[start - 1])) { start--; } while (end < text.Length - 1 && syntaxFacts.IsIdentifierPartCharacter(text[end])) { end++; } return text.GetSubText(TextSpan.FromBounds(start, end)).ToString(); } return string.Empty; } private bool IsValid(SyntaxToken token, TextSpan span) { // If the token doesn't actually intersect with our position, give up return token.Kind() == SyntaxKind.EndIfDirectiveTrivia || token.Span.IntersectsWith(span); } private string TryGetText(SyntaxToken token, SemanticModel semanticModel, Document document, ISyntaxFactsService syntaxFacts, CancellationToken cancellationToken) { string text = null; if (TryGetTextForContextualKeyword(token, document, syntaxFacts, out text) || TryGetTextForKeyword(token, document, syntaxFacts, out text) || TryGetTextForPreProcessor(token, document, syntaxFacts, out text) || TryGetTextForSymbol(token, semanticModel, document, cancellationToken, out text) || TryGetTextForOperator(token, document, out text)) { return text; } return string.Empty; } private bool TryGetTextForSymbol(SyntaxToken token, SemanticModel semanticModel, Document document, CancellationToken cancellationToken, out string text) { ISymbol symbol; if (token.Parent is TypeArgumentListSyntax) { var genericName = token.GetAncestor<GenericNameSyntax>(); symbol = semanticModel.GetSymbolInfo(genericName, cancellationToken).Symbol ?? semanticModel.GetTypeInfo(genericName, cancellationToken).Type; } else if (token.Parent is NullableTypeSyntax && token.IsKind(SyntaxKind.QuestionToken)) { text = "System.Nullable`1"; return true; } else { symbol = semanticModel.GetSemanticInfo(token, document.Project.Solution.Workspace, cancellationToken) .GetAnySymbol(includeType: true); if (symbol == null) { var bindableParent = document.GetLanguageService<ISyntaxFactsService>().GetBindableParent(token); var overloads = semanticModel.GetMemberGroup(bindableParent); symbol = overloads.FirstOrDefault(); } } // Local: return the name if it's the declaration, otherwise the type if (symbol is ILocalSymbol && !symbol.DeclaringSyntaxReferences.Any(d => d.GetSyntax().DescendantTokens().Contains(token))) { symbol = ((ILocalSymbol)symbol).Type; } // Range variable: use the type if (symbol is IRangeVariableSymbol) { var info = semanticModel.GetTypeInfo(token.Parent, cancellationToken); symbol = info.Type; } // Just use syntaxfacts for operators if (symbol is IMethodSymbol && ((IMethodSymbol)symbol).MethodKind == MethodKind.BuiltinOperator) { text = null; return false; } text = symbol != null ? FormatSymbol(symbol) : null; return symbol != null; } private bool TryGetTextForOperator(SyntaxToken token, Document document, out string text) { var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (syntaxFacts.IsOperator(token) || syntaxFacts.IsPredefinedOperator(token) || SyntaxFacts.IsAssignmentExpressionOperatorToken(token.Kind())) { text = Keyword(syntaxFacts.GetText(token.RawKind)); return true; } if (token.IsKind(SyntaxKind.ColonColonToken)) { text = "::_CSharpKeyword"; return true; } if (token.Kind() == SyntaxKind.ColonToken && token.Parent is NameColonSyntax) { text = "cs_namedParameter"; return true; } if (token.IsKind(SyntaxKind.QuestionToken) && token.Parent is ConditionalExpressionSyntax) { text = "?_CSharpKeyword"; return true; } if (token.IsKind(SyntaxKind.EqualsGreaterThanToken)) { text = "=>_CSharpKeyword"; return true; } if (token.IsKind(SyntaxKind.PlusEqualsToken)) { text = "+=_CSharpKeyword"; return true; } if (token.IsKind(SyntaxKind.MinusEqualsToken)) { text = "-=_CSharpKeyword"; return true; } text = null; return false; } private bool TryGetTextForPreProcessor(SyntaxToken token, Document document, ISyntaxFactsService syntaxFacts, out string text) { if (syntaxFacts.IsPreprocessorKeyword(token)) { text = "#" + token.Text; return true; } if (token.IsKind(SyntaxKind.EndOfDirectiveToken) && token.GetAncestor<RegionDirectiveTriviaSyntax>() != null) { text = "#region"; return true; } text = null; return false; } private bool TryGetTextForContextualKeyword(SyntaxToken token, Document document, ISyntaxFactsService syntaxFacts, out string text) { if (token.IsContextualKeyword()) { switch (token.Kind()) { case SyntaxKind.PartialKeyword: if (token.Parent.GetAncestorOrThis<MethodDeclarationSyntax>() != null) { text = "partialmethod_CSharpKeyword"; return true; } else if (token.Parent.GetAncestorOrThis<ClassDeclarationSyntax>() != null) { text = "partialtype_CSharpKeyword"; return true; } break; case SyntaxKind.WhereKeyword: if (token.Parent.GetAncestorOrThis<TypeParameterConstraintClauseSyntax>() != null) { text = "whereconstraint_CSharpKeyword"; } else { text = "whereclause_CSharpKeyword"; } return true; } } text = null; return false; } private bool TryGetTextForKeyword(SyntaxToken token, Document document, ISyntaxFactsService syntaxFacts, out string text) { if (token.Kind() == SyntaxKind.InKeyword) { if (token.GetAncestor<FromClauseSyntax>() != null) { text = "from_CSharpKeyword"; return true; } if (token.GetAncestor<JoinClauseSyntax>() != null) { text = "join_CSharpKeyword"; return true; } } if (token.IsKeyword()) { text = Keyword(token.Text); return true; } if (token.ValueText == "var" && token.IsKind(SyntaxKind.IdentifierToken) && token.Parent.Parent is VariableDeclarationSyntax && token.Parent == ((VariableDeclarationSyntax)token.Parent.Parent).Type) { text = "var_CSharpKeyword"; return true; } if (syntaxFacts.IsTypeNamedDynamic(token, token.Parent)) { text = "dynamic_CSharpKeyword"; return true; } text = null; return false; } private static string FormatNamespaceOrTypeSymbol(INamespaceOrTypeSymbol symbol) { var displayString = symbol.ToDisplayString(TypeFormat); var type = symbol as ITypeSymbol; if (type != null && type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T) { return "System.Nullable`1"; } if (symbol.GetTypeArguments().Any()) { return $"{displayString}`{symbol.GetTypeArguments().Length}"; } return displayString; } public override string FormatSymbol(ISymbol symbol) { if (symbol is ITypeSymbol || symbol is INamespaceSymbol) { return FormatNamespaceOrTypeSymbol((INamespaceOrTypeSymbol)symbol); } if (symbol.MatchesKind(SymbolKind.Alias, SymbolKind.Local, SymbolKind.Parameter)) { return FormatSymbol(symbol.GetSymbolType()); } var containingType = FormatNamespaceOrTypeSymbol(symbol.ContainingType); var name = symbol.ToDisplayString(NameFormat); if (symbol.IsConstructor()) { return $"{containingType}.#ctor"; } if (symbol.GetTypeArguments().Any()) { return $"{containingType}.{name}``{symbol.GetTypeArguments().Length}"; } return $"{containingType}.{name}"; } } }
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.Azure.Management.Sql.Models; namespace Microsoft.Azure.Management.Sql.Models { /// <summary> /// Represents the properties of a Service Tier Advisor. /// </summary> public partial class ServiceTierAdvisorProperties { private double? _activeTimeRatio; /// <summary> /// Optional. Gets the activeTimeRatio for service tier advisor. /// </summary> public double? ActiveTimeRatio { get { return this._activeTimeRatio; } set { this._activeTimeRatio = value; } } private double? _avgDtu; /// <summary> /// Optional. Gets or sets avgDtu for service tier advisor. /// </summary> public double? AvgDtu { get { return this._avgDtu; } set { this._avgDtu = value; } } private double _confidence; /// <summary> /// Optional. Gets or sets confidence for service tier advisor. /// </summary> public double Confidence { get { return this._confidence; } set { this._confidence = value; } } private string _currentServiceLevelObjective; /// <summary> /// Optional. Gets or sets currentServiceLevelObjective for service /// tier advisor. /// </summary> public string CurrentServiceLevelObjective { get { return this._currentServiceLevelObjective; } set { this._currentServiceLevelObjective = value; } } private System.Guid? _currentServiceLevelObjectiveId; /// <summary> /// Optional. Gets or sets currentServiceLevelObjectiveId for service /// tier advisor. /// </summary> public System.Guid? CurrentServiceLevelObjectiveId { get { return this._currentServiceLevelObjectiveId; } set { this._currentServiceLevelObjectiveId = value; } } private string _databaseSizeBasedRecommendationServiceLevelObjective; /// <summary> /// Optional. Gets or sets /// databaseSizeBasedRecommendationServiceLevelObjective for service /// tier advisor. /// </summary> public string DatabaseSizeBasedRecommendationServiceLevelObjective { get { return this._databaseSizeBasedRecommendationServiceLevelObjective; } set { this._databaseSizeBasedRecommendationServiceLevelObjective = value; } } private System.Guid? _databaseSizeBasedRecommendationServiceLevelObjectiveId; /// <summary> /// Optional. Gets or sets /// databaseSizeBasedRecommendationServiceLevelObjectiveId for service /// tier advisor. /// </summary> public System.Guid? DatabaseSizeBasedRecommendationServiceLevelObjectiveId { get { return this._databaseSizeBasedRecommendationServiceLevelObjectiveId; } set { this._databaseSizeBasedRecommendationServiceLevelObjectiveId = value; } } private string _disasterPlanBasedRecommendationServiceLevelObjective; /// <summary> /// Optional. Gets or sets /// disasterPlanBasedRecommendationServiceLevelObjective for service /// tier advisor. /// </summary> public string DisasterPlanBasedRecommendationServiceLevelObjective { get { return this._disasterPlanBasedRecommendationServiceLevelObjective; } set { this._disasterPlanBasedRecommendationServiceLevelObjective = value; } } private System.Guid? _disasterPlanBasedRecommendationServiceLevelObjectiveId; /// <summary> /// Optional. Gets or sets /// disasterPlanBasedRecommendationServiceLevelObjectiveId for service /// tier advisor. /// </summary> public System.Guid? DisasterPlanBasedRecommendationServiceLevelObjectiveId { get { return this._disasterPlanBasedRecommendationServiceLevelObjectiveId; } set { this._disasterPlanBasedRecommendationServiceLevelObjectiveId = value; } } private double? _maxDtu; /// <summary> /// Optional. Gets or sets maxDtu for service tier advisor. /// </summary> public double? MaxDtu { get { return this._maxDtu; } set { this._maxDtu = value; } } private double? _maxSizeInGB; /// <summary> /// Optional. Gets or sets maxSizeInGB for service tier advisor. /// </summary> public double? MaxSizeInGB { get { return this._maxSizeInGB; } set { this._maxSizeInGB = value; } } private double? _minDtu; /// <summary> /// Optional. Gets or sets minDtu for service tier advisor. /// </summary> public double? MinDtu { get { return this._minDtu; } set { this._minDtu = value; } } private System.DateTime? _observationPeriodEnd; /// <summary> /// Optional. Gets the observation period start. /// </summary> public System.DateTime? ObservationPeriodEnd { get { return this._observationPeriodEnd; } set { this._observationPeriodEnd = value; } } private System.DateTime? _observationPeriodStart; /// <summary> /// Optional. Gets the observation period start. /// </summary> public System.DateTime? ObservationPeriodStart { get { return this._observationPeriodStart; } set { this._observationPeriodStart = value; } } private string _overallRecommendationServiceLevelObjective; /// <summary> /// Optional. Gets or sets overallRecommendationServiceLevelObjective /// for service tier advisor. /// </summary> public string OverallRecommendationServiceLevelObjective { get { return this._overallRecommendationServiceLevelObjective; } set { this._overallRecommendationServiceLevelObjective = value; } } private System.Guid? _overallRecommendationServiceLevelObjectiveId; /// <summary> /// Optional. Gets or sets overallRecommendationServiceLevelObjectiveId /// for service tier advisor. /// </summary> public System.Guid? OverallRecommendationServiceLevelObjectiveId { get { return this._overallRecommendationServiceLevelObjectiveId; } set { this._overallRecommendationServiceLevelObjectiveId = value; } } private IList<SloUsageMetric> _serviceLevelObjectiveUsageMetrics; /// <summary> /// Optional. Gets or sets serviceLevelObjectiveUsageMetrics for the /// service tier advisor. /// </summary> public IList<SloUsageMetric> ServiceLevelObjectiveUsageMetrics { get { return this._serviceLevelObjectiveUsageMetrics; } set { this._serviceLevelObjectiveUsageMetrics = value; } } private string _usageBasedRecommendationServiceLevelObjective; /// <summary> /// Optional. Gets or sets /// usageBasedRecommendationServiceLevelObjective for service tier /// advisor. /// </summary> public string UsageBasedRecommendationServiceLevelObjective { get { return this._usageBasedRecommendationServiceLevelObjective; } set { this._usageBasedRecommendationServiceLevelObjective = value; } } private System.Guid? _usageBasedRecommendationServiceLevelObjectiveId; /// <summary> /// Optional. Gets or sets /// usageBasedRecommendationServiceLevelObjectiveId for service tier /// advisor. /// </summary> public System.Guid? UsageBasedRecommendationServiceLevelObjectiveId { get { return this._usageBasedRecommendationServiceLevelObjectiveId; } set { this._usageBasedRecommendationServiceLevelObjectiveId = value; } } /// <summary> /// Initializes a new instance of the ServiceTierAdvisorProperties /// class. /// </summary> public ServiceTierAdvisorProperties() { this.ServiceLevelObjectiveUsageMetrics = new LazyList<SloUsageMetric>(); } } }
namespace PlugInDemo.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class AbpZero_Initial : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), AuthenticationSource = c.String(maxLength: 64), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), UserName = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), EmailAddress = c.String(nullable: false, maxLength: 256), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 128), PasswordResetCode = c.String(maxLength: 128), LastLoginTime = c.DateTime(), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId) .ForeignKey("dbo.AbpTenants", t => t.TenantId) .Index(t => t.TenantId) .Index(t => t.UserId); CreateTable( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), TenancyName = c.String(nullable: false, maxLength: 64), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); } public override void Down() { DropForeignKey("dbo.AbpRoles", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles"); DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpSettings", "TenantId", "dbo.AbpTenants"); DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers"); DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" }); DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); DropIndex("dbo.AbpSettings", new[] { "UserId" }); DropIndex("dbo.AbpSettings", new[] { "TenantId" }); DropIndex("dbo.AbpUserRoles", new[] { "UserId" }); DropIndex("dbo.AbpUserLogins", new[] { "UserId" }); DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" }); DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" }); DropIndex("dbo.AbpUsers", new[] { "TenantId" }); DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" }); DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" }); DropIndex("dbo.AbpRoles", new[] { "TenantId" }); DropIndex("dbo.AbpPermissions", new[] { "UserId" }); DropIndex("dbo.AbpPermissions", new[] { "RoleId" }); DropTable("dbo.AbpTenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpSettings"); DropTable("dbo.AbpUserRoles"); DropTable("dbo.AbpUserLogins"); DropTable("dbo.AbpUsers", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpPermissions"); DropTable("dbo.AbpAuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
// 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 ILCompiler.DependencyAnalysisFramework; using Internal.IL; using Internal.Runtime; using Internal.TypeSystem; using System; using System.Collections.Generic; using Debug = System.Diagnostics.Debug; using GenericVariance = Internal.Runtime.GenericVariance; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Given a type, EETypeNode writes an EEType data structure in the format expected by the runtime. /// /// Format of an EEType: /// /// Field Size | Contents /// ----------------+----------------------------------- /// UInt16 | Component Size. For arrays this is the element type size, for strings it is 2 (.NET uses /// | UTF16 character encoding), for generic type definitions it is the number of generic parameters, /// | and 0 for all other types. /// | /// UInt16 | EETypeKind (Normal, Array, Pointer type). Flags for: IsValueType, IsCrossModule, HasPointers, /// | HasOptionalFields, IsInterface, IsGeneric. Top 5 bits are used for enum CorElementType to /// | record whether it's back by an Int32, Int16 etc /// | /// Uint32 | Base size. /// | /// [Pointer Size] | Related type. Base type for regular types. Element type for arrays / pointer types. /// | /// UInt16 | Number of VTable slots (X) /// | /// UInt16 | Number of interfaces implemented by type (Y) /// | /// UInt32 | Hash code /// | /// [Pointer Size] | Pointer to containing Module indirection cell /// | /// X * [Ptr Size] | VTable entries (optional) /// | /// Y * [Ptr Size] | Pointers to interface map data structures (optional) /// | /// [Pointer Size] | Pointer to finalizer method (optional) /// | /// [Pointer Size] | Pointer to optional fields (optional) /// | /// [Pointer Size] | Pointer to the generic type argument of a Nullable&lt;T&gt; (optional) /// | /// [Pointer Size] | Pointer to the generic type definition EEType (optional) /// | /// [Pointer Size] | Pointer to the generic argument and variance info (optional) /// </summary> internal partial class EETypeNode : ObjectNode, ISymbolNode, IEETypeNode { protected TypeDesc _type; protected EETypeOptionalFieldsBuilder _optionalFieldsBuilder = new EETypeOptionalFieldsBuilder(); public EETypeNode(TypeDesc type) { _type = type; } public override string GetName() { return ((ISymbolNode)this).MangledName; } public override bool ShouldSkipEmittingObjectNode(NodeFactory factory) { // If there is a constructed version of this node in the graph, emit that instead return ((DependencyNode)factory.ConstructedTypeSymbol(_type)).Marked; } public TypeDesc Type { get { return _type; } } public override ObjectNodeSection Section { get { if (_type.Context.Target.IsWindows) return ObjectNodeSection.ReadOnlyDataSection; else return ObjectNodeSection.DataSection; } } public override bool ShouldShareNodeAcrossModules(NodeFactory factory) { return factory.CompilationModuleGroup.ShouldShareAcrossModules(_type); } public override bool StaticDependenciesAreComputed { get { return true; } } public void SetDispatchMapIndex(int index) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.DispatchMap, checked((uint)index)); } int ISymbolNode.Offset { get { return GCDescSize; } } string ISymbolNode.MangledName { get { return "__EEType_" + NodeFactory.NameMangler.GetMangledTypeName(_type); } } public override ObjectData GetData(NodeFactory factory, bool relocsOnly) { ObjectDataBuilder objData = new ObjectDataBuilder(factory); objData.Alignment = 16; objData.DefinedSymbols.Add(this); ComputeOptionalEETypeFields(factory); OutputGCDesc(ref objData); OutputComponentSize(ref objData); OutputFlags(factory, ref objData); OutputBaseSize(ref objData); OutputRelatedType(factory, ref objData); // Avoid consulting VTable slots until they're guaranteed complete during final data emission if (!relocsOnly) { OutputVirtualSlotAndInterfaceCount(factory, ref objData); } objData.EmitInt(_type.GetHashCode()); objData.EmitPointerReloc(factory.ModuleManagerIndirection); // Avoid consulting VTable slots until they're guaranteed complete during final data emission if (!relocsOnly) { OutputVirtualSlots(factory, ref objData, _type, _type); } OutputInterfaceMap(factory, ref objData); OutputFinalizerMethod(factory, ref objData); OutputOptionalFields(factory, ref objData); OutputNullableTypeParameter(factory, ref objData); OutputGenericInstantiationDetails(factory, ref objData); return objData.ToObjectData(); } /// <summary> /// Returns the offset within an EEType of the beginning of VTable entries /// </summary> /// <param name="pointerSize">The size of a pointer in bytes in the target architecture</param> public static int GetVTableOffset(int pointerSize) { return 16 + 2 * pointerSize; } protected virtual int GCDescSize => 0; protected virtual void OutputGCDesc(ref ObjectDataBuilder builder) { // Non-constructed EETypeNodes get no GC Desc Debug.Assert(GCDescSize == 0); } private void OutputComponentSize(ref ObjectDataBuilder objData) { if (_type.IsArray) { int elementSize = ((ArrayType)_type).ElementType.GetElementSize(); if (elementSize >= 64 * 1024) { // TODO: Array of type 'X' cannot be created because base value type is too large. throw new TypeLoadException(); } objData.EmitShort((short)elementSize); } else if (_type.IsString) { objData.EmitShort(2); } else { objData.EmitShort(0); } } private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData) { UInt16 flags = EETypeBuilderHelpers.ComputeFlags(_type); if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime flags |= (UInt16)EETypeFlags.GenericVarianceFlag; } // Todo: RelatedTypeViaIATFlag when we support cross-module EETypes // Todo: Generic Type Definition EETypes if (_optionalFieldsBuilder.IsAtLeastOneFieldUsed()) { flags |= (UInt16)EETypeFlags.OptionalFieldsFlag; } objData.EmitShort((short)flags); } private void OutputBaseSize(ref ObjectDataBuilder objData) { int pointerSize = _type.Context.Target.PointerSize; int minimumObjectSize = pointerSize * 3; int objectSize; if (_type.IsDefType) { objectSize = pointerSize + ((DefType)_type).InstanceByteCount; // +pointerSize for SyncBlock if (_type.IsValueType) objectSize += pointerSize; // + EETypePtr field inherited from System.Object } else if (_type.IsArray) { objectSize = 3 * pointerSize; // SyncBlock + EETypePtr + Length if (!_type.IsSzArray) objectSize += 2 * _type.Context.GetWellKnownType(WellKnownType.Int32).GetElementSize() * ((ArrayType)_type).Rank; } else if (_type.IsPointer) { // Object size 0 is a sentinel value in the runtime for parameterized types that means "Pointer Type" objData.EmitInt(0); return; } else throw new NotImplementedException(); objectSize = AlignmentHelper.AlignUp(objectSize, pointerSize); objectSize = Math.Max(minimumObjectSize, objectSize); if (_type.IsString) { // If this is a string, throw away objectSize we computed so far. Strings are special. // SyncBlock + EETypePtr + length + firstChar objectSize = 2 * pointerSize + _type.Context.GetWellKnownType(WellKnownType.Int32).GetElementSize() + _type.Context.GetWellKnownType(WellKnownType.Char).GetElementSize(); } objData.EmitInt(objectSize); } protected virtual ISymbolNode GetBaseTypeNode(NodeFactory factory) { return _type.BaseType != null ? factory.NecessaryTypeSymbol(_type.BaseType) : null; } private void OutputRelatedType(NodeFactory factory, ref ObjectDataBuilder objData) { ISymbolNode relatedTypeNode = null; if (_type.IsArray || _type.IsPointer) { var parameterType = ((ParameterizedType)_type).ParameterType; relatedTypeNode = factory.NecessaryTypeSymbol(parameterType); } else { TypeDesc baseType = _type.BaseType; if (baseType != null) { relatedTypeNode = GetBaseTypeNode(factory); } } if (relatedTypeNode != null) { objData.EmitPointerReloc(relatedTypeNode); } else { objData.EmitZeroPointer(); } } protected virtual void OutputVirtualSlotAndInterfaceCount(NodeFactory factory, ref ObjectDataBuilder objData) { objData.EmitShort(0); objData.EmitShort(0); } protected virtual void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType) { // Non-constructed EETypes have no VTable } protected virtual void OutputInterfaceMap(NodeFactory factory, ref ObjectDataBuilder objData) { // Non-constructed EETypes have no interface map } private void OutputFinalizerMethod(NodeFactory factory, ref ObjectDataBuilder objData) { MethodDesc finalizerMethod = _type.GetFinalizer(); if (finalizerMethod != null) { objData.EmitPointerReloc(factory.MethodEntrypoint(finalizerMethod)); } } private void OutputOptionalFields(NodeFactory factory, ref ObjectDataBuilder objData) { if(_optionalFieldsBuilder.IsAtLeastOneFieldUsed()) { objData.EmitPointerReloc(factory.EETypeOptionalFields(_optionalFieldsBuilder)); } } private void OutputNullableTypeParameter(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.IsNullable) { objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.Instantiation[0])); } } private void OutputGenericInstantiationDetails(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.HasInstantiation && !_type.IsTypeDefinition) { objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.GetTypeDefinition())); GenericCompositionDetails details; if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime details = new GenericCompositionDetails(_type.Instantiation, new[] { GenericVariance.ArrayCovariant }); } else details = new GenericCompositionDetails(_type); objData.EmitPointerReloc(factory.GenericComposition(details)); } } /// <summary> /// Populate the OptionalFieldsRuntimeBuilder if any optional fields are required. /// </summary> private void ComputeOptionalEETypeFields(NodeFactory factory) { ComputeRareFlags(factory); ComputeNullableValueOffset(); ComputeICastableVirtualMethodSlots(factory); ComputeValueTypeFieldPadding(); } void ComputeRareFlags(NodeFactory factory) { uint flags = 0; if (_type.IsNullable) { flags |= (uint)EETypeRareFlags.IsNullableFlag; } if (factory.TypeSystemContext.HasLazyStaticConstructor(_type)) { flags |= (uint)EETypeRareFlags.HasCctorFlag; } if (EETypeBuilderHelpers.ComputeRequiresAlign8(_type)) { flags |= (uint)EETypeRareFlags.RequiresAlign8Flag; } if (_type.IsDefType && ((DefType)_type).IsHfa) { flags |= (uint)EETypeRareFlags.IsHFAFlag; } if (flags != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.RareFlags, flags); } } /// <summary> /// To support boxing / unboxing, the offset of the value field of a Nullable type is recorded on the EEType. /// This is variable according to the alignment requirements of the Nullable&lt;T&gt; type parameter. /// </summary> void ComputeNullableValueOffset() { if (!_type.IsNullable) return; var field = _type.GetKnownField("value"); // In the definition of Nullable<T>, the first field should be the boolean representing "hasValue" Debug.Assert(field.Offset > 0); // The contract with the runtime states the Nullable value offset is stored with the boolean "hasValue" size subtracted // to get a small encoding size win. _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.NullableValueOffset, (uint)field.Offset - 1); } /// <summary> /// ICastable is a special interface whose two methods are not invoked using regular interface dispatch. /// Instead, their VTable slots are recorded on the EEType of an object implementing ICastable and are /// called directly. /// </summary> void ComputeICastableVirtualMethodSlots(NodeFactory factory) { // TODO: This method is untested (we don't support interfaces yet) if (_type.IsInterface) return; foreach (DefType itf in _type.RuntimeInterfaces) { if (itf == factory.ICastableInterface) { var isInstMethod = itf.GetKnownMethod("IsInstanceOfInterface", null); var getImplTypeMethod = itf.GetKnownMethod("GetImplType", null); int isInstMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, isInstMethod); int getImplTypeMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, getImplTypeMethod); if (isInstMethodSlot != -1 || getImplTypeMethodSlot != -1) { var rareFlags = _optionalFieldsBuilder.GetFieldValue(EETypeOptionalFieldsElement.RareFlags, 0); rareFlags |= (uint)EETypeRareFlags.ICastableFlag; _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.RareFlags, rareFlags); } if (isInstMethodSlot != -1) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.ICastableIsInstSlot, (uint)isInstMethodSlot); } if (getImplTypeMethodSlot != -1) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.ICastableGetImplTypeSlot, (uint)getImplTypeMethodSlot); } } } } void ComputeValueTypeFieldPadding() { if (!_type.IsValueType) return; DefType defType = _type as DefType; Debug.Assert(defType != null); uint valueTypeFieldPadding = checked((uint)(defType.InstanceByteCount - defType.InstanceByteCountUnaligned)); uint valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(valueTypeFieldPadding, (uint)defType.InstanceFieldAlignment); if (valueTypeFieldPaddingEncoded != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldsElement.ValueTypeFieldPadding, valueTypeFieldPaddingEncoded); } } protected override void OnMarked(NodeFactory context) { //Debug.Assert(_type.IsTypeDefinition || !_type.HasSameTypeDefinition(context.ArrayOfTClass), "Asking for Array<T> EEType"); } } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading.Tasks; using AsyncToolkit.Runtime; namespace AsyncToolkit { [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(FutureAsyncMethodBuilder))] public partial struct Future : IEquatable<Future>, IFuture { private readonly Promise _promise; private readonly object _value; public bool IsCompleted => _promise == null || _promise.IsCompleted; public bool IsSucceeded => _promise == null || _promise.IsSucceeded; public bool IsFailed => _promise != null && _promise.IsFailed; public Exception Exception => _promise?.Exception; internal Future(object value) { _promise = null; _value = value; } internal Future(Promise promise) { _promise = promise ?? throw new ArgumentNullException(nameof(promise)); _value = null; } [Pure] internal Promise GetPromise() { return _promise; } public FutureAwaiter GetAwaiter() { return new FutureAwaiter(this); } /// <summary> /// Continue the execution on the specified scheduler after an await /// </summary> /// <param name="scheduler">The scheduler</param> /// <param name="synchronousIfCompleted"> /// Allow the continuation to bypass the scheduler and be called synchronously if the promise is already completed. /// </param> public ScheduledFutureAwaitable ContinueOn(FutureScheduler scheduler, bool synchronousIfCompleted = true) { return new ScheduledFutureAwaitable(this, scheduler, synchronousIfCompleted); } public Future ContinueWith(Action<Future> action, FutureScheduler scheduler = null) { if (IsCompleted && (scheduler == null || scheduler is SynchronousScheduler)) { try { action(this); return new Future(); } catch (Exception ex) { return Future.FromException(ex); } } var self = this; var continueWith = new Promise<VoidType>(); _promise.AddContinuation(() => { try { action(self); continueWith.SetValue(VoidType.Value); } catch (Exception ex) { continueWith.SetException(ex); } }, scheduler); return continueWith.Future; } public Future<TResult> ContinueWith<TResult>(Func<Future, TResult> func, FutureScheduler scheduler = null) { if (IsCompleted && (scheduler == null || scheduler is SynchronousScheduler)) { try { return Future.FromValue<TResult>(func(this)); } catch (Exception ex) { return Future.FromException<TResult>(ex); } } var self = this; var continueWith = new Promise<TResult>(); _promise.AddContinuation(() => { try { continueWith.SetValue(func(self)); } catch (Exception ex) { continueWith.SetException(ex); } }, scheduler); return continueWith.Future; } public Task ToTask() { if (IsCompleted) { if (IsSucceeded) return Task.CompletedTask; if (IsFailed) return Task.FromException(Exception); } var promise = _promise; var tcs = new TaskCompletionSource<VoidType>(); promise.UnsafeAddContinuation(() => { if (promise.IsSucceeded) tcs.SetResult(VoidType.Value); else tcs.SetException(promise.Exception); }); return tcs.Task; } public void ThrowIfFailed() { _promise?.ThrowIfFailed(); } Future IFuture.ToFuture() { return this; } Future<TCast> IFuture.ToFuture<TCast>() { return ToFutureOf<TCast>(); } internal Future<T> ToFutureOf<T>() { return _promise != null ? new Future<T>((Promise<T>)_promise) : new Future<T>((T)_value); } #region Equality members public override int GetHashCode() { if (_promise != null) return _promise.GetHashCode(); return RuntimeHelpers.GetHashCode(_value); } public override bool Equals(object obj) { var future = obj as IFuture; if (future != null) return Equals(future.ToFuture()); return false; } public bool Equals(Future other) { if (_promise != null || other._promise != null) return ReferenceEquals(_promise, other._promise); if (ReferenceEquals(_value, other._value)) return true; if (other._value == null) return false; if (other._value.GetType().IsValueType) return Equals(_value, other._value); return false; } public static bool operator ==(Future left, Future right) { return left.Equals(right); } public static bool operator !=(Future left, Future right) { return !left.Equals(right); } #endregion } [StructLayout(LayoutKind.Auto)] [AsyncMethodBuilder(typeof(FutureAsyncMethodBuilder<>))] public struct Future<T> : IEquatable<Future<T>>, IFuture { private readonly Promise<T> _promise; private readonly T _value; public bool IsCompleted => _promise == null || _promise.IsCompleted; public bool IsSucceeded => _promise == null || _promise.IsSucceeded; public bool IsFailed => _promise != null && _promise.IsFailed; public T Value { get { if (_promise != null) return _promise.Value; return _value; } } public Exception Exception => _promise?.Exception; internal Future(T value) { _promise = null; _value = value; } internal Future(Promise<T> promise) { _promise = promise ?? throw new ArgumentNullException(nameof(promise)); _value = default(T); } [Pure] internal Promise<T> GetPromise() { return _promise; } public FutureAwaiter<T> GetAwaiter() { return new FutureAwaiter<T>(this); } /// <summary> /// Continue the execution on the specified scheduler after an await /// </summary> /// <param name="scheduler">The scheduler</param> /// <param name="synchronousIfCompleted"> /// Allow the continuation to bypass the scheduler and be called synchronously if the promise is already completed. /// </param> public ScheduledFutureAwaitable<T> ContinueOn(FutureScheduler scheduler, bool synchronousIfCompleted = true) { return new ScheduledFutureAwaitable<T>(this, scheduler, synchronousIfCompleted); } public Future ContinueWith(Action<Future<T>> action, FutureScheduler scheduler = null) { if (IsCompleted && (scheduler == null || scheduler is SynchronousScheduler)) { try { action(this); return new Future(); } catch (Exception ex) { return Future.FromException(ex); } } var self = this; var continueWith = new Promise<VoidType>(); _promise.AddContinuation(() => { try { action(self); continueWith.SetValue(VoidType.Value); } catch (Exception ex) { continueWith.SetException(ex); } }, scheduler); return continueWith.Future; } public Future<TResult> ContinueWith<TResult>(Func<Future<T>, TResult> func, FutureScheduler scheduler = null) { if (IsCompleted && (scheduler == null || scheduler is SynchronousScheduler)) { try { return Future.FromValue(func(this)); } catch (Exception ex) { return Future.FromException<TResult>(ex); } } var self = this; var continueWith = new Promise<TResult>(); _promise.AddContinuation(() => { try { continueWith.SetValue(func(self)); } catch (Exception ex) { continueWith.SetException(ex); } }, scheduler); return continueWith.Future; } public Task<T> ToTask() { if (IsCompleted) { if (IsSucceeded) return Task.FromResult(Value); if (IsFailed) return Task.FromException<T>(Exception); } var promise = _promise; var tcs = new TaskCompletionSource<T>(); promise.UnsafeAddContinuation(() => { if (promise.IsSucceeded) tcs.SetResult(promise.Value); else tcs.SetException(promise.Exception); }); return tcs.Task; } public void ThrowIfFailed() { _promise?.ThrowIfFailed(); } Future IFuture.ToFuture() { return this; } Future<TCast> IFuture.ToFuture<TCast>() { return _promise != null ? new Future<TCast>((Promise<TCast>)(object)_promise) : new Future<TCast>((TCast)(object)_value); } public static implicit operator Future(Future<T> future) { return future._promise != null ? new Future(future._promise) : new Future(future._value); } public static explicit operator Future<T>(Future future) { return future.ToFutureOf<T>(); } #region Equality members public override int GetHashCode() { if (_promise != null) return _promise.GetHashCode(); if (_value is ValueType) return _value.GetHashCode(); return RuntimeHelpers.GetHashCode(_value); } public override bool Equals(object obj) { if (obj is Future<T>) return Equals((Future<T>)obj); if (obj is Future) return ((Future)obj).Equals((Future)this); return false; } public bool Equals(Future<T> other) { if (_promise != null || other._promise != null) return ReferenceEquals(_promise, other._promise); if (default(T) is ValueType) return EqualityComparer<T>.Default.Equals(_value, other._value); return ReferenceEquals(_value, other._value); } public static bool operator ==(Future<T> left, Future<T> right) { return left.Equals(right); } public static bool operator !=(Future<T> left, Future<T> right) { return !left.Equals(right); } #endregion } }
// // PreviewPopup.cs // // Author: // Ruben Vermeersch <[email protected]> // Larry Ewing <[email protected]> // // Copyright (C) 2004-2010 Novell, Inc. // Copyright (C) 2008, 2010 Ruben Vermeersch // Copyright (C) 2004-2006 Larry Ewing // // 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 Cairo; using Gdk; using FSpot.Core; using FSpot.Widgets; using FSpot.Utils; using FSpot.Gui; namespace FSpot.Widgets { public class PreviewPopup : Gtk.Window { readonly CollectionGridView view; readonly Gtk.Image image; readonly Gtk.Label label; bool show_histogram; public bool ShowHistogram { get { return show_histogram; } set { if (value != show_histogram) item = -1; show_histogram = value; } } readonly Histogram hist; DisposableCache<string, Pixbuf> preview_cache = new DisposableCache<string, Pixbuf> (50); int item = -1; public int Item { get { return item; } set { if (value != item) { item = value; UpdateImage (); } UpdatePosition (); } } void AddHistogram (Pixbuf pixbuf) { if (show_histogram) { Pixbuf image = hist.Generate (pixbuf); double scalex = 0.5; double scaley = 0.5; int width = (int)(image.Width * scalex); int height = (int)(image.Height * scaley); image.Composite (pixbuf, pixbuf.Width - width - 10, pixbuf.Height - height - 10, width, height, pixbuf.Width - width - 10, pixbuf.Height - height - 10, scalex, scaley, InterpType.Bilinear, 200); } } protected override void OnRealized () { bool composited = CompositeUtils.IsComposited (Screen) && CompositeUtils.SetRgbaColormap (this); AppPaintable = composited; base.OnRealized (); } protected override bool OnExposeEvent (EventExpose args) { int round = 12; Context g = CairoHelper.Create (GdkWindow); g.Operator = Operator.Source; g.SetSource (new SolidPattern (new Cairo.Color (0, 0, 0, 0))); g.Paint (); g.Operator = Operator.Over; g.SetSource (new SolidPattern (new Cairo.Color (0, 0, 0, .7))); g.MoveTo (round, 0); //g.LineTo (Allocation.Width - round, 0); g.Arc (Allocation.Width - round, round, round, - Math.PI * 0.5, 0); //g.LineTo (Allocation.Width, Allocation.Height - round); g.Arc (Allocation.Width - round, Allocation.Height - round, round, 0, Math.PI * 0.5); //g.LineTo (round, Allocation.Height); g.Arc (round, Allocation.Height - round, round, Math.PI * 0.5, Math.PI); g.Arc (round, round, round, Math.PI, Math.PI * 1.5); g.ClosePath (); g.Fill (); g.Dispose (); return base.OnExposeEvent (args); } void UpdateImage () { IPhoto item = view.Collection [Item]; string orig_path = item.DefaultVersion.Uri.LocalPath; Pixbuf pixbuf = FSpot.Utils.PixbufUtils.ShallowCopy (preview_cache.Get (orig_path + show_histogram)); if (pixbuf == null) { // A bizarre pixbuf = hack to try to deal with cinematic displays, etc. int preview_size = ((Screen.Width + Screen.Height)/2)/3; try { pixbuf = PhotoLoader.LoadAtMaxSize (item, preview_size, preview_size); } catch (Exception) { pixbuf = null; } if (pixbuf != null) { preview_cache.Add (orig_path + show_histogram, pixbuf); AddHistogram (pixbuf); image.Pixbuf = pixbuf; } else { image.Pixbuf = PixbufUtils.ErrorPixbuf; } } else { image.Pixbuf = pixbuf; pixbuf.Dispose (); } string desc = String.Empty; if (!string.IsNullOrEmpty (item.Description)) desc = item.Description + Environment.NewLine; desc += item.Time + " " + item.Name; label.Text = desc; } void UpdatePosition () { int x, y; Gdk.Rectangle bounds = view.CellBounds (Item); Gtk.Requisition requisition = SizeRequest (); Resize (requisition.Width, requisition.Height); view.GdkWindow.GetOrigin (out x, out y); // Acount for scrolling bounds.X -= (int)view.Hadjustment.Value; bounds.Y -= (int)view.Vadjustment.Value; // calculate the cell center x += bounds.X + (bounds.Width / 2); y += bounds.Y + (bounds.Height / 2); // find the window's x location limiting it to the screen x = Math.Max (0, x - requisition.Width / 2); x = Math.Min (x, Screen.Width - requisition.Width); // find the window's y location offset above or below depending on space y = Math.Max (0, y - requisition.Height / 2); y = Math.Min (y, Screen.Height - requisition.Height); Move (x, y); } void UpdateItem (int x, int y) { int itemAtPosition = view.CellAtPosition (x, y); if (itemAtPosition >= 0) { Item = itemAtPosition; Show (); } else { Hide (); } } void UpdateItem () { int x, y; view.GetPointer (out x, out y); x += (int) view.Hadjustment.Value; y += (int) view.Vadjustment.Value; UpdateItem (x, y); } void HandleIconViewMotion (object sender, Gtk.MotionNotifyEventArgs args) { if (!Visible) return; int x = (int) args.Event.X; int y = (int) args.Event.Y; view.GrabFocus (); UpdateItem (x, y); } void HandleIconViewKeyPress (object sender, Gtk.KeyPressEventArgs args) { switch (args.Event.Key) { case Key.v: ShowHistogram = false; UpdateItem (); args.RetVal = true; break; case Key.V: ShowHistogram = true; UpdateItem (); args.RetVal = true; break; } } void HandleKeyRelease (object sender, Gtk.KeyReleaseEventArgs args) { switch (args.Event.Key) { case Key.v: case Key.V: case Key.h: Hide (); break; } } void HandleButtonPress (object sender, Gtk.ButtonPressEventArgs args) { Hide (); } void HandleIconViewDestroy (object sender, Gtk.DestroyEventArgs args) { Destroy (); } void HandleDestroyed (object sender, EventArgs args) { preview_cache.Dispose (); } protected override bool OnMotionNotifyEvent (EventMotion args) { // // We look for motion events on the popup window so that // if the pointer manages to get over the window we can // Update the image properly and/or get out of the way. // UpdateItem (); return false; } public PreviewPopup (SelectionCollectionGridView view) : base (Gtk.WindowType.Toplevel) { var vbox = new Gtk.VBox (); Add (vbox); AddEvents ((int) (EventMask.PointerMotionMask | EventMask.KeyReleaseMask | EventMask.ButtonPressMask)); Decorated = false; SkipTaskbarHint = true; SkipPagerHint = true; SetPosition (Gtk.WindowPosition.None); KeyReleaseEvent += HandleKeyRelease; ButtonPressEvent += HandleButtonPress; Destroyed += HandleDestroyed; this.view = view; view.MotionNotifyEvent += HandleIconViewMotion; view.KeyPressEvent += HandleIconViewKeyPress; view.KeyReleaseEvent += HandleKeyRelease; view.DestroyEvent += HandleIconViewDestroy; BorderWidth = 6; hist = new Histogram (); hist.RedColorHint = 127; hist.GreenColorHint = 127; hist.BlueColorHint = 127; hist.BackgroundColorHint = 0xff; image = new Gtk.Image (); image.CanFocus = false; label = new Gtk.Label (String.Empty); label.CanFocus = false; label.ModifyFg (Gtk.StateType.Normal, new Gdk.Color (127, 127, 127)); label.ModifyBg (Gtk.StateType.Normal, new Gdk.Color (0, 0, 0)); ModifyFg (Gtk.StateType.Normal, new Gdk.Color (127, 127, 127)); ModifyBg (Gtk.StateType.Normal, new Gdk.Color (0, 0, 0)); vbox.PackStart (image, true, true, 0); vbox.PackStart (label, true, false, 0); vbox.ShowAll (); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ClosedXML.Excel { internal class XLConditionalFormat: IXLConditionalFormat, IXLStylized { public XLConditionalFormat(XLRange range, Boolean copyDefaultModify = false) { Range = range; Style = new XLStyle(this, range.Worksheet.Style); Values = new XLDictionary<XLFormula>(); Colors = new XLDictionary<XLColor>(); ContentTypes = new XLDictionary<XLCFContentType>(); IconSetOperators = new XLDictionary<XLCFIconSetOperator>(); CopyDefaultModify = copyDefaultModify; } public XLConditionalFormat(XLConditionalFormat other) { Range = other.Range; Style = new XLStyle(this, other.Style); Values = new XLDictionary<XLFormula>(other.Values); Colors = new XLDictionary<XLColor>(other.Colors); ContentTypes = new XLDictionary<XLCFContentType>(other.ContentTypes); IconSetOperators = new XLDictionary<XLCFIconSetOperator>(other.IconSetOperators); ConditionalFormatType = other.ConditionalFormatType; TimePeriod = other.TimePeriod; IconSetStyle = other.IconSetStyle; Operator = other.Operator; Bottom = other.Bottom; Percent = other.Percent; ReverseIconOrder = other.ReverseIconOrder; ShowIconOnly = other.ShowIconOnly; ShowBarOnly = other.ShowBarOnly; } public Boolean CopyDefaultModify { get; set; } private IXLStyle _style; private Int32 _styleCacheId; public IXLStyle Style{ get { return GetStyle(); } set { SetStyle(value); } } private IXLStyle GetStyle() { //return _style; if (_style != null) return _style; return _style = new XLStyle(this, Range.Worksheet.Workbook.GetStyleById(_styleCacheId), CopyDefaultModify); } private void SetStyle(IXLStyle styleToUse) { //_style = new XLStyle(this, styleToUse); _styleCacheId = Range.Worksheet.Workbook.GetStyleId(styleToUse); _style = null; StyleChanged = false; } public IEnumerable<IXLStyle> Styles { get { UpdatingStyle = true; yield return Style; UpdatingStyle = false; } } public bool UpdatingStyle { get; set; } public IXLStyle InnerStyle { get; set; } public IXLRanges RangesUsed { get { return new XLRanges(); } } public bool StyleChanged { get; set; } public XLDictionary<XLFormula> Values { get; private set; } public XLDictionary<XLColor> Colors { get; private set; } public XLDictionary<XLCFContentType> ContentTypes { get; private set; } public XLDictionary<XLCFIconSetOperator> IconSetOperators { get; private set; } public IXLRange Range { get; set; } public XLConditionalFormatType ConditionalFormatType { get; set; } public XLTimePeriod TimePeriod { get; set; } public XLIconSetStyle IconSetStyle { get; set; } public XLCFOperator Operator { get; set; } public Boolean Bottom { get; set; } public Boolean Percent { get; set; } public Boolean ReverseIconOrder { get; set; } public Boolean ShowIconOnly { get; set; } public Boolean ShowBarOnly { get; set; } public void CopyFrom(IXLConditionalFormat other) { Style = other.Style; ConditionalFormatType = other.ConditionalFormatType; TimePeriod = other.TimePeriod; IconSetStyle = other.IconSetStyle; Operator = other.Operator; Bottom = other.Bottom; Percent = other.Percent; ReverseIconOrder = other.ReverseIconOrder; ShowIconOnly = other.ShowIconOnly; ShowBarOnly = other.ShowBarOnly; Values.Clear(); other.Values.ForEach(kp => Values.Add(kp.Key, new XLFormula(kp.Value))); //CopyDictionary(Values, other.Values); CopyDictionary(Colors, other.Colors); CopyDictionary(ContentTypes, other.ContentTypes); CopyDictionary(IconSetOperators, other.IconSetOperators); } private void CopyDictionary<T>(XLDictionary<T> target, XLDictionary<T> source) { target.Clear(); source.ForEach(kp => target.Add(kp.Key, kp.Value)); } public IXLStyle WhenIsBlank() { ConditionalFormatType = XLConditionalFormatType.IsBlank; return Style; } public IXLStyle WhenNotBlank() { ConditionalFormatType = XLConditionalFormatType.NotBlank; return Style; } public IXLStyle WhenIsError() { ConditionalFormatType = XLConditionalFormatType.IsError; return Style; } public IXLStyle WhenNotError() { ConditionalFormatType = XLConditionalFormatType.NotError; return Style; } public IXLStyle WhenDateIs(XLTimePeriod timePeriod) { TimePeriod = timePeriod; ConditionalFormatType = XLConditionalFormatType.TimePeriod; return Style; } public IXLStyle WhenContains(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.ContainsText; Operator = XLCFOperator.Contains; return Style; } public IXLStyle WhenNotContains(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.NotContainsText; Operator = XLCFOperator.NotContains; return Style; } public IXLStyle WhenStartsWith(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.StartsWith; Operator = XLCFOperator.StartsWith; return Style; } public IXLStyle WhenEndsWith(String value) { Values.Initialize(new XLFormula { Value = value }); ConditionalFormatType = XLConditionalFormatType.EndsWith; Operator = XLCFOperator.EndsWith; return Style; } public IXLStyle WhenEquals(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.Equal; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotEquals(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.NotEqual; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenGreaterThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.GreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenLessThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.LessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrGreaterThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.EqualOrGreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrLessThan(String value) { Values.Initialize(new XLFormula { Value = value }); Operator = XLCFOperator.EqualOrLessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenBetween(String minValue, String maxValue) { Values.Initialize(new XLFormula { Value = minValue }); Values.Add(new XLFormula { Value = maxValue }); Operator = XLCFOperator.Between; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotBetween(String minValue, String maxValue) { Values.Initialize(new XLFormula { Value = minValue }); Values.Add(new XLFormula { Value = maxValue }); Operator = XLCFOperator.NotBetween; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEquals(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.Equal; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotEquals(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.NotEqual; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenGreaterThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.GreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenLessThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.LessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrGreaterThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.EqualOrGreaterThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenEqualOrLessThan(Double value) { Values.Initialize(new XLFormula(value)); Operator = XLCFOperator.EqualOrLessThan; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenBetween(Double minValue, Double maxValue) { Values.Initialize(new XLFormula (minValue)); Values.Add(new XLFormula(maxValue)); Operator = XLCFOperator.Between; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenNotBetween(Double minValue, Double maxValue) { Values.Initialize(new XLFormula(minValue)); Values.Add(new XLFormula(maxValue)); Operator = XLCFOperator.NotBetween; ConditionalFormatType = XLConditionalFormatType.CellIs; return Style; } public IXLStyle WhenIsDuplicate() { ConditionalFormatType = XLConditionalFormatType.IsDuplicate; return Style; } public IXLStyle WhenIsUnique() { ConditionalFormatType = XLConditionalFormatType.IsUnique; return Style; } public IXLStyle WhenIsTrue(String formula) { String f = formula.TrimStart()[0] == '=' ? formula : "=" + formula; Values.Initialize(new XLFormula {Value = f}); ConditionalFormatType = XLConditionalFormatType.Expression; return Style; } public IXLStyle WhenIsTop(Int32 value, XLTopBottomType topBottomType = XLTopBottomType.Items) { Values.Initialize(new XLFormula(value)); Percent = topBottomType == XLTopBottomType.Percent; ConditionalFormatType = XLConditionalFormatType.Top10; Bottom = false; return Style; } public IXLStyle WhenIsBottom(Int32 value, XLTopBottomType topBottomType = XLTopBottomType.Items) { Values.Initialize(new XLFormula(value)); Percent = topBottomType == XLTopBottomType.Percent; ConditionalFormatType = XLConditionalFormatType.Top10; Bottom = true; return Style; } public IXLCFColorScaleMin ColorScale() { ConditionalFormatType = XLConditionalFormatType.ColorScale; return new XLCFColorScaleMin(this); } public IXLCFDataBarMin DataBar(XLColor color, Boolean showBarOnly = false) { Colors.Initialize(color); ShowBarOnly = showBarOnly; ConditionalFormatType = XLConditionalFormatType.DataBar; return new XLCFDataBarMin(this); } public IXLCFIconSet IconSet(XLIconSetStyle iconSetStyle, Boolean reverseIconOrder = false, Boolean showIconOnly = false) { IconSetOperators.Clear(); Values.Clear(); ContentTypes.Clear(); ConditionalFormatType = XLConditionalFormatType.IconSet; IconSetStyle = iconSetStyle; ReverseIconOrder = reverseIconOrder; ShowIconOnly = showIconOnly; return new XLCFIconSet(this); } } }
using System.Collections.Generic; using System.IO; using System.Xml; using NUnit.Framework; namespace SIL.WritingSystems.Tests { [TestFixture] public class LdmlInXmlWritingSystemRepositoryInterfaceTests : WritingSystemRepositoryTests { public override IWritingSystemRepository CreateNewStore() { return new LdmlInXmlWritingSystemRepository(); } } [TestFixture] public class LdmlInXmlWritingSystemRepositoryTests { private string _testFilePath; private LdmlInXmlWritingSystemRepository _writingSystemRepository; [SetUp] public void Setup() { _testFilePath = Path.GetTempFileName(); _writingSystemRepository = new LdmlInXmlWritingSystemRepository(); } [TearDown] public void TearDown() { File.Delete(_testFilePath); } private void WriteLdmlFile(string filePath, IEnumerable<WritingSystemDefinition> writingSystems) { XmlWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("someroot"); xmlWriter.WriteStartElement("writingsystems"); var adaptor = new LdmlDataMapper(_writingSystemRepository.WritingSystemFactory); foreach (WritingSystemDefinition ws in writingSystems) { adaptor.Write(xmlWriter, ws, null); } xmlWriter.WriteEndElement(); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); } private void WriteAllDefinitionsToFile(string filePath, LdmlInXmlWritingSystemRepository repository) { XmlWriter xmlWriter = new XmlTextWriter(filePath, System.Text.Encoding.UTF8); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("someroot"); repository.SaveAllDefinitions(xmlWriter); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); } [Test] public void SaveAllToXmlReaderReadAsFile_ReadsBackCorrect() { WritingSystemDefinition ws1 = new WritingSystemDefinition(); ws1.Language = "en"; _writingSystemRepository.Set(ws1); WritingSystemDefinition ws2 = new WritingSystemDefinition(); ws2.Language = "fr"; _writingSystemRepository.Set(ws2); Assert.AreEqual(2, _writingSystemRepository.Count); XmlWriter xmlWriter = new XmlTextWriter(_testFilePath, System.Text.Encoding.UTF8); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("someroot"); _writingSystemRepository.SaveAllDefinitions(xmlWriter); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); LdmlInXmlWritingSystemRepository testRepository = new LdmlInXmlWritingSystemRepository(); Assert.AreEqual(0, testRepository.Count); testRepository.LoadAllDefinitions(_testFilePath); Assert.AreEqual(2, testRepository.Count); } [Test] public void SaveAllToXmlReaderReadAsXmlReader_ReadsBackCorrect() { WritingSystemDefinition ws1 = new WritingSystemDefinition(); ws1.Language = "en"; _writingSystemRepository.Set(ws1); WritingSystemDefinition ws2 = new WritingSystemDefinition(); ws2.Language = "fr"; _writingSystemRepository.Set(ws2); Assert.AreEqual(2, _writingSystemRepository.Count); XmlWriter xmlWriter = new XmlTextWriter(_testFilePath, System.Text.Encoding.UTF8); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("someroot"); _writingSystemRepository.SaveAllDefinitions(xmlWriter); xmlWriter.WriteEndElement(); xmlWriter.WriteEndDocument(); xmlWriter.Close(); XmlReader xmlReader = new XmlTextReader(new StreamReader(_testFilePath)); xmlReader.ReadToFollowing("writingsystems"); LdmlInXmlWritingSystemRepository testRepository = new LdmlInXmlWritingSystemRepository(); Assert.AreEqual(0, testRepository.Count); testRepository.LoadAllDefinitions(xmlReader); Assert.AreEqual(2, testRepository.Count); xmlReader.Close(); } #if false [Test] public void SavesWhenNotPreexisting() { _writingSystemRepository.StoreDefinition(_writingSystem); AssertWritingSystemFileExists(_writingSystem); } private void AssertWritingSystemFileExists(WritingSystemDefinition writingSystem) { AssertWritingSystemFileExists(writingSystem, _writingSystemRepository); } private void AssertWritingSystemFileExists(WritingSystemDefinition writingSystem, LdmlInXmlWritingSystemRepository repository) { string path = repository.PathToWritingSystem(writingSystem); Assert.IsTrue(File.Exists(path)); } [Test] public void FileNameWhenNothingKnown() { Assert.AreEqual("unknown.ldml", _writingSystemRepository.GetFileName(_writingSystem)); } [Test] public void FileNameWhenOnlyHaveIso() { _writingSystem.ISO = "en"; Assert.AreEqual("en.ldml", _writingSystemRepository.GetFileName(_writingSystem)); } [Test] public void FileNameWhenHaveIsoAndRegion() { _writingSystem.ISO = "en"; _writingSystem.Region = "us"; Assert.AreEqual("en-us.ldml", _writingSystemRepository.GetFileName(_writingSystem)); } [Test] public void SavesWhenPreexisting() { _writingSystem.ISO = "en"; _writingSystemRepository.StoreDefinition(_writingSystem); _writingSystemRepository.StoreDefinition(_writingSystem); WritingSystemDefinition ws2 = new WritingSystemDefinition(); _writingSystem.ISO = "en"; _writingSystemRepository.StoreDefinition(ws2); } [Test] public void RegressionWhereUnchangedDefDeleted() { _writingSystem.ISO = "blah"; _writingSystemRepository.StoreDefinition(_writingSystem); WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("blah"); _writingSystemRepository.StoreDefinition(ws2); AssertWritingSystemFileExists(_writingSystem); } [Test] public void SavesWhenDirectoryNotFound() { var newRepository = new LdmlInXmlWritingSystemRepository(); newRepository.StoreDefinition(_writingSystem); AssertWritingSystemFileExists(_writingSystem, newRepository); } [Test] public void UpdatesFileNameWhenISOChanges() { _writingSystem.ISO = "1"; _writingSystemRepository.StoreDefinition(_writingSystem); string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, "1.ldml"); Assert.IsTrue(File.Exists(path)); WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("1"); ws2.ISO = "2"; _writingSystemRepository.StoreDefinition(ws2); Assert.IsFalse(File.Exists(path)); path = Path.Combine(_writingSystemRepository.PathToWritingSystems, "2.ldml"); Assert.IsTrue(File.Exists(path)); } [Test] public void MakesNewFileIfNeeded() { _writingSystem.ISO = "blah"; _writingSystemRepository.StoreDefinition(_writingSystem); AssertXmlFile.AtLeastOneMatch(PathToWS, "ldml/identity/language[@type='blah']"); } [Test] public void CanSetVariantToLDMLUsingSameWS() { _writingSystemRepository.StoreDefinition(_writingSystem); _writingSystem.Variant = "piglatin"; _writingSystemRepository.StoreDefinition(_writingSystem); AssertXmlFile.AtLeastOneMatch(PathToWS, "ldml/identity/variant[@type='piglatin']"); } [Test] public void CanSetVariantToExistingLDML() { _writingSystem.ISO = "blah"; _writingSystem.Abbreviation = "bl";//crucially, abbreviation isn't part of the name of the file _writingSystemRepository.StoreDefinition(_writingSystem); //here, the task is not to overwrite what was in ther already WritingSystemDefinition ws2 = new WritingSystemDefinition(); ws2 = _writingSystemRepository.LoadDefinition("blah"); ws2.Variant = "piglatin"; _writingSystemRepository.StoreDefinition(ws2); string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, _writingSystemRepository.GetFileName(ws2)); AssertXmlFile.AtLeastOneMatch(path, "ldml/identity/variant[@type='piglatin']"); AssertXmlFile.AtLeastOneMatch(path, "ldml/special/palaso:abbreviation[@value='bl']", LdmlAdaptor.MakeNameSpaceManager()); } [Test] public void CanReadVariant() { _writingSystem.ISO = "en"; _writingSystem.Variant = "piglatin"; _writingSystemRepository.StoreDefinition(_writingSystem); //here, the task is not to overwrite what was in ther already WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("en-piglatin"); Assert.AreEqual("piglatin", ws2.Variant); } [Test] public void CanSaveAndReadDefaultFont() { _writingSystem.ISO = "en"; _writingSystem.DefaultFontName = "Courier"; _writingSystemRepository.StoreDefinition(_writingSystem); //here, the task is not to overwrite what was in ther already WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("en"); Assert.AreEqual("Courier", ws2.DefaultFontName); } [Test] public void CanSaveAndReadKeyboardName() { _writingSystem.ISO = "en"; _writingSystem.Keyboard = "Thai"; _writingSystemRepository.StoreDefinition(_writingSystem); //here, the task is not to overwrite what was in ther already WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("en"); Assert.AreEqual("Thai", ws2.Keyboard); } [Test] public void CanSaveAndReadRightToLeft() { _writingSystem.ISO = "en"; Assert.IsFalse(_writingSystem.RightToLeftScript); _writingSystem.RightToLeftScript = true; Assert.IsTrue(_writingSystem.RightToLeftScript); _writingSystemRepository.StoreDefinition(_writingSystem); //here, the task is not to overwrite what was in ther already WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("en"); Assert.IsTrue(ws2.RightToLeftScript); } [Test] public void CanRemoveVariant() { _writingSystem.ISO = "en"; _writingSystem.Variant = "piglatin"; _writingSystemRepository.StoreDefinition(_writingSystem); string path = _writingSystemRepository.PathToWritingSystem(_writingSystem); AssertXmlFile.AtLeastOneMatch(path, "ldml/identity/variant"); _writingSystem.Variant = string.Empty; _writingSystemRepository.StoreDefinition(_writingSystem); TestUtilities.AssertXPathIsNull(PathToWS, "ldml/identity/variant"); } [Test] public void CanRemoveAbbreviation() { _writingSystem.ISO = "en"; _writingSystem.Abbreviation = "abbrev"; _writingSystemRepository.StoreDefinition(_writingSystem); string path = _writingSystemRepository.PathToWritingSystem(_writingSystem); AssertXmlFile.AtLeastOneMatch(path, "ldml/special/palaso:abbreviation", LdmlAdaptor.MakeNameSpaceManager()); _writingSystem.Abbreviation = string.Empty; _writingSystemRepository.StoreDefinition(_writingSystem); TestUtilities.AssertXPathIsNull(PathToWS, "ldml/special/palaso:abbreviation", LdmlAdaptor.MakeNameSpaceManager()); } [Test] public void WritesAbbreviationToLDML() { _writingSystem.ISO = "blah"; _writingSystem.Abbreviation = "bl"; _writingSystemRepository.StoreDefinition(_writingSystem); AssertXmlFile.AtLeastOneMatch(PathToWS, "ldml/special/palaso:abbreviation[@value='bl']", LdmlAdaptor.MakeNameSpaceManager()); } private string PathToWS { get { return _writingSystemRepository.PathToWritingSystem(_writingSystem); } } [Test] public void CanDeleteFileThatIsNotInTrash() { _writingSystem.ISO = "blah"; _writingSystemRepository.StoreDefinition(_writingSystem); string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, _writingSystemRepository.GetFileName(_writingSystem)); Assert.IsTrue(File.Exists(path)); _writingSystemRepository.DeleteDefinition(_writingSystem); Assert.IsFalse(File.Exists(path)); AssertFileIsInTrash(_writingSystem); } private void AssertFileIsInTrash(WritingSystemDefinition definition) { string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, "trash"); path = Path.Combine(path, _writingSystemRepository.GetFileName(definition)); Assert.IsTrue(File.Exists(path)); } [Test] public void CanDeleteFileMatchingOneThatWasPreviouslyTrashed() { _writingSystem.ISO = "blah"; _writingSystemRepository.StoreDefinition(_writingSystem); _writingSystemRepository.DeleteDefinition(_writingSystem); AssertFileIsInTrash(_writingSystem); WritingSystemDefinition ws2 = new WritingSystemDefinition(); ws2.ISO = "blah"; _writingSystemRepository.StoreDefinition(ws2); _writingSystemRepository.DeleteDefinition(ws2); string path = Path.Combine(_writingSystemRepository.PathToWritingSystems, _writingSystemRepository.GetFileName(_writingSystem)); Assert.IsFalse(File.Exists(path)); AssertFileIsInTrash(_writingSystem); } [Test] public void MarkedNotModifiedWhenNew() { //not worth saving until has some data Assert.IsFalse(_writingSystem.Modified); } [Test] public void MarkedAsModifiedWhenISOChanges() { _writingSystem.ISO = "foo"; Assert.IsTrue(_writingSystem.Modified); } [Test] public void MarkedAsNotModifiedWhenLoaded() { _writingSystem.ISO = "blah"; _writingSystemRepository.StoreDefinition(_writingSystem); WritingSystemDefinition ws2 = _writingSystemRepository.LoadDefinition("blah"); Assert.IsFalse(ws2.Modified); } [Test] public void MarkedAsNotModifiedWhenSaved() { _writingSystem.ISO = "bla"; Assert.IsTrue(_writingSystem.Modified); _writingSystemRepository.StoreDefinition(_writingSystem); Assert.IsFalse(_writingSystem.Modified); _writingSystem.ISO = "foo"; Assert.IsTrue(_writingSystem.Modified); } [Test] public void LoadDefinitionCanFabricateEnglish() { _writingSystemRepository.DontSetDefaultDefinitions = false; Assert.AreEqual("English", _writingSystemRepository.LoadDefinition("en-Latn").LanguageName); } [Test] public void DefaultDefinitionListIncludesActiveOSLanguages() { _writingSystemRepository.DontSetDefaultDefinitions = false; _writingSystemRepository.SystemWritingSystemProvider = new DummyWritingSystemProvider(); IList<WritingSystemDefinition> list = _writingSystemRepository.WritingSystemDefinitions; Assert.IsTrue(ContainsLanguageWithName(list, "test")); } [Test] public void DefaultLanguageNotSetedIfInTrash() { _writingSystemRepository.DontSetDefaultDefinitions = false; _writingSystemRepository.SystemWritingSystemProvider = new DummyWritingSystemProvider(); IList<WritingSystemDefinition> list = _writingSystemRepository.WritingSystemDefinitions; Assert.IsTrue(ContainsLanguageWithName(list, "test")); WritingSystemDefinition ws2 = _writingSystemRepository.WritingSystemDefinitions[0]; Assert.IsNotNull(ws2); _writingSystemRepository.DeleteDefinition(ws2); var repository = new LdmlInXmlWritingSystemRepository(_testDir); repository.DontSetDefaultDefinitions = false; repository.SystemWritingSystemProvider = new DummyWritingSystemProvider(); Assert.IsFalse(ContainsLanguageWithName(repository.WritingSystemDefinitions, "test")); } private bool ContainsLanguageWithName(IList<WritingSystemDefinition> list, string name) { foreach (WritingSystemDefinition definition in list) { if (definition.LanguageName == name) return true; } return false; } class DummyWritingSystemProvider : IEnumerable<WritingSystemDefinition> { #region IEnumerable<WritingSystemDefinition> Members public IEnumerable<WritingSystemDefinition> ActiveOSLanguages { get { yield return new WritingSystemDefinition("tst", "", "", "", "test", "", false); } } #endregion } #endif } }
namespace Humidifier.Budgets { using System.Collections.Generic; using BudgetTypes; public class Budget : Humidifier.Resource { public override string AWSTypeName { get { return @"AWS::Budgets::Budget"; } } /// <summary> /// NotificationsWithSubscribers /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-budgets-budget.html#cfn-budgets-budget-notificationswithsubscribers /// Required: False /// UpdateType: Immutable /// Type: List /// ItemType: NotificationWithSubscribers /// </summary> public List<NotificationWithSubscribers> NotificationsWithSubscribers { get; set; } /// <summary> /// Budget /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-budgets-budget.html#cfn-budgets-budget-budget /// Required: True /// UpdateType: Mutable /// Type: BudgetData /// </summary> public BudgetData Budget_ { get; set; } } namespace BudgetTypes { public class BudgetData { /// <summary> /// BudgetLimit /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-budgetdata.html#cfn-budgets-budget-budgetdata-budgetlimit /// Required: False /// UpdateType: Mutable /// Type: Spend /// </summary> public Spend BudgetLimit { get; set; } /// <summary> /// TimePeriod /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-budgetdata.html#cfn-budgets-budget-budgetdata-timeperiod /// Required: False /// UpdateType: Mutable /// Type: TimePeriod /// </summary> public TimePeriod TimePeriod { get; set; } /// <summary> /// TimeUnit /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-budgetdata.html#cfn-budgets-budget-budgetdata-timeunit /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic TimeUnit { get; set; } /// <summary> /// PlannedBudgetLimits /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-budgetdata.html#cfn-budgets-budget-budgetdata-plannedbudgetlimits /// Required: False /// UpdateType: Immutable /// PrimitiveType: Json /// </summary> public dynamic PlannedBudgetLimits { get; set; } /// <summary> /// CostFilters /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-budgetdata.html#cfn-budgets-budget-budgetdata-costfilters /// Required: False /// UpdateType: Mutable /// PrimitiveType: Json /// </summary> public dynamic CostFilters { get; set; } /// <summary> /// BudgetName /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-budgetdata.html#cfn-budgets-budget-budgetdata-budgetname /// Required: False /// UpdateType: Immutable /// PrimitiveType: String /// </summary> public dynamic BudgetName { get; set; } /// <summary> /// CostTypes /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-budgetdata.html#cfn-budgets-budget-budgetdata-costtypes /// Required: False /// UpdateType: Mutable /// Type: CostTypes /// </summary> public CostTypes CostTypes { get; set; } /// <summary> /// BudgetType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-budgetdata.html#cfn-budgets-budget-budgetdata-budgettype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic BudgetType { get; set; } } public class CostTypes { /// <summary> /// IncludeSupport /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includesupport /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeSupport { get; set; } /// <summary> /// IncludeOtherSubscription /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includeothersubscription /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeOtherSubscription { get; set; } /// <summary> /// IncludeTax /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includetax /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeTax { get; set; } /// <summary> /// IncludeSubscription /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includesubscription /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeSubscription { get; set; } /// <summary> /// UseBlended /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-useblended /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic UseBlended { get; set; } /// <summary> /// IncludeUpfront /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includeupfront /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeUpfront { get; set; } /// <summary> /// IncludeDiscount /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includediscount /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeDiscount { get; set; } /// <summary> /// IncludeCredit /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includecredit /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeCredit { get; set; } /// <summary> /// IncludeRecurring /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includerecurring /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeRecurring { get; set; } /// <summary> /// UseAmortized /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-useamortized /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic UseAmortized { get; set; } /// <summary> /// IncludeRefund /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includerefund /// Required: False /// UpdateType: Mutable /// PrimitiveType: Boolean /// </summary> public dynamic IncludeRefund { get; set; } } public class NotificationWithSubscribers { /// <summary> /// Subscribers /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-notificationwithsubscribers.html#cfn-budgets-budget-notificationwithsubscribers-subscribers /// Required: True /// UpdateType: Mutable /// Type: List /// ItemType: Subscriber /// </summary> public List<Subscriber> Subscribers { get; set; } /// <summary> /// Notification /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-notificationwithsubscribers.html#cfn-budgets-budget-notificationwithsubscribers-notification /// Required: True /// UpdateType: Mutable /// Type: Notification /// </summary> public Notification Notification { get; set; } } public class Subscriber { /// <summary> /// SubscriptionType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-subscriber.html#cfn-budgets-budget-subscriber-subscriptiontype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic SubscriptionType { get; set; } /// <summary> /// Address /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-subscriber.html#cfn-budgets-budget-subscriber-address /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Address { get; set; } } public class Notification { /// <summary> /// ComparisonOperator /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-notification.html#cfn-budgets-budget-notification-comparisonoperator /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ComparisonOperator { get; set; } /// <summary> /// NotificationType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-notification.html#cfn-budgets-budget-notification-notificationtype /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic NotificationType { get; set; } /// <summary> /// Threshold /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-notification.html#cfn-budgets-budget-notification-threshold /// Required: True /// UpdateType: Mutable /// PrimitiveType: Double /// </summary> public dynamic Threshold { get; set; } /// <summary> /// ThresholdType /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-notification.html#cfn-budgets-budget-notification-thresholdtype /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic ThresholdType { get; set; } } public class TimePeriod { /// <summary> /// Start /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-timeperiod.html#cfn-budgets-budget-timeperiod-start /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Start { get; set; } /// <summary> /// End /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-timeperiod.html#cfn-budgets-budget-timeperiod-end /// Required: False /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic End { get; set; } } public class Spend { /// <summary> /// Amount /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-spend.html#cfn-budgets-budget-spend-amount /// Required: True /// UpdateType: Mutable /// PrimitiveType: Double /// </summary> public dynamic Amount { get; set; } /// <summary> /// Unit /// http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-spend.html#cfn-budgets-budget-spend-unit /// Required: True /// UpdateType: Mutable /// PrimitiveType: String /// </summary> public dynamic Unit { get; set; } } } }
//Added SortedList.cs - System.Collections.SortedList implementation. namespace Morph.Collections { /// <summary> /// Represents a collection of associated keys and values /// that are sorted by the keys and are accessible by key /// and by index. /// </summary> public class SortedList : System.Collections.IDictionary, System.Collections.ICollection, System.Collections.IEnumerable, System.ICloneable { internal struct Slot { internal object key; internal object value; } const int INITIAL_SIZE = 16; private enum EnumeratorMode : int { KEY_MODE = 0, VALUE_MODE, ENTRY_MODE } private int inUse; private int modificationCount; private Slot[] table; private System.Collections.IComparer comparer; private int defaultCapacity; // // Constructors // public SortedList() : this(null, INITIAL_SIZE) { } public SortedList(int initialCapacity) : this(null, initialCapacity) { } public SortedList(System.Collections.IComparer comparer, int capacity) { if (capacity < 0) throw new System.ArgumentOutOfRangeException("capacity"); if (capacity == 0) defaultCapacity = 0; else defaultCapacity = INITIAL_SIZE; this.comparer = comparer; InitTable(capacity, true); } public SortedList(System.Collections.IComparer comparer) { this.comparer = comparer; InitTable(INITIAL_SIZE, true); } public SortedList(System.Collections.IDictionary d) : this(d, null) { } // LAMESPEC: MSDN docs talk about an InvalidCastException but // I wasn't able to duplicate such a case in the unit tests. public SortedList(System.Collections.IDictionary d, System.Collections.IComparer comparer) { if (d == null) throw new System.ArgumentNullException("dictionary"); InitTable(d.Count, true); this.comparer = comparer; System.Collections.IDictionaryEnumerator it = d.GetEnumerator(); while (it.MoveNext()) { Add(it.Key, it.Value); } } // // Properties // // ICollection public virtual int Count { get { return inUse; } } public virtual bool IsSynchronized { get { return false; } } public virtual object SyncRoot { get { return this; } } // IDictionary public virtual bool IsFixedSize { get { return false; } } public virtual bool IsReadOnly { get { return false; } } public virtual System.Collections.ICollection Keys { get { return new ListKeys(this); } } public virtual System.Collections.ICollection Values { get { return new ListValues(this); } } public virtual object this[object key] { get { if (key == null) throw new System.ArgumentNullException(); return GetImpl(key); } set { if (key == null) throw new System.ArgumentNullException(); if (IsReadOnly) throw new System.NotSupportedException("SortedList is Read Only."); if (Find(key) < 0 && IsFixedSize) throw new System.NotSupportedException("Key not found and SortedList is fixed size."); PutImpl(key, value, true); } } public virtual int Capacity { get { return table.Length; } set { int current = this.table.Length; if (inUse > value) { throw new System.ArgumentOutOfRangeException("capacity too small"); } else if (value == 0) { // return to default size Slot[] newTable = new Slot[defaultCapacity]; System.Array.Copy(table, newTable, inUse); this.table = newTable; } else if (value > inUse) { Slot[] newTable = new Slot[value]; System.Array.Copy(table, newTable, inUse); this.table = newTable; } else if (value > current) { Slot[] newTable = new Slot[value]; System.Array.Copy(table, newTable, current); this.table = newTable; } } } // // Public instance methods. // // IEnumerable System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this, EnumeratorMode.ENTRY_MODE); } // IDictionary public virtual void Add(object key, object value) { PutImpl(key, value, false); } public virtual void Clear() { defaultCapacity = INITIAL_SIZE; this.table = new Slot[defaultCapacity]; inUse = 0; modificationCount++; } public virtual bool Contains(object key) { if (null == key) throw new System.ArgumentNullException(); try { return (Find(key) >= 0); } catch (System.Exception) { throw new System.InvalidOperationException(); } } public virtual System.Collections.IDictionaryEnumerator GetEnumerator() { return new Enumerator(this, EnumeratorMode.ENTRY_MODE); } public virtual void Remove(object key) { int i = IndexOfKey(key); if (i >= 0) RemoveAt(i); } // ICollection public virtual void CopyTo(System.Array array, int arrayIndex) { if (null == array) throw new System.ArgumentNullException(); if (arrayIndex < 0) throw new System.ArgumentOutOfRangeException(); if (array.Rank > 1) throw new System.ArgumentException("array is multi-dimensional"); if (arrayIndex >= array.Length) throw new System.ArgumentNullException("arrayIndex is greater than or equal to array.Length"); if (Count > (array.Length - arrayIndex)) throw new System.ArgumentNullException("Not enough space in array from arrayIndex to end of array"); System.Collections.IDictionaryEnumerator it = GetEnumerator(); int i = arrayIndex; while (it.MoveNext()) { array.SetValue(it.Entry, i++); } } // ICloneable public virtual object Clone() { SortedList sl = new SortedList(this, comparer); sl.modificationCount = this.modificationCount; return sl; } // // SortedList // public virtual System.Collections.IList GetKeyList() { return new ListKeys(this); } public virtual System.Collections.IList GetValueList() { return new ListValues(this); } public virtual void RemoveAt(int index) { Slot[] table = this.table; int cnt = Count; if (index >= 0 && index < cnt) { if (index != cnt - 1) { System.Array.Copy(table, index + 1, table, index, cnt - 1 - index); } else { table[index].key = null; table[index].value = null; } --inUse; ++modificationCount; } else { throw new System.ArgumentOutOfRangeException("index out of range"); } } public virtual int IndexOfKey(object key) { if (null == key) throw new System.ArgumentNullException(); int indx = 0; try { indx = Find(key); } catch (System.Exception) { throw new System.InvalidOperationException(); } return (indx | (indx >> 31)); } public virtual int IndexOfValue(object value) { if (inUse == 0) return -1; for (int i = 0; i < inUse; i++) { Slot current = this.table[i]; if (Equals(value, current.value)) return i; } return -1; } public virtual bool ContainsKey(object key) { if (null == key) throw new System.ArgumentNullException(); try { return Contains(key); } catch (System.Exception) { throw new System.InvalidOperationException(); } } public virtual bool ContainsValue(object value) { return IndexOfValue(value) >= 0; } public virtual object GetByIndex(int index) { if (index >= 0 && index < Count) return table[index].value; else throw new System.ArgumentOutOfRangeException("index out of range"); } public virtual void SetByIndex(int index, object value) { if (index >= 0 && index < Count) table[index].value = value; else throw new System.ArgumentOutOfRangeException("index out of range"); } public virtual object GetKey(int index) { if (index >= 0 && index < Count) return table[index].key; else throw new System.ArgumentOutOfRangeException("index out of range"); } public static SortedList Synchronized(SortedList list) { if (list == null) throw new System.ArgumentNullException("Base list is null."); return new SynchedSortedList(list); } public virtual void TrimToSize() { // From Beta2: // Trimming an empty SortedList sets the capacity // of the SortedList to the default capacity, // not zero. if (Count == 0) Resize(defaultCapacity, false); else Resize(Count, true); } // // Private methods // private void Resize(int n, bool copy) { Slot[] table = this.table; Slot[] newTable = new Slot[n]; if (copy) System.Array.Copy(table, 0, newTable, 0, n); this.table = newTable; } private void EnsureCapacity(int n, int free) { Slot[] table = this.table; Slot[] newTable = null; int cap = Capacity; bool gap = (free >= 0 && free < Count); if (n > cap) { newTable = new Slot[n << 1]; } if (newTable != null) { if (gap) { int copyLen = free; if (copyLen > 0) { System.Array.Copy(table, 0, newTable, 0, copyLen); } copyLen = Count - free; if (copyLen > 0) { System.Array.Copy(table, free, newTable, free + 1, copyLen); } } else { // Just a resizing, copy the entire table. System.Array.Copy(table, newTable, Count); } this.table = newTable; } else if (gap) { System.Array.Copy(table, free, table, free + 1, Count - free); } } private void PutImpl(object key, object value, bool overwrite) { if (key == null) throw new System.ArgumentNullException("null key"); Slot[] table = this.table; int freeIndx = -1; try { freeIndx = Find(key); } catch (System.Exception) { throw new System.InvalidOperationException(); } if (freeIndx >= 0) { if (!overwrite) { throw new System.ArgumentException("Key '" + key.ToString() + "' already exists in list."); } table[freeIndx].value = value; ++modificationCount; return; } freeIndx = ~freeIndx; if (freeIndx > Capacity + 1) throw new System.Exception("SortedList::internal error (" + key.ToString() + ", " + value.ToString() + ") at [" + freeIndx.ToString() + "]"); EnsureCapacity(Count + 1, freeIndx); table = this.table; table[freeIndx].key = key; table[freeIndx].value = value; ++inUse; ++modificationCount; } private object GetImpl(object key) { int i = Find(key); if (i >= 0) return table[i].value; else return null; } private void InitTable(int capacity, bool forceSize) { if (!forceSize && (capacity < defaultCapacity)) capacity = defaultCapacity; this.table = new Slot[capacity]; this.inUse = 0; this.modificationCount = 0; } private void CopyToArray(System.Array arr, int i, EnumeratorMode mode) { if (arr == null) throw new System.ArgumentNullException("arr"); if (i < 0 || i + this.Count > arr.Length) throw new System.ArgumentOutOfRangeException("i"); System.Collections.IEnumerator it = new Enumerator(this, mode); while (it.MoveNext()) { arr.SetValue(it.Current, i++); } } private int Find(object key) { Slot[] table = this.table; int len = Count; if (len == 0) return ~0; System.Collections.IComparer comparer = (this.comparer == null)? System.Collections.Comparer.Default : this.comparer; int left = 0; int right = len - 1; while (left <= right) { int guess = (left + right) >> 1; int cmp = comparer.Compare(table[guess].key, key); if (cmp == 0) return guess; if (cmp < 0) left = guess + 1; else right = guess - 1; } return ~left; } // // Inner classes // private sealed class Enumerator : System.ICloneable, System.Collections.IDictionaryEnumerator, System.Collections.IEnumerator { private SortedList host; private int stamp; private int pos; private int size; private EnumeratorMode mode; private object currentKey; private object currentValue; bool invalid = false; private readonly static string xstr = "SortedList.Enumerator: snapshot out of sync."; public Enumerator(SortedList host, EnumeratorMode mode) { this.host = host; stamp = host.modificationCount; size = host.Count; this.mode = mode; Reset(); } public Enumerator(SortedList host) : this(host, EnumeratorMode.ENTRY_MODE) { } public void Reset() { if (host.modificationCount != stamp || invalid) throw new System.InvalidOperationException(xstr); pos = -1; currentKey = null; currentValue = null; } public bool MoveNext() { if (host.modificationCount != stamp || invalid) throw new System.InvalidOperationException(xstr); Slot[] table = host.table; if (++pos < size) { Slot entry = table[pos]; currentKey = entry.key; currentValue = entry.value; return true; } currentKey = null; currentValue = null; return false; } public System.Collections.DictionaryEntry Entry { get { if (invalid || pos >= size || pos == -1) throw new System.InvalidOperationException(xstr); return new System.Collections.DictionaryEntry(currentKey, currentValue); } } public object Key { get { if (invalid || pos >= size || pos == -1) throw new System.InvalidOperationException(xstr); return currentKey; } } public object Value { get { if (invalid || pos >= size || pos == -1) throw new System.InvalidOperationException(xstr); return currentValue; } } public object Current { get { if (invalid || pos >= size || pos == -1) throw new System.InvalidOperationException(xstr); switch (mode) { case EnumeratorMode.KEY_MODE: return currentKey; case EnumeratorMode.VALUE_MODE: return currentValue; case EnumeratorMode.ENTRY_MODE: return this.Entry; default: throw new System.NotSupportedException(mode + " is not a supported mode."); } } } // ICloneable public object Clone() { Enumerator e = new Enumerator(host, mode); e.stamp = stamp; e.pos = pos; e.size = size; e.currentKey = currentKey; e.currentValue = currentValue; e.invalid = invalid; return e; } } private class ListKeys : System.Collections.IList, System.Collections.IEnumerable { private SortedList host; public ListKeys(SortedList host) { if (host == null) throw new System.ArgumentNullException(); this.host = host; } // // ICollection // public virtual int Count { get { return host.Count; } } public virtual bool IsSynchronized { get { return host.IsSynchronized; } } public virtual object SyncRoot { get { return host.SyncRoot; } } public virtual void CopyTo(System.Array array, int arrayIndex) { host.CopyToArray(array, arrayIndex, EnumeratorMode.KEY_MODE); } // // IList // public virtual bool IsFixedSize { get { return true; } } public virtual bool IsReadOnly { get { return true; } } public virtual object this[int index] { get { return host.GetKey(index); } set { throw new System.NotSupportedException("attempt to modify a key"); } } public virtual int Add(object value) { throw new System.NotSupportedException("IList::Add not supported"); } public virtual void Clear() { throw new System.NotSupportedException("IList::Clear not supported"); } public virtual bool Contains(object key) { return host.Contains(key); } public virtual int IndexOf(object key) { return host.IndexOfKey(key); } public virtual void Insert(int index, object value) { throw new System.NotSupportedException("IList::Insert not supported"); } public virtual void Remove(object value) { throw new System.NotSupportedException("IList::Remove not supported"); } public virtual void RemoveAt(int index) { throw new System.NotSupportedException("IList::RemoveAt not supported"); } // // IEnumerable // public virtual System.Collections.IEnumerator GetEnumerator() { return new SortedList.Enumerator(host, EnumeratorMode.KEY_MODE); } } private class ListValues : System.Collections.IList, System.Collections.IEnumerable { private SortedList host; public ListValues(SortedList host) { if (host == null) throw new System.ArgumentNullException(); this.host = host; } // // ICollection // public virtual int Count { get { return host.Count; } } public virtual bool IsSynchronized { get { return host.IsSynchronized; } } public virtual object SyncRoot { get { return host.SyncRoot; } } public virtual void CopyTo(System.Array array, int arrayIndex) { host.CopyToArray(array, arrayIndex, EnumeratorMode.VALUE_MODE); } // // IList // public virtual bool IsFixedSize { get { return true; } } public virtual bool IsReadOnly { get { return true; } } public virtual object this[int index] { get { return host.GetByIndex(index); } set { throw new System.NotSupportedException("This operation is not supported on GetValueList return"); } } public virtual int Add(object value) { throw new System.NotSupportedException("IList::Add not supported"); } public virtual void Clear() { throw new System.NotSupportedException("IList::Clear not supported"); } public virtual bool Contains(object value) { return host.ContainsValue(value); } public virtual int IndexOf(object value) { return host.IndexOfValue(value); } public virtual void Insert(int index, object value) { throw new System.NotSupportedException("IList::Insert not supported"); } public virtual void Remove(object value) { throw new System.NotSupportedException("IList::Remove not supported"); } public virtual void RemoveAt(int index) { throw new System.NotSupportedException("IList::RemoveAt not supported"); } // // IEnumerable // public virtual System.Collections.IEnumerator GetEnumerator() { return new SortedList.Enumerator(host, EnumeratorMode.VALUE_MODE); } } private class SynchedSortedList : SortedList { private SortedList host; public SynchedSortedList(SortedList host) { if (host == null) throw new System.ArgumentNullException(); this.host = host; } public override int Capacity { get { lock (host.SyncRoot) { return host.Capacity; } } set { lock (host.SyncRoot) { host.Capacity = value; } } } // ICollection public override int Count { get { return host.Count; } } public override bool IsSynchronized { get { return true; } } public override object SyncRoot { get { return host.SyncRoot; } } // IDictionary public override bool IsFixedSize { get { return host.IsFixedSize; } } public override bool IsReadOnly { get { return host.IsReadOnly; } } public override System.Collections.ICollection Keys { get { System.Collections.ICollection keys = null; lock (host.SyncRoot) { keys = host.Keys; } return keys; } } public override System.Collections.ICollection Values { get { System.Collections.ICollection vals = null; lock (host.SyncRoot) { vals = host.Values; } return vals; } } public override object this[object key] { get { lock (host.SyncRoot) { return host.GetImpl(key); } } set { lock (host.SyncRoot) { host.PutImpl(key, value, true); } } } // ICollection public override void CopyTo(System.Array array, int arrayIndex) { lock (host.SyncRoot) { host.CopyTo(array, arrayIndex); } } // IDictionary public override void Add(object key, object value) { lock (host.SyncRoot) { host.PutImpl(key, value, false); } } public override void Clear() { lock (host.SyncRoot) { host.Clear(); } } public override bool Contains(object key) { lock (host.SyncRoot) { return (host.Find(key) >= 0); } } public override System.Collections.IDictionaryEnumerator GetEnumerator() { lock (host.SyncRoot) { return host.GetEnumerator(); } } public override void Remove(object key) { lock (host.SyncRoot) { host.Remove(key); } } public override bool ContainsKey(object key) { lock (host.SyncRoot) { return host.Contains(key); } } public override bool ContainsValue(object value) { lock (host.SyncRoot) { return host.ContainsValue(value); } } // ICloneable public override object Clone() { lock (host.SyncRoot) { return (host.Clone() as SortedList); } } // // SortedList overrides // public override object GetByIndex(int index) { lock (host.SyncRoot) { return host.GetByIndex(index); } } public override object GetKey(int index) { lock (host.SyncRoot) { return host.GetKey(index); } } public override System.Collections.IList GetKeyList() { lock (host.SyncRoot) { return new ListKeys(host); } } public override System.Collections.IList GetValueList() { lock (host.SyncRoot) { return new ListValues(host); } } public override void RemoveAt(int index) { lock (host.SyncRoot) { host.RemoveAt(index); } } public override int IndexOfKey(object key) { lock (host.SyncRoot) { return host.IndexOfKey(key); } } public override int IndexOfValue(object val) { lock (host.SyncRoot) { return host.IndexOfValue(val); } } public override void SetByIndex(int index, object value) { lock (host.SyncRoot) { host.SetByIndex(index, value); } } public override void TrimToSize() { lock (host.SyncRoot) { host.TrimToSize(); } } } // SynchedSortedList } // SortedList } // System.Collections
using System; using Xunit; using Xunit.Sdk; namespace FluentAssertions.Specs.Primitives { public class NullableBooleanAssertionSpecs { [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_have_a_value_it_should_succeed() { // Arrange bool? nullableBoolean = true; // Act / Assert nullableBoolean.Should().HaveValue(); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_not_be_null_it_should_succeed() { // Arrange bool? nullableBoolean = true; // Act / Assert nullableBoolean.Should().NotBeNull(); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_have_a_value_it_should_fail() { // Arrange bool? nullableBoolean = null; // Act Action act = () => nullableBoolean.Should().HaveValue(); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_not_be_null_it_should_fail() { // Arrange bool? nullableBoolean = null; // Act Action act = () => nullableBoolean.Should().NotBeNull(); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_have_a_value_it_should_fail_with_descriptive_message() { // Arrange bool? nullableBoolean = null; // Act Action act = () => nullableBoolean.Should().HaveValue("because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("Expected a value because we want to test the failure message."); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_not_be_null_it_should_fail_with_descriptive_message() { // Arrange bool? nullableBoolean = null; // Act Action act = () => nullableBoolean.Should().NotBeNull("because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("Expected a value because we want to test the failure message."); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_not_have_a_value_it_should_succeed() { // Arrange bool? nullableBoolean = null; // Act / Assert nullableBoolean.Should().NotHaveValue(); } [Fact] public void When_asserting_nullable_boolean_value_without_a_value_to_be_null_it_should_succeed() { // Arrange bool? nullableBoolean = null; // Act / Assert nullableBoolean.Should().BeNull(); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_not_have_a_value_it_should_fail() { // Arrange bool? nullableBoolean = true; // Act Action act = () => nullableBoolean.Should().NotHaveValue(); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_be_null_it_should_fail() { // Arrange bool? nullableBoolean = true; // Act Action act = () => nullableBoolean.Should().BeNull(); // Assert act.Should().Throw<XunitException>(); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_be_not_have_a_value_it_should_fail_with_descriptive_message() { // Arrange bool? nullableBoolean = true; // Act Action act = () => nullableBoolean.Should().NotHaveValue("because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("Did not expect a value because we want to test the failure message, but found True."); } [Fact] public void When_asserting_nullable_boolean_value_with_a_value_to_be_null_it_should_fail_with_descriptive_message() { // Arrange bool? nullableBoolean = true; // Act Action act = () => nullableBoolean.Should().BeNull("because we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("Did not expect a value because we want to test the failure message, but found True."); } [Fact] public void When_asserting_boolean_null_value_is_false_it_should_fail() { // Arrange bool? nullableBoolean = null; // Act Action action = () => nullableBoolean.Should().BeFalse("we want to test the failure {0}", "message"); // Assert action.Should().Throw<XunitException>() .WithMessage("Expected nullableBoolean to be false because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_boolean_null_value_is_true_it_sShould_fail() { // Arrange bool? nullableBoolean = null; // Act Action action = () => nullableBoolean.Should().BeTrue("we want to test the failure {0}", "message"); // Assert action.Should().Throw<XunitException>() .WithMessage("Expected nullableBoolean to be true because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_boolean_null_value_to_be_equal_to_different_nullable_boolean_should_fail() { // Arrange bool? nullableBoolean = null; bool? differentNullableBoolean = false; // Act Action action = () => nullableBoolean.Should().Be(differentNullableBoolean, "we want to test the failure {0}", "message"); // Assert action.Should().Throw<XunitException>() .WithMessage("Expected False because we want to test the failure message, but found <null>."); } [Fact] public void When_asserting_boolean_null_value_to_be_equal_to_null_it_should_succeed() { // Arrange bool? nullableBoolean = null; bool? otherNullableBoolean = null; // Act Action action = () => nullableBoolean.Should().Be(otherNullableBoolean); // Assert action.Should().NotThrow(); } [Fact] public void When_asserting_true_is_not_false_it_should_succeed() { // Arrange bool? trueBoolean = true; // Act Action action = () => trueBoolean.Should().NotBeFalse(); // Assert action.Should().NotThrow(); } [Fact] public void When_asserting_null_is_not_false_it_should_succeed() { // Arrange bool? nullValue = null; // Act Action action = () => nullValue.Should().NotBeFalse(); // Assert action.Should().NotThrow(); } [Fact] public void When_asserting_false_is_not_false_it_should_fail_with_descriptive_message() { // Arrange bool? falseBoolean = false; // Act Action action = () => falseBoolean.Should().NotBeFalse("we want to test the failure message"); // Assert action.Should().Throw<XunitException>() .WithMessage("Expected*falseBoolean*not*False*because we want to test the failure message, but found False."); } [Fact] public void When_asserting_false_is_not_true_it_should_succeed() { // Arrange bool? trueBoolean = false; // Act Action action = () => trueBoolean.Should().NotBeTrue(); // Assert action.Should().NotThrow(); } [Fact] public void When_asserting_null_is_not_true_it_should_succeed() { // Arrange bool? nullValue = null; // Act Action action = () => nullValue.Should().NotBeTrue(); // Assert action.Should().NotThrow(); } [Fact] public void When_asserting_true_is_not_true_it_should_fail_with_descriptive_message() { // Arrange bool? falseBoolean = true; // Act Action action = () => falseBoolean.Should().NotBeTrue("we want to test the failure message"); // Assert action.Should().Throw<XunitException>() .WithMessage("Expected*falseBoolean*not*True*because we want to test the failure message, but found True."); } [Fact] public void Should_support_chaining_constraints_with_and() { // Arrange bool? nullableBoolean = true; // Act / Assert nullableBoolean.Should() .HaveValue() .And .BeTrue(); } } }
using Lucene.Net.Attributes; using Lucene.Net.Diagnostics; using NUnit.Framework; using System; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Util.Packed { /* * 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. */ [TestFixture] public class TestEliasFanoSequence : LuceneTestCase { private static EliasFanoEncoder MakeEncoder(long[] values, long indexInterval) { long upperBound = -1L; foreach (long value in values) { Assert.IsTrue(value >= upperBound); // test data ok upperBound = value; } EliasFanoEncoder efEncoder = new EliasFanoEncoder(values.Length, upperBound, indexInterval); foreach (long value in values) { efEncoder.EncodeNext(value); } return efEncoder; } private static void TstDecodeAllNext(long[] values, EliasFanoDecoder efd) { efd.ToBeforeSequence(); long nextValue = efd.NextValue(); foreach (long expValue in values) { Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == nextValue, "nextValue at end too early"); Assert.AreEqual(expValue, nextValue); nextValue = efd.NextValue(); } Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, nextValue); } private static void TstDecodeAllPrev(long[] values, EliasFanoDecoder efd) { efd.ToAfterSequence(); for (int i = values.Length - 1; i >= 0; i--) { long previousValue = efd.PreviousValue(); Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == previousValue, "previousValue at end too early"); Assert.AreEqual(values[i], previousValue); } Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, efd.PreviousValue()); } private static void TstDecodeAllAdvanceToExpected(long[] values, EliasFanoDecoder efd) { efd.ToBeforeSequence(); long previousValue = -1L; long index = 0; foreach (long expValue in values) { if (expValue > previousValue) { long advanceValue = efd.AdvanceToValue(expValue); Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == advanceValue, "advanceValue at end too early"); Assert.AreEqual(expValue, advanceValue); Assert.AreEqual(index, efd.CurrentIndex()); previousValue = expValue; } index++; } long advanceValue_ = efd.AdvanceToValue(previousValue + 1); Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, advanceValue_, "at end"); } private static void TstDecodeAdvanceToMultiples(long[] values, EliasFanoDecoder efd, long m) { // test advancing to multiples of m if (Debugging.AssertsEnabled) Debugging.Assert(m > 0); long previousValue = -1L; long index = 0; long mm = m; efd.ToBeforeSequence(); foreach (long expValue in values) { // mm > previousValue if (expValue >= mm) { long advanceValue = efd.AdvanceToValue(mm); Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == advanceValue, "advanceValue at end too early"); Assert.AreEqual(expValue, advanceValue); Assert.AreEqual(index, efd.CurrentIndex()); previousValue = expValue; do { mm += m; } while (mm <= previousValue); } index++; } long advanceValue_ = efd.AdvanceToValue(mm); Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, advanceValue_); } private static void TstDecodeBackToMultiples(long[] values, EliasFanoDecoder efd, long m) { // test backing to multiples of m if (Debugging.AssertsEnabled) Debugging.Assert(m > 0); efd.ToAfterSequence(); int index = values.Length - 1; if (index < 0) { long advanceValue = efd.BackToValue(0); Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, advanceValue); return; // empty values, nothing to go back to/from } long expValue = values[index]; long previousValue = expValue + 1; long mm = (expValue / m) * m; while (index >= 0) { expValue = values[index]; if (Debugging.AssertsEnabled) Debugging.Assert(mm < previousValue); if (expValue <= mm) { long backValue_ = efd.BackToValue(mm); Assert.IsFalse(EliasFanoDecoder.NO_MORE_VALUES == backValue_, "backToValue at end too early"); Assert.AreEqual(expValue, backValue_); Assert.AreEqual(index, efd.CurrentIndex()); previousValue = expValue; do { mm -= m; } while (mm >= previousValue); } index--; } long backValue = efd.BackToValue(mm); Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, backValue); } private static void TstEqual(string mes, long[] exp, long[] act) { Assert.AreEqual(exp.Length, act.Length, mes + ".Length"); for (int i = 0; i < exp.Length; i++) { if (exp[i] != act[i]) { Assert.Fail(mes + "[" + i + "] " + exp[i] + " != " + act[i]); } } } private static void TstDecodeAll(EliasFanoEncoder efEncoder, long[] values) { TstDecodeAllNext(values, efEncoder.GetDecoder()); TstDecodeAllPrev(values, efEncoder.GetDecoder()); TstDecodeAllAdvanceToExpected(values, efEncoder.GetDecoder()); } private static void TstEFS(long[] values, long[] expHighLongs, long[] expLowLongs) { EliasFanoEncoder efEncoder = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL); TstEqual("upperBits", expHighLongs, efEncoder.UpperBits); TstEqual("lowerBits", expLowLongs, efEncoder.LowerBits); TstDecodeAll(efEncoder, values); } private static void TstEFS2(long[] values) { EliasFanoEncoder efEncoder = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL); TstDecodeAll(efEncoder, values); } private static void TstEFSadvanceToAndBackToMultiples(long[] values, long maxValue, long minAdvanceMultiple) { EliasFanoEncoder efEncoder = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL); for (long m = minAdvanceMultiple; m <= maxValue; m += 1) { TstDecodeAdvanceToMultiples(values, efEncoder.GetDecoder(), m); TstDecodeBackToMultiples(values, efEncoder.GetDecoder(), m); } } private EliasFanoEncoder TstEFVI(long[] values, long indexInterval, long[] expIndexBits) { EliasFanoEncoder efEncVI = MakeEncoder(values, indexInterval); TstEqual("upperZeroBitPositionIndex", expIndexBits, efEncVI.IndexBits); return efEncVI; } [Test] public virtual void TestEmpty() { long[] values = new long[0]; long[] expHighBits = new long[0]; long[] expLowBits = new long[0]; TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestOneValue1() { long[] values = new long[] { 0 }; long[] expHighBits = new long[] { 0x1L }; long[] expLowBits = new long[] { }; TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestTwoValues1() { long[] values = new long[] { 0, 0 }; long[] expHighBits = new long[] { 0x3L }; long[] expLowBits = new long[] { }; TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestOneValue2() { long[] values = new long[] { 63 }; long[] expHighBits = new long[] { 2 }; long[] expLowBits = new long[] { 31 }; TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestOneMaxValue() { long[] values = new long[] { long.MaxValue }; long[] expHighBits = new long[] { 2 }; long[] expLowBits = new long[] { long.MaxValue / 2 }; TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestTwoMinMaxValues() { long[] values = new long[] { 0, long.MaxValue }; long[] expHighBits = new long[] { 0x11 }; long[] expLowBits = new long[] { unchecked((long)0xE000000000000000L), 0x03FFFFFFFFFFFFFFL }; TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestTwoMaxValues() { long[] values = new long[] { long.MaxValue, long.MaxValue }; long[] expHighBits = new long[] { 0x18 }; long[] expLowBits = new long[] { -1L, 0x03FFFFFFFFFFFFFFL }; TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestExample1() // Figure 1 from Vigna 2012 paper { long[] values = new long[] { 5, 8, 8, 15, 32 }; long[] expLowBits = new long[] { Convert.ToInt64("0011000001", 2) }; // reverse block and bit order long[] expHighBits = new long[] { Convert.ToInt64("1000001011010", 2) }; // reverse block and bit order TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestHashCodeEquals() { long[] values = new long[] { 5, 8, 8, 15, 32 }; EliasFanoEncoder efEncoder1 = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL); EliasFanoEncoder efEncoder2 = MakeEncoder(values, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL); Assert.AreEqual(efEncoder1, efEncoder2); Assert.AreEqual(efEncoder1.GetHashCode(), efEncoder2.GetHashCode()); EliasFanoEncoder efEncoder3 = MakeEncoder(new long[] { 1, 2, 3 }, EliasFanoEncoder.DEFAULT_INDEX_INTERVAL); Assert.IsFalse(efEncoder1.Equals(efEncoder3)); Assert.IsFalse(efEncoder3.Equals(efEncoder1)); Assert.IsFalse(efEncoder1.GetHashCode() == efEncoder3.GetHashCode()); // implementation ok for these. } [Test] public virtual void TestMonotoneSequences() { for (int s = 2; s < 1222; s++) { long[] values = new long[s]; for (int i = 0; i < s; i++) { values[i] = (i / 2); // upperbound smaller than number of values, only upper bits encoded } TstEFS2(values); } } [Test, Slow, LuceneNetSpecific, Ignore("For debugging only")] public virtual void TestMonotoneSequencesLonger() { for (int s = 2; s < 4422; s++) { long[] values = new long[s]; for (int i = 0; i < s; i++) { values[i] = (i / 2); // upperbound smaller than number of values, only upper bits encoded } TstEFS2(values); } } [Test] public virtual void TestStrictMonotoneSequences() { for (int s = 2; s < 1222; s++) { var values = new long[s]; for (int i = 0; i < s; i++) { values[i] = i * ((long)i - 1) / 2; // Add a gap of (s-1) to previous // s = (s*(s+1) - (s-1)*s)/2 } TstEFS2(values); } } [Test, Slow, LuceneNetSpecific, Ignore("For debugging only")] public virtual void TestStrictMonotoneSequencesLonger() { for (int s = 2; s < 4422; s++) { var values = new long[s]; for (int i = 0; i < s; i++) { values[i] = i * ((long)i - 1) / 2; // Add a gap of (s-1) to previous // s = (s*(s+1) - (s-1)*s)/2 } TstEFS2(values); } } [Test] public virtual void TestHighBitLongZero() { const int s = 65; long[] values = new long[s]; for (int i = 0; i < s - 1; i++) { values[i] = 0; } values[s - 1] = 128; long[] expHighBits = new long[] { -1, 0, 0, 1 }; long[] expLowBits = new long[0]; TstEFS(values, expHighBits, expLowBits); } [Test] public virtual void TestAdvanceToAndBackToMultiples() { for (int s = 2; s < 130; s++) { long[] values = new long[s]; for (int i = 0; i < s; i++) { values[i] = i * ((long)i + 1) / 2; // Add a gap of s to previous // s = (s*(s+1) - (s-1)*s)/2 } TstEFSadvanceToAndBackToMultiples(values, values[s - 1], 10); } } [Test] public virtual void TestEmptyIndex() { long indexInterval = 2; long[] emptyLongs = new long[0]; TstEFVI(emptyLongs, indexInterval, emptyLongs); } [Test] public virtual void TestMaxContentEmptyIndex() { long indexInterval = 2; long[] twoLongs = new long[] { 0, 1 }; long[] emptyLongs = new long[0]; TstEFVI(twoLongs, indexInterval, emptyLongs); } [Test] public virtual void TestMinContentNonEmptyIndex() { long indexInterval = 2; long[] twoLongs = new long[] { 0, 2 }; long[] indexLongs = new long[] { 3 }; // high bits 1001, index position after zero bit. TstEFVI(twoLongs, indexInterval, indexLongs); } [Test] public virtual void TestIndexAdvanceToLast() { long indexInterval = 2; long[] twoLongs = new long[] { 0, 2 }; long[] indexLongs = new long[] { 3 }; // high bits 1001 EliasFanoEncoder efEncVI = TstEFVI(twoLongs, indexInterval, indexLongs); Assert.AreEqual(2, efEncVI.GetDecoder().AdvanceToValue(2)); } [Test] public virtual void TestIndexAdvanceToAfterLast() { long indexInterval = 2; long[] twoLongs = new long[] { 0, 2 }; long[] indexLongs = new long[] { 3 }; // high bits 1001 EliasFanoEncoder efEncVI = TstEFVI(twoLongs, indexInterval, indexLongs); Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, efEncVI.GetDecoder().AdvanceToValue(3)); } [Test] public virtual void TestIndexAdvanceToFirst() { long indexInterval = 2; long[] twoLongs = new long[] { 0, 2 }; long[] indexLongs = new long[] { 3 }; // high bits 1001 EliasFanoEncoder efEncVI = TstEFVI(twoLongs, indexInterval, indexLongs); Assert.AreEqual(0, efEncVI.GetDecoder().AdvanceToValue(0)); } [Test] public virtual void TestTwoIndexEntries() { long indexInterval = 2; long[] twoLongs = new long[] { 0, 1, 2, 3, 4, 5 }; long[] indexLongs = new long[] { 4 + 8 * 16 }; // high bits 0b10101010101 EliasFanoEncoder efEncVI = TstEFVI(twoLongs, indexInterval, indexLongs); EliasFanoDecoder efDecVI = efEncVI.GetDecoder(); Assert.AreEqual(0, efDecVI.AdvanceToValue(0), "advance 0"); Assert.AreEqual(5, efDecVI.AdvanceToValue(5), "advance 5"); Assert.AreEqual(EliasFanoDecoder.NO_MORE_VALUES, efDecVI.AdvanceToValue(5), "advance 6"); } [Test] public virtual void TestExample2a() // Figure 2 from Vigna 2012 paper { long indexInterval = 4; long[] values = new long[] { 5, 8, 8, 15, 32 }; // two low bits, high values 1,2,2,3,8. long[] indexLongs = new long[] { 8 + 12 * 16 }; // high bits 0b 0001 0000 0101 1010 EliasFanoEncoder efEncVI = TstEFVI(values, indexInterval, indexLongs); EliasFanoDecoder efDecVI = efEncVI.GetDecoder(); Assert.AreEqual(32, efDecVI.AdvanceToValue(22), "advance 22"); } [Test] public virtual void TestExample2b() // Figure 2 from Vigna 2012 paper { long indexInterval = 4; long[] values = new long[] { 5, 8, 8, 15, 32 }; // two low bits, high values 1,2,2,3,8. long[] indexLongs = new long[] { 8 + 12 * 16 }; // high bits 0b 0001 0000 0101 1010 EliasFanoEncoder efEncVI = TstEFVI(values, indexInterval, indexLongs); EliasFanoDecoder efDecVI = efEncVI.GetDecoder(); Assert.AreEqual(5, efDecVI.NextValue(), "initial next"); Assert.AreEqual(32, efDecVI.AdvanceToValue(22), "advance 22"); } [Test] public virtual void TestExample2NoIndex1() // Figure 2 from Vigna 2012 paper, no index, test broadword selection. { long indexInterval = 16; long[] values = new long[] { 5, 8, 8, 15, 32 }; // two low bits, high values 1,2,2,3,8. long[] indexLongs = new long[0]; // high bits 0b 0001 0000 0101 1010 EliasFanoEncoder efEncVI = TstEFVI(values, indexInterval, indexLongs); EliasFanoDecoder efDecVI = efEncVI.GetDecoder(); Assert.AreEqual(32, efDecVI.AdvanceToValue(22), "advance 22"); } [Test] public virtual void TestExample2NoIndex2() // Figure 2 from Vigna 2012 paper, no index, test broadword selection. { long indexInterval = 16; long[] values = new long[] { 5, 8, 8, 15, 32 }; // two low bits, high values 1,2,2,3,8. long[] indexLongs = new long[0]; // high bits 0b 0001 0000 0101 1010 EliasFanoEncoder efEncVI = TstEFVI(values, indexInterval, indexLongs); EliasFanoDecoder efDecVI = efEncVI.GetDecoder(); Assert.AreEqual(5, efDecVI.NextValue(), "initial next"); Assert.AreEqual(32, efDecVI.AdvanceToValue(22), "advance 22"); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace HomeBot.Api.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Collections; using System.IO; using Org.BouncyCastle.Crypto.Prng; using Org.BouncyCastle.Security; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Tls { public abstract class TlsProtocol { private static readonly string TLS_ERROR_MESSAGE = "Internal TLS error, this could be an attack"; /* * Our Connection states */ protected const short CS_START = 0; protected const short CS_CLIENT_HELLO = 1; protected const short CS_SERVER_HELLO = 2; protected const short CS_SERVER_SUPPLEMENTAL_DATA = 3; protected const short CS_SERVER_CERTIFICATE = 4; protected const short CS_CERTIFICATE_STATUS = 5; protected const short CS_SERVER_KEY_EXCHANGE = 6; protected const short CS_CERTIFICATE_REQUEST = 7; protected const short CS_SERVER_HELLO_DONE = 8; protected const short CS_CLIENT_SUPPLEMENTAL_DATA = 9; protected const short CS_CLIENT_CERTIFICATE = 10; protected const short CS_CLIENT_KEY_EXCHANGE = 11; protected const short CS_CERTIFICATE_VERIFY = 12; protected const short CS_CLIENT_FINISHED = 13; protected const short CS_SERVER_SESSION_TICKET = 14; protected const short CS_SERVER_FINISHED = 15; protected const short CS_END = 16; /* * Queues for data from some protocols. */ private ByteQueue mApplicationDataQueue = new ByteQueue(); private ByteQueue mAlertQueue = new ByteQueue(2); private ByteQueue mHandshakeQueue = new ByteQueue(); // private ByteQueue mHeartbeatQueue = new ByteQueue(); /* * The Record Stream we use */ internal RecordStream mRecordStream; protected SecureRandom mSecureRandom; private TlsStream mTlsStream = null; private volatile bool mClosed = false; private volatile bool mFailedWithError = false; private volatile bool mAppDataReady = false; private volatile bool mSplitApplicationDataRecords = true; private byte[] mExpectedVerifyData = null; protected TlsSession mTlsSession = null; protected SessionParameters mSessionParameters = null; protected SecurityParameters mSecurityParameters = null; protected Certificate mPeerCertificate = null; protected int[] mOfferedCipherSuites = null; protected byte[] mOfferedCompressionMethods = null; protected IDictionary mClientExtensions = null; protected IDictionary mServerExtensions = null; protected short mConnectionState = CS_START; protected bool mResumedSession = false; protected bool mReceivedChangeCipherSpec = false; protected bool mSecureRenegotiation = false; protected bool mAllowCertificateStatus = false; protected bool mExpectSessionTicket = false; public TlsProtocol(Stream stream, SecureRandom secureRandom) : this(stream, stream, secureRandom) { } public TlsProtocol(Stream input, Stream output, SecureRandom secureRandom) { this.mRecordStream = new RecordStream(this, input, output); this.mSecureRandom = secureRandom; } protected abstract TlsContext Context { get; } internal abstract AbstractTlsContext ContextAdmin { get; } protected abstract TlsPeer Peer { get; } protected virtual void HandleChangeCipherSpecMessage() { } protected abstract void HandleHandshakeMessage(byte type, byte[] buf); protected virtual void HandleWarningMessage(byte description) { } protected virtual void ApplyMaxFragmentLengthExtension() { if (mSecurityParameters.maxFragmentLength >= 0) { if (!MaxFragmentLength.IsValid((byte)mSecurityParameters.maxFragmentLength)) throw new TlsFatalAlert(AlertDescription.internal_error); int plainTextLimit = 1 << (8 + mSecurityParameters.maxFragmentLength); mRecordStream.SetPlaintextLimit(plainTextLimit); } } protected virtual void CheckReceivedChangeCipherSpec(bool expected) { if (expected != mReceivedChangeCipherSpec) throw new TlsFatalAlert(AlertDescription.unexpected_message); } protected virtual void CleanupHandshake() { if (this.mExpectedVerifyData != null) { Arrays.Fill(this.mExpectedVerifyData, (byte)0); this.mExpectedVerifyData = null; } this.mSecurityParameters.Clear(); this.mPeerCertificate = null; this.mOfferedCipherSuites = null; this.mOfferedCompressionMethods = null; this.mClientExtensions = null; this.mServerExtensions = null; this.mResumedSession = false; this.mReceivedChangeCipherSpec = false; this.mSecureRenegotiation = false; this.mAllowCertificateStatus = false; this.mExpectSessionTicket = false; } protected virtual void CompleteHandshake() { try { /* * We will now read data, until we have completed the handshake. */ while (this.mConnectionState != CS_END) { if (this.mClosed) { // TODO What kind of exception/alert? } SafeReadRecord(); } this.mRecordStream.FinaliseHandshake(); this.mSplitApplicationDataRecords = !TlsUtilities.IsTlsV11(Context); /* * If this was an initial handshake, we are now ready to send and receive application data. */ if (!mAppDataReady) { this.mAppDataReady = true; this.mTlsStream = new TlsStream(this); } if (this.mTlsSession != null) { if (this.mSessionParameters == null) { this.mSessionParameters = new SessionParameters.Builder() .SetCipherSuite(this.mSecurityParameters.CipherSuite) .SetCompressionAlgorithm(this.mSecurityParameters.CompressionAlgorithm) .SetMasterSecret(this.mSecurityParameters.MasterSecret) .SetPeerCertificate(this.mPeerCertificate) .SetPskIdentity(this.mSecurityParameters.PskIdentity) .SetSrpIdentity(this.mSecurityParameters.SrpIdentity) // TODO Consider filtering extensions that aren't relevant to resumed sessions .SetServerExtensions(this.mServerExtensions) .Build(); this.mTlsSession = new TlsSessionImpl(this.mTlsSession.SessionID, this.mSessionParameters); } ContextAdmin.SetResumableSession(this.mTlsSession); } Peer.NotifyHandshakeComplete(); } finally { CleanupHandshake(); } } protected internal void ProcessRecord(byte protocol, byte[] buf, int offset, int len) { /* * Have a look at the protocol type, and add it to the correct queue. */ switch (protocol) { case ContentType.alert: { mAlertQueue.AddData(buf, offset, len); ProcessAlert(); break; } case ContentType.application_data: { if (!mAppDataReady) throw new TlsFatalAlert(AlertDescription.unexpected_message); mApplicationDataQueue.AddData(buf, offset, len); ProcessApplicationData(); break; } case ContentType.change_cipher_spec: { ProcessChangeCipherSpec(buf, offset, len); break; } case ContentType.handshake: { mHandshakeQueue.AddData(buf, offset, len); ProcessHandshake(); break; } case ContentType.heartbeat: { if (!mAppDataReady) throw new TlsFatalAlert(AlertDescription.unexpected_message); // TODO[RFC 6520] // mHeartbeatQueue.AddData(buf, offset, len); // ProcessHeartbeat(); break; } default: /* * Uh, we don't know this protocol. * * RFC2246 defines on page 13, that we should ignore this. */ break; } } private void ProcessHandshake() { bool read; do { read = false; /* * We need the first 4 bytes, they contain type and length of the message. */ if (mHandshakeQueue.Available >= 4) { byte[] beginning = new byte[4]; mHandshakeQueue.Read(beginning, 0, 4, 0); byte type = TlsUtilities.ReadUint8(beginning, 0); int len = TlsUtilities.ReadUint24(beginning, 1); /* * Check if we have enough bytes in the buffer to read the full message. */ if (mHandshakeQueue.Available >= (len + 4)) { /* * Read the message. */ byte[] buf = mHandshakeQueue.RemoveData(len, 4); CheckReceivedChangeCipherSpec(mConnectionState == CS_END || type == HandshakeType.finished); /* * RFC 2246 7.4.9. The value handshake_messages includes all handshake messages * starting at client hello up to, but not including, this finished message. * [..] Note: [Also,] Hello Request messages are omitted from handshake hashes. */ switch (type) { case HandshakeType.hello_request: break; case HandshakeType.finished: default: { TlsContext ctx = Context; if (type == HandshakeType.finished && this.mExpectedVerifyData == null && ctx.SecurityParameters.MasterSecret != null) { this.mExpectedVerifyData = CreateVerifyData(!ctx.IsServer); } mRecordStream.UpdateHandshakeData(beginning, 0, 4); mRecordStream.UpdateHandshakeData(buf, 0, len); break; } } /* * Now, parse the message. */ HandleHandshakeMessage(type, buf); read = true; } } } while (read); } private void ProcessApplicationData() { /* * There is nothing we need to do here. * * This function could be used for callbacks when application data arrives in the future. */ } private void ProcessAlert() { while (mAlertQueue.Available >= 2) { /* * An alert is always 2 bytes. Read the alert. */ byte[] tmp = mAlertQueue.RemoveData(2, 0); byte level = tmp[0]; byte description = tmp[1]; Peer.NotifyAlertReceived(level, description); if (level == AlertLevel.fatal) { /* * RFC 2246 7.2.1. The session becomes unresumable if any connection is terminated * without proper close_notify messages with level equal to warning. */ InvalidateSession(); this.mFailedWithError = true; this.mClosed = true; mRecordStream.SafeClose(); throw new IOException(TLS_ERROR_MESSAGE); } else { /* * RFC 5246 7.2.1. The other party MUST respond with a close_notify alert of its own * and close down the connection immediately, discarding any pending writes. */ // TODO Can close_notify be a fatal alert? if (description == AlertDescription.close_notify) { HandleClose(false); } /* * If it is just a warning, we continue. */ HandleWarningMessage(description); } } } /** * This method is called, when a change cipher spec message is received. * * @throws IOException If the message has an invalid content or the handshake is not in the correct * state. */ private void ProcessChangeCipherSpec(byte[] buf, int off, int len) { for (int i = 0; i < len; ++i) { byte message = TlsUtilities.ReadUint8(buf, off + i); if (message != ChangeCipherSpec.change_cipher_spec) throw new TlsFatalAlert(AlertDescription.decode_error); if (this.mReceivedChangeCipherSpec || mAlertQueue.Available > 0 || mHandshakeQueue.Available > 0) { throw new TlsFatalAlert(AlertDescription.unexpected_message); } mRecordStream.ReceivedReadCipherSpec(); this.mReceivedChangeCipherSpec = true; HandleChangeCipherSpecMessage(); } } protected internal virtual int ApplicationDataAvailable() { return mApplicationDataQueue.Available; } /** * Read data from the network. The method will return immediately, if there is still some data * left in the buffer, or block until some application data has been read from the network. * * @param buf The buffer where the data will be copied to. * @param offset The position where the data will be placed in the buffer. * @param len The maximum number of bytes to read. * @return The number of bytes read. * @throws IOException If something goes wrong during reading data. */ protected internal virtual int ReadApplicationData(byte[] buf, int offset, int len) { if (len < 1) return 0; while (mApplicationDataQueue.Available == 0) { /* * We need to read some data. */ if (this.mClosed) { if (this.mFailedWithError) { /* * Something went terribly wrong, we should throw an IOException */ throw new IOException(TLS_ERROR_MESSAGE); } /* * Connection has been closed, there is no more data to read. */ return 0; } SafeReadRecord(); } len = System.Math.Min(len, mApplicationDataQueue.Available); mApplicationDataQueue.RemoveData(buf, offset, len, 0); return len; } protected virtual void SafeReadRecord() { try { if (!mRecordStream.ReadRecord()) { // TODO It would be nicer to allow graceful connection close if between records // this.FailWithError(AlertLevel.warning, AlertDescription.close_notify); throw new EndOfStreamException(); } } catch (TlsFatalAlert e) { if (!mClosed) { this.FailWithError(AlertLevel.fatal, e.AlertDescription, "Failed to read record", e); } throw e; } catch (Exception e) { if (!mClosed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to read record", e); } throw e; } } protected virtual void SafeWriteRecord(byte type, byte[] buf, int offset, int len) { try { mRecordStream.WriteRecord(type, buf, offset, len); } catch (TlsFatalAlert e) { if (!mClosed) { this.FailWithError(AlertLevel.fatal, e.AlertDescription, "Failed to write record", e); } throw e; } catch (Exception e) { if (!mClosed) { this.FailWithError(AlertLevel.fatal, AlertDescription.internal_error, "Failed to write record", e); } throw e; } } /** * Send some application data to the remote system. * <p/> * The method will handle fragmentation internally. * * @param buf The buffer with the data. * @param offset The position in the buffer where the data is placed. * @param len The length of the data. * @throws IOException If something goes wrong during sending. */ protected internal virtual void WriteData(byte[] buf, int offset, int len) { if (this.mClosed) { if (this.mFailedWithError) throw new IOException(TLS_ERROR_MESSAGE); throw new IOException("Sorry, connection has been closed, you cannot write more data"); } while (len > 0) { /* * RFC 5246 6.2.1. Zero-length fragments of Application data MAY be sent as they are * potentially useful as a traffic analysis countermeasure. * * NOTE: Actually, implementations appear to have settled on 1/n-1 record splitting. */ if (this.mSplitApplicationDataRecords) { /* * Protect against known IV attack! * * DO NOT REMOVE THIS CODE, EXCEPT YOU KNOW EXACTLY WHAT YOU ARE DOING HERE. */ SafeWriteRecord(ContentType.application_data, buf, offset, 1); ++offset; --len; } if (len > 0) { // Fragment data according to the current fragment limit. int toWrite = System.Math.Min(len, mRecordStream.GetPlaintextLimit()); SafeWriteRecord(ContentType.application_data, buf, offset, toWrite); offset += toWrite; len -= toWrite; } } } protected virtual void WriteHandshakeMessage(byte[] buf, int off, int len) { while (len > 0) { // Fragment data according to the current fragment limit. int toWrite = System.Math.Min(len, mRecordStream.GetPlaintextLimit()); SafeWriteRecord(ContentType.handshake, buf, off, toWrite); off += toWrite; len -= toWrite; } } /// <summary>The secure bidirectional stream for this connection</summary> public virtual Stream Stream { get { return this.mTlsStream; } } /** * Terminate this connection with an alert. Can be used for normal closure too. * * @param alertLevel * See {@link AlertLevel} for values. * @param alertDescription * See {@link AlertDescription} for values. * @throws IOException * If alert was fatal. */ protected virtual void FailWithError(byte alertLevel, byte alertDescription, string message, Exception cause) { /* * Check if the connection is still open. */ if (!mClosed) { /* * Prepare the message */ this.mClosed = true; if (alertLevel == AlertLevel.fatal) { /* * RFC 2246 7.2.1. The session becomes unresumable if any connection is terminated * without proper close_notify messages with level equal to warning. */ // TODO This isn't quite in the right place. Also, as of TLS 1.1 the above is obsolete. InvalidateSession(); this.mFailedWithError = true; } RaiseAlert(alertLevel, alertDescription, message, cause); mRecordStream.SafeClose(); if (alertLevel != AlertLevel.fatal) { return; } } throw new IOException(TLS_ERROR_MESSAGE); } protected virtual void InvalidateSession() { if (this.mSessionParameters != null) { this.mSessionParameters.Clear(); this.mSessionParameters = null; } if (this.mTlsSession != null) { this.mTlsSession.Invalidate(); this.mTlsSession = null; } } protected virtual void ProcessFinishedMessage(MemoryStream buf) { if (mExpectedVerifyData == null) throw new TlsFatalAlert(AlertDescription.internal_error); byte[] verify_data = TlsUtilities.ReadFully(mExpectedVerifyData.Length, buf); AssertEmpty(buf); /* * Compare both checksums. */ if (!Arrays.ConstantTimeAreEqual(mExpectedVerifyData, verify_data)) { /* * Wrong checksum in the finished message. */ throw new TlsFatalAlert(AlertDescription.decrypt_error); } } protected virtual void RaiseAlert(byte alertLevel, byte alertDescription, string message, Exception cause) { Peer.NotifyAlertRaised(alertLevel, alertDescription, message, cause); byte[] error = new byte[]{ alertLevel, alertDescription }; SafeWriteRecord(ContentType.alert, error, 0, 2); } protected virtual void RaiseWarning(byte alertDescription, string message) { RaiseAlert(AlertLevel.warning, alertDescription, message, null); } protected virtual void SendCertificateMessage(Certificate certificate) { if (certificate == null) { certificate = Certificate.EmptyChain; } if (certificate.IsEmpty) { TlsContext context = Context; if (!context.IsServer) { ProtocolVersion serverVersion = Context.ServerVersion; if (serverVersion.IsSsl) { string errorMessage = serverVersion.ToString() + " client didn't provide credentials"; RaiseWarning(AlertDescription.no_certificate, errorMessage); return; } } } HandshakeMessage message = new HandshakeMessage(HandshakeType.certificate); certificate.Encode(message); message.WriteToRecordStream(this); } protected virtual void SendChangeCipherSpecMessage() { byte[] message = new byte[]{ 1 }; SafeWriteRecord(ContentType.change_cipher_spec, message, 0, message.Length); mRecordStream.SentWriteCipherSpec(); } protected virtual void SendFinishedMessage() { byte[] verify_data = CreateVerifyData(Context.IsServer); HandshakeMessage message = new HandshakeMessage(HandshakeType.finished, verify_data.Length); message.Write(verify_data, 0, verify_data.Length); message.WriteToRecordStream(this); } protected virtual void SendSupplementalDataMessage(IList supplementalData) { HandshakeMessage message = new HandshakeMessage(HandshakeType.supplemental_data); WriteSupplementalData(message, supplementalData); message.WriteToRecordStream(this); } protected virtual byte[] CreateVerifyData(bool isServer) { TlsContext context = Context; string asciiLabel = isServer ? ExporterLabel.server_finished : ExporterLabel.client_finished; byte[] sslSender = isServer ? TlsUtilities.SSL_SERVER : TlsUtilities.SSL_CLIENT; byte[] hash = GetCurrentPrfHash(context, mRecordStream.HandshakeHash, sslSender); return TlsUtilities.CalculateVerifyData(context, asciiLabel, hash); } /** * Closes this connection. * * @throws IOException If something goes wrong during closing. */ public virtual void Close() { HandleClose(true); } protected virtual void HandleClose(bool user_canceled) { if (!mClosed) { if (user_canceled && !mAppDataReady) { RaiseWarning(AlertDescription.user_canceled, "User canceled handshake"); } this.FailWithError(AlertLevel.warning, AlertDescription.close_notify, "Connection closed", null); } } protected internal virtual void Flush() { mRecordStream.Flush(); } protected internal virtual bool IsClosed { get { return mClosed; } } protected virtual short ProcessMaxFragmentLengthExtension(IDictionary clientExtensions, IDictionary serverExtensions, byte alertDescription) { short maxFragmentLength = TlsExtensionsUtilities.GetMaxFragmentLengthExtension(serverExtensions); if (maxFragmentLength >= 0) { if (!MaxFragmentLength.IsValid((byte)maxFragmentLength) || (!this.mResumedSession && maxFragmentLength != TlsExtensionsUtilities .GetMaxFragmentLengthExtension(clientExtensions))) { throw new TlsFatalAlert(alertDescription); } } return maxFragmentLength; } protected virtual void RefuseRenegotiation() { /* * RFC 5746 4.5 SSLv3 clients that refuse renegotiation SHOULD use a fatal * handshake_failure alert. */ if (TlsUtilities.IsSsl(Context)) throw new TlsFatalAlert(AlertDescription.handshake_failure); RaiseWarning(AlertDescription.no_renegotiation, "Renegotiation not supported"); } /** * Make sure the InputStream 'buf' now empty. Fail otherwise. * * @param buf The InputStream to check. * @throws IOException If 'buf' is not empty. */ protected internal static void AssertEmpty(MemoryStream buf) { if (buf.Position < buf.Length) throw new TlsFatalAlert(AlertDescription.decode_error); } protected internal static byte[] CreateRandomBlock(bool useGmtUnixTime, IRandomGenerator randomGenerator) { byte[] result = new byte[32]; randomGenerator.NextBytes(result); if (useGmtUnixTime) { TlsUtilities.WriteGmtUnixTime(result, 0); } return result; } protected internal static byte[] CreateRenegotiationInfo(byte[] renegotiated_connection) { return TlsUtilities.EncodeOpaque8(renegotiated_connection); } protected internal static void EstablishMasterSecret(TlsContext context, TlsKeyExchange keyExchange) { byte[] pre_master_secret = keyExchange.GeneratePremasterSecret(); try { context.SecurityParameters.masterSecret = TlsUtilities.CalculateMasterSecret(context, pre_master_secret); } finally { // TODO Is there a way to ensure the data is really overwritten? /* * RFC 2246 8.1. The pre_master_secret should be deleted from memory once the * master_secret has been computed. */ if (pre_master_secret != null) { Arrays.Fill(pre_master_secret, (byte)0); } } } /** * 'sender' only relevant to SSLv3 */ protected internal static byte[] GetCurrentPrfHash(TlsContext context, TlsHandshakeHash handshakeHash, byte[] sslSender) { IDigest d = handshakeHash.ForkPrfHash(); if (sslSender != null && TlsUtilities.IsSsl(context)) { d.BlockUpdate(sslSender, 0, sslSender.Length); } return DigestUtilities.DoFinal(d); } protected internal static IDictionary ReadExtensions(MemoryStream input) { if (input.Position >= input.Length) return null; byte[] extBytes = TlsUtilities.ReadOpaque16(input); AssertEmpty(input); MemoryStream buf = new MemoryStream(extBytes, false); // Integer -> byte[] IDictionary extensions = Platform.CreateHashtable(); while (buf.Position < buf.Length) { int extension_type = TlsUtilities.ReadUint16(buf); byte[] extension_data = TlsUtilities.ReadOpaque16(buf); /* * RFC 3546 2.3 There MUST NOT be more than one extension of the same type. */ if (extensions.Contains(extension_type)) throw new TlsFatalAlert(AlertDescription.illegal_parameter); extensions.Add(extension_type, extension_data); } return extensions; } protected internal static IList ReadSupplementalDataMessage(MemoryStream input) { byte[] supp_data = TlsUtilities.ReadOpaque24(input); AssertEmpty(input); MemoryStream buf = new MemoryStream(supp_data, false); IList supplementalData = Platform.CreateArrayList(); while (buf.Position < buf.Length) { int supp_data_type = TlsUtilities.ReadUint16(buf); byte[] data = TlsUtilities.ReadOpaque16(buf); supplementalData.Add(new SupplementalDataEntry(supp_data_type, data)); } return supplementalData; } protected internal static void WriteExtensions(Stream output, IDictionary extensions) { MemoryStream buf = new MemoryStream(); foreach (int extension_type in extensions.Keys) { byte[] extension_data = (byte[])extensions[extension_type]; TlsUtilities.CheckUint16(extension_type); TlsUtilities.WriteUint16(extension_type, buf); TlsUtilities.WriteOpaque16(extension_data, buf); } byte[] extBytes = buf.ToArray(); TlsUtilities.WriteOpaque16(extBytes, output); } protected internal static void WriteSupplementalData(Stream output, IList supplementalData) { MemoryStream buf = new MemoryStream(); foreach (SupplementalDataEntry entry in supplementalData) { int supp_data_type = entry.DataType; TlsUtilities.CheckUint16(supp_data_type); TlsUtilities.WriteUint16(supp_data_type, buf); TlsUtilities.WriteOpaque16(entry.Data, buf); } byte[] supp_data = buf.ToArray(); TlsUtilities.WriteOpaque24(supp_data, output); } protected internal static int GetPrfAlgorithm(TlsContext context, int ciphersuite) { bool isTLSv12 = TlsUtilities.IsTlsV12(context); switch (ciphersuite) { case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: case CipherSuite.TLS_PSK_DHE_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_DHE_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_CCM: case CipherSuite.TLS_PSK_WITH_AES_128_CCM_8: case CipherSuite.TLS_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_PSK_WITH_AES_256_CCM: case CipherSuite.TLS_PSK_WITH_AES_256_CCM_8: case CipherSuite.TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_128_CCM: case CipherSuite.TLS_RSA_WITH_AES_128_CCM_8: case CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_AES_256_CCM: case CipherSuite.TLS_RSA_WITH_AES_256_CCM_8: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256: case CipherSuite.TLS_RSA_WITH_NULL_SHA256: { if (isTLSv12) { return PrfAlgorithm.tls_prf_sha256; } throw new TlsFatalAlert(AlertDescription.illegal_parameter); } case CipherSuite.TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384: case CipherSuite.TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384: { if (isTLSv12) { return PrfAlgorithm.tls_prf_sha384; } throw new TlsFatalAlert(AlertDescription.illegal_parameter); } case CipherSuite.TLS_DHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_DHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_ECDHE_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_PSK_WITH_NULL_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_AES_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384: case CipherSuite.TLS_RSA_PSK_WITH_NULL_SHA384: { if (isTLSv12) { return PrfAlgorithm.tls_prf_sha384; } return PrfAlgorithm.tls_prf_legacy; } default: { if (isTLSv12) { return PrfAlgorithm.tls_prf_sha256; } return PrfAlgorithm.tls_prf_legacy; } } } internal class HandshakeMessage : MemoryStream { internal HandshakeMessage(byte handshakeType) : this(handshakeType, 60) { } internal HandshakeMessage(byte handshakeType, int length) : base(length + 4) { TlsUtilities.WriteUint8(handshakeType, this); // Reserve space for length TlsUtilities.WriteUint24(0, this); } internal void Write(byte[] data) { Write(data, 0, data.Length); } internal void WriteToRecordStream(TlsProtocol protocol) { // Patch actual length back in long length = Length - 4; TlsUtilities.CheckUint24(length); this.Position = 1; TlsUtilities.WriteUint24((int)length, this); byte[] buffer = ToArray(); protocol.WriteHandshakeMessage(buffer /*GetBuffer()*/, 0, (int)Length); this.Dispose(); } } } } #endif
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 WebApiBook.ProcessingArchitecture.ProcessesApi.v2.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>(); } /// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and 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)) { 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="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [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; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// KCM Transfer Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KCM_TFRDataSet : EduHubDataSet<KCM_TFR> { /// <inheritdoc /> public override string Name { get { return "KCM_TFR"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal KCM_TFRDataSet(EduHubContext Context) : base(Context) { Index_KCM_TRANS_ID = new Lazy<NullDictionary<string, KCM_TFR>>(() => this.ToNullDictionary(i => i.KCM_TRANS_ID)); Index_ORIG_SCHOOL = new Lazy<Dictionary<string, IReadOnlyList<KCM_TFR>>>(() => this.ToGroupedDictionary(i => i.ORIG_SCHOOL)); Index_TID = new Lazy<Dictionary<int, KCM_TFR>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KCM_TFR" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KCM_TFR" /> fields for each CSV column header</returns> internal override Action<KCM_TFR, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KCM_TFR, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "ORIG_SCHOOL": mapper[i] = (e, v) => e.ORIG_SCHOOL = v; break; case "KCM_TRANS_ID": mapper[i] = (e, v) => e.KCM_TRANS_ID = v; break; case "KCMKEY": mapper[i] = (e, v) => e.KCMKEY = v; break; case "KCMKEY_NEW": mapper[i] = (e, v) => e.KCMKEY_NEW = v; break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "DISABILITY": mapper[i] = (e, v) => e.DISABILITY = v; break; case "IMP_STATUS": mapper[i] = (e, v) => e.IMP_STATUS = v; break; case "IMP_DATE": mapper[i] = (e, v) => e.IMP_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KCM_TFR" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KCM_TFR" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KCM_TFR" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KCM_TFR}"/> of entities</returns> internal override IEnumerable<KCM_TFR> ApplyDeltaEntities(IEnumerable<KCM_TFR> Entities, List<KCM_TFR> DeltaEntities) { HashSet<string> Index_KCM_TRANS_ID = new HashSet<string>(DeltaEntities.Select(i => i.KCM_TRANS_ID)); HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.ORIG_SCHOOL; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = false; overwritten = overwritten || Index_KCM_TRANS_ID.Remove(entity.KCM_TRANS_ID); overwritten = overwritten || Index_TID.Remove(entity.TID); if (entity.ORIG_SCHOOL.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, KCM_TFR>> Index_KCM_TRANS_ID; private Lazy<Dictionary<string, IReadOnlyList<KCM_TFR>>> Index_ORIG_SCHOOL; private Lazy<Dictionary<int, KCM_TFR>> Index_TID; #endregion #region Index Methods /// <summary> /// Find KCM_TFR by KCM_TRANS_ID field /// </summary> /// <param name="KCM_TRANS_ID">KCM_TRANS_ID value used to find KCM_TFR</param> /// <returns>Related KCM_TFR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCM_TFR FindByKCM_TRANS_ID(string KCM_TRANS_ID) { return Index_KCM_TRANS_ID.Value[KCM_TRANS_ID]; } /// <summary> /// Attempt to find KCM_TFR by KCM_TRANS_ID field /// </summary> /// <param name="KCM_TRANS_ID">KCM_TRANS_ID value used to find KCM_TFR</param> /// <param name="Value">Related KCM_TFR entity</param> /// <returns>True if the related KCM_TFR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKCM_TRANS_ID(string KCM_TRANS_ID, out KCM_TFR Value) { return Index_KCM_TRANS_ID.Value.TryGetValue(KCM_TRANS_ID, out Value); } /// <summary> /// Attempt to find KCM_TFR by KCM_TRANS_ID field /// </summary> /// <param name="KCM_TRANS_ID">KCM_TRANS_ID value used to find KCM_TFR</param> /// <returns>Related KCM_TFR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCM_TFR TryFindByKCM_TRANS_ID(string KCM_TRANS_ID) { KCM_TFR value; if (Index_KCM_TRANS_ID.Value.TryGetValue(KCM_TRANS_ID, out value)) { return value; } else { return null; } } /// <summary> /// Find KCM_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find KCM_TFR</param> /// <returns>List of related KCM_TFR entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCM_TFR> FindByORIG_SCHOOL(string ORIG_SCHOOL) { return Index_ORIG_SCHOOL.Value[ORIG_SCHOOL]; } /// <summary> /// Attempt to find KCM_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find KCM_TFR</param> /// <param name="Value">List of related KCM_TFR entities</param> /// <returns>True if the list of related KCM_TFR entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByORIG_SCHOOL(string ORIG_SCHOOL, out IReadOnlyList<KCM_TFR> Value) { return Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out Value); } /// <summary> /// Attempt to find KCM_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find KCM_TFR</param> /// <returns>List of related KCM_TFR entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KCM_TFR> TryFindByORIG_SCHOOL(string ORIG_SCHOOL) { IReadOnlyList<KCM_TFR> value; if (Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out value)) { return value; } else { return null; } } /// <summary> /// Find KCM_TFR by TID field /// </summary> /// <param name="TID">TID value used to find KCM_TFR</param> /// <returns>Related KCM_TFR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCM_TFR FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find KCM_TFR by TID field /// </summary> /// <param name="TID">TID value used to find KCM_TFR</param> /// <param name="Value">Related KCM_TFR entity</param> /// <returns>True if the related KCM_TFR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out KCM_TFR Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find KCM_TFR by TID field /// </summary> /// <param name="TID">TID value used to find KCM_TFR</param> /// <returns>Related KCM_TFR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KCM_TFR TryFindByTID(int TID) { KCM_TFR value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KCM_TFR table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KCM_TFR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KCM_TFR]( [TID] int IDENTITY NOT NULL, [ORIG_SCHOOL] varchar(8) NOT NULL, [KCM_TRANS_ID] varchar(30) NULL, [KCMKEY] varchar(10) NULL, [KCMKEY_NEW] varchar(10) NULL, [DESCRIPTION] varchar(30) NULL, [DISABILITY] varchar(1) NULL, [IMP_STATUS] varchar(15) NULL, [IMP_DATE] datetime NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [KCM_TFR_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [KCM_TFR_Index_KCM_TRANS_ID] ON [dbo].[KCM_TFR] ( [KCM_TRANS_ID] ASC ); CREATE CLUSTERED INDEX [KCM_TFR_Index_ORIG_SCHOOL] ON [dbo].[KCM_TFR] ( [ORIG_SCHOOL] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCM_TFR]') AND name = N'KCM_TFR_Index_KCM_TRANS_ID') ALTER INDEX [KCM_TFR_Index_KCM_TRANS_ID] ON [dbo].[KCM_TFR] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCM_TFR]') AND name = N'KCM_TFR_Index_TID') ALTER INDEX [KCM_TFR_Index_TID] ON [dbo].[KCM_TFR] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCM_TFR]') AND name = N'KCM_TFR_Index_KCM_TRANS_ID') ALTER INDEX [KCM_TFR_Index_KCM_TRANS_ID] ON [dbo].[KCM_TFR] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KCM_TFR]') AND name = N'KCM_TFR_Index_TID') ALTER INDEX [KCM_TFR_Index_TID] ON [dbo].[KCM_TFR] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KCM_TFR"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KCM_TFR"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KCM_TFR> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_KCM_TRANS_ID = new List<string>(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_KCM_TRANS_ID.Add(entity.KCM_TRANS_ID); Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[KCM_TFR] WHERE"); // Index_KCM_TRANS_ID builder.Append("[KCM_TRANS_ID] IN ("); for (int index = 0; index < Index_KCM_TRANS_ID.Count; index++) { if (index != 0) builder.Append(", "); // KCM_TRANS_ID var parameterKCM_TRANS_ID = $"@p{parameterIndex++}"; builder.Append(parameterKCM_TRANS_ID); command.Parameters.Add(parameterKCM_TRANS_ID, SqlDbType.VarChar, 30).Value = (object)Index_KCM_TRANS_ID[index] ?? DBNull.Value; } builder.AppendLine(") OR"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCM_TFR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCM_TFR data set</returns> public override EduHubDataSetDataReader<KCM_TFR> GetDataSetDataReader() { return new KCM_TFRDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KCM_TFR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KCM_TFR data set</returns> public override EduHubDataSetDataReader<KCM_TFR> GetDataSetDataReader(List<KCM_TFR> Entities) { return new KCM_TFRDataReader(new EduHubDataSetLoadedReader<KCM_TFR>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KCM_TFRDataReader : EduHubDataSetDataReader<KCM_TFR> { public KCM_TFRDataReader(IEduHubDataSetReader<KCM_TFR> Reader) : base (Reader) { } public override int FieldCount { get { return 12; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // ORIG_SCHOOL return Current.ORIG_SCHOOL; case 2: // KCM_TRANS_ID return Current.KCM_TRANS_ID; case 3: // KCMKEY return Current.KCMKEY; case 4: // KCMKEY_NEW return Current.KCMKEY_NEW; case 5: // DESCRIPTION return Current.DESCRIPTION; case 6: // DISABILITY return Current.DISABILITY; case 7: // IMP_STATUS return Current.IMP_STATUS; case 8: // IMP_DATE return Current.IMP_DATE; case 9: // LW_DATE return Current.LW_DATE; case 10: // LW_TIME return Current.LW_TIME; case 11: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // KCM_TRANS_ID return Current.KCM_TRANS_ID == null; case 3: // KCMKEY return Current.KCMKEY == null; case 4: // KCMKEY_NEW return Current.KCMKEY_NEW == null; case 5: // DESCRIPTION return Current.DESCRIPTION == null; case 6: // DISABILITY return Current.DISABILITY == null; case 7: // IMP_STATUS return Current.IMP_STATUS == null; case 8: // IMP_DATE return Current.IMP_DATE == null; case 9: // LW_DATE return Current.LW_DATE == null; case 10: // LW_TIME return Current.LW_TIME == null; case 11: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // ORIG_SCHOOL return "ORIG_SCHOOL"; case 2: // KCM_TRANS_ID return "KCM_TRANS_ID"; case 3: // KCMKEY return "KCMKEY"; case 4: // KCMKEY_NEW return "KCMKEY_NEW"; case 5: // DESCRIPTION return "DESCRIPTION"; case 6: // DISABILITY return "DISABILITY"; case 7: // IMP_STATUS return "IMP_STATUS"; case 8: // IMP_DATE return "IMP_DATE"; case 9: // LW_DATE return "LW_DATE"; case 10: // LW_TIME return "LW_TIME"; case 11: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "ORIG_SCHOOL": return 1; case "KCM_TRANS_ID": return 2; case "KCMKEY": return 3; case "KCMKEY_NEW": return 4; case "DESCRIPTION": return 5; case "DISABILITY": return 6; case "IMP_STATUS": return 7; case "IMP_DATE": return 8; case "LW_DATE": return 9; case "LW_TIME": return 10; case "LW_USER": return 11; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// Copyright 2022 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 gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.DataQnA.V1Alpha.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedQuestionServiceClientTest { [xunit::FactAttribute] public void GetQuestionRequestObject() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetQuestionRequest request = new GetQuestionRequest { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), ReadMask = new wkt::FieldMask(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetQuestion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.GetQuestion(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetQuestionRequestObjectAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetQuestionRequest request = new GetQuestionRequest { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), ReadMask = new wkt::FieldMask(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetQuestionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.GetQuestionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.GetQuestionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetQuestion() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetQuestionRequest request = new GetQuestionRequest { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetQuestion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.GetQuestion(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetQuestionAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetQuestionRequest request = new GetQuestionRequest { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetQuestionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.GetQuestionAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.GetQuestionAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetQuestionResourceNames() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetQuestionRequest request = new GetQuestionRequest { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetQuestion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.GetQuestion(request.QuestionName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetQuestionResourceNamesAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetQuestionRequest request = new GetQuestionRequest { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.GetQuestionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.GetQuestionAsync(request.QuestionName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.GetQuestionAsync(request.QuestionName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateQuestionRequestObject() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.CreateQuestion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.CreateQuestion(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateQuestionRequestObjectAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.CreateQuestionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.CreateQuestionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.CreateQuestionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateQuestion() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.CreateQuestion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.CreateQuestion(request.Parent, request.Question); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateQuestionAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.CreateQuestionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.CreateQuestionAsync(request.Parent, request.Question, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.CreateQuestionAsync(request.Parent, request.Question, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateQuestionResourceNames() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.CreateQuestion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.CreateQuestion(request.ParentAsLocationName, request.Question); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateQuestionResourceNamesAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); CreateQuestionRequest request = new CreateQuestionRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Question = new Question(), }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.CreateQuestionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.CreateQuestionAsync(request.ParentAsLocationName, request.Question, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.CreateQuestionAsync(request.ParentAsLocationName, request.Question, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ExecuteQuestionRequestObject() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); ExecuteQuestionRequest request = new ExecuteQuestionRequest { Name = "name1c9368b0", InterpretationIndex = -988014087, }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.ExecuteQuestion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.ExecuteQuestion(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ExecuteQuestionRequestObjectAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); ExecuteQuestionRequest request = new ExecuteQuestionRequest { Name = "name1c9368b0", InterpretationIndex = -988014087, }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.ExecuteQuestionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.ExecuteQuestionAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.ExecuteQuestionAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ExecuteQuestion() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); ExecuteQuestionRequest request = new ExecuteQuestionRequest { Name = "name1c9368b0", InterpretationIndex = -988014087, }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.ExecuteQuestion(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question response = client.ExecuteQuestion(request.Name, request.InterpretationIndex); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ExecuteQuestionAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); ExecuteQuestionRequest request = new ExecuteQuestionRequest { Name = "name1c9368b0", InterpretationIndex = -988014087, }; Question expectedResponse = new Question { QuestionName = QuestionName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), Scopes = { "scopes35c99a1e", }, Query = "queryf0c71c1b", DataSourceAnnotations = { "data_source_annotationscbcadb22", }, InterpretError = new InterpretError(), Interpretations = { new Interpretation(), }, CreateTime = new wkt::Timestamp(), UserEmail = "user_emaildc7bc240", DebugFlags = new DebugFlags(), DebugInfo = new wkt::Any(), }; mockGrpcClient.Setup(x => x.ExecuteQuestionAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Question>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); Question responseCallSettings = await client.ExecuteQuestionAsync(request.Name, request.InterpretationIndex, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Question responseCancellationToken = await client.ExecuteQuestionAsync(request.Name, request.InterpretationIndex, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetUserFeedbackRequestObject() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetUserFeedbackRequest request = new GetUserFeedbackRequest { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.GetUserFeedback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback response = client.GetUserFeedback(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetUserFeedbackRequestObjectAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetUserFeedbackRequest request = new GetUserFeedbackRequest { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.GetUserFeedbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserFeedback>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback responseCallSettings = await client.GetUserFeedbackAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserFeedback responseCancellationToken = await client.GetUserFeedbackAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetUserFeedback() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetUserFeedbackRequest request = new GetUserFeedbackRequest { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.GetUserFeedback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback response = client.GetUserFeedback(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetUserFeedbackAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetUserFeedbackRequest request = new GetUserFeedbackRequest { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.GetUserFeedbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserFeedback>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback responseCallSettings = await client.GetUserFeedbackAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserFeedback responseCancellationToken = await client.GetUserFeedbackAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetUserFeedbackResourceNames() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetUserFeedbackRequest request = new GetUserFeedbackRequest { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.GetUserFeedback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback response = client.GetUserFeedback(request.UserFeedbackName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetUserFeedbackResourceNamesAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); GetUserFeedbackRequest request = new GetUserFeedbackRequest { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.GetUserFeedbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserFeedback>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback responseCallSettings = await client.GetUserFeedbackAsync(request.UserFeedbackName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserFeedback responseCancellationToken = await client.GetUserFeedbackAsync(request.UserFeedbackName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateUserFeedbackRequestObject() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); UpdateUserFeedbackRequest request = new UpdateUserFeedbackRequest { UserFeedback = new UserFeedback(), UpdateMask = new wkt::FieldMask(), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.UpdateUserFeedback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback response = client.UpdateUserFeedback(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateUserFeedbackRequestObjectAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); UpdateUserFeedbackRequest request = new UpdateUserFeedbackRequest { UserFeedback = new UserFeedback(), UpdateMask = new wkt::FieldMask(), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.UpdateUserFeedbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserFeedback>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback responseCallSettings = await client.UpdateUserFeedbackAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserFeedback responseCancellationToken = await client.UpdateUserFeedbackAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateUserFeedback() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); UpdateUserFeedbackRequest request = new UpdateUserFeedbackRequest { UserFeedback = new UserFeedback(), UpdateMask = new wkt::FieldMask(), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.UpdateUserFeedback(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback response = client.UpdateUserFeedback(request.UserFeedback, request.UpdateMask); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateUserFeedbackAsync() { moq::Mock<QuestionService.QuestionServiceClient> mockGrpcClient = new moq::Mock<QuestionService.QuestionServiceClient>(moq::MockBehavior.Strict); UpdateUserFeedbackRequest request = new UpdateUserFeedbackRequest { UserFeedback = new UserFeedback(), UpdateMask = new wkt::FieldMask(), }; UserFeedback expectedResponse = new UserFeedback { UserFeedbackName = UserFeedbackName.FromProjectLocationQuestion("[PROJECT]", "[LOCATION]", "[QUESTION]"), FreeFormFeedback = "free_form_feedbackab42f4bb", Rating = UserFeedback.Types.UserFeedbackRating.Unspecified, }; mockGrpcClient.Setup(x => x.UpdateUserFeedbackAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserFeedback>(stt::Task.FromResult(expectedResponse), null, null, null, null)); QuestionServiceClient client = new QuestionServiceClientImpl(mockGrpcClient.Object, null); UserFeedback responseCallSettings = await client.UpdateUserFeedbackAsync(request.UserFeedback, request.UpdateMask, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserFeedback responseCancellationToken = await client.UpdateUserFeedbackAsync(request.UserFeedback, request.UpdateMask, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * 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. *******************************************************************************/ // // Novell.Directory.Ldap.Utilclass.DN.cs // // Author: // Sunil Kumar ([email protected]) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.Ldap.Utilclass { /// <summary> A DN encapsulates a Distinguished Name (an ldap name with context). A DN /// does not need to be fully distinguished, or extend to the Root of a /// directory. It provides methods to get information about the DN and to /// manipulate the DN. /// /// The following are examples of valid DN: /// <ul> /// <li>cn=admin,ou=marketing,o=corporation</li> /// <li>cn=admin,ou=marketing</li> /// <li>2.5.4.3=admin,ou=marketing</li> /// <li>oid.2.5.4.3=admin,ou=marketing</li> /// </ul> /// /// Note: Multivalued attributes are all considered to be one /// component and are represented in one RDN (see RDN) /// /// /// </summary> /// <seealso cref="RDN"> /// </seealso> public class DN : System.Object { private void InitBlock() { rdnList = new System.Collections.ArrayList(); } /// <summary> Retrieves a list of RDN Objects, or individual names of the DN</summary> /// <returns> list of RDNs /// </returns> virtual public System.Collections.ArrayList RDNs { get { int size = rdnList.Count; System.Collections.ArrayList v = new System.Collections.ArrayList(size); for (int i = 0; i < size; i++) { v.Add(rdnList[i]); } return v; } } /// <summary> Returns the Parent of this DN</summary> /// <returns> Parent DN /// </returns> virtual public DN Parent { get { DN parent = new DN(); parent.rdnList = (System.Collections.ArrayList) this.rdnList.Clone(); if (parent.rdnList.Count >= 1) parent.rdnList.Remove(rdnList[0]); //remove first object return parent; } } //parser state identifiers. private const int LOOK_FOR_RDN_ATTR_TYPE = 1; private const int ALPHA_ATTR_TYPE = 2; private const int OID_ATTR_TYPE = 3; private const int LOOK_FOR_RDN_VALUE = 4; private const int QUOTED_RDN_VALUE = 5; private const int HEX_RDN_VALUE = 6; private const int UNQUOTED_RDN_VALUE = 7; /* State transition table: Parsing starts in state 1. State COMMA DIGIT "Oid." ALPHA EQUAL QUOTE SHARP HEX -------------------------------------------------------------------- 1 Err 3 3 2 Err Err Err Err 2 Err Err Err 2 4 Err Err Err 3 Err 3 Err Err 4 Err Err Err 4 Err 7 Err 7 Err 5 6 7 5 1 5 Err 5 Err 1 Err 7 6 1 6 Err Err Err Err Err 6 7 1 7 Err 7 Err Err Err 7 */ private System.Collections.ArrayList rdnList; public DN() { InitBlock(); return ; } /// <summary> Constructs a new DN based on the specified string representation of a /// distinguished name. The syntax of the DN must conform to that specified /// in RFC 2253. /// /// </summary> /// <param name="dnString">a string representation of the distinguished name /// </param> /// <exception> IllegalArgumentException if the the value of the dnString /// parameter does not adhere to the syntax described in /// RFC 2253 /// </exception> public DN(System.String dnString) { InitBlock(); /* the empty string is a valid DN */ if (dnString.Length == 0) return ; char currChar; char nextChar; int currIndex; char[] tokenBuf = new char[dnString.Length]; int tokenIndex; int lastIndex; int valueStart; int state; int trailingSpaceCount = 0; System.String attrType = ""; System.String attrValue = ""; System.String rawValue = ""; int hexDigitCount = 0; RDN currRDN = new RDN(); //indicates whether an OID number has a first digit of ZERO bool firstDigitZero = false; tokenIndex = 0; currIndex = 0; valueStart = 0; state = LOOK_FOR_RDN_ATTR_TYPE; lastIndex = dnString.Length - 1; while (currIndex <= lastIndex) { currChar = dnString[currIndex]; switch (state) { case LOOK_FOR_RDN_ATTR_TYPE: while (currChar == ' ' && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if (isAlpha(currChar)) { if (dnString.Substring(currIndex).StartsWith("oid.") || dnString.Substring(currIndex).StartsWith("OID.")) { //form is "oid.###.##.###... or OID.###.##.###... currIndex += 4; //skip oid. prefix and get to actual oid if (currIndex > lastIndex) throw new System.ArgumentException(dnString); currChar = dnString[currIndex]; if (isDigit(currChar)) { tokenBuf[tokenIndex++] = currChar; state = OID_ATTR_TYPE; } else throw new System.ArgumentException(dnString); } else { tokenBuf[tokenIndex++] = currChar; state = ALPHA_ATTR_TYPE; } } else if (isDigit(currChar)) { --currIndex; state = OID_ATTR_TYPE; } else if (!(System.Char.GetUnicodeCategory(currChar) == System.Globalization.UnicodeCategory.SpaceSeparator)) throw new System.ArgumentException(dnString); break; case ALPHA_ATTR_TYPE: if (isAlpha(currChar) || isDigit(currChar) || (currChar == '-')) tokenBuf[tokenIndex++] = currChar; else { //skip any spaces while ((currChar == ' ') && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if (currChar == '=') { attrType = new System.String(tokenBuf, 0, tokenIndex); tokenIndex = 0; state = LOOK_FOR_RDN_VALUE; } else throw new System.ArgumentException(dnString); } break; case OID_ATTR_TYPE: if (!isDigit(currChar)) throw new System.ArgumentException(dnString); firstDigitZero = (currChar == '0')?true:false; tokenBuf[tokenIndex++] = currChar; currChar = dnString[++currIndex]; if ((isDigit(currChar) && firstDigitZero) || (currChar == '.' && firstDigitZero)) { throw new System.ArgumentException(dnString); } //consume all numbers. while (isDigit(currChar) && (currIndex < lastIndex)) { tokenBuf[tokenIndex++] = currChar; currChar = dnString[++currIndex]; } if (currChar == '.') { tokenBuf[tokenIndex++] = currChar; //The state remains at OID_ATTR_TYPE } else { //skip any spaces while (currChar == ' ' && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if (currChar == '=') { attrType = new System.String(tokenBuf, 0, tokenIndex); tokenIndex = 0; state = LOOK_FOR_RDN_VALUE; } else throw new System.ArgumentException(dnString); } break; case LOOK_FOR_RDN_VALUE: while (currChar == ' ') { if (currIndex < lastIndex) currChar = dnString[++currIndex]; else throw new System.ArgumentException(dnString); } if (currChar == '"') { state = QUOTED_RDN_VALUE; valueStart = currIndex; } else if (currChar == '#') { hexDigitCount = 0; tokenBuf[tokenIndex++] = currChar; valueStart = currIndex; state = HEX_RDN_VALUE; } else { valueStart = currIndex; //check this character again in the UNQUOTED_RDN_VALUE state currIndex--; state = UNQUOTED_RDN_VALUE; } break; case UNQUOTED_RDN_VALUE: if (currChar == '\\') { if (!(currIndex < lastIndex)) throw new System.ArgumentException(dnString); currChar = dnString[++currIndex]; if (isHexDigit(currChar)) { if (!(currIndex < lastIndex)) throw new System.ArgumentException(dnString); nextChar = dnString[++currIndex]; if (isHexDigit(nextChar)) { tokenBuf[tokenIndex++] = hexToChar(currChar, nextChar); trailingSpaceCount = 0; } else throw new System.ArgumentException(dnString); } else if (needsEscape(currChar) || currChar == '#' || currChar == '=' || currChar == ' ') { tokenBuf[tokenIndex++] = currChar; trailingSpaceCount = 0; } else throw new System.ArgumentException(dnString); } else if (currChar == ' ') { trailingSpaceCount++; tokenBuf[tokenIndex++] = currChar; } else if ((currChar == ',') || (currChar == ';') || (currChar == '+')) { attrValue = new System.String(tokenBuf, 0, tokenIndex - trailingSpaceCount); rawValue = dnString.Substring(valueStart, (currIndex - trailingSpaceCount) - (valueStart)); currRDN.add(attrType, attrValue, rawValue); if (currChar != '+') { rdnList.Add(currRDN); currRDN = new RDN(); } trailingSpaceCount = 0; tokenIndex = 0; state = LOOK_FOR_RDN_ATTR_TYPE; } else if (needsEscape(currChar)) { throw new System.ArgumentException(dnString); } else { trailingSpaceCount = 0; tokenBuf[tokenIndex++] = currChar; } break; //end UNQUOTED RDN VALUE case QUOTED_RDN_VALUE: if (currChar == '"') { rawValue = dnString.Substring(valueStart, (currIndex + 1) - (valueStart)); if (currIndex < lastIndex) currChar = dnString[++currIndex]; //skip any spaces while ((currChar == ' ') && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if ((currChar == ',') || (currChar == ';') || (currChar == '+') || (currIndex == lastIndex)) { attrValue = new System.String(tokenBuf, 0, tokenIndex); currRDN.add(attrType, attrValue, rawValue); if (currChar != '+') { rdnList.Add(currRDN); currRDN = new RDN(); } trailingSpaceCount = 0; tokenIndex = 0; state = LOOK_FOR_RDN_ATTR_TYPE; } else throw new System.ArgumentException(dnString); } else if (currChar == '\\') { currChar = dnString[++currIndex]; if (isHexDigit(currChar)) { nextChar = dnString[++currIndex]; if (isHexDigit(nextChar)) { tokenBuf[tokenIndex++] = hexToChar(currChar, nextChar); trailingSpaceCount = 0; } else throw new System.ArgumentException(dnString); } else if (needsEscape(currChar) || currChar == '#' || currChar == '=' || currChar == ' ') { tokenBuf[tokenIndex++] = currChar; trailingSpaceCount = 0; } else throw new System.ArgumentException(dnString); } else tokenBuf[tokenIndex++] = currChar; break; //end QUOTED RDN VALUE case HEX_RDN_VALUE: if ((!isHexDigit(currChar)) || (currIndex > lastIndex)) { //check for odd number of hex digits if ((hexDigitCount % 2) != 0 || hexDigitCount == 0) throw new System.ArgumentException(dnString); else { rawValue = dnString.Substring(valueStart, (currIndex) - (valueStart)); //skip any spaces while ((currChar == ' ') && (currIndex < lastIndex)) currChar = dnString[++currIndex]; if ((currChar == ',') || (currChar == ';') || (currChar == '+') || (currIndex == lastIndex)) { attrValue = new System.String(tokenBuf, 0, tokenIndex); //added by cameron currRDN.add(attrType, attrValue, rawValue); if (currChar != '+') { rdnList.Add(currRDN); currRDN = new RDN(); } tokenIndex = 0; state = LOOK_FOR_RDN_ATTR_TYPE; } else { throw new System.ArgumentException(dnString); } } } else { tokenBuf[tokenIndex++] = currChar; hexDigitCount++; } break; //end HEX RDN VALUE } //end switch currIndex++; } //end while //check ending state if (state == UNQUOTED_RDN_VALUE || (state == HEX_RDN_VALUE && (hexDigitCount % 2) == 0) && hexDigitCount != 0) { attrValue = new System.String(tokenBuf, 0, tokenIndex - trailingSpaceCount); rawValue = dnString.Substring(valueStart, (currIndex - trailingSpaceCount) - (valueStart)); currRDN.add(attrType, attrValue, rawValue); rdnList.Add(currRDN); } else if (state == LOOK_FOR_RDN_VALUE) { //empty value is valid attrValue = ""; rawValue = dnString.Substring(valueStart); currRDN.add(attrType, attrValue, rawValue); rdnList.Add(currRDN); } else { throw new System.ArgumentException(dnString); } } //end DN constructor (string dn) /// <summary> Checks a character to see if it is an ascii alphabetic character in /// ranges 65-90 or 97-122. /// /// </summary> /// <param name="ch">the character to be tested. /// </param> /// <returns> <code>true</code> if the character is an ascii alphabetic /// character /// </returns> private bool isAlpha(char ch) { if (((ch < 91) && (ch > 64)) || ((ch < 123) && (ch > 96))) //ASCII A-Z return true; else return false; } /// <summary> Checks a character to see if it is an ascii digit (0-9) character in /// the ascii value range 48-57. /// /// </summary> /// <param name="ch">the character to be tested. /// </param> /// <returns> <code>true</code> if the character is an ascii alphabetic /// character /// </returns> private bool isDigit(char ch) { if ((ch < 58) && (ch > 47)) //ASCII 0-9 return true; else return false; } /// <summary> Checks a character to see if it is valid hex digit 0-9, a-f, or /// A-F (ASCII value ranges 48-47, 65-70, 97-102). /// /// </summary> /// <param name="ch">the character to be tested. /// </param> /// <returns> <code>true</code> if the character is a valid hex digit /// </returns> private static bool isHexDigit(char ch) { if (((ch < 58) && (ch > 47)) || ((ch < 71) && (ch > 64)) || ((ch < 103) && (ch > 96))) //ASCII A-F return true; else return false; } /// <summary> Checks a character to see if it must always be escaped in the /// string representation of a DN. We must tests for space, sharp, and /// equals individually. /// /// </summary> /// <param name="ch">the character to be tested. /// </param> /// <returns> <code>true</code> if the character needs to be escaped in at /// least some instances. /// </returns> private bool needsEscape(char ch) { if ((ch == ',') || (ch == '+') || (ch == '\"') || (ch == ';') || (ch == '<') || (ch == '>') || (ch == '\\')) return true; else return false; } /// <summary> Converts two valid hex digit characters that form the string /// representation of an ascii character value to the actual ascii /// character. /// /// </summary> /// <param name="hex1">the hex digit for the high order byte. /// </param> /// <param name="hex0">the hex digit for the low order byte. /// </param> /// <returns> the character whose value is represented by the parameters. /// </returns> private static char hexToChar(char hex1, char hex0) { int result; if ((hex1 < 58) && (hex1 > 47)) //ASCII 0-9 result = (hex1 - 48) * 16; else if ((hex1 < 71) && (hex1 > 64)) //ASCII a-f result = (hex1 - 55) * 16; else if ((hex1 < 103) && (hex1 > 96)) //ASCII A-F result = (hex1 - 87) * 16; else throw new System.ArgumentException("Not hex digit"); if ((hex0 < 58) && (hex0 > 47)) //ASCII 0-9 result += (hex0 - 48); else if ((hex0 < 71) && (hex0 > 64)) //ASCII a-f result += (hex0 - 55); else if ((hex0 < 103) && (hex0 > 96)) //ASCII A-F result += (hex0 - 87); else throw new System.ArgumentException("Not hex digit"); return (char) result; } /// <summary> Creates and returns a string that represents this DN. The string /// follows RFC 2253, which describes String representation of DN's and /// RDN's /// /// </summary> /// <returns> A DN string. /// </returns> public override System.String ToString() { int length = rdnList.Count; System.String dn = ""; if (length < 1) return null; dn = rdnList[0].ToString(); for (int i = 1; i < length; i++) { dn += ("," + rdnList[i].ToString()); } return dn; } /// <summary> Compares this DN to the specified DN to determine if they are equal. /// /// </summary> /// <param name="toDN">the DN to compare to /// </param> /// <returns> <code>true</code> if the DNs are equal; otherwise /// <code>false</code> /// </returns> public System.Collections.ArrayList getrdnList() { return this.rdnList; } public override bool Equals(System.Object toDN) { return Equals((DN) toDN); } public bool Equals(DN toDN) { System.Collections.ArrayList aList=toDN.getrdnList(); int length = aList.Count; if (this.rdnList.Count != length) return false; for (int i = 0; i < length; i++) { if (!((RDN) rdnList[i]).equals((RDN) toDN.getrdnList()[i])) return false; } return true; } /// <summary> return a string array of the individual RDNs contained in the DN /// /// </summary> /// <param name="noTypes"> If true, returns only the values of the /// components, and not the names, e.g. "Babs /// Jensen", "Accounting", "Acme", "us" - instead of /// "cn=Babs Jensen", "ou=Accounting", "o=Acme", and /// "c=us". /// </param> /// <returns> <code>String[]</code> containing the rdns in the DN with /// the leftmost rdn in the first element of the array /// /// </returns> public virtual System.String[] explodeDN(bool noTypes) { int length = rdnList.Count; System.String[] rdns = new System.String[length]; for (int i = 0; i < length; i++) rdns[i] = ((RDN) rdnList[i]).toString(noTypes); return rdns; } /// <summary> Retrieves the count of RDNs, or individule names, in the Distinguished name</summary> /// <returns> the count of RDN /// </returns> public virtual int countRDNs() { return rdnList.Count; } /// <summary>Determines if this DN is <I>contained</I> by the DN passed in. For /// example: "cn=admin, ou=marketing, o=corporation" is contained by /// "o=corporation", "ou=marketing, o=corporation", and "ou=marketing" /// but <B>not</B> by "cn=admin" or "cn=admin,ou=marketing,o=corporation" /// Note: For users of Netscape's SDK this method is comparable to contains /// /// </summary> /// <param name="containerDN">of a container /// </param> /// <returns> true if containerDN contains this DN /// </returns> public virtual bool isDescendantOf(DN containerDN) { int i = containerDN.rdnList.Count - 1; //index to an RDN of the ContainerDN int j = this.rdnList.Count - 1; //index to an RDN of the ContainedDN //Search from the end of the DN for an RDN that matches the end RDN of //containerDN. while (!((RDN) this.rdnList[j]).equals((RDN) containerDN.rdnList[i])) { j--; if (j <= 0) return false; //if the end RDN of containerDN does not have any equal //RDN in rdnList, then containerDN does not contain this DN } i--; //avoid a redundant compare j--; //step backwards to verify that all RDNs in containerDN exist in this DN for (; i >= 0 && j >= 0; i--, j--) { if (!((RDN) this.rdnList[j]).equals((RDN) containerDN.rdnList[i])) return false; } if (j == 0 && i == 0) //the DNs are identical and thus not contained return false; return true; } /// <summary> Adds the RDN to the beginning of the current DN.</summary> /// <param name="rdn">an RDN to be added /// </param> public virtual void addRDN(RDN rdn) { rdnList.Insert(0, rdn); } /// <summary> Adds the RDN to the beginning of the current DN.</summary> /// <param name="rdn">an RDN to be added /// </param> public virtual void addRDNToFront(RDN rdn) { rdnList.Insert(0, rdn); } /// <summary> Adds the RDN to the end of the current DN</summary> /// <param name="rdn">an RDN to be added /// </param> public virtual void addRDNToBack(RDN rdn) { rdnList.Add(rdn); } } //end class DN }
//----------------------------------------------------------------------- // <copyright file="TcpStages.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Net; using System.Threading.Tasks; using Akka.Actor; using Akka.IO; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using Akka.Util; using Akka.Util.Internal; using StreamTcp = Akka.Streams.Dsl.Tcp; using Tcp = Akka.IO.Tcp; namespace Akka.Streams.Implementation.IO { /// <summary> /// INTERNAL API /// </summary> internal sealed class ConnectionSourceStage : GraphStageWithMaterializedValue<SourceShape<StreamTcp.IncomingConnection>, Task<StreamTcp.ServerBinding>> { #region internal classes private sealed class ConnectionSourceStageLogic : TimerGraphStageLogic, IOutHandler { private const string BindShutdownTimer = "BindTimer"; private readonly AtomicCounterLong _connectionFlowsAwaitingInitialization = new AtomicCounterLong(); private readonly ConnectionSourceStage _stage; private readonly TaskCompletionSource<StreamTcp.ServerBinding> _bindingPromise; private readonly TaskCompletionSource<NotUsed> _unbindPromise = new TaskCompletionSource<NotUsed>(); private IActorRef _listener; public ConnectionSourceStageLogic(Shape shape, ConnectionSourceStage stage, TaskCompletionSource<StreamTcp.ServerBinding> bindingPromise) : base(shape) { _stage = stage; _bindingPromise = bindingPromise; SetHandler(_stage._out, this); } public void OnPull() { // Ignore if still binding _listener?.Tell(new Tcp.ResumeAccepting(1), StageActorRef); } public void OnDownstreamFinish() => TryUnbind(); private StreamTcp.IncomingConnection ConnectionFor(Tcp.Connected connected, IActorRef connection) { _connectionFlowsAwaitingInitialization.IncrementAndGet(); var tcpFlow = Flow.FromGraph(new IncomingConnectionStage(connection, connected.RemoteAddress, _stage._halfClose)) .Via(new Detacher<ByteString>()) // must read ahead for proper completions .MapMaterializedValue(unit => { _connectionFlowsAwaitingInitialization.DecrementAndGet(); return unit; }); // FIXME: Previous code was wrong, must add new tests var handler = tcpFlow; if (_stage._idleTimeout.HasValue) handler = tcpFlow.Join(BidiFlow.BidirectionalIdleTimeout<ByteString, ByteString>(_stage._idleTimeout.Value)); return new StreamTcp.IncomingConnection(connected.LocalAddress, connected.RemoteAddress, handler); } private void TryUnbind() { if (_listener == null) return; StageActorRef.Unwatch(_listener); SetKeepGoing(true); _listener.Tell(Tcp.Unbind.Instance, StageActorRef); } protected internal override void OnTimer(object timerKey) { if (BindShutdownTimer.Equals(timerKey)) CompleteStage(); // TODO need to manually shut down instead right? } public override void PreStart() { GetStageActorRef(Receive); _stage._tcpManager.Tell(new Tcp.Bind(StageActorRef, _stage._endpoint, _stage._backlog, _stage._options, pullMode: true), StageActorRef); } private void Receive(Tuple<IActorRef, object> args) { var sender = args.Item1; var msg = args.Item2; msg.Match() .With<Tcp.Bound>(bound => { _listener = sender; StageActorRef.Watch(_listener); if (IsAvailable(_stage._out)) _listener.Tell(new Tcp.ResumeAccepting(1), StageActorRef); var thisStage = StageActorRef; _bindingPromise.TrySetResult(new StreamTcp.ServerBinding(bound.LocalAddress, () => { // Beware, sender must be explicit since stageActor.ref will be invalid to access after the stage stopped thisStage.Tell(Tcp.Unbind.Instance, thisStage); return _unbindPromise.Task; })); }) .With<Tcp.CommandFailed>(() => { var ex = BindFailedException.Instance; _bindingPromise.TrySetException(ex); _unbindPromise.TrySetResult(NotUsed.Instance); FailStage(ex); }) .With<Tcp.Connected>(c => { Push(_stage._out, ConnectionFor(c, sender)); }) .With<Tcp.Unbind>(() => { if (!IsClosed(_stage._out) && _listener != null) TryUnbind(); }) .With<Tcp.Unbound>(() => // If we're unbound then just shut down { if (_connectionFlowsAwaitingInitialization.Current == 0) CompleteStage(); else ScheduleOnce(BindShutdownTimer, _stage._bindShutdownTimeout); }) .With<Terminated>(terminated => { if (Equals(terminated.ActorRef, _listener)) FailStage(new IllegalStateException("IO Listener actor terminated unexpectedly")); }); } public override void PostStop() { _unbindPromise.TrySetResult(NotUsed.Instance); _bindingPromise.TrySetException( new NoSuchElementException("Binding was unbound before it was completely finished")); } } #endregion private readonly IActorRef _tcpManager; private readonly EndPoint _endpoint; private readonly int _backlog; private readonly IImmutableList<Inet.SocketOption> _options; private readonly bool _halfClose; private readonly TimeSpan? _idleTimeout; private readonly TimeSpan _bindShutdownTimeout; private readonly Outlet<StreamTcp.IncomingConnection> _out = new Outlet<StreamTcp.IncomingConnection>("IncomingConnections.out"); public ConnectionSourceStage(IActorRef tcpManager, EndPoint endpoint, int backlog, IImmutableList<Inet.SocketOption> options, bool halfClose, TimeSpan? idleTimeout, TimeSpan bindShutdownTimeout) { _tcpManager = tcpManager; _endpoint = endpoint; _backlog = backlog; _options = options; _halfClose = halfClose; _idleTimeout = idleTimeout; _bindShutdownTimeout = bindShutdownTimeout; Shape = new SourceShape<StreamTcp.IncomingConnection>(_out); } public override SourceShape<StreamTcp.IncomingConnection> Shape { get; } protected override Attributes InitialAttributes { get; } = Attributes.CreateName("ConnectionSource"); // TODO: Timeout on bind public override ILogicAndMaterializedValue<Task<StreamTcp.ServerBinding>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var bindingPromise = new TaskCompletionSource<StreamTcp.ServerBinding>(); var logic = new ConnectionSourceStageLogic(Shape, this, bindingPromise); return new LogicAndMaterializedValue<Task<StreamTcp.ServerBinding>>(logic, bindingPromise.Task); } } /// <summary> /// INTERNAL API /// </summary> public class IncomingConnectionStage : GraphStage<FlowShape<ByteString, ByteString>> { private readonly IActorRef _connection; private readonly EndPoint _remoteAddress; private readonly bool _halfClose; private readonly AtomicBoolean _hasBeenCreated = new AtomicBoolean(); private readonly Inlet<ByteString> _bytesIn = new Inlet<ByteString>("IncomingTCP.in"); private readonly Outlet<ByteString> _bytesOut = new Outlet<ByteString>("IncomingTCP.out"); public IncomingConnectionStage(IActorRef connection, EndPoint remoteAddress, bool halfClose) { _connection = connection; _remoteAddress = remoteAddress; _halfClose = halfClose; Shape = new FlowShape<ByteString, ByteString>(_bytesIn, _bytesOut); } public override FlowShape<ByteString, ByteString> Shape { get; } protected override Attributes InitialAttributes { get; } = Attributes.CreateName("IncomingConnection"); protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) { if (_hasBeenCreated.Value) throw new IllegalStateException("Cannot materialize an incoming connection Flow twice."); _hasBeenCreated.Value = true; return new TcpConnectionStage.TcpStreamLogic(Shape, new TcpConnectionStage.Inbound(_connection, _halfClose)); } public override string ToString() => $"TCP-from {_remoteAddress}"; } /// <summary> /// INTERNAL API /// </summary> internal static class TcpConnectionStage { private class WriteAck : Tcp.Event { public static readonly WriteAck Instance = new WriteAck(); private WriteAck() { } } internal interface ITcpRole { bool HalfClose { get; } } internal struct Outbound : ITcpRole { public Outbound(IActorRef manager, Tcp.Connect connectCmd, TaskCompletionSource<EndPoint> localAddressPromise, bool halfClose) { Manager = manager; ConnectCmd = connectCmd; LocalAddressPromise = localAddressPromise; HalfClose = halfClose; } public readonly IActorRef Manager; public readonly Tcp.Connect ConnectCmd; public readonly TaskCompletionSource<EndPoint> LocalAddressPromise; public bool HalfClose { get; } } internal struct Inbound : ITcpRole { public Inbound(IActorRef connection, bool halfClose) { Connection = connection; HalfClose = halfClose; } public readonly IActorRef Connection; public bool HalfClose { get; } } internal sealed class TcpStreamLogic : GraphStageLogic { private readonly ITcpRole _role; private readonly Inlet<ByteString> _bytesIn; private readonly Outlet<ByteString> _bytesOut; private IActorRef _connection; private readonly OutHandler _readHandler; public TcpStreamLogic(FlowShape<ByteString, ByteString> shape, ITcpRole role) : base(shape) { _role = role; _bytesIn = shape.Inlet; _bytesOut = shape.Outlet; _readHandler = new LambdaOutHandler( onPull: () => _connection.Tell(Tcp.ResumeReading.Instance, StageActorRef), onDownstreamFinish: () => { if (!IsClosed(_bytesIn)) _connection.Tell(Tcp.ResumeReading.Instance, StageActorRef); else { _connection.Tell(Tcp.Abort.Instance, StageActorRef); CompleteStage(); } }); // No reading until role have been decided SetHandler(_bytesOut, onPull: DoNothing); SetHandler(_bytesIn, onPush: () => { var elem = Grab(_bytesIn); ReactiveStreamsCompliance.RequireNonNullElement(elem); _connection.Tell(Tcp.Write.Create(elem, WriteAck.Instance), StageActorRef); }, onUpstreamFinish: () => { // Reading has stopped before, either because of cancel, or PeerClosed, so just Close now // (or half-close is turned off) if (IsClosed(_bytesOut) || !_role.HalfClose) _connection.Tell(Tcp.Close.Instance, StageActorRef); // We still read, so we only close the write side else if (_connection != null) _connection.Tell(Tcp.ConfirmedClose.Instance, StageActorRef); else CompleteStage(); }, onUpstreamFailure: ex => { if (_connection != null) { if (Interpreter.Log.IsDebugEnabled) Interpreter.Log.Debug( $"Aborting tcp connection because of upstream failure: {ex.Message}\n{ex.StackTrace}"); _connection.Tell(Tcp.Abort.Instance, StageActorRef); } else FailStage(ex); }); } public override void PreStart() { SetKeepGoing(true); if (_role is Inbound) { var inbound = (Inbound)_role; SetHandler(_bytesOut, _readHandler); _connection = inbound.Connection; GetStageActorRef(Connected).Watch(_connection); _connection.Tell(new Tcp.Register(StageActorRef, keepOpenonPeerClosed: true, useResumeWriting: false), StageActorRef); Pull(_bytesIn); } else { var outbound = (Outbound)_role; GetStageActorRef(Connecting(outbound)).Watch(outbound.Manager); outbound.Manager.Tell(outbound.ConnectCmd, StageActorRef); } } public override void PostStop() { if (_role is Outbound) { var outbound = (Outbound) _role; // Fail if has not been completed with an address earlier outbound.LocalAddressPromise.TrySetException(new StreamTcpException("Connection failed")); } } private StageActorRef.Receive Connecting(Outbound outbound) { return args => { var sender = args.Item1; var msg = args.Item2; msg.Match() .With<Terminated>(() => FailStage(new StreamTcpException("The IO manager actor (TCP) has terminated. Stopping now."))) .With<Tcp.CommandFailed>(failed => FailStage(new StreamTcpException($"Tcp command {failed.Cmd} failed"))) .With<Tcp.Connected>(c => { ((Outbound)_role).LocalAddressPromise.TrySetResult(c.LocalAddress); _connection = sender; SetHandler(_bytesOut, _readHandler); StageActorRef.Unwatch(outbound.Manager); StageActorRef.Become(Connected); StageActorRef.Watch(_connection); _connection.Tell(new Tcp.Register(StageActorRef, keepOpenonPeerClosed: true, useResumeWriting: false), StageActorRef); if (IsAvailable(_bytesOut)) _connection.Tell(Tcp.ResumeReading.Instance, StageActorRef); Pull(_bytesIn); }); }; } private void Connected(Tuple<IActorRef, object> args) { var msg = args.Item2; msg.Match() .With<Terminated>(() => FailStage(new StreamTcpException("The connection actor has terminated. Stopping now."))) .With<Tcp.CommandFailed>(failed => FailStage(new StreamTcpException($"Tcp command {failed.Cmd} failed"))) .With<Tcp.ErrorClosed>(cause => FailStage(new StreamTcpException($"The connection closed with error: {cause}"))) .With<Tcp.Aborted>(() => FailStage(new StreamTcpException("The connection has been aborted"))) .With<Tcp.Closed>(CompleteStage) .With<Tcp.ConfirmedClosed>(CompleteStage) .With<Tcp.PeerClosed>(() => Complete(_bytesOut)) .With<Tcp.Received>(received => { // Keep on reading even when closed. There is no "close-read-side" in TCP if (IsClosed(_bytesOut)) _connection.Tell(Tcp.ResumeReading.Instance, StageActorRef); else Push(_bytesOut, received.Data); }) .With<WriteAck>(() => { if (!IsClosed(_bytesIn)) Pull(_bytesIn); }); } } } /// <summary> /// INTERNAL API /// </summary> internal sealed class OutgoingConnectionStage : GraphStageWithMaterializedValue<FlowShape<ByteString, ByteString>, Task<StreamTcp.OutgoingConnection>> { private readonly IActorRef _tcpManager; private readonly EndPoint _remoteAddress; private readonly EndPoint _localAddress; private readonly IImmutableList<Inet.SocketOption> _options; private readonly bool _halfClose; private readonly TimeSpan? _connectionTimeout; private readonly Inlet<ByteString> _bytesIn = new Inlet<ByteString>("IncomingTCP.in"); private readonly Outlet<ByteString> _bytesOut = new Outlet<ByteString>("IncomingTCP.out"); public OutgoingConnectionStage(IActorRef tcpManager, EndPoint remoteAddress, EndPoint localAddress = null, IImmutableList<Inet.SocketOption> options = null, bool halfClose = true, TimeSpan? connectionTimeout = null) { _tcpManager = tcpManager; _remoteAddress = remoteAddress; _localAddress = localAddress; _options = options; _halfClose = halfClose; _connectionTimeout = connectionTimeout; Shape = new FlowShape<ByteString, ByteString>(_bytesIn, _bytesOut); } protected override Attributes InitialAttributes { get; } = Attributes.CreateName("OutgoingConnection"); public override FlowShape<ByteString, ByteString> Shape { get; } public override ILogicAndMaterializedValue<Task<StreamTcp.OutgoingConnection>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var localAddressPromise = new TaskCompletionSource<EndPoint>(); var outgoingConnectionPromise = new TaskCompletionSource<StreamTcp.OutgoingConnection>(); localAddressPromise.Task.ContinueWith( t => { if (t.IsCanceled) outgoingConnectionPromise.TrySetCanceled(); else if (t.IsFaulted) outgoingConnectionPromise.TrySetException(t.Exception); else outgoingConnectionPromise.TrySetResult(new StreamTcp.OutgoingConnection(_remoteAddress, t.Result)); }, TaskContinuationOptions.AttachedToParent); var logic = new TcpConnectionStage.TcpStreamLogic(Shape, new TcpConnectionStage.Outbound(_tcpManager, new Tcp.Connect(_remoteAddress, _localAddress, _options, _connectionTimeout, pullMode: true), localAddressPromise, _halfClose)); return new LogicAndMaterializedValue<Task<StreamTcp.OutgoingConnection>>(logic, outgoingConnectionPromise.Task); } public override string ToString() => $"TCP-to {_remoteAddress}"; } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using d60.Cirqus.Events; using d60.Cirqus.Exceptions; using d60.Cirqus.Extensions; using d60.Cirqus.Numbers; using d60.Cirqus.Serialization; using Npgsql; using NpgsqlTypes; namespace d60.Cirqus.PostgreSql.Events { public class PostgreSqlEventStore : IEventStore { readonly Action<NpgsqlConnection> _additionalConnectionSetup; readonly string _connectionString; readonly string _tableName; readonly MetadataSerializer _metadataSerializer = new MetadataSerializer(); public PostgreSqlEventStore(string connectionStringOrConnectionStringName, string tableName, bool automaticallyCreateSchema = true, Action<NpgsqlConnection> additionalConnectionSetup = null) { _tableName = tableName; _connectionString = SqlHelper.GetConnectionString(connectionStringOrConnectionStringName); _additionalConnectionSetup = additionalConnectionSetup; if (automaticallyCreateSchema) { CreateSchema(); } } void CreateSchema() { var sql = string.Format(@" DO $$ BEGIN IF NOT EXISTS ( SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relname = '{0}' ) THEN CREATE TABLE IF NOT EXISTS ""{0}"" ( ""id"" BIGSERIAL NOT NULL, ""batchId"" UUID NOT NULL, ""aggId"" VARCHAR(255) NOT NULL, ""seqNo"" BIGINT NOT NULL, ""globSeqNo"" BIGINT NOT NULL, ""meta"" BYTEA NOT NULL, ""data"" BYTEA NOT NULL, PRIMARY KEY (""id"") ); CREATE UNIQUE INDEX ""Idx_{0}_aggId_seqNo"" ON ""{0}"" (""aggId"", ""seqNo""); CREATE UNIQUE INDEX ""Idx_{0}_globSeqNo"" ON ""{0}"" (""globSeqNo""); END IF; END$$; ", _tableName); using (var connection = GetConnection()) using (var command = connection.CreateCommand()) { command.CommandText = sql; command.ExecuteNonQuery(); } } public void Save(Guid batchId, IEnumerable<EventData> batch) { var eventList = batch.ToList(); try { using (var connection = GetConnection()) using (var tx = connection.BeginTransaction()) { var nextSequenceNumber = GetNextGlobalSequenceNumber(connection, tx); foreach (var e in eventList) { e.Meta[DomainEvent.MetadataKeys.GlobalSequenceNumber] = (nextSequenceNumber++).ToString(Metadata.NumberCulture); e.Meta[DomainEvent.MetadataKeys.BatchId] = batchId.ToString(); } EventValidation.ValidateBatchIntegrity(batchId, eventList); foreach (var e in eventList) { using (var cmd = connection.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@" INSERT INTO ""{0}"" ( ""batchId"", ""aggId"", ""seqNo"", ""globSeqNo"", ""data"", ""meta"" ) VALUES ( @batchId, @aggId, @seqNo, @globSeqNo, @data, @meta ) ", _tableName); cmd.Parameters.AddWithValue("batchId", batchId); cmd.Parameters.AddWithValue("aggId", e.GetAggregateRootId()); cmd.Parameters.AddWithValue("seqNo", NpgsqlDbType.Bigint, e.Meta[DomainEvent.MetadataKeys.SequenceNumber]); cmd.Parameters.AddWithValue("globSeqNo", NpgsqlDbType.Bigint, e.Meta[DomainEvent.MetadataKeys.GlobalSequenceNumber]); cmd.Parameters.AddWithValue("data", e.Data); cmd.Parameters.AddWithValue("meta", Encoding.UTF8.GetBytes(_metadataSerializer.Serialize(e.Meta))); cmd.ExecuteNonQuery(); } } tx.Commit(); } } catch (PostgresException exception) { if (exception.SqlState == "23505") { throw new ConcurrencyException(batchId, eventList, exception); } throw; } } long GetNextGlobalSequenceNumber(NpgsqlConnection conn, NpgsqlTransaction tx) { using (var cmd = conn.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@"SELECT MAX(""globSeqNo"") FROM ""{0}""", _tableName); var result = cmd.ExecuteScalar(); return result != DBNull.Value ? (long)result + 1 : 0; } } NpgsqlConnection GetConnection() { var connection = new NpgsqlConnection(_connectionString); if (_additionalConnectionSetup != null) _additionalConnectionSetup.Invoke(connection); connection.Open(); return connection; } public IEnumerable<EventData> Load(string aggregateRootId, long firstSeq = 0) { using (var connection = GetConnection()) { using (var tx = connection.BeginTransaction()) { using (var cmd = connection.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@"SELECT ""data"", ""meta"" FROM ""{0}"" WHERE ""aggId"" = @aggId AND ""seqNo"" >= @firstSeqNo ORDER BY ""seqNo""", _tableName); cmd.Parameters.AddWithValue("aggId", aggregateRootId); cmd.Parameters.AddWithValue("firstSeqNo", NpgsqlDbType.Bigint, firstSeq); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { yield return ReadEvent(reader); } } } tx.Commit(); } } } public IEnumerable<EventData> Stream(long globalSequenceNumber = 0) { using (var connection = GetConnection()) { using (var tx = connection.BeginTransaction()) { using (var cmd = connection.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@" SELECT ""data"", ""meta"" FROM ""{0}"" WHERE ""globSeqNo"" >= @cutoff ORDER BY ""globSeqNo""", _tableName); cmd.Parameters.AddWithValue("cutoff", NpgsqlDbType.Bigint, globalSequenceNumber); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { yield return ReadEvent(reader); } } } } } } EventData ReadEvent(IDataRecord reader) { var data = (byte[]) reader["data"]; var meta = (byte[]) reader["meta"]; return EventData.FromMetadata(_metadataSerializer.Deserialize(Encoding.UTF8.GetString(meta)), data); } public long GetNextGlobalSequenceNumber() { using (var connection = GetConnection()) { using (var tx = connection.BeginTransaction()) { return GetNextGlobalSequenceNumber(connection, tx); } } } public void DropEvents() { using (var connection = GetConnection()) { using (var tx = connection.BeginTransaction()) { using (var cmd = connection.CreateCommand()) { cmd.Transaction = tx; cmd.CommandText = string.Format(@"DELETE FROM ""{0}""", _tableName); cmd.ExecuteNonQuery(); } tx.Commit(); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Windows.Forms; using JustGestures.GestureParts; using JustGestures.Languages; namespace JustGestures { [Serializable] public class GesturesCollection : List<MyGesture>, ITranslation { List<MyGesture> m_gestures = new List<MyGesture>(); List<MyGesture> m_groups = new List<MyGesture>(); Dictionary<string, List<MyGesture>> m_matchedGestures = new Dictionary<string, List<MyGesture>>(); Dictionary<MyGesture, List<MyGesture>> m_hiddenActions = new Dictionary<MyGesture, List<MyGesture>>(); public List<MyGesture> Gestures { get { return m_gestures; } } public List<MyGesture> Groups { get { return m_groups; } } #region ITranslation Members private void TranslateGestures() { foreach (MyGesture gest in this) gest.ChangeDescription(); } public void Translate() { TranslateGestures(); } #endregion public MyGesture this[string key] { get { foreach (MyGesture gest in this) if (gest.ID == key) return gest; foreach (MyGesture group in m_hiddenActions.Keys) foreach (MyGesture gest in m_hiddenActions[group]) if (gest.ID == key) return gest; return null; } } public new MyGesture this[int index] { set { if (value.IsGroup) { int groupIndex = m_groups.IndexOf(base[index]); base[index] = value; UpdateGroupGestures(m_groups[groupIndex].ID, base[index]); m_groups[groupIndex] = value; } else { RemoveGesture(base[index]); base[index] = value; AddGesture(base[index]); } } get { return base[index]; } } private void UpdateGroupGestures(string oldGroupID, MyGesture newGroup) { // update group for all gestures foreach (MyGesture gest in m_gestures) { if (gest.AppGroup.ID == oldGroupID) gest.AppGroup = newGroup; } // check if the hidden group should be updated MyGesture hiddenGroup = null; foreach (MyGesture group in m_hiddenActions.Keys) { if (group.ID == oldGroupID) { hiddenGroup = group; break; } } // update gestures in hidden group if (hiddenGroup != null) { newGroup.IsExpanded = false; // move gestures to new group and update them m_hiddenActions.Add(newGroup, m_hiddenActions[hiddenGroup]); foreach (MyGesture gest in m_hiddenActions[newGroup]) gest.AppGroup = newGroup; // remove old group m_hiddenActions.Remove(hiddenGroup); } } public List<MyGesture> MatchedGestures(string curveName) { if (m_matchedGestures.ContainsKey(curveName)) return m_matchedGestures[curveName]; else return new List<MyGesture>(); //return null; } public MouseActivator GetCurve(string curveName) { if (m_matchedGestures.ContainsKey(curveName)) return m_matchedGestures[curveName][0].Activator; else return null; } public Dictionary<string, ClassicCurve> GetCurves() { Dictionary<string, ClassicCurve> curves = new Dictionary<string, ClassicCurve>(); if (m_matchedGestures != null) { foreach (string key in m_matchedGestures.Keys) if (m_matchedGestures[key][0].Activator.Type == MouseActivator.Types.ClassicCurve) curves.Add(key, m_matchedGestures[key][0].Activator); } return curves; } /// <summary> /// Get all gestures and actions (ignores collapsed groups) /// </summary> /// <returns></returns> public List<MyGesture> GetAll() { List<MyGesture> gestures = new List<MyGesture>(); foreach (MyGesture gest in this) { gestures.Add(gest); if (gest.IsGroup && !gest.IsExpanded) { if (m_hiddenActions != null && m_hiddenActions.ContainsKey(gest)) { foreach (MyGesture hiddenGest in m_hiddenActions[gest]) gestures.Add(hiddenGest); } else { // even though group is marked es collapsed the hidden actions has not been populated yet // will be done during GestureListView initialization } } } return gestures; } public GesturesCollection() : base() { //this.Add(MyGesture.GlobalGroup); } public GesturesCollection(MyGesture[] gestures) : base() { if (gestures != null) foreach (MyGesture gest in gestures) this.Add(gest); } public new void Insert(int index, MyGesture gesture) { base.Insert(index, gesture); AddGesture(gesture); } /// <summary> /// Inerts new gesture after the similar actions /// </summary> /// <param name="gesture"></param> /// <returns></returns> public int AutoInsert(MyGesture gesture) { int index = 0; if (!gesture.IsGroup) { int groupId; for (groupId = 0; groupId < m_groups.Count; groupId++) if (m_groups[groupId].ID == gesture.AppGroup.ID) { gesture.AppGroup = m_groups[groupId]; break; } if (m_groups[groupId].IsExpanded) { // insert directly into list if the group is expanded index = InsertIntoExpandedGroup(gesture, groupId); } else { // insert into hidden collection because group is collapsed index = InsertIntoCollapsedGroup(gesture, groupId); } } else { index = this.Count; base.Add(gesture); AddGesture(gesture); } return index; } private int InsertIntoExpandedGroup(MyGesture gestToInsert, int groupId) { int index = 0; // if there is no suitable group or no groupt at all if (groupId < m_groups.Count) index = base.IndexOf(m_groups[groupId]); groupId++; int lastIndex = groupId < m_groups.Count ? base.IndexOf(m_groups[groupId]) : this.Count; if (index != lastIndex) { List<MyGesture> gestures = this.GetRange(index + 1, lastIndex - index - 1); int posInList = GetPositionToInsert(gestures, gestToInsert); index += posInList; } else index++; Insert(index, gestToInsert); return index; } private int InsertIntoCollapsedGroup(MyGesture gestToInsert, int groupId) { int index = 0; List<MyGesture> groupActions = m_hiddenActions[m_groups[groupId]]; index = GetPositionToInsert(groupActions, gestToInsert); index--; groupActions.Insert(index, gestToInsert); AddGesture(gestToInsert); // return -1 which will indicates that action should not be added because group is collapsed return -1; } private static int GetPositionToInsert(List<MyGesture> gestures, MyGesture gestToInsert) { int index = 0; bool sameType = false; for (int i = 0; i < gestures.Count; i++) { index++; MyGesture gest = gestures[i]; if (gest.Action.IsSameType(gestToInsert.Action)) { if (!sameType) sameType = true; } else { if (sameType) { index--; break; } } } index++; return index; } public new void Add(MyGesture gesture) { //int index = this.Count; //if (!gesture.IsGroup) //{ // int i; // for (i = 0; i < m_groups.Count; i++) // if (m_groups[i].ID == gesture.AppGroup.ID) // { // gesture.AppGroup = m_groups[i]; // break; // } // i++; // if (i < m_groups.Count) // { // index = base.IndexOf(m_groups[i]); // Insert(index, gesture); // } // else // { // base.Add(gesture); // AddGesture(gesture); // } //} //else { base.Add(gesture); AddGesture(gesture); } //return index; } private void AddGesture(MyGesture gesture) { if (!gesture.IsGroup) { m_gestures.Add(gesture); if (m_matchedGestures.ContainsKey(gesture.Activator.ID)) { int i = 0; //if (gesture.ItemPos != -1) //{ // while (i < m_matchedGestures[gesture.Activator.ID].Count // && gesture.ItemPos > m_matchedGestures[gesture.Activator.ID][i].ItemPos) // i++; //} //else { i = m_matchedGestures[gesture.Activator.ID].Count; gesture.ItemPos = i; } m_matchedGestures[gesture.Activator.ID].Insert(i, gesture); } else { gesture.ItemPos = 0; m_matchedGestures.Add(gesture.Activator.ID, new List<MyGesture>() { gesture }); } } else m_groups.Add(gesture); } public new string RemoveAt(int index) { if (index < base.Count) { MyGesture gesture = base[index]; return this.Remove(gesture); } else return string.Empty; } public new string Remove(MyGesture gesture) { string curve = string.Empty; if (!MyGesture.Equals(gesture, MyGesture.GlobalGroup)) { curve = RemoveGesture(gesture); base.Remove(gesture); } return curve; } private string RemoveGesture(MyGesture gesture) { string curve = string.Empty; if (!gesture.IsGroup) { m_gestures.Remove(gesture); if (m_matchedGestures[gesture.Activator.ID].Count > 1) { int index = m_matchedGestures[gesture.Activator.ID].IndexOf(gesture); m_matchedGestures[gesture.Activator.ID].Remove(gesture); while (index < m_matchedGestures[gesture.Activator.ID].Count) { m_matchedGestures[gesture.Activator.ID][index].ItemPos--; index++; } } else { curve = gesture.Activator.ID; m_matchedGestures.Remove(gesture.Activator.ID); } } else m_groups.Remove(gesture); return curve; } public void SortMatchedGestures(string curveName) { if (m_matchedGestures.ContainsKey(curveName)) m_matchedGestures[curveName].Sort(ComperByIndexes); } private static int ComperByIndexes(MyGesture x, MyGesture y) { return x.ItemPos.CompareTo(y.ItemPos); } public List<MyGesture> GetGroupActions(MyGesture group) { if (m_hiddenActions != null && m_hiddenActions.ContainsKey(group)) return m_hiddenActions[group]; else { int end = this.Count; int start = group.Index; MyGesture groupGest = this[start]; int next = m_groups.IndexOf(groupGest); next++; if (next < m_groups.Count) end = m_groups[next].Index; start++; if (start != end) return this.GetRange(start, end - start); else return new List<MyGesture>(); } } /// <summary> /// Return true if group doesn't have any acctions /// </summary> /// <param name="group"></param> /// <returns></returns> public bool IsEmptyGroup(MyGesture group) { return GetGroupActions(group).Count == 0; } /// <summary> /// Collapse all groups that are set as collapsed. /// </summary> public void UpdateCollapsedGroups() { foreach (MyGesture group in m_groups) if (!group.IsExpanded) CollapseGroup(group); } public void CollapseGroup(MyGesture group) { if (m_hiddenActions == null) m_hiddenActions = new Dictionary<MyGesture, List<MyGesture>>(); if (!m_hiddenActions.ContainsKey(group)) { List<MyGesture> groupActions = GetGroupActions(group); m_hiddenActions.Add(group, groupActions); foreach (MyGesture gesture in groupActions) { base.Remove(gesture); } } } public List<MyGesture> ExpandGroup(MyGesture group) { if (m_hiddenActions == null || !m_hiddenActions.ContainsKey(group)) return new List<MyGesture>(); else { List<MyGesture> actions = m_hiddenActions[group]; base.InsertRange(group.Index + 1, actions); m_hiddenActions.Remove(group); return actions; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; namespace VisualParamGenerator { class VisualParamGenerator { public static readonly System.Globalization.CultureInfo EnUsCulture = new System.Globalization.CultureInfo("en-us"); static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("Usage: VisualParamGenerator.exe [template.cs] [_VisualParams_.cs]"); return; } else if (!File.Exists(args[0])) { Console.WriteLine("Couldn't find file " + args[0]); return; } XmlNodeList list; TextWriter writer; try { writer = new StreamWriter(args[1]); } catch (Exception) { Console.WriteLine("Couldn't open " + args[1] + " for writing"); return; } try { // Read in the template.cs file and write it to our output TextReader reader = new StreamReader(args[0]); writer.WriteLine(reader.ReadToEnd()); reader.Close(); } catch (Exception) { Console.WriteLine("Couldn't read from file " + args[0]); return; } try { // Read in avatar_lad.xml Stream stream = OpenMetaverse.Helpers.GetResourceStream("avatar_lad.xml"); if (stream != null) { StreamReader reader = new StreamReader(stream); XmlDocument doc = new XmlDocument(); doc.LoadXml(reader.ReadToEnd()); list = doc.GetElementsByTagName("param"); } else { Console.WriteLine("Failed to load resource avatar_lad.xml. Are you missing a data folder?"); return; } } catch (Exception e) { Console.WriteLine(e.ToString()); return; } SortedList<int, string> IDs = new SortedList<int, string>(); Dictionary<int, string> Alphas = new Dictionary<int, string>(); Dictionary<int, string> Colors = new Dictionary<int, string>(); StringWriter output = new StringWriter(); // Make sure we end up with 218 Group-0 VisualParams as a sanity check int count = 0; foreach (XmlNode node in list) { if (node.Attributes["group"] == null) { // Sanity check that a group is assigned Console.WriteLine("Encountered a param with no group set!"); continue; } if ((node.Attributes["shared"] != null) && (node.Attributes["shared"].Value.Equals("1"))) { // This param will have been already been defined continue; } if ((node.Attributes["edit_group"] == null)) { // This param is calculated by the client based on other params continue; } // Confirm this is a valid VisualParam if (node.Attributes["id"] != null && node.Attributes["name"] != null) { try { int id = Int32.Parse(node.Attributes["id"].Value); string bumpAttrib = "false"; bool skipColor = false; if (node.ParentNode.Name == "layer") { if (node.ParentNode.Attributes["render_pass"] != null && node.ParentNode.Attributes["render_pass"].Value == "bump") { bumpAttrib = "true"; } for (int nodeNr = 0; nodeNr < node.ParentNode.ChildNodes.Count; nodeNr++) { XmlNode lnode = node.ParentNode.ChildNodes[nodeNr]; if (lnode.Name == "texture") { if (lnode.Attributes["local_texture_alpha_only"] != null && lnode.Attributes["local_texture_alpha_only"].Value.ToLower() == "true") { skipColor = true; } } } } if (node.HasChildNodes) { for (int nodeNr = 0; nodeNr < node.ChildNodes.Count; nodeNr++) { #region Alpha mask and bumps if (node.ChildNodes[nodeNr].Name == "param_alpha") { XmlNode anode = node.ChildNodes[nodeNr]; string tga_file = "string.Empty"; string skip_if_zero = "false"; string multiply_blend = "false"; string domain = "0"; if (anode.Attributes["domain"] != null) domain = anode.Attributes["domain"].Value; if (anode.Attributes["tga_file"] != null) tga_file = string.Format("\"{0}\"", anode.Attributes["tga_file"].Value); ; if (anode.Attributes["skip_if_zero"] != null && anode.Attributes["skip_if_zero"].Value.ToLower() == "true") skip_if_zero = "true"; if (anode.Attributes["multiply_blend"] != null && anode.Attributes["multiply_blend"].Value.ToLower() == "true") multiply_blend = "true"; Alphas.Add(id, string.Format("new VisualAlphaParam({0}f, {1}, {2}, {3})", domain, tga_file, skip_if_zero, multiply_blend)); } #endregion #region Colors else if (node.ChildNodes[nodeNr].Name == "param_color" && node.ChildNodes[nodeNr].HasChildNodes) { XmlNode cnode = node.ChildNodes[nodeNr]; string operation = "VisualColorOperation.Add"; List<string> colors = new List<string>(); if (cnode.Attributes["operation"] != null) { switch (cnode.Attributes["operation"].Value) { case "blend": operation = "VisualColorOperation.Blend"; break; case "multiply": operation = "VisualColorOperation.Blend"; break; } } foreach (XmlNode cvalue in cnode.ChildNodes) { if (cvalue.Name == "value" && cvalue.Attributes["color"] != null) { Match m = Regex.Match(cvalue.Attributes["color"].Value, @"((?<val>\d+)(?:, *)?){4}"); if (!m.Success) { continue; } CaptureCollection val = m.Groups["val"].Captures; colors.Add(string.Format("new Color4({0}, {1}, {2}, {3})", val[0], val[1], val[2], val[3])); } } if (colors.Count > 0 && !skipColor) { string colorsStr = string.Join(", ", colors.ToArray()); Colors.Add(id, string.Format("new VisualColorParam({0}, new Color4[] {{ {1} }})", operation, colorsStr)); } } #endregion } } // Check for duplicates if (IDs.ContainsKey(id)) continue; string name = node.Attributes["name"].Value; int group = Int32.Parse(node.Attributes["group"].Value); string wearable = "null"; if (node.Attributes["wearable"] != null) wearable = "\"" + node.Attributes["wearable"].Value + "\""; string label = "String.Empty"; if (node.Attributes["label"] != null) label = "\"" + node.Attributes["label"].Value + "\""; string label_min = "String.Empty"; if (node.Attributes["label_min"] != null) label_min = "\"" + node.Attributes["label_min"].Value + "\""; string label_max = "String.Empty"; if (node.Attributes["label_max"] != null) label_max = "\"" + node.Attributes["label_max"].Value + "\""; float min = Single.Parse(node.Attributes["value_min"].Value, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat); float max = Single.Parse(node.Attributes["value_max"].Value, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat); float def; if (node.Attributes["value_default"] != null) def = Single.Parse(node.Attributes["value_default"].Value, System.Globalization.NumberStyles.Float, EnUsCulture.NumberFormat); else def = min; string drivers = "null"; if (node.HasChildNodes) { for (int nodeNr = 0; nodeNr < node.ChildNodes.Count; nodeNr++) { XmlNode cnode = node.ChildNodes[nodeNr]; if (cnode.Name == "param_driver" && cnode.HasChildNodes) { List<string> driverIDs = new List<string>(); foreach (XmlNode dnode in cnode.ChildNodes) { if (dnode.Name == "driven" && dnode.Attributes["id"] != null) { driverIDs.Add(dnode.Attributes["id"].Value); } } if (driverIDs.Count > 0) { drivers = string.Format("new int[] {{ {0} }}", string.Join(", ", driverIDs.ToArray())); } } } } IDs.Add(id, String.Format(" Params[{0}] = new VisualParam({0}, \"{1}\", {2}, {3}, {4}, {5}, {6}, {7}f, {8}f, {9}f, {10}, {11}, ", id, name, group, wearable, label, label_min, label_max, def, min, max, bumpAttrib, drivers)); if (group == 0) ++count; } catch (Exception e) { Console.WriteLine(e.ToString()); } } } if (count != 218) { Console.WriteLine("Ended up with the wrong number of Group-0 VisualParams! Exiting..."); return; } // Now that we've collected all the entries and sorted them, add them to our output buffer foreach (KeyValuePair<int, string> line in IDs) { output.Write(line.Value); if (Alphas.ContainsKey(line.Key)) { output.Write(Alphas[line.Key] + ", "); } else { output.Write("null, "); } if (Colors.ContainsKey(line.Key)) { output.Write(Colors[line.Key]); } else { output.Write("null"); } output.WriteLine(");"); } output.Write(" }" + Environment.NewLine); output.Write(" }" + Environment.NewLine); output.Write("}" + Environment.NewLine); try { writer.Write(output.ToString()); writer.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } }
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [Cmdlet("New", "AzureRmDiskConfig", SupportsShouldProcess = true)] [OutputType(typeof(PSDisk))] public partial class NewAzureRmDiskConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)] [Alias("AccountType")] public StorageAccountTypes? SkuName { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public OperatingSystemTypes? OsType { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public int? DiskSizeGB { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] public string Location { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public DiskCreateOption? CreateOption { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string StorageAccountId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public ImageDiskReference ImageReference { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SourceUri { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public string SourceResourceId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public bool? EncryptionSettingsEnabled { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public KeyVaultAndSecretReference DiskEncryptionKey { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public KeyVaultAndKeyReference KeyEncryptionKey { get; set; } protected override void ProcessRecord() { if (ShouldProcess("Disk", "New")) { Run(); } } private void Run() { // Sku Microsoft.Azure.Management.Compute.Models.DiskSku vSku = null; // CreationData Microsoft.Azure.Management.Compute.Models.CreationData vCreationData = null; // EncryptionSettings Microsoft.Azure.Management.Compute.Models.EncryptionSettings vEncryptionSettings = null; if (this.SkuName != null) { if (vSku == null) { vSku = new Microsoft.Azure.Management.Compute.Models.DiskSku(); } vSku.Name = this.SkuName; } if (this.CreateOption.HasValue) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.CreateOption = this.CreateOption.Value; } if (this.StorageAccountId != null) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.StorageAccountId = this.StorageAccountId; } if (this.ImageReference != null) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.ImageReference = this.ImageReference; } if (this.SourceUri != null) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.SourceUri = this.SourceUri; } if (this.SourceResourceId != null) { if (vCreationData == null) { vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData(); } vCreationData.SourceResourceId = this.SourceResourceId; } if (this.EncryptionSettingsEnabled != null) { if (vEncryptionSettings == null) { vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings(); } vEncryptionSettings.Enabled = this.EncryptionSettingsEnabled; } if (this.DiskEncryptionKey != null) { if (vEncryptionSettings == null) { vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings(); } vEncryptionSettings.DiskEncryptionKey = this.DiskEncryptionKey; } if (this.KeyEncryptionKey != null) { if (vEncryptionSettings == null) { vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings(); } vEncryptionSettings.KeyEncryptionKey = this.KeyEncryptionKey; } var vDisk = new PSDisk { OsType = this.OsType, DiskSizeGB = this.DiskSizeGB, Location = this.Location, Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value), Sku = vSku, CreationData = vCreationData, EncryptionSettings = vEncryptionSettings, }; WriteObject(vDisk); } } }
using Lucene.Net.Index; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using IBits = Lucene.Net.Util.IBits; using BytesRef = Lucene.Net.Util.BytesRef; using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory; using Directory = Lucene.Net.Store.Directory; namespace Lucene.Net.Codecs.Lucene3x { /* * 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 DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using DocsEnum = Lucene.Net.Index.DocsEnum; using FieldInfo = Lucene.Net.Index.FieldInfo; using FieldInfos = Lucene.Net.Index.FieldInfos; using Fields = Lucene.Net.Index.Fields; using IndexFileNames = Lucene.Net.Index.IndexFileNames; using IndexFormatTooNewException = Lucene.Net.Index.IndexFormatTooNewException; using IndexFormatTooOldException = Lucene.Net.Index.IndexFormatTooOldException; using IndexInput = Lucene.Net.Store.IndexInput; using IOContext = Lucene.Net.Store.IOContext; using IOUtils = Lucene.Net.Util.IOUtils; using SegmentInfo = Lucene.Net.Index.SegmentInfo; using Terms = Lucene.Net.Index.Terms; using TermsEnum = Lucene.Net.Index.TermsEnum; [Obsolete("Only for reading existing 3.x indexes")] internal class Lucene3xTermVectorsReader : TermVectorsReader { // NOTE: if you make a new format, it must be larger than // the current format // Changed strings to UTF8 with length-in-bytes not length-in-chars internal const int FORMAT_UTF8_LENGTH_IN_BYTES = 4; // NOTE: always change this if you switch to a new format! // whenever you add a new format, make it 1 larger (positive version logic)! public const int FORMAT_CURRENT = FORMAT_UTF8_LENGTH_IN_BYTES; // when removing support for old versions, leave the last supported version here public const int FORMAT_MINIMUM = FORMAT_UTF8_LENGTH_IN_BYTES; //The size in bytes that the FORMAT_VERSION will take up at the beginning of each file internal const int FORMAT_SIZE = 4; public const sbyte STORE_POSITIONS_WITH_TERMVECTOR = 0x1; public const sbyte STORE_OFFSET_WITH_TERMVECTOR = 0x2; /// <summary> /// Extension of vectors fields file. </summary> public const string VECTORS_FIELDS_EXTENSION = "tvf"; /// <summary> /// Extension of vectors documents file. </summary> public const string VECTORS_DOCUMENTS_EXTENSION = "tvd"; /// <summary> /// Extension of vectors index file. </summary> public const string VECTORS_INDEX_EXTENSION = "tvx"; private readonly FieldInfos fieldInfos; private IndexInput tvx; private IndexInput tvd; private IndexInput tvf; private int size; private int numTotalDocs; // The docID offset where our docs begin in the index // file. this will be 0 if we have our own private file. private int docStoreOffset; // when we are inside a compound share doc store (CFX), // (lucene 3.0 indexes only), we privately open our own fd. // TODO: if we are worried, maybe we could eliminate the // extra fd somehow when you also have vectors... private readonly CompoundFileDirectory storeCFSReader; private readonly int format; // used by clone internal Lucene3xTermVectorsReader(FieldInfos fieldInfos, IndexInput tvx, IndexInput tvd, IndexInput tvf, int size, int numTotalDocs, int docStoreOffset, int format) { this.fieldInfos = fieldInfos; this.tvx = tvx; this.tvd = tvd; this.tvf = tvf; this.size = size; this.numTotalDocs = numTotalDocs; this.docStoreOffset = docStoreOffset; this.format = format; this.storeCFSReader = null; } public Lucene3xTermVectorsReader(Directory d, SegmentInfo si, FieldInfos fieldInfos, IOContext context) { string segment = Lucene3xSegmentInfoFormat.GetDocStoreSegment(si); int docStoreOffset = Lucene3xSegmentInfoFormat.GetDocStoreOffset(si); int size = si.DocCount; bool success = false; try { if (docStoreOffset != -1 && Lucene3xSegmentInfoFormat.GetDocStoreIsCompoundFile(si)) { d = storeCFSReader = new CompoundFileDirectory(si.Dir, IndexFileNames.SegmentFileName(segment, "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION), context, false); } else { storeCFSReader = null; } string idxName = IndexFileNames.SegmentFileName(segment, "", VECTORS_INDEX_EXTENSION); tvx = d.OpenInput(idxName, context); format = CheckValidFormat(tvx); string fn = IndexFileNames.SegmentFileName(segment, "", VECTORS_DOCUMENTS_EXTENSION); tvd = d.OpenInput(fn, context); int tvdFormat = CheckValidFormat(tvd); fn = IndexFileNames.SegmentFileName(segment, "", VECTORS_FIELDS_EXTENSION); tvf = d.OpenInput(fn, context); int tvfFormat = CheckValidFormat(tvf); Debug.Assert(format == tvdFormat); Debug.Assert(format == tvfFormat); numTotalDocs = (int)(tvx.Length >> 4); if (-1 == docStoreOffset) { this.docStoreOffset = 0; this.size = numTotalDocs; Debug.Assert(size == 0 || numTotalDocs == size); } else { this.docStoreOffset = docStoreOffset; this.size = size; // Verify the file is long enough to hold all of our // docs Debug.Assert(numTotalDocs >= size + docStoreOffset, "numTotalDocs=" + numTotalDocs + " size=" + size + " docStoreOffset=" + docStoreOffset); } this.fieldInfos = fieldInfos; success = true; } finally { // With lock-less commits, it's entirely possible (and // fine) to hit a FileNotFound exception above. In // this case, we want to explicitly close any subset // of things that were opened so that we don't have to // wait for a GC to do so. if (!success) { try { Dispose(); } // keep our original exception catch (Exception) { } } } } // Not private to avoid synthetic access$NNN methods internal virtual void SeekTvx(int docNum) { tvx.Seek((docNum + docStoreOffset) * 16L + FORMAT_SIZE); } private int CheckValidFormat(IndexInput @in) { int format = @in.ReadInt32(); if (format < FORMAT_MINIMUM) { throw new IndexFormatTooOldException(@in, format, FORMAT_MINIMUM, FORMAT_CURRENT); } if (format > FORMAT_CURRENT) { throw new IndexFormatTooNewException(@in, format, FORMAT_MINIMUM, FORMAT_CURRENT); } return format; } protected override void Dispose(bool disposing) { if (disposing) { IOUtils.Dispose(tvx, tvd, tvf, storeCFSReader); } } /// <summary> /// The number of documents in the reader. /// <para/> /// NOTE: This was size() in Lucene. /// </summary> internal virtual int Count => size; private class TVFields : Fields { private readonly Lucene3xTermVectorsReader outerInstance; private readonly int[] fieldNumbers; private readonly long[] fieldFPs; private readonly IDictionary<int, int> fieldNumberToIndex = new Dictionary<int, int>(); public TVFields(Lucene3xTermVectorsReader outerInstance, int docID) { this.outerInstance = outerInstance; outerInstance.SeekTvx(docID); outerInstance.tvd.Seek(outerInstance.tvx.ReadInt64()); int fieldCount = outerInstance.tvd.ReadVInt32(); Debug.Assert(fieldCount >= 0); if (fieldCount != 0) { fieldNumbers = new int[fieldCount]; fieldFPs = new long[fieldCount]; for (int fieldUpto = 0; fieldUpto < fieldCount; fieldUpto++) { int fieldNumber = outerInstance.tvd.ReadVInt32(); fieldNumbers[fieldUpto] = fieldNumber; fieldNumberToIndex[fieldNumber] = fieldUpto; } long position = outerInstance.tvx.ReadInt64(); fieldFPs[0] = position; for (int fieldUpto = 1; fieldUpto < fieldCount; fieldUpto++) { position += outerInstance.tvd.ReadVInt64(); fieldFPs[fieldUpto] = position; } } else { // TODO: we can improve writer here, eg write 0 into // tvx file, so we know on first read from tvx that // this doc has no TVs fieldNumbers = null; fieldFPs = null; } } public override IEnumerator<string> GetEnumerator() { return new IteratorAnonymousInnerClassHelper(this); } private class IteratorAnonymousInnerClassHelper : IEnumerator<string> { private readonly TVFields outerInstance; private string current; private int i, upTo; public IteratorAnonymousInnerClassHelper(TVFields outerInstance) { this.outerInstance = outerInstance; upTo = this.outerInstance.fieldNumbers.Length; i = 0; } public bool MoveNext() { if (outerInstance.fieldNumbers != null && i < upTo) { current = outerInstance.outerInstance.fieldInfos.FieldInfo(outerInstance.fieldNumbers[i++]).Name; return true; } return false; } public string Current => current; object IEnumerator.Current => Current; public void Reset() { throw new NotSupportedException(); } public void Dispose() { } } public override Terms GetTerms(string field) { FieldInfo fieldInfo = outerInstance.fieldInfos.FieldInfo(field); if (fieldInfo == null) { // No such field return null; } int fieldIndex; if (!fieldNumberToIndex.TryGetValue(fieldInfo.Number, out fieldIndex)) { // Term vectors were not indexed for this field return null; } return new TVTerms(outerInstance, fieldFPs[fieldIndex]); } public override int Count { get { if (fieldNumbers == null) { return 0; } else { return fieldNumbers.Length; } } } } private class TVTerms : Terms { private readonly Lucene3xTermVectorsReader outerInstance; private readonly int numTerms; private readonly long tvfFPStart; private readonly bool storePositions; private readonly bool storeOffsets; private readonly bool unicodeSortOrder; public TVTerms(Lucene3xTermVectorsReader outerInstance, long tvfFP) { this.outerInstance = outerInstance; outerInstance.tvf.Seek(tvfFP); numTerms = outerInstance.tvf.ReadVInt32(); byte bits = outerInstance.tvf.ReadByte(); storePositions = (bits & STORE_POSITIONS_WITH_TERMVECTOR) != 0; storeOffsets = (bits & STORE_OFFSET_WITH_TERMVECTOR) != 0; tvfFPStart = outerInstance.tvf.GetFilePointer(); unicodeSortOrder = outerInstance.SortTermsByUnicode(); } public override TermsEnum GetIterator(TermsEnum reuse) { TVTermsEnum termsEnum; if (reuse is TVTermsEnum) { termsEnum = (TVTermsEnum)reuse; if (!termsEnum.CanReuse(outerInstance.tvf)) { termsEnum = new TVTermsEnum(outerInstance); } } else { termsEnum = new TVTermsEnum(outerInstance); } termsEnum.Reset(numTerms, tvfFPStart, storePositions, storeOffsets, unicodeSortOrder); return termsEnum; } public override long Count => numTerms; public override long SumTotalTermFreq => -1; public override long SumDocFreq => // Every term occurs in just one doc: numTerms; public override int DocCount => 1; public override IComparer<BytesRef> Comparer { get { if (unicodeSortOrder) { return BytesRef.UTF8SortedAsUnicodeComparer; } else { return BytesRef.UTF8SortedAsUTF16Comparer; } } } public override bool HasFreqs => true; public override bool HasOffsets => storeOffsets; public override bool HasPositions => storePositions; public override bool HasPayloads => false; } internal class TermAndPostings { internal BytesRef Term { get; set; } internal int Freq { get; set; } internal int[] Positions { get; set; } internal int[] StartOffsets { get; set; } internal int[] EndOffsets { get; set; } } private class TVTermsEnum : TermsEnum { private readonly Lucene3xTermVectorsReader outerInstance; internal bool unicodeSortOrder; internal readonly IndexInput origTVF; internal readonly IndexInput tvf; internal int numTerms; internal int currentTerm; internal bool storePositions; internal bool storeOffsets; internal TermAndPostings[] termAndPostings; // NOTE: tvf is pre-positioned by caller public TVTermsEnum(Lucene3xTermVectorsReader outerInstance) { this.outerInstance = outerInstance; this.origTVF = outerInstance.tvf; tvf = (IndexInput)origTVF.Clone(); } public virtual bool CanReuse(IndexInput tvf) { return tvf == origTVF; } public virtual void Reset(int numTerms, long tvfFPStart, bool storePositions, bool storeOffsets, bool unicodeSortOrder) { this.numTerms = numTerms; this.storePositions = storePositions; this.storeOffsets = storeOffsets; currentTerm = -1; tvf.Seek(tvfFPStart); this.unicodeSortOrder = unicodeSortOrder; ReadVectors(); if (unicodeSortOrder) { Array.Sort(termAndPostings, Comparer<TermAndPostings>.Create((left, right) => left.Term.CompareTo(right.Term))); } } private void ReadVectors() { termAndPostings = new TermAndPostings[numTerms]; BytesRef lastTerm = new BytesRef(); for (int i = 0; i < numTerms; i++) { TermAndPostings t = new TermAndPostings(); BytesRef term = new BytesRef(); term.CopyBytes(lastTerm); int start = tvf.ReadVInt32(); int deltaLen = tvf.ReadVInt32(); term.Length = start + deltaLen; term.Grow(term.Length); tvf.ReadBytes(term.Bytes, start, deltaLen); t.Term = term; int freq = tvf.ReadVInt32(); t.Freq = freq; if (storePositions) { int[] positions = new int[freq]; int pos = 0; for (int posUpto = 0; posUpto < freq; posUpto++) { int delta = tvf.ReadVInt32(); if (delta == -1) { delta = 0; // LUCENE-1542 correction } pos += delta; positions[posUpto] = pos; } t.Positions = positions; } if (storeOffsets) { int[] startOffsets = new int[freq]; int[] endOffsets = new int[freq]; int offset = 0; for (int posUpto = 0; posUpto < freq; posUpto++) { startOffsets[posUpto] = offset + tvf.ReadVInt32(); offset = endOffsets[posUpto] = startOffsets[posUpto] + tvf.ReadVInt32(); } t.StartOffsets = startOffsets; t.EndOffsets = endOffsets; } lastTerm.CopyBytes(term); termAndPostings[i] = t; } } // NOTE: slow! (linear scan) public override SeekStatus SeekCeil(BytesRef text) { IComparer<BytesRef> comparer = Comparer; for (int i = 0; i < numTerms; i++) { int cmp = comparer.Compare(text, termAndPostings[i].Term); if (cmp < 0) { currentTerm = i; return SeekStatus.NOT_FOUND; } else if (cmp == 0) { currentTerm = i; return SeekStatus.FOUND; } } currentTerm = termAndPostings.Length; return SeekStatus.END; } public override void SeekExact(long ord) { throw new NotSupportedException(); } public override BytesRef Next() { if (++currentTerm >= numTerms) { return null; } return Term; } public override BytesRef Term => termAndPostings[currentTerm].Term; public override long Ord => throw new NotSupportedException(); public override int DocFreq => 1; public override long TotalTermFreq => termAndPostings[currentTerm].Freq; public override DocsEnum Docs(IBits liveDocs, DocsEnum reuse, DocsFlags flags) // ignored { TVDocsEnum docsEnum; if (reuse != null && reuse is TVDocsEnum) { docsEnum = (TVDocsEnum)reuse; } else { docsEnum = new TVDocsEnum(); } docsEnum.Reset(liveDocs, termAndPostings[currentTerm]); return docsEnum; } public override DocsAndPositionsEnum DocsAndPositions(IBits liveDocs, DocsAndPositionsEnum reuse, DocsAndPositionsFlags flags) { if (!storePositions && !storeOffsets) { return null; } TVDocsAndPositionsEnum docsAndPositionsEnum; if (reuse != null && reuse is TVDocsAndPositionsEnum) { docsAndPositionsEnum = (TVDocsAndPositionsEnum)reuse; } else { docsAndPositionsEnum = new TVDocsAndPositionsEnum(); } docsAndPositionsEnum.Reset(liveDocs, termAndPostings[currentTerm]); return docsAndPositionsEnum; } public override IComparer<BytesRef> Comparer { get { if (unicodeSortOrder) { return BytesRef.UTF8SortedAsUnicodeComparer; } else { return BytesRef.UTF8SortedAsUTF16Comparer; } } } } // NOTE: sort of a silly class, since you can get the // freq() already by TermsEnum.totalTermFreq private class TVDocsEnum : DocsEnum { internal bool didNext; internal int doc = -1; internal int freq; internal IBits liveDocs; public override int Freq => freq; public override int DocID => doc; public override int NextDoc() { if (!didNext && (liveDocs == null || liveDocs.Get(0))) { didNext = true; return (doc = 0); } else { return (doc = NO_MORE_DOCS); } } public override int Advance(int target) { if (!didNext && target == 0) { return NextDoc(); } else { return (doc = NO_MORE_DOCS); } } public virtual void Reset(IBits liveDocs, TermAndPostings termAndPostings) { this.liveDocs = liveDocs; this.freq = termAndPostings.Freq; this.doc = -1; didNext = false; } public override long GetCost() { return 1; } } private class TVDocsAndPositionsEnum : DocsAndPositionsEnum { private bool didNext; private int doc = -1; private int nextPos; private IBits liveDocs; private int[] positions; private int[] startOffsets; private int[] endOffsets; public override int Freq { get { if (positions != null) { return positions.Length; } else { Debug.Assert(startOffsets != null); return startOffsets.Length; } } } public override int DocID => doc; public override int NextDoc() { if (!didNext && (liveDocs == null || liveDocs.Get(0))) { didNext = true; return (doc = 0); } else { return (doc = NO_MORE_DOCS); } } public override int Advance(int target) { if (!didNext && target == 0) { return NextDoc(); } else { return (doc = NO_MORE_DOCS); } } public virtual void Reset(IBits liveDocs, TermAndPostings termAndPostings) { this.liveDocs = liveDocs; this.positions = termAndPostings.Positions; this.startOffsets = termAndPostings.StartOffsets; this.endOffsets = termAndPostings.EndOffsets; this.doc = -1; didNext = false; nextPos = 0; } public override BytesRef GetPayload() { return null; } public override int NextPosition() { //Debug.Assert((positions != null && nextPos < positions.Length) || startOffsets != null && nextPos < startOffsets.Length); // LUCENENET: The above assertion was for control flow when testing. In Java, it would throw an AssertionError, which is // caught by the BaseTermVectorsFormatTestCase.assertEquals(RandomTokenStream tk, FieldType ft, Terms terms) method in the // part that is checking for an error after reading to the end of the enumerator. // Since there is no way to turn on assertions in a release build in .NET, we are throwing an InvalidOperationException // in this case, which matches the behavior of Lucene 8. See #267. if (((positions != null && nextPos < positions.Length) || startOffsets != null && nextPos < startOffsets.Length) == false) throw new InvalidOperationException("Read past last position"); if (positions != null) { return positions[nextPos++]; } else { nextPos++; return -1; } } public override int StartOffset { get { if (startOffsets != null) { return startOffsets[nextPos - 1]; } else { return -1; } } } public override int EndOffset { get { if (endOffsets != null) { return endOffsets[nextPos - 1]; } else { return -1; } } } public override long GetCost() { return 1; } } public override Fields Get(int docID) { if (tvx != null) { Fields fields = new TVFields(this, docID); if (fields.Count == 0) { // TODO: we can improve writer here, eg write 0 into // tvx file, so we know on first read from tvx that // this doc has no TVs return null; } else { return fields; } } else { return null; } } public override object Clone() { IndexInput cloneTvx = null; IndexInput cloneTvd = null; IndexInput cloneTvf = null; // These are null when a TermVectorsReader was created // on a segment that did not have term vectors saved if (tvx != null && tvd != null && tvf != null) { cloneTvx = (IndexInput)tvx.Clone(); cloneTvd = (IndexInput)tvd.Clone(); cloneTvf = (IndexInput)tvf.Clone(); } return new Lucene3xTermVectorsReader(fieldInfos, cloneTvx, cloneTvd, cloneTvf, size, numTotalDocs, docStoreOffset, format); } // If this returns, we do the surrogates shuffle so that the // terms are sorted by unicode sort order. this should be // true when segments are used for "normal" searching; // it's only false during testing, to create a pre-flex // index, using the test-only PreFlexRW. protected internal virtual bool SortTermsByUnicode() { return true; } public override long RamBytesUsed() { // everything is disk-based return 0; } public override void CheckIntegrity() { } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; namespace System.Linq.Expressions { /// <summary> /// The base type for all nodes in Expression Trees. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")] public abstract partial class Expression { private static readonly CacheDict<Type, MethodInfo> s_lambdaDelegateCache = new CacheDict<Type, MethodInfo>(40); private static volatile CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>> s_lambdaFactories; // For 4.0, many frequently used Expression nodes have had their memory // footprint reduced by removing the Type and NodeType fields. This has // large performance benefits to all users of Expression Trees. // // To support the 3.5 protected constructor, we store the fields that // used to be here in a ConditionalWeakTable. private class ExtensionInfo { public ExtensionInfo(ExpressionType nodeType, Type type) { NodeType = nodeType; Type = type; } internal readonly ExpressionType NodeType; internal readonly Type Type; } private static ConditionalWeakTable<Expression, ExtensionInfo> s_legacyCtorSupportTable; /// <summary> /// Constructs a new instance of <see cref="Expression"/>. /// </summary> /// <param name="nodeType">The <see ctype="ExpressionType"/> of the <see cref="Expression"/>.</param> /// <param name="type">The <see cref="Type"/> of the <see cref="Expression"/>.</param> [Obsolete("use a different constructor that does not take ExpressionType. Then override NodeType and Type properties to provide the values that would be specified to this constructor.")] protected Expression(ExpressionType nodeType, Type type) { // Can't enforce anything that V1 didn't if (s_legacyCtorSupportTable == null) { Interlocked.CompareExchange( ref s_legacyCtorSupportTable, new ConditionalWeakTable<Expression, ExtensionInfo>(), null ); } s_legacyCtorSupportTable.Add(this, new ExtensionInfo(nodeType, type)); } /// <summary> /// Constructs a new instance of <see cref="Expression"/>. /// </summary> protected Expression() { } /// <summary> /// The <see cref="ExpressionType"/> of the <see cref="Expression"/>. /// </summary> public virtual ExpressionType NodeType { get { ExtensionInfo extInfo; if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out extInfo)) { return extInfo.NodeType; } // the extension expression failed to override NodeType throw Error.ExtensionNodeMustOverrideProperty("Expression.NodeType"); } } /// <summary> /// The <see cref="Type"/> of the value represented by this <see cref="Expression"/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")] public virtual Type Type { get { ExtensionInfo extInfo; if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out extInfo)) { return extInfo.Type; } // the extension expression failed to override Type throw Error.ExtensionNodeMustOverrideProperty("Expression.Type"); } } /// <summary> /// Indicates that the node can be reduced to a simpler node. If this /// returns true, Reduce() can be called to produce the reduced form. /// </summary> public virtual bool CanReduce { get { return false; } } /// <summary> /// Reduces this node to a simpler expression. If CanReduce returns /// true, this should return a valid expression. This method is /// allowed to return another node which itself must be reduced. /// </summary> /// <returns>The reduced expression.</returns> public virtual Expression Reduce() { if (CanReduce) throw Error.ReducibleMustOverrideReduce(); return this; } /// <summary> /// Reduces the node and then calls the visitor delegate on the reduced expression. /// Throws an exception if the node isn't reducible. /// </summary> /// <param name="visitor">An instance of <see cref="Func{Expression, Expression}"/>.</param> /// <returns>The expression being visited, or an expression which should replace it in the tree.</returns> /// <remarks> /// Override this method to provide logic to walk the node's children. /// A typical implementation will call visitor.Visit on each of its /// children, and if any of them change, should return a new copy of /// itself with the modified children. /// </remarks> protected internal virtual Expression VisitChildren(ExpressionVisitor visitor) { if (!CanReduce) throw Error.MustBeReducible(); return visitor.Visit(ReduceAndCheck()); } /// <summary> /// Dispatches to the specific visit method for this node type. For /// example, <see cref="MethodCallExpression" /> will call into /// <see cref="ExpressionVisitor.VisitMethodCall" />. /// </summary> /// <param name="visitor">The visitor to visit this node with.</param> /// <returns>The result of visiting this node.</returns> /// <remarks> /// This default implementation for <see cref="ExpressionType.Extension" /> /// nodes will call <see cref="ExpressionVisitor.VisitExtension" />. /// Override this method to call into a more specific method on a derived /// visitor class of ExprressionVisitor. However, it should still /// support unknown visitors by calling VisitExtension. /// </remarks> protected internal virtual Expression Accept(ExpressionVisitor visitor) { return visitor.VisitExtension(this); } /// <summary> /// Reduces this node to a simpler expression. If CanReduce returns /// true, this should return a valid expression. This method is /// allowed to return another node which itself must be reduced. /// </summary> /// <returns>The reduced expression.</returns> /// <remarks > /// Unlike Reduce, this method checks that the reduced node satisfies /// certain invariants. /// </remarks> public Expression ReduceAndCheck() { if (!CanReduce) throw Error.MustBeReducible(); var newNode = Reduce(); // 1. Reduction must return a new, non-null node // 2. Reduction must return a new node whose result type can be assigned to the type of the original node if (newNode == null || newNode == this) throw Error.MustReduceToDifferent(); if (!TypeUtils.AreReferenceAssignable(Type, newNode.Type)) throw Error.ReducedNotCompatible(); return newNode; } /// <summary> /// Reduces the expression to a known node type (i.e. not an Extension node) /// or simply returns the expression if it is already a known type. /// </summary> /// <returns>The reduced expression.</returns> public Expression ReduceExtensions() { var node = this; while (node.NodeType == ExpressionType.Extension) { node = node.ReduceAndCheck(); } return node; } /// <summary> /// Creates a <see cref="String"/> representation of the Expression. /// </summary> /// <returns>A <see cref="String"/> representation of the Expression.</returns> public override string ToString() { return ExpressionStringBuilder.ExpressionToString(this); } /// <summary> /// Creates a <see cref="String"/> representation of the Expression. /// </summary> /// <returns>A <see cref="String"/> representation of the Expression.</returns> private string DebugView { // Note that this property is often accessed using reflection. As such it will have more dependencies than one // might surmise from its being internal, and removing it requires greater caution than with other internal methods. get { using (System.IO.StringWriter writer = new System.IO.StringWriter(CultureInfo.CurrentCulture)) { DebugViewWriter.WriteTo(this, writer); return writer.ToString(); } } } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is called from various methods where we internally hold onto an IList of T /// or a readonly collection of T. We check to see if we've already returned a /// readonly collection of T and if so simply return the other one. Otherwise we do /// a thread-safe replacement of the list w/ a readonly collection which wraps it. /// /// Ultimately this saves us from having to allocate a ReadOnlyCollection for our /// data types because the compiler is capable of going directly to the IList of T. /// </summary> internal static ReadOnlyCollection<T> ReturnReadOnly<T>(ref IList<T> collection) { return ExpressionUtils.ReturnReadOnly<T>(ref collection); } /// <summary> /// Helper used for ensuring we only return 1 instance of a ReadOnlyCollection of T. /// /// This is similar to the ReturnReadOnly of T. This version supports nodes which hold /// onto multiple Expressions where one is typed to object. That object field holds either /// an expression or a ReadOnlyCollection of Expressions. When it holds a ReadOnlyCollection /// the IList which backs it is a ListArgumentProvider which uses the Expression which /// implements IArgumentProvider to get 2nd and additional values. The ListArgumentProvider /// continues to hold onto the 1st expression. /// /// This enables users to get the ReadOnlyCollection w/o it consuming more memory than if /// it was just an array. Meanwhile The DLR internally avoids accessing which would force /// the readonly collection to be created resulting in a typical memory savings. /// </summary> internal static ReadOnlyCollection<Expression> ReturnReadOnly(IArgumentProvider provider, ref object collection) { return ExpressionUtils.ReturnReadOnly(provider, ref collection); } /// <summary> /// Helper which is used for specialized subtypes which use ReturnReadOnly(ref object, ...). /// This is the reverse version of ReturnReadOnly which takes an IArgumentProvider. /// /// This is used to return the 1st argument. The 1st argument is typed as object and either /// contains a ReadOnlyCollection or the Expression. We check for the Expression and if it's /// present we return that, otherwise we return the 1st element of the ReadOnlyCollection. /// </summary> internal static T ReturnObject<T>(object collectionOrT) where T : class { return ExpressionUtils.ReturnObject<T>(collectionOrT); } private static void RequiresCanRead(Expression expression, string paramName) { ExpressionUtils.RequiresCanRead(expression, paramName); } private static void RequiresCanRead(IReadOnlyList<Expression> items, string paramName) { Debug.Assert(items != null); // this is called a lot, avoid allocating an enumerator if we can... for (int i = 0; i < items.Count; i++) { RequiresCanRead(items[i], paramName); } } private static void RequiresCanWrite(Expression expression, string paramName) { if (expression == null) { throw new ArgumentNullException(paramName); } switch (expression.NodeType) { case ExpressionType.Index: PropertyInfo indexer = ((IndexExpression)expression).Indexer; if (indexer == null || indexer.CanWrite) { return; } break; case ExpressionType.MemberAccess: MemberInfo member = ((MemberExpression)expression).Member; PropertyInfo prop = member as PropertyInfo; if (prop != null) { if(prop.CanWrite) { return; } } else { Debug.Assert(member is FieldInfo); FieldInfo field = (FieldInfo)member; if (!(field.IsInitOnly || field.IsLiteral)) { return; } } break; case ExpressionType.Parameter: return; } throw new ArgumentException(Strings.ExpressionMustBeWriteable, paramName); } } }
//--------------------------------------------------------------------------- // // <copyright file="WindowsRebar.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: HWND-based Rebar Proxy // // History: // Jean-Francois Peyroux. Created // // using System; using System.Collections; using System.Text; using System.Runtime.InteropServices; using System.ComponentModel; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows; using MS.Win32; namespace MS.Internal.AutomationProxies { class WindowsRebar: ProxyHwnd, IRawElementProviderHwndOverride { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors WindowsRebar (IntPtr hwnd, ProxyFragment parent, int item) : base( hwnd, parent, item ) { _sType = ST.Get(STID.LocalizedControlTypeRebar); _fIsContent = false; // support for events _createOnEvent = new WinEventTracker.ProxyRaiseEvents (RaiseEvents); } #endregion #region Proxy Create // Static Create method called by UIAutomation to create this proxy. // returns null if unsuccessful internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild, int idObject) { return Create(hwnd, idChild); } private static IRawElementProviderSimple Create(IntPtr hwnd, int idChild) { // Something is wrong if idChild is not zero if (idChild != 0) { System.Diagnostics.Debug.Assert (idChild == 0, "Invalid Child Id, idChild != 0"); throw new ArgumentOutOfRangeException("idChild", idChild, SR.Get(SRID.ShouldBeZero)); } return new WindowsRebar(hwnd, null, idChild); } // Static Create method called by the event tracker system internal static void RaiseEvents (IntPtr hwnd, int eventId, object idProp, int idObject, int idChild) { if (idObject != NativeMethods.OBJID_VSCROLL && idObject != NativeMethods.OBJID_HSCROLL) { WindowsRebar wtv = new WindowsRebar (hwnd, null, -1); wtv.DispatchEvents (eventId, idProp, idObject, idChild); } } #endregion //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxyFragment Interface // Returns the next sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Returns null if no next child internal override ProxySimple GetNextSibling (ProxySimple child) { int item = child._item; // If the index of the next node would be out of range... if (item >= 0 && (item + 1) < Count) { // return a node to represent the requested item. return CreateRebarItem (item + 1); } return null; } // Returns the previous sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Returns null is no previous internal override ProxySimple GetPreviousSibling (ProxySimple child) { // If the index of the previous node would be out of range... int item = child._item; if (item > 0 && item < Count) { return CreateRebarItem (item - 1); } return null; } // Returns the first child element in the raw hierarchy. internal override ProxySimple GetFirstChild () { return Count > 0 ? CreateRebarItem (0) : null; } // Returns the last child element in the raw hierarchy. internal override ProxySimple GetLastChild () { int count = Count; return count > 0 ? CreateRebarItem (count - 1) : null; } // Returns a Proxy element corresponding to the specified screen coordinates. internal override ProxySimple ElementProviderFromPoint (int x, int y) { int x1 = x; int y1 = y; NativeMethods.Win32Rect rebarRect = new NativeMethods.Win32Rect (); if (!Misc.GetWindowRect(_hwnd, ref rebarRect)) { return null; } if (x >= rebarRect.left && x <= rebarRect.right && y >= rebarRect.top && y <= rebarRect.bottom) { x = x - rebarRect.left; y = y - rebarRect.top; NativeMethods.Win32Point pt = new NativeMethods.Win32Point (x, y); int BandID = getRebarBandIDFromPoint (pt); if (-1 != BandID) { return CreateRebarItem (BandID).ElementProviderFromPoint (x1, y1); } } return null; } #endregion #region IRawElementProviderHwndOverride Interface //------------------------------------------------------ // // Interface IRawElementProviderHwndOverride // //------------------------------------------------------ IRawElementProviderSimple IRawElementProviderHwndOverride.GetOverrideProviderForHwnd (IntPtr hwnd) { // return the appropriate placeholder for the given hwnd... // loop over all the band to find it. for (RebarBandItem band = (RebarBandItem) GetFirstChild (); band != null; band = (RebarBandItem) GetNextSibling (band)) { if (band.HwndBand == hwnd) { return new RebarBandChildOverrideProxy (hwnd, band, band._item); } } // Should never get here return null; } #endregion IRawElementProviderHwndOverride Interface // ------------------------------------------------------ // // Private Methods // // ------------------------------------------------------ #region Private Methods // Creates a list item RawElementBase Item private RebarBandItem CreateRebarItem (int index) { return new RebarBandItem (_hwnd, this, index); } private int Count { get { return Misc.ProxySendMessageInt(_hwnd, NativeMethods.RB_GETBANDCOUNT, IntPtr.Zero, IntPtr.Zero); } } private unsafe int getRebarBandIDFromPoint (NativeMethods.Win32Point pt) { NativeMethods.RB_HITTESTINFO rbHitTestInfo = new NativeMethods.RB_HITTESTINFO (); rbHitTestInfo.pt = pt; rbHitTestInfo.uFlags = 0; rbHitTestInfo.iBand = 0; return XSendMessage.XSendGetIndex(_hwnd, NativeMethods.RB_HITTEST, IntPtr.Zero, new IntPtr(&rbHitTestInfo), Marshal.SizeOf(rbHitTestInfo.GetType())); } #endregion //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private enum CommonControlStyles { // CCS_TOP = 0x00000001, // CCS_NOMOVEY = 0x00000002, // CCS_BOTTOM = 0x00000003, // CCS_NORESIZE = 0x00000004, // CCS_NOPARENTALIGN = 0x00000008, // CCS_ADJUSTABLE = 0x00000020, // CCS_NODIVIDER = 0x00000040, CCS_VERT = 0x00000080, // CCS_LEFT = (CCS_VERT | CCS_TOP), // CCS_RIGHT = (CCS_VERT | CCS_BOTTOM), // CCS_NOMOVEX = (CCS_VERT | CCS_NOMOVEY) } private const int RBBIM_CHILD = 0x10; #endregion // ------------------------------------------------------ // // RebarBandItem Private Class // //------------------------------------------------------ #region RebarBandItem class RebarBandItem: ProxyFragment, IInvokeProvider { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors internal RebarBandItem (IntPtr hwnd, ProxyFragment parent, int item) : base (hwnd, parent, item) { // Set the strings to return properly the properties. _sType = ST.Get(STID.LocalizedControlTypeRebarBand); _fIsContent = false; } #endregion //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple // Gets the bounding rectangle for this element internal override Rect BoundingRectangle { get { return GetBoundingRectangle (_hwnd, _item); } } //Gets the controls help text internal override string HelpText { get { IntPtr hwndToolTip = Misc.ProxySendMessage(_hwnd, NativeMethods.RB_GETTOOLTIPS, IntPtr.Zero, IntPtr.Zero); return Misc.GetItemToolTipText(_hwnd, hwndToolTip, _item); } } //Gets the localized name internal override string LocalizedName { get { return ST.Get(STID.LocalizedNameWindowsReBarBandItem); } } #endregion #region ProxyFragment Interface // Returns the next sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Returns null if no next child internal override ProxySimple GetNextSibling (ProxySimple child) { return null; } // Returns the previous sibling element in the raw hierarchy. // Peripheral controls have always negative values. // Returns null is no previous internal override ProxySimple GetPreviousSibling (ProxySimple child) { return null; } // Returns the first child element in the raw hierarchy. internal override ProxySimple GetFirstChild () { IntPtr hwndBand = HwndBand; if (hwndBand != IntPtr.Zero) { return new RebarBandChildOverrideProxy (HwndBand, this, _item); } return null; } // Returns the last child element in the raw hierarchy. internal override ProxySimple GetLastChild () { // By construction, a rebar band can only have one children return GetFirstChild (); } // Returns a Proxy element corresponding to the specified screen coordinates. internal override ProxySimple ElementProviderFromPoint (int x, int y) { IntPtr hwndBand = HwndBand; if (hwndBand != IntPtr.Zero && Misc.PtInWindowRect(hwndBand, x, y)) { return null; } return this; } internal override object GetElementProperty(AutomationProperty idProp) { if (idProp == AutomationElement.IsControlElementProperty) { // // return false; } return base.GetElementProperty(idProp); } #endregion #region InvokeInteropPattern void IInvokeProvider.Invoke () { // Make sure that the control is enabled if (!SafeNativeMethods.IsWindowEnabled(_hwnd)) { throw new ElementNotEnabledException(); } Misc.PostMessage(_hwnd, NativeMethods.RB_PUSHCHEVRON, (IntPtr)_item, IntPtr.Zero); } #endregion //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods // Returns the bounding rectangle of the control. internal static Rect GetBoundingRectangle (IntPtr hwnd, int item) { NativeMethods.Win32Rect rectW32 = NativeMethods.Win32Rect.Empty; unsafe { if (!XSendMessage.XSend(hwnd, NativeMethods.RB_GETRECT, new IntPtr(item), new IntPtr(&rectW32), Marshal.SizeOf(rectW32.GetType()), XSendMessage.ErrorValue.Zero)) { return Rect.Empty; } } if (!Misc.MapWindowPoints(hwnd, IntPtr.Zero, ref rectW32, 2)) { return Rect.Empty; } // Work around a bug in the common control. Swap the X and Y value for vertical // rebar bands if (Misc.IsBitSet(Misc.GetWindowStyle(hwnd), (int)CommonControlStyles.CCS_VERT)) { return new Rect (rectW32.left, rectW32.top, rectW32.bottom - rectW32.top, rectW32.right - rectW32.left); } else { return rectW32.ToRect(Misc.IsControlRTL(hwnd)); } } internal IntPtr HwndBand { get { if (_hwndBand == IntPtr.Zero) { NativeMethods.REBARBANDINFO rebarBandInfo = new NativeMethods.REBARBANDINFO(); rebarBandInfo.fMask = RBBIM_CHILD; unsafe { if (XSendMessage.XSend(_hwnd, NativeMethods.RB_GETBANDINFOA, new IntPtr(_item), new IntPtr(&rebarBandInfo), Marshal.SizeOf(rebarBandInfo.GetType()), XSendMessage.ErrorValue.Zero)) { _hwndBand = rebarBandInfo.hwndChild; } } } return _hwndBand; } } #endregion //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields IntPtr _hwndBand = IntPtr.Zero; #endregion } #endregion // ------------------------------------------------------ // // RebarBandChildOverrideProxy Private Class // //------------------------------------------------------ #region RebarBandChildOverrideProxy class RebarBandChildOverrideProxy: ProxyHwnd { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors internal RebarBandChildOverrideProxy (IntPtr hwnd, ProxyFragment parent, int item) : base (hwnd, parent, item) { _fIsContent = false; } #endregion //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface internal override ProviderOptions ProviderOptions { get { return base.ProviderOptions | ProviderOptions.OverrideProvider; } } // Process all the Logical and Raw Element Properties internal override object GetElementProperty (AutomationProperty idProp) { if (idProp == AutomationElement.IsControlElementProperty) { // // // In IE6, the rebar band HWND tree was only one level deep: // // rebar / rebar band / rebar item (Toolbar32) // // In IE7, the HWND tree is the same but the rebar item is // a window acting as another container, for instance: // // rebar / rebar band / rebar item (FavBandClass) / children (Toolbar32) // // Hide windows that are intermediate containers from the control view Accessible accThis = Accessible.Wrap(this.AccessibleObject); if ((accThis != null) && (accThis.ChildCount == 1)) { Accessible accWind = accThis.FirstChild; if ((accWind != null) && (accWind.Role == AccessibleRole.Window)) { return false; } } } // No property should be handled by the override proxy // Overrides the ProxySimple implementation. return null; } #endregion } #endregion } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Overlays; using osu.Game.Screens; using osu.Game.Screens.Menu; using osu.Game.Screens.Play; using osu.Game.Tests.Beatmaps.IO; using osuTK.Input; using static osu.Game.Tests.Visual.Navigation.TestSceneScreenNavigation; namespace osu.Game.Tests.Visual.Navigation { public class TestScenePerformFromScreen : OsuGameTestScene { private bool actionPerformed; public override void SetUpSteps() { AddStep("reset status", () => actionPerformed = false); base.SetUpSteps(); } [Test] public void TestPerformAtMenu() { AddStep("perform immediately", () => Game.PerformFromScreen(_ => actionPerformed = true)); AddAssert("did perform", () => actionPerformed); } [Test] public void TestPerformAtSongSelect() { PushAndConfirm(() => new TestPlaySongSelect()); AddStep("perform immediately", () => Game.PerformFromScreen(_ => actionPerformed = true, new[] { typeof(TestPlaySongSelect) })); AddAssert("did perform", () => actionPerformed); AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen is TestPlaySongSelect); } [Test] public void TestPerformAtMenuFromSongSelect() { PushAndConfirm(() => new TestPlaySongSelect()); AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true)); AddUntilStep("returned to menu", () => Game.ScreenStack.CurrentScreen is MainMenu); AddAssert("did perform", () => actionPerformed); } [Test] public void TestPerformAtSongSelectFromPlayerLoader() { importAndWaitForSongSelect(); AddStep("Press enter", () => InputManager.Key(Key.Enter)); AddUntilStep("Wait for new screen", () => Game.ScreenStack.CurrentScreen is PlayerLoader); AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true, new[] { typeof(TestPlaySongSelect) })); AddUntilStep("returned to song select", () => Game.ScreenStack.CurrentScreen is TestPlaySongSelect); AddAssert("did perform", () => actionPerformed); } [Test] public void TestPerformAtMenuFromPlayerLoader() { importAndWaitForSongSelect(); AddStep("Press enter", () => InputManager.Key(Key.Enter)); AddUntilStep("Wait for new screen", () => Game.ScreenStack.CurrentScreen is PlayerLoader); AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true)); AddUntilStep("returned to song select", () => Game.ScreenStack.CurrentScreen is MainMenu); AddAssert("did perform", () => actionPerformed); } [Test] public void TestOverlaysAlwaysClosed() { ChatOverlay chat = null; AddUntilStep("is at menu", () => Game.ScreenStack.CurrentScreen is MainMenu); AddUntilStep("wait for chat load", () => (chat = Game.ChildrenOfType<ChatOverlay>().SingleOrDefault()) != null); AddStep("show chat", () => InputManager.Key(Key.F8)); AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true)); AddUntilStep("still at menu", () => Game.ScreenStack.CurrentScreen is MainMenu); AddAssert("did perform", () => actionPerformed); AddAssert("chat closed", () => chat.State.Value == Visibility.Hidden); } [TestCase(true)] [TestCase(false)] public void TestPerformBlockedByDialog(bool confirmed) { DialogBlockingScreen blocker = null; PushAndConfirm(() => blocker = new DialogBlockingScreen()); AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true)); AddWaitStep("wait a bit", 10); AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen is DialogBlockingScreen); AddAssert("did not perform", () => !actionPerformed); AddAssert("only one exit attempt", () => blocker.ExitAttempts == 1); AddUntilStep("wait for dialog display", () => Game.Dependencies.Get<DialogOverlay>().IsLoaded); if (confirmed) { AddStep("accept dialog", () => InputManager.Key(Key.Number1)); AddUntilStep("wait for dialog dismissed", () => Game.Dependencies.Get<DialogOverlay>().CurrentDialog == null); AddUntilStep("did perform", () => actionPerformed); } else { AddStep("cancel dialog", () => InputManager.Key(Key.Number2)); AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen is DialogBlockingScreen); AddAssert("did not perform", () => !actionPerformed); } } [TestCase(true)] [TestCase(false)] public void TestPerformBlockedByDialogNested(bool confirmSecond) { DialogBlockingScreen blocker = null; DialogBlockingScreen blocker2 = null; PushAndConfirm(() => blocker = new DialogBlockingScreen()); PushAndConfirm(() => blocker2 = new DialogBlockingScreen()); AddStep("try to perform", () => Game.PerformFromScreen(_ => actionPerformed = true)); AddUntilStep("wait for dialog", () => blocker2.ExitAttempts == 1); AddWaitStep("wait a bit", 10); AddUntilStep("wait for dialog display", () => Game.Dependencies.Get<DialogOverlay>().IsLoaded); AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen == blocker2); AddAssert("did not perform", () => !actionPerformed); AddAssert("only one exit attempt", () => blocker2.ExitAttempts == 1); AddStep("accept dialog", () => InputManager.Key(Key.Number1)); AddUntilStep("screen changed", () => Game.ScreenStack.CurrentScreen == blocker); AddUntilStep("wait for second dialog", () => blocker.ExitAttempts == 1); AddAssert("did not perform", () => !actionPerformed); AddAssert("only one exit attempt", () => blocker.ExitAttempts == 1); if (confirmSecond) { AddStep("accept dialog", () => InputManager.Key(Key.Number1)); AddUntilStep("did perform", () => actionPerformed); } else { AddStep("cancel dialog", () => InputManager.Key(Key.Number2)); AddAssert("screen didn't change", () => Game.ScreenStack.CurrentScreen == blocker); AddAssert("did not perform", () => !actionPerformed); } } private void importAndWaitForSongSelect() { AddStep("import beatmap", () => ImportBeatmapTest.LoadQuickOszIntoOsu(Game).Wait()); PushAndConfirm(() => new TestPlaySongSelect()); AddUntilStep("beatmap updated", () => Game.Beatmap.Value.BeatmapSetInfo.OnlineBeatmapSetID == 241526); } public class DialogBlockingScreen : OsuScreen { [Resolved] private DialogOverlay dialogOverlay { get; set; } private int dialogDisplayCount; public int ExitAttempts { get; private set; } public override bool OnExiting(IScreen next) { ExitAttempts++; if (dialogDisplayCount++ < 1) { dialogOverlay.Push(new ConfirmExitDialog(this.Exit, () => { })); return true; } return base.OnExiting(next); } } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Serialization.Json; using System.Text; using JsonPair = System.Collections.Generic.KeyValuePair<string, System.Json.JsonValue>; namespace System.Json { public abstract class JsonValue : IEnumerable { private static readonly UTF8Encoding s_encoding = new UTF8Encoding(false, true); public static JsonValue Load(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } return Load(new StreamReader(stream, true)); } public static JsonValue Load(TextReader textReader) { if (textReader == null) { throw new ArgumentNullException(nameof(textReader)); } return ToJsonValue(new JavaScriptReader(textReader).Read()); } private static IEnumerable<KeyValuePair<string, JsonValue>> ToJsonPairEnumerable(IEnumerable<KeyValuePair<string, object>> kvpc) { foreach (KeyValuePair<string, object> kvp in kvpc) { yield return new KeyValuePair<string, JsonValue>(kvp.Key, ToJsonValue(kvp.Value)); } } private static IEnumerable<JsonValue> ToJsonValueEnumerable(IEnumerable<object> arr) { foreach (object obj in arr) { yield return ToJsonValue(obj); } } private static JsonValue ToJsonValue(object ret) { if (ret == null) { return null; } var kvpc = ret as IEnumerable<KeyValuePair<string, object>>; if (kvpc != null) { return new JsonObject(ToJsonPairEnumerable(kvpc)); } var arr = ret as IEnumerable<object>; if (arr != null) { return new JsonArray(ToJsonValueEnumerable(arr)); } if (ret is bool) return new JsonPrimitive((bool)ret); if (ret is decimal) return new JsonPrimitive((decimal)ret); if (ret is double) return new JsonPrimitive((double)ret); if (ret is int) return new JsonPrimitive((int)ret); if (ret is long) return new JsonPrimitive((long)ret); if (ret is string) return new JsonPrimitive((string)ret); Debug.Assert(ret is ulong); return new JsonPrimitive((ulong)ret); } public static JsonValue Parse(string jsonString) { if (jsonString == null) { throw new ArgumentNullException(nameof(jsonString)); } return Load(new StringReader(jsonString)); } public virtual int Count { get { throw new InvalidOperationException(); } } public abstract JsonType JsonType { get; } public virtual JsonValue this[int index] { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public virtual JsonValue this[string key] { get { throw new InvalidOperationException(); } set { throw new InvalidOperationException(); } } public virtual bool ContainsKey(string key) { throw new InvalidOperationException(); } public virtual void Save(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } using (StreamWriter writer = new StreamWriter(stream, s_encoding, 1024, true)) { Save(writer); } } public virtual void Save(TextWriter textWriter) { if (textWriter == null) { throw new ArgumentNullException(nameof(textWriter)); } SaveInternal(textWriter); } private void SaveInternal(TextWriter w) { switch (JsonType) { case JsonType.Object: w.Write('{'); bool following = false; foreach (JsonPair pair in ((JsonObject)this)) { if (following) { w.Write(", "); } w.Write('\"'); w.Write(EscapeString(pair.Key)); w.Write("\": "); if (pair.Value == null) { w.Write("null"); } else { pair.Value.SaveInternal(w); } following = true; } w.Write('}'); break; case JsonType.Array: w.Write('['); following = false; foreach (JsonValue v in ((JsonArray)this)) { if (following) { w.Write(", "); } if (v != null) { v.SaveInternal(w); } else { w.Write("null"); } following = true; } w.Write(']'); break; case JsonType.Boolean: w.Write(this ? "true" : "false"); break; case JsonType.String: w.Write('"'); w.Write(EscapeString(((JsonPrimitive)this).GetFormattedString())); w.Write('"'); break; default: w.Write(((JsonPrimitive)this).GetFormattedString()); break; } } public override string ToString() { var sw = new StringWriter(); Save(sw); return sw.ToString(); } IEnumerator IEnumerable.GetEnumerator() { throw new InvalidOperationException(); } // Characters which have to be escaped: // - Required by JSON Spec: Control characters, '"' and '\\' // - Broken surrogates to make sure the JSON string is valid Unicode // (and can be encoded as UTF8) // - JSON does not require U+2028 and U+2029 to be escaped, but // JavaScript does require this: // http://stackoverflow.com/questions/2965293/javascript-parse-error-on-u2028-unicode-character/9168133#9168133 // - '/' also does not have to be escaped, but escaping it when // preceeded by a '<' avoids problems with JSON in HTML <script> tags private static bool NeedEscape(string src, int i) { char c = src[i]; return c < 32 || c == '"' || c == '\\' // Broken lead surrogate || (c >= '\uD800' && c <= '\uDBFF' && (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF')) // Broken tail surrogate || (c >= '\uDC00' && c <= '\uDFFF' && (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF')) // To produce valid JavaScript || c == '\u2028' || c == '\u2029' // Escape "</" for <script> tags || (c == '/' && i > 0 && src[i - 1] == '<'); } internal static string EscapeString(string src) { if (src != null) { for (int i = 0; i < src.Length; i++) { if (NeedEscape(src, i)) { var sb = new StringBuilder(); if (i > 0) { sb.Append(src, 0, i); } return DoEscapeString(sb, src, i); } } } return src; } private static string DoEscapeString(StringBuilder sb, string src, int cur) { int start = cur; for (int i = cur; i < src.Length; i++) if (NeedEscape(src, i)) { sb.Append(src, start, i - start); switch (src[i]) { case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '\"': sb.Append("\\\""); break; case '\\': sb.Append("\\\\"); break; case '/': sb.Append("\\/"); break; default: sb.Append("\\u"); sb.Append(((int)src[i]).ToString("x04")); break; } start = i + 1; } sb.Append(src, start, src.Length - start); return sb.ToString(); } // CLI -> JsonValue public static implicit operator JsonValue(bool value) => new JsonPrimitive(value); public static implicit operator JsonValue(byte value) => new JsonPrimitive(value); public static implicit operator JsonValue(char value) => new JsonPrimitive(value); public static implicit operator JsonValue(decimal value) => new JsonPrimitive(value); public static implicit operator JsonValue(double value) => new JsonPrimitive(value); public static implicit operator JsonValue(float value) => new JsonPrimitive(value); public static implicit operator JsonValue(int value) => new JsonPrimitive(value); public static implicit operator JsonValue(long value) => new JsonPrimitive(value); [CLSCompliant(false)] public static implicit operator JsonValue(sbyte value) => new JsonPrimitive(value); public static implicit operator JsonValue(short value) => new JsonPrimitive(value); public static implicit operator JsonValue(string value) => new JsonPrimitive(value); [CLSCompliant(false)] public static implicit operator JsonValue(uint value) => new JsonPrimitive(value); [CLSCompliant(false)] public static implicit operator JsonValue(ulong value) => new JsonPrimitive(value); [CLSCompliant(false)] public static implicit operator JsonValue(ushort value) => new JsonPrimitive(value); public static implicit operator JsonValue(DateTime value) => new JsonPrimitive(value); public static implicit operator JsonValue(DateTimeOffset value) => new JsonPrimitive(value); public static implicit operator JsonValue(Guid value) => new JsonPrimitive(value); public static implicit operator JsonValue(TimeSpan value) => new JsonPrimitive(value); public static implicit operator JsonValue(Uri value) => new JsonPrimitive(value); // JsonValue -> CLI public static implicit operator bool (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToBoolean(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator byte (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToByte(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator char (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToChar(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator decimal (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToDecimal(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator double (JsonValue value) { if (value == null) throw new ArgumentNullException(nameof(value)); return Convert.ToDouble(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator float (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToSingle(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator int (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToInt32(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator long (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToInt64(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } [CLSCompliant(false)] public static implicit operator sbyte (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToSByte(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator short (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToInt16(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator string (JsonValue value) { return value != null ? (string)((JsonPrimitive)value).Value : null; } [CLSCompliant(false)] public static implicit operator uint (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToUInt32(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } [CLSCompliant(false)] public static implicit operator ulong (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToUInt64(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } [CLSCompliant(false)] public static implicit operator ushort (JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Convert.ToUInt16(((JsonPrimitive)value).Value, NumberFormatInfo.InvariantInfo); } public static implicit operator DateTime(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (DateTime)((JsonPrimitive)value).Value; } public static implicit operator DateTimeOffset(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (DateTimeOffset)((JsonPrimitive)value).Value; } public static implicit operator TimeSpan(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (TimeSpan)((JsonPrimitive)value).Value; } public static implicit operator Guid(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (Guid)((JsonPrimitive)value).Value; } public static implicit operator Uri(JsonValue value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return (Uri)((JsonPrimitive)value).Value; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace BTDB.KVDBLayer.BTreeMem; class BTreeRoot : IBTreeRootNode { readonly long _transactionId; long _keyValueCount; IBTreeNode? _rootNode; public BTreeRoot(long transactionId) { _transactionId = transactionId; } public void CreateOrUpdate(ref CreateOrUpdateCtx ctx) { ctx.TransactionId = _transactionId; if (ctx.Stack == null) ctx.Stack = new List<NodeIdxPair>(); else ctx.Stack.Clear(); if (_rootNode == null) { _rootNode = ctx.Key.Length > BTreeLeafComp.MaxTotalLen ? BTreeLeaf.CreateFirst(ref ctx) : BTreeLeafComp.CreateFirst(ref ctx); _keyValueCount = 1; ctx.Stack.Add(new NodeIdxPair { Node = _rootNode, Idx = 0 }); ctx.KeyIndex = 0; ctx.Created = true; return; } ctx.Depth = 0; _rootNode.CreateOrUpdate(ref ctx); if (ctx.Split) { _rootNode = new BTreeBranch(ctx.TransactionId, ctx.Node1, ctx.Node2); ctx.Stack.Insert(0, new NodeIdxPair { Node = _rootNode, Idx = ctx.SplitInRight ? 1 : 0 }); } else if (ctx.Update) { _rootNode = ctx.Node1; } if (ctx.Created) { _keyValueCount++; } } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, in ReadOnlySpan<byte> key) { throw new InvalidOperationException(); } public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, in ReadOnlySpan<byte> key, uint prefixLen) { stack.Clear(); if (_rootNode == null) { keyIndex = -1; return FindResult.NotFound; } var result = _rootNode.FindKey(stack, out keyIndex, key); if (result == FindResult.Previous) { if (keyIndex < 0) { keyIndex = 0; stack[^1] = new NodeIdxPair { Node = stack[^1].Node, Idx = 0 }; result = FindResult.Next; } else { if (!KeyStartsWithPrefix(key.Slice(0, (int)prefixLen), GetKeyFromStack(stack))) { result = FindResult.Next; keyIndex++; if (!FindNextKey(stack)) { return FindResult.NotFound; } } } if (!KeyStartsWithPrefix(key.Slice(0, (int)prefixLen), GetKeyFromStack(stack))) { return FindResult.NotFound; } } return result; } internal static bool KeyStartsWithPrefix(in ReadOnlySpan<byte> prefix, in ReadOnlySpan<byte> key) { if (key.Length < prefix.Length) return false; return prefix.SequenceEqual(key.Slice(0, prefix.Length)); } static ReadOnlySpan<byte> GetKeyFromStack(List<NodeIdxPair> stack) { var last = stack[^1]; return ((IBTreeLeafNode)last.Node).GetKey(last.Idx); } public long CalcKeyCount() { return _keyValueCount; } public byte[] GetLeftMostKey() { return _rootNode!.GetLeftMostKey(); } public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex) { Debug.Assert(keyIndex >= 0 && keyIndex < _keyValueCount); stack.Clear(); _rootNode!.FillStackByIndex(stack, keyIndex); } public long FindLastWithPrefix(in ReadOnlySpan<byte> prefix) { if (_rootNode == null) return -1; return _rootNode.FindLastWithPrefix(prefix); } public bool NextIdxValid(int idx) { return false; } public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx) { stack.Add(new NodeIdxPair { Node = _rootNode!, Idx = 0 }); _rootNode.FillStackByLeftMost(stack, 0); } public void FillStackByRightMost(List<NodeIdxPair> stack, int idx) { throw new ArgumentException(); } public int GetLastChildrenIdx() { return 0; } public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex) { throw new ArgumentException(); } public IBTreeNode EraseOne(long transactionId, long keyIndex) { throw new ArgumentException(); } public long TransactionId => _transactionId; public ulong CommitUlong { get; set; } public IBTreeRootNode NewTransactionRoot() { ulong[]? newulongs = null; if (_ulongs != null) { newulongs = new ulong[_ulongs.Length]; Array.Copy(_ulongs, newulongs, newulongs.Length); } return new BTreeRoot(_transactionId + 1) { _keyValueCount = _keyValueCount, _rootNode = _rootNode, CommitUlong = CommitUlong, _ulongs = newulongs }; } public void EraseRange(long firstKeyIndex, long lastKeyIndex) { Debug.Assert(firstKeyIndex >= 0); Debug.Assert(lastKeyIndex < _keyValueCount); if (firstKeyIndex == 0 && lastKeyIndex == _keyValueCount - 1) { _rootNode = null; _keyValueCount = 0; return; } if (firstKeyIndex == lastKeyIndex) { _keyValueCount--; _rootNode = _rootNode!.EraseOne(TransactionId, firstKeyIndex); } else { _keyValueCount -= lastKeyIndex - firstKeyIndex + 1; _rootNode = _rootNode!.EraseRange(TransactionId, firstKeyIndex, lastKeyIndex); } } public bool FindNextKey(List<NodeIdxPair> stack) { int idx = stack.Count - 1; while (idx >= 0) { var pair = stack[idx]; if (pair.Node.NextIdxValid(pair.Idx)) { stack.RemoveRange(idx + 1, stack.Count - idx - 1); stack[idx] = new NodeIdxPair { Node = pair.Node, Idx = pair.Idx + 1 }; pair.Node.FillStackByLeftMost(stack, pair.Idx + 1); return true; } idx--; } return false; } public bool FindPreviousKey(List<NodeIdxPair> stack) { int idx = stack.Count - 1; while (idx >= 0) { var pair = stack[idx]; if (pair.Idx > 0) { stack.RemoveRange(idx + 1, stack.Count - idx - 1); stack[idx] = new NodeIdxPair { Node = pair.Node, Idx = pair.Idx - 1 }; pair.Node.FillStackByRightMost(stack, pair.Idx - 1); return true; } idx--; } return false; } public void BuildTree(long keyCount, Func<BTreeLeafMember> memberGenerator) { _keyValueCount = keyCount; if (keyCount == 0) { _rootNode = null; return; } _rootNode = BuildTreeNode(keyCount, memberGenerator); } IBTreeNode BuildTreeNode(long keyCount, Func<BTreeLeafMember> memberGenerator) { var leafCount = (keyCount + BTreeLeafComp.MaxMembers - 1) / BTreeLeafComp.MaxMembers; var order = 0L; var done = 0L; return BuildBranchNode(leafCount, () => { order++; var reach = keyCount * order / leafCount; var todo = (int)(reach - done); done = reach; var keyValues = new BTreeLeafMember[todo]; long totalKeyLen = 0; for (var i = 0; i < keyValues.Length; i++) { keyValues[i] = memberGenerator(); totalKeyLen += keyValues[i].Key.Length; } if (totalKeyLen > BTreeLeafComp.MaxTotalLen) { return new BTreeLeaf(_transactionId, keyValues); } return new BTreeLeafComp(_transactionId, keyValues); }); } IBTreeNode BuildBranchNode(long count, Func<IBTreeNode> generator) { if (count == 1) return generator(); var children = (count + BTreeBranch.MaxChildren - 1) / BTreeBranch.MaxChildren; var order = 0L; var done = 0L; return BuildBranchNode(children, () => { order++; var reach = count * order / children; var todo = (int)(reach - done); done = reach; return new BTreeBranch(_transactionId, todo, generator); }); } ulong[]? _ulongs; public ulong GetUlong(uint idx) { if (_ulongs == null) return 0; return idx >= _ulongs.Length ? 0 : _ulongs[idx]; } public void SetUlong(uint idx, ulong value) { if (_ulongs == null || idx >= _ulongs.Length) Array.Resize(ref _ulongs, (int)(idx + 1)); _ulongs[idx] = value; } public uint GetUlongCount() { return _ulongs == null ? 0U : (uint)_ulongs.Length; } public string? DescriptionForLeaks { get; set; } }
// 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 sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>MobileAppCategoryConstant</c> resource.</summary> public sealed partial class MobileAppCategoryConstantName : gax::IResourceName, sys::IEquatable<MobileAppCategoryConstantName> { /// <summary>The possible contents of <see cref="MobileAppCategoryConstantName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>mobileAppCategoryConstants/{mobile_app_category_id}</c>. /// </summary> MobileAppCategory = 1, } private static gax::PathTemplate s_mobileAppCategory = new gax::PathTemplate("mobileAppCategoryConstants/{mobile_app_category_id}"); /// <summary> /// Creates a <see cref="MobileAppCategoryConstantName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="MobileAppCategoryConstantName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static MobileAppCategoryConstantName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new MobileAppCategoryConstantName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="MobileAppCategoryConstantName"/> with the pattern /// <c>mobileAppCategoryConstants/{mobile_app_category_id}</c>. /// </summary> /// <param name="mobileAppCategoryId">The <c>MobileAppCategory</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="MobileAppCategoryConstantName"/> constructed from the provided ids. /// </returns> public static MobileAppCategoryConstantName FromMobileAppCategory(string mobileAppCategoryId) => new MobileAppCategoryConstantName(ResourceNameType.MobileAppCategory, mobileAppCategoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(mobileAppCategoryId, nameof(mobileAppCategoryId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="MobileAppCategoryConstantName"/> with /// pattern <c>mobileAppCategoryConstants/{mobile_app_category_id}</c>. /// </summary> /// <param name="mobileAppCategoryId">The <c>MobileAppCategory</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MobileAppCategoryConstantName"/> with pattern /// <c>mobileAppCategoryConstants/{mobile_app_category_id}</c>. /// </returns> public static string Format(string mobileAppCategoryId) => FormatMobileAppCategory(mobileAppCategoryId); /// <summary> /// Formats the IDs into the string representation of this <see cref="MobileAppCategoryConstantName"/> with /// pattern <c>mobileAppCategoryConstants/{mobile_app_category_id}</c>. /// </summary> /// <param name="mobileAppCategoryId">The <c>MobileAppCategory</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="MobileAppCategoryConstantName"/> with pattern /// <c>mobileAppCategoryConstants/{mobile_app_category_id}</c>. /// </returns> public static string FormatMobileAppCategory(string mobileAppCategoryId) => s_mobileAppCategory.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(mobileAppCategoryId, nameof(mobileAppCategoryId))); /// <summary> /// Parses the given resource name string into a new <see cref="MobileAppCategoryConstantName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>mobileAppCategoryConstants/{mobile_app_category_id}</c></description></item> /// </list> /// </remarks> /// <param name="mobileAppCategoryConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="MobileAppCategoryConstantName"/> if successful.</returns> public static MobileAppCategoryConstantName Parse(string mobileAppCategoryConstantName) => Parse(mobileAppCategoryConstantName, false); /// <summary> /// Parses the given resource name string into a new <see cref="MobileAppCategoryConstantName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>mobileAppCategoryConstants/{mobile_app_category_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="mobileAppCategoryConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="MobileAppCategoryConstantName"/> if successful.</returns> public static MobileAppCategoryConstantName Parse(string mobileAppCategoryConstantName, bool allowUnparsed) => TryParse(mobileAppCategoryConstantName, allowUnparsed, out MobileAppCategoryConstantName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MobileAppCategoryConstantName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>mobileAppCategoryConstants/{mobile_app_category_id}</c></description></item> /// </list> /// </remarks> /// <param name="mobileAppCategoryConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="MobileAppCategoryConstantName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string mobileAppCategoryConstantName, out MobileAppCategoryConstantName result) => TryParse(mobileAppCategoryConstantName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="MobileAppCategoryConstantName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>mobileAppCategoryConstants/{mobile_app_category_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="mobileAppCategoryConstantName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="MobileAppCategoryConstantName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string mobileAppCategoryConstantName, bool allowUnparsed, out MobileAppCategoryConstantName result) { gax::GaxPreconditions.CheckNotNull(mobileAppCategoryConstantName, nameof(mobileAppCategoryConstantName)); gax::TemplatedResourceName resourceName; if (s_mobileAppCategory.TryParseName(mobileAppCategoryConstantName, out resourceName)) { result = FromMobileAppCategory(resourceName[0]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(mobileAppCategoryConstantName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private MobileAppCategoryConstantName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string mobileAppCategoryId = null) { Type = type; UnparsedResource = unparsedResourceName; MobileAppCategoryId = mobileAppCategoryId; } /// <summary> /// Constructs a new instance of a <see cref="MobileAppCategoryConstantName"/> class from the component parts of /// pattern <c>mobileAppCategoryConstants/{mobile_app_category_id}</c> /// </summary> /// <param name="mobileAppCategoryId">The <c>MobileAppCategory</c> ID. Must not be <c>null</c> or empty.</param> public MobileAppCategoryConstantName(string mobileAppCategoryId) : this(ResourceNameType.MobileAppCategory, mobileAppCategoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(mobileAppCategoryId, nameof(mobileAppCategoryId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>MobileAppCategory</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string MobileAppCategoryId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.MobileAppCategory: return s_mobileAppCategory.Expand(MobileAppCategoryId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as MobileAppCategoryConstantName); /// <inheritdoc/> public bool Equals(MobileAppCategoryConstantName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(MobileAppCategoryConstantName a, MobileAppCategoryConstantName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(MobileAppCategoryConstantName a, MobileAppCategoryConstantName b) => !(a == b); } public partial class MobileAppCategoryConstant { /// <summary> /// <see cref="gagvr::MobileAppCategoryConstantName"/>-typed view over the <see cref="ResourceName"/> resource /// name property. /// </summary> internal MobileAppCategoryConstantName ResourceNameAsMobileAppCategoryConstantName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::MobileAppCategoryConstantName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::MobileAppCategoryConstantName"/>-typed view over the <see cref="Name"/> resource name /// property. /// </summary> internal MobileAppCategoryConstantName MobileAppCategoryConstantName { get => string.IsNullOrEmpty(Name) ? null : gagvr::MobileAppCategoryConstantName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
namespace java.nio { [global::MonoJavaBridge.JavaClass(typeof(global::java.nio.IntBuffer_))] public abstract partial class IntBuffer : java.nio.Buffer, java.lang.Comparable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static IntBuffer() { InitJNI(); } protected IntBuffer(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _get14225; public abstract int get(); internal static global::MonoJavaBridge.MethodId _get14226; public virtual global::java.nio.IntBuffer get(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer._get14226, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._get14226, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _get14227; public virtual global::java.nio.IntBuffer get(int[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer._get14227, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._get14227, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _get14228; public abstract int get(int arg0); internal static global::MonoJavaBridge.MethodId _put14229; public virtual global::java.nio.IntBuffer put(java.nio.IntBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer._put14229, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._put14229, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _put14230; public abstract global::java.nio.IntBuffer put(int arg0); internal static global::MonoJavaBridge.MethodId _put14231; public abstract global::java.nio.IntBuffer put(int arg0, int arg1); internal static global::MonoJavaBridge.MethodId _put14232; public virtual global::java.nio.IntBuffer put(int[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer._put14232, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._put14232, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _put14233; public virtual global::java.nio.IntBuffer put(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer._put14233, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._put14233, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _equals14234; public override bool equals(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.IntBuffer._equals14234, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._equals14234, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _toString14235; public override global::java.lang.String toString() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer._toString14235)) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._toString14235)) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _hashCode14236; public override int hashCode() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.IntBuffer._hashCode14236); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._hashCode14236); } internal static global::MonoJavaBridge.MethodId _compareTo14237; public virtual int compareTo(java.lang.Object arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.IntBuffer._compareTo14237, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._compareTo14237, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _compareTo14238; public virtual int compareTo(java.nio.IntBuffer arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.IntBuffer._compareTo14238, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._compareTo14238, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _isDirect14239; public abstract bool isDirect(); internal static global::MonoJavaBridge.MethodId _hasArray14240; public sealed override bool hasArray() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.IntBuffer._hasArray14240); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._hasArray14240); } internal static global::MonoJavaBridge.MethodId _array14241; public override global::java.lang.Object array() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer._array14241)) as java.lang.Object; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._array14241)) as java.lang.Object; } internal static global::MonoJavaBridge.MethodId _arrayOffset14242; public sealed override int arrayOffset() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.IntBuffer._arrayOffset14242); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._arrayOffset14242); } internal static global::MonoJavaBridge.MethodId _wrap14243; public static global::java.nio.IntBuffer wrap(int[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._wrap14243, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _wrap14244; public static global::java.nio.IntBuffer wrap(int[] arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._wrap14244, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _allocate14245; public static global::java.nio.IntBuffer allocate(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(java.nio.IntBuffer.staticClass, global::java.nio.IntBuffer._allocate14245, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _duplicate14246; public abstract global::java.nio.IntBuffer duplicate(); internal static global::MonoJavaBridge.MethodId _slice14247; public abstract global::java.nio.IntBuffer slice(); internal static global::MonoJavaBridge.MethodId _asReadOnlyBuffer14248; public abstract global::java.nio.IntBuffer asReadOnlyBuffer(); internal static global::MonoJavaBridge.MethodId _compact14249; public abstract global::java.nio.IntBuffer compact(); internal static global::MonoJavaBridge.MethodId _order14250; public abstract global::java.nio.ByteOrder order(); private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.IntBuffer.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/IntBuffer")); global::java.nio.IntBuffer._get14225 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "get", "()I"); global::java.nio.IntBuffer._get14226 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "get", "([I)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._get14227 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "get", "([III)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._get14228 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "get", "(I)I"); global::java.nio.IntBuffer._put14229 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "put", "(Ljava/nio/IntBuffer;)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._put14230 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "put", "(I)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._put14231 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "put", "(II)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._put14232 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "put", "([III)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._put14233 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "put", "([I)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._equals14234 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "equals", "(Ljava/lang/Object;)Z"); global::java.nio.IntBuffer._toString14235 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "toString", "()Ljava/lang/String;"); global::java.nio.IntBuffer._hashCode14236 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "hashCode", "()I"); global::java.nio.IntBuffer._compareTo14237 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "compareTo", "(Ljava/lang/Object;)I"); global::java.nio.IntBuffer._compareTo14238 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "compareTo", "(Ljava/nio/IntBuffer;)I"); global::java.nio.IntBuffer._isDirect14239 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "isDirect", "()Z"); global::java.nio.IntBuffer._hasArray14240 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "hasArray", "()Z"); global::java.nio.IntBuffer._array14241 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "array", "()Ljava/lang/Object;"); global::java.nio.IntBuffer._arrayOffset14242 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "arrayOffset", "()I"); global::java.nio.IntBuffer._wrap14243 = @__env.GetStaticMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "wrap", "([III)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._wrap14244 = @__env.GetStaticMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "wrap", "([I)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._allocate14245 = @__env.GetStaticMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "allocate", "(I)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._duplicate14246 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "duplicate", "()Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._slice14247 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "slice", "()Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._asReadOnlyBuffer14248 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "asReadOnlyBuffer", "()Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._compact14249 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "compact", "()Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer._order14250 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer.staticClass, "order", "()Ljava/nio/ByteOrder;"); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.nio.IntBuffer))] public sealed partial class IntBuffer_ : java.nio.IntBuffer { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static IntBuffer_() { InitJNI(); } internal IntBuffer_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _get14251; public override int get() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.IntBuffer_._get14251); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._get14251); } internal static global::MonoJavaBridge.MethodId _get14252; public override int get(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::java.nio.IntBuffer_._get14252, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._get14252, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _put14253; public override global::java.nio.IntBuffer put(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_._put14253, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._put14253, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _put14254; public override global::java.nio.IntBuffer put(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_._put14254, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._put14254, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _isDirect14255; public override bool isDirect() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.IntBuffer_._isDirect14255); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._isDirect14255); } internal static global::MonoJavaBridge.MethodId _duplicate14256; public override global::java.nio.IntBuffer duplicate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_._duplicate14256)) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._duplicate14256)) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _slice14257; public override global::java.nio.IntBuffer slice() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_._slice14257)) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._slice14257)) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _asReadOnlyBuffer14258; public override global::java.nio.IntBuffer asReadOnlyBuffer() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_._asReadOnlyBuffer14258)) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._asReadOnlyBuffer14258)) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _compact14259; public override global::java.nio.IntBuffer compact() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_._compact14259)) as java.nio.IntBuffer; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._compact14259)) as java.nio.IntBuffer; } internal static global::MonoJavaBridge.MethodId _order14260; public override global::java.nio.ByteOrder order() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_._order14260)) as java.nio.ByteOrder; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._order14260)) as java.nio.ByteOrder; } internal static global::MonoJavaBridge.MethodId _isReadOnly14261; public override bool isReadOnly() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::java.nio.IntBuffer_._isReadOnly14261); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::java.nio.IntBuffer_.staticClass, global::java.nio.IntBuffer_._isReadOnly14261); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.nio.IntBuffer_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/nio/IntBuffer")); global::java.nio.IntBuffer_._get14251 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "get", "()I"); global::java.nio.IntBuffer_._get14252 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "get", "(I)I"); global::java.nio.IntBuffer_._put14253 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "put", "(I)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer_._put14254 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "put", "(II)Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer_._isDirect14255 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "isDirect", "()Z"); global::java.nio.IntBuffer_._duplicate14256 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "duplicate", "()Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer_._slice14257 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "slice", "()Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer_._asReadOnlyBuffer14258 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "asReadOnlyBuffer", "()Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer_._compact14259 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "compact", "()Ljava/nio/IntBuffer;"); global::java.nio.IntBuffer_._order14260 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "order", "()Ljava/nio/ByteOrder;"); global::java.nio.IntBuffer_._isReadOnly14261 = @__env.GetMethodIDNoThrow(global::java.nio.IntBuffer_.staticClass, "isReadOnly", "()Z"); } } }
using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Search { /* * 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. */ /// <summary> /// Base class for <see cref="Scorer"/>s that score disjunctions. /// Currently this just provides helper methods to manage the heap. /// </summary> internal abstract class DisjunctionScorer : Scorer { protected readonly Scorer[] m_subScorers; /// <summary> /// The document number of the current match. </summary> protected int m_doc = -1; protected int m_numScorers; protected DisjunctionScorer(Weight weight, Scorer[] subScorers) : base(weight) { this.m_subScorers = subScorers; this.m_numScorers = subScorers.Length; Heapify(); } /// <summary> /// Organize subScorers into a min heap with scorers generating the earliest document on top. /// </summary> protected void Heapify() { for (int i = (m_numScorers >> 1) - 1; i >= 0; i--) { HeapAdjust(i); } } /// <summary> /// The subtree of subScorers at root is a min heap except possibly for its root element. /// Bubble the root down as required to make the subtree a heap. /// </summary> protected void HeapAdjust(int root) { Scorer scorer = m_subScorers[root]; int doc = scorer.DocID; int i = root; while (i <= (m_numScorers >> 1) - 1) { int lchild = (i << 1) + 1; Scorer lscorer = m_subScorers[lchild]; int ldoc = lscorer.DocID; int rdoc = int.MaxValue, rchild = (i << 1) + 2; Scorer rscorer = null; if (rchild < m_numScorers) { rscorer = m_subScorers[rchild]; rdoc = rscorer.DocID; } if (ldoc < doc) { if (rdoc < ldoc) { m_subScorers[i] = rscorer; m_subScorers[rchild] = scorer; i = rchild; } else { m_subScorers[i] = lscorer; m_subScorers[lchild] = scorer; i = lchild; } } else if (rdoc < doc) { m_subScorers[i] = rscorer; m_subScorers[rchild] = scorer; i = rchild; } else { return; } } } /// <summary> /// Remove the root <see cref="Scorer"/> from subScorers and re-establish it as a heap /// </summary> protected void HeapRemoveRoot() { if (m_numScorers == 1) { m_subScorers[0] = null; m_numScorers = 0; } else { m_subScorers[0] = m_subScorers[m_numScorers - 1]; m_subScorers[m_numScorers - 1] = null; --m_numScorers; HeapAdjust(0); } } public override sealed ICollection<ChildScorer> GetChildren() { List<ChildScorer> children = new List<ChildScorer>(m_numScorers); for (int i = 0; i < m_numScorers; i++) { children.Add(new ChildScorer(m_subScorers[i], "SHOULD")); } return children; } public override long GetCost() { long sum = 0; for (int i = 0; i < m_numScorers; i++) { sum += m_subScorers[i].GetCost(); } return sum; } public override int DocID { get { return m_doc; } } public override int NextDoc() { Debug.Assert(m_doc != NO_MORE_DOCS); while (true) { if (m_subScorers[0].NextDoc() != NO_MORE_DOCS) { HeapAdjust(0); } else { HeapRemoveRoot(); if (m_numScorers == 0) { return m_doc = NO_MORE_DOCS; } } if (m_subScorers[0].DocID != m_doc) { AfterNext(); return m_doc; } } } public override int Advance(int target) { Debug.Assert(m_doc != NO_MORE_DOCS); while (true) { if (m_subScorers[0].Advance(target) != NO_MORE_DOCS) { HeapAdjust(0); } else { HeapRemoveRoot(); if (m_numScorers == 0) { return m_doc = NO_MORE_DOCS; } } if (m_subScorers[0].DocID >= target) { AfterNext(); return m_doc; } } } /// <summary> /// Called after <see cref="NextDoc()"/> or <see cref="Advance(int)"/> land on a new document. /// <para/> /// <c>subScorers[0]</c> will be positioned to the new docid, /// which could be <c>NO_MORE_DOCS</c> (subclass must handle this). /// <para/> /// Implementations should assign <c>doc</c> appropriately, and do any /// other work necessary to implement <see cref="Scorer.GetScore()"/> and <see cref="Index.DocsEnum.Freq"/> /// </summary> // TODO: make this less horrible protected abstract void AfterNext(); } }
// 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. #nullable enable using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Text; namespace System.IO { /// <summary>Contains internal path helpers that are shared between many projects.</summary> internal static partial class PathInternal { // All paths in Win32 ultimately end up becoming a path to a File object in the Windows object manager. Passed in paths get mapped through // DosDevice symbolic links in the object tree to actual File objects under \Devices. To illustrate, this is what happens with a typical // path "Foo" passed as a filename to any Win32 API: // // 1. "Foo" is recognized as a relative path and is appended to the current directory (say, "C:\" in our example) // 2. "C:\Foo" is prepended with the DosDevice namespace "\??\" // 3. CreateFile tries to create an object handle to the requested file "\??\C:\Foo" // 4. The Object Manager recognizes the DosDevices prefix and looks // a. First in the current session DosDevices ("\Sessions\1\DosDevices\" for example, mapped network drives go here) // b. If not found in the session, it looks in the Global DosDevices ("\GLOBAL??\") // 5. "C:" is found in DosDevices (in our case "\GLOBAL??\C:", which is a symbolic link to "\Device\HarddiskVolume6") // 6. The full path is now "\Device\HarddiskVolume6\Foo", "\Device\HarddiskVolume6" is a File object and parsing is handed off // to the registered parsing method for Files // 7. The registered open method for File objects is invoked to create the file handle which is then returned // // There are multiple ways to directly specify a DosDevices path. The final format of "\??\" is one way. It can also be specified // as "\\.\" (the most commonly documented way) and "\\?\". If the question mark syntax is used the path will skip normalization // (essentially GetFullPathName()) and path length checks. // Windows Kernel-Mode Object Manager // https://msdn.microsoft.com/en-us/library/windows/hardware/ff565763.aspx // https://channel9.msdn.com/Shows/Going+Deep/Windows-NT-Object-Manager // // Introduction to MS-DOS Device Names // https://msdn.microsoft.com/en-us/library/windows/hardware/ff548088.aspx // // Local and Global MS-DOS Device Names // https://msdn.microsoft.com/en-us/library/windows/hardware/ff554302.aspx internal const char DirectorySeparatorChar = '\\'; internal const char AltDirectorySeparatorChar = '/'; internal const char VolumeSeparatorChar = ':'; internal const char PathSeparator = ';'; internal const string DirectorySeparatorCharAsString = "\\"; internal const string ExtendedPathPrefix = @"\\?\"; internal const string UncPathPrefix = @"\\"; internal const string UncExtendedPrefixToInsert = @"?\UNC\"; internal const string UncExtendedPathPrefix = @"\\?\UNC\"; internal const string DevicePathPrefix = @"\\.\"; internal const string ParentDirectoryPrefix = @"..\"; internal const int MaxShortPath = 260; internal const int MaxShortDirectoryPath = 248; // \\?\, \\.\, \??\ internal const int DevicePrefixLength = 4; // \\ internal const int UncPrefixLength = 2; // \\?\UNC\, \\.\UNC\ internal const int UncExtendedPrefixLength = 8; /// <summary> /// Returns true if the given character is a valid drive letter /// </summary> internal static bool IsValidDriveChar(char value) { return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z')); } internal static bool EndsWithPeriodOrSpace(string? path) { if (string.IsNullOrEmpty(path)) return false; char c = path[path.Length - 1]; return c == ' ' || c == '.'; } /// <summary> /// Adds the extended path prefix (\\?\) if not already a device path, IF the path is not relative, /// AND the path is more than 259 characters. (> MAX_PATH + null). This will also insert the extended /// prefix if the path ends with a period or a space. Trailing periods and spaces are normally eaten /// away from paths during normalization, but if we see such a path at this point it should be /// normalized and has retained the final characters. (Typically from one of the *Info classes) /// </summary> [return: NotNullIfNotNull("path")] internal static string? EnsureExtendedPrefixIfNeeded(string? path) { if (path != null && (path.Length >= MaxShortPath || EndsWithPeriodOrSpace(path))) { return EnsureExtendedPrefix(path); } else { return path; } } /// <summary> /// Adds the extended path prefix (\\?\) if not relative or already a device path. /// </summary> internal static string EnsureExtendedPrefix(string path) { // Putting the extended prefix on the path changes the processing of the path. It won't get normalized, which // means adding to relative paths will prevent them from getting the appropriate current directory inserted. // If it already has some variant of a device path (\??\, \\?\, \\.\, //./, etc.) we don't need to change it // as it is either correct or we will be changing the behavior. When/if Windows supports long paths implicitly // in the future we wouldn't want normalization to come back and break existing code. // In any case, all internal usages should be hitting normalize path (Path.GetFullPath) before they hit this // shimming method. (Or making a change that doesn't impact normalization, such as adding a filename to a // normalized base path.) if (IsPartiallyQualified(path.AsSpan()) || IsDevice(path.AsSpan())) return path; // Given \\server\share in longpath becomes \\?\UNC\server\share if (path.StartsWith(UncPathPrefix, StringComparison.OrdinalIgnoreCase)) return path.Insert(2, UncExtendedPrefixToInsert); return ExtendedPathPrefix + path; } /// <summary> /// Returns true if the path uses any of the DOS device path syntaxes. ("\\.\", "\\?\", or "\??\") /// </summary> internal static bool IsDevice(ReadOnlySpan<char> path) { // If the path begins with any two separators is will be recognized and normalized and prepped with // "\??\" for internal usage correctly. "\??\" is recognized and handled, "/??/" is not. return IsExtended(path) || ( path.Length >= DevicePrefixLength && IsDirectorySeparator(path[0]) && IsDirectorySeparator(path[1]) && (path[2] == '.' || path[2] == '?') && IsDirectorySeparator(path[3]) ); } /// <summary> /// Returns true if the path is a device UNC (\\?\UNC\, \\.\UNC\) /// </summary> internal static bool IsDeviceUNC(ReadOnlySpan<char> path) { return path.Length >= UncExtendedPrefixLength && IsDevice(path) && IsDirectorySeparator(path[7]) && path[4] == 'U' && path[5] == 'N' && path[6] == 'C'; } /// <summary> /// Returns true if the path uses the canonical form of extended syntax ("\\?\" or "\??\"). If the /// path matches exactly (cannot use alternate directory separators) Windows will skip normalization /// and path length checks. /// </summary> internal static bool IsExtended(ReadOnlySpan<char> path) { // While paths like "//?/C:/" will work, they're treated the same as "\\.\" paths. // Skipping of normalization will *only* occur if back slashes ('\') are used. return path.Length >= DevicePrefixLength && path[0] == '\\' && (path[1] == '\\' || path[1] == '?') && path[2] == '?' && path[3] == '\\'; } /// <summary> /// Check for known wildcard characters. '*' and '?' are the most common ones. /// </summary> internal static bool HasWildCardCharacters(ReadOnlySpan<char> path) { // Question mark is part of dos device syntax so we have to skip if we are int startIndex = IsDevice(path) ? ExtendedPathPrefix.Length : 0; // [MS - FSA] 2.1.4.4 Algorithm for Determining if a FileName Is in an Expression // https://msdn.microsoft.com/en-us/library/ff469270.aspx for (int i = startIndex; i < path.Length; i++) { char c = path[i]; if (c <= '?') // fast path for common case - '?' is highest wildcard character { if (c == '\"' || c == '<' || c == '>' || c == '*' || c == '?') return true; } } return false; } /// <summary> /// Gets the length of the root of the path (drive, share, etc.). /// </summary> internal static int GetRootLength(ReadOnlySpan<char> path) { int pathLength = path.Length; int i = 0; bool deviceSyntax = IsDevice(path); bool deviceUnc = deviceSyntax && IsDeviceUNC(path); if ((!deviceSyntax || deviceUnc) && pathLength > 0 && IsDirectorySeparator(path[0])) { // UNC or simple rooted path (e.g. "\foo", NOT "\\?\C:\foo") if (deviceUnc || (pathLength > 1 && IsDirectorySeparator(path[1]))) { // UNC (\\?\UNC\ or \\), scan past server\share // Start past the prefix ("\\" or "\\?\UNC\") i = deviceUnc ? UncExtendedPrefixLength : UncPrefixLength; // Skip two separators at most int n = 2; while (i < pathLength && (!IsDirectorySeparator(path[i]) || --n > 0)) i++; } else { // Current drive rooted (e.g. "\foo") i = 1; } } else if (deviceSyntax) { // Device path (e.g. "\\?\.", "\\.\") // Skip any characters following the prefix that aren't a separator i = DevicePrefixLength; while (i < pathLength && !IsDirectorySeparator(path[i])) i++; // If there is another separator take it, as long as we have had at least one // non-separator after the prefix (e.g. don't take "\\?\\", but take "\\?\a\") if (i < pathLength && i > DevicePrefixLength && IsDirectorySeparator(path[i])) i++; } else if (pathLength >= 2 && path[1] == VolumeSeparatorChar && IsValidDriveChar(path[0])) { // Valid drive specified path ("C:", "D:", etc.) i = 2; // If the colon is followed by a directory separator, move past it (e.g "C:\") if (pathLength > 2 && IsDirectorySeparator(path[2])) i++; } return i; } /// <summary> /// Returns true if the path specified is relative to the current drive or working directory. /// Returns false if the path is fixed to a specific drive or UNC path. This method does no /// validation of the path (URIs will be returned as relative as a result). /// </summary> /// <remarks> /// Handles paths that use the alternate directory separator. It is a frequent mistake to /// assume that rooted paths (Path.IsPathRooted) are not relative. This isn't the case. /// "C:a" is drive relative- meaning that it will be resolved against the current directory /// for C: (rooted, but relative). "C:\a" is rooted and not relative (the current directory /// will not be used to modify the path). /// </remarks> internal static bool IsPartiallyQualified(ReadOnlySpan<char> path) { if (path.Length < 2) { // It isn't fixed, it must be relative. There is no way to specify a fixed // path with one character (or less). return true; } if (IsDirectorySeparator(path[0])) { // There is no valid way to specify a relative path with two initial slashes or // \? as ? isn't valid for drive relative paths and \??\ is equivalent to \\?\ return !(path[1] == '?' || IsDirectorySeparator(path[1])); } // The only way to specify a fixed path that doesn't begin with two slashes // is the drive, colon, slash format- i.e. C:\ return !((path.Length >= 3) && (path[1] == VolumeSeparatorChar) && IsDirectorySeparator(path[2]) // To match old behavior we'll check the drive character for validity as the path is technically // not qualified if you don't have a valid drive. "=:\" is the "=" file's default data stream. && IsValidDriveChar(path[0])); } /// <summary> /// True if the given character is a directory separator. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static bool IsDirectorySeparator(char c) { return c == DirectorySeparatorChar || c == AltDirectorySeparatorChar; } /// <summary> /// Normalize separators in the given path. Converts forward slashes into back slashes and compresses slash runs, keeping initial 2 if present. /// Also trims initial whitespace in front of "rooted" paths (see PathStartSkip). /// /// This effectively replicates the behavior of the legacy NormalizePath when it was called with fullCheck=false and expandShortpaths=false. /// The current NormalizePath gets directory separator normalization from Win32's GetFullPathName(), which will resolve relative paths and as /// such can't be used here (and is overkill for our uses). /// /// Like the current NormalizePath this will not try and analyze periods/spaces within directory segments. /// </summary> /// <remarks> /// The only callers that used to use Path.Normalize(fullCheck=false) were Path.GetDirectoryName() and Path.GetPathRoot(). Both usages do /// not need trimming of trailing whitespace here. /// /// GetPathRoot() could technically skip normalizing separators after the second segment- consider as a future optimization. /// /// For legacy desktop behavior with ExpandShortPaths: /// - It has no impact on GetPathRoot() so doesn't need consideration. /// - It could impact GetDirectoryName(), but only if the path isn't relative (C:\ or \\Server\Share). /// /// In the case of GetDirectoryName() the ExpandShortPaths behavior was undocumented and provided inconsistent results if the path was /// fixed/relative. For example: "C:\PROGRA~1\A.TXT" would return "C:\Program Files" while ".\PROGRA~1\A.TXT" would return ".\PROGRA~1". If you /// ultimately call GetFullPath() this doesn't matter, but if you don't or have any intermediate string handling could easily be tripped up by /// this undocumented behavior. /// /// We won't match this old behavior because: /// /// 1. It was undocumented /// 2. It was costly (extremely so if it actually contained '~') /// 3. Doesn't play nice with string logic /// 4. Isn't a cross-plat friendly concept/behavior /// </remarks> internal static string NormalizeDirectorySeparators(string path) { if (string.IsNullOrEmpty(path)) return path; char current; // Make a pass to see if we need to normalize so we can potentially skip allocating bool normalized = true; for (int i = 0; i < path.Length; i++) { current = path[i]; if (IsDirectorySeparator(current) && (current != DirectorySeparatorChar // Check for sequential separators past the first position (we need to keep initial two for UNC/extended) || (i > 0 && i + 1 < path.Length && IsDirectorySeparator(path[i + 1])))) { normalized = false; break; } } if (normalized) return path; Span<char> initialBuffer = stackalloc char[MaxShortPath]; ValueStringBuilder builder = new ValueStringBuilder(initialBuffer); int start = 0; if (IsDirectorySeparator(path[start])) { start++; builder.Append(DirectorySeparatorChar); } for (int i = start; i < path.Length; i++) { current = path[i]; // If we have a separator if (IsDirectorySeparator(current)) { // If the next is a separator, skip adding this if (i + 1 < path.Length && IsDirectorySeparator(path[i + 1])) { continue; } // Ensure it is the primary separator current = DirectorySeparatorChar; } builder.Append(current); } return builder.ToString(); } /// <summary> /// Returns true if the path is effectively empty for the current OS. /// For unix, this is empty or null. For Windows, this is empty, null, or /// just spaces ((char)32). /// </summary> internal static bool IsEffectivelyEmpty(ReadOnlySpan<char> path) { if (path.IsEmpty) return true; foreach (char c in path) { if (c != ' ') return false; } return true; } } }
namespace Caliburn.ShellFramework.Menus { using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Windows.Controls; using System.Windows.Input; using PresentationFramework; using PresentationFramework.ApplicationModel; using PresentationFramework.RoutedMessaging; using Resources; /// <summary> /// The default implementation of <see cref="IMenu"/>. /// </summary> public class MenuModel : BindableCollection<IMenu>, IMenu, IShortcut { static IInputManager inputManager; static IResourceManager resourceManager; /// <summary> /// Initializes the menu model system. /// </summary> /// <param name="inputManager">The input manager.</param> /// <param name="resourceManager">The resource manager.</param> public static void Initialize(IInputManager inputManager, IResourceManager resourceManager) { MenuModel.inputManager = inputManager; MenuModel.resourceManager = resourceManager; } private readonly Func<IEnumerable<IResult>> execute; private readonly Func<bool> canExecute = () => true; private string text; private IMenu parent; private ModifierKeys modifiers; private Key key; private string displayName; /// <summary> /// Gets the separator model. /// </summary> /// <value>The separator.</value> public static MenuModel Separator { get { return new MenuModel { IsSeparator = true }; } } /// <summary> /// Initializes a new instance of the <see cref="MenuModel"/> class. /// </summary> public MenuModel() {} /// <summary> /// Initializes a new instance of the <see cref="MenuModel"/> class. /// </summary> /// <param name="text">The text.</param> public MenuModel(string text) : this() { Text = text; } /// <summary> /// Initializes a new instance of the <see cref="MenuModel"/> class. /// </summary> /// <param name="text">The text.</param> /// <param name="execute">The action.</param> public MenuModel(string text, Func<IEnumerable<IResult>> execute) : this(text) { this.execute = execute; } /// <summary> /// Initializes a new instance of the <see cref="MenuModel"/> class. /// </summary> /// <param name="text">The text.</param> /// <param name="execute">The action.</param> /// <param name="canExecute">The action guard.</param> public MenuModel(string text, Func<IEnumerable<IResult>> execute, Func<bool> canExecute) : this(text, execute) { this.canExecute = canExecute; } /// <summary> /// Gets or Sets the Parent /// </summary> /// <value></value> public IMenu Parent { get { return parent; } set { parent = value; OnPropertyChanged(new PropertyChangedEventArgs("Parent")); } } /// <summary> /// Gets or Sets the Parent /// </summary> /// <value></value> object IChild.Parent { get { return Parent; } set { Parent = (IMenu)value; } } /// <summary> /// Gets or Sets the Display Name /// </summary> /// <value></value> public string DisplayName { get { return displayName; } set { displayName = value; OnPropertyChanged(new PropertyChangedEventArgs("DisplayName")); } } /// <summary> /// Gets or sets the text. /// </summary> /// <value>The text.</value> public string Text { get { return text; } set { text = value; OnPropertyChanged(new PropertyChangedEventArgs("Text")); DisplayName = string.IsNullOrEmpty(Text) ? null : Text.Replace("_", string.Empty); } } /// <summary> /// Gets or sets the icon. /// </summary> /// <value>The icon.</value> public Image Icon { get; private set; } /// <summary> /// Gets or sets a value indicating whether this instance is separator. /// </summary> /// <value> /// <c>true</c> if this instance is separator; otherwise, <c>false</c>. /// </value> public bool IsSeparator { get; private set; } /// <summary> /// Gets the action text. /// </summary> /// <value>The action text.</value> public string ActionText { get { return "Execute"; } } /// <summary> /// Gets the input gesture text. /// </summary> /// <value>The input gesture text.</value> public string InputGestureText { get { return inputManager.GetDisplayString(key, modifiers); } } /// <summary> /// Gets the children. /// </summary> /// <value>The children.</value> public IObservableCollection<IMenu> Children { get { return this; } } /// <summary> /// Gets a value indicating whether the action can execute. /// </summary> /// <value> /// <c>true</c> if it can execute; otherwise, <c>false</c>. /// </value> public bool CanExecute { get { return canExecute(); } } /// <summary> /// Executes this menu action. /// </summary> /// <returns></returns> public IEnumerable<IResult> Execute() { return execute != null ? execute() : new IResult[] {}; } /// <summary> /// Sets the item at the specified position. /// </summary> /// <param name="index">The index to set the item at.</param> /// <param name="item">The item to set.</param> protected override void SetItemBase(int index, IMenu item) { base.SetItemBase(index, item); item.Parent = this; } /// <summary> /// Inserts the item to the specified position. /// </summary> /// <param name="index">The index to insert at.</param> /// <param name="item">The item to be inserted.</param> protected override void InsertItemBase(int index, IMenu item) { base.InsertItemBase(index, item); item.Parent = this; } /// <summary> /// Gets or sets the modifers. /// </summary> /// <value>The modifers.</value> ModifierKeys IShortcut.Modifers { get { return modifiers; } set { modifiers = value; } } /// <summary> /// Gets or sets the key. /// </summary> /// <value>The key.</value> Key IShortcut.Key { get { return key; } set { key = value; } } /// <summary> /// Adds a global shortcut to the menu item. /// </summary> /// <param name="modifiers">The modifiers.</param> /// <param name="key">The key.</param> /// <returns>The item.</returns> public MenuModel WithGlobalShortcut(ModifierKeys modifiers, Key key) { this.modifiers = modifiers; this.key = key; inputManager.AddShortcut(this); return this; } /// <summary> /// Adds an icon using the default location resolution to the menu item in the calling assembly. /// </summary> /// <returns>The item.</returns> public MenuModel WithIcon() { return WithIcon(Assembly.GetCallingAssembly(), ResourceExtensions.DetermineIconPath(DisplayName)); } /// <summary> /// Adds an icon to the menu item, searching the calling assmebly for the resource. /// </summary> /// <param name="path">The path.</param> /// <returns>The item.</returns> public MenuModel WithIcon(string path) { return WithIcon(Assembly.GetCallingAssembly(), path); } /// <summary> /// Adds an icon to the menu item. /// </summary> /// <param name="source">The source assmelby.</param> /// <param name="path">The path.</param> /// <returns>The item.</returns> public MenuModel WithIcon(Assembly source, string path) { var iconSource = resourceManager.GetBitmap(path, source.GetAssemblyName()); if (iconSource != null) Icon = new Image { Source = iconSource }; return this; } } }