context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// #define UP_USE_WII_INPUT_MANAGER // #define UP_USE_CN_INPUT_MANAGER using UnityEngine; using System.Collections.Generic; using System; #if UP_USE_CN_INPUT_MANAGER using CnControls; #endif #if UP_USE_WII_INPUT_MANAGER using WiimoteApi; #endif // TODO player selection?! namespace UnityPlatformer { /// <summary> /// internal map of Wiimote library buttons /// TODO nunchuck, and other pads? /// </summary> public enum WiiButtons { WII_BUTTON_1, WII_BUTTON_2, WII_BUTTON_A, WII_BUTTON_B, WII_BUTTON_PLUS, WII_BUTTON_MINUS, WII_BUTTON_HOME } /// <summary> /// Keyboard, Touch and Wii /// /// Touch use CnControls [https://www.assetstore.unity3d.com/en/#!/content/15233] /// to enable touch you need to uncomment '\#define UP_USE_CN_INPUT_MANAGER' /// at the top of this file\n /// Wii controls use WiimoteApi [https://github.com/Flafla2/Unity-Wiimote] to enable wiimote support you need to /// uncomment '\#define UP_USE_WII_INPUT_MANAGER' at the top of this file /// </summary> public class DefaultInput : PlatformerInput { /// <summary> /// Maps between various inputs methods and action (string) /// </summary> [Serializable] public class InputMapping { /// <summary> /// constructor /// </summary> public InputMapping(String _action, String _handheld, String _keyboard, WiiButtons _wii) { action = _action; handheld = _handheld; keyboard = _keyboard; wii = _wii; } /// <summary> /// action identifier /// </summary> public String action; /// <summary> /// CNInput name /// </summary> public String handheld; /// <summary> /// Keyboard name /// </summary> public String keyboard; /// <summary> /// Button in a wiimote /// </summary> public WiiButtons wii; }; /// <summary> /// List of action - button/key mapping /// </summary> public List<InputMapping> inputsMap = new List<InputMapping> { // default map new InputMapping ( "Jump", "Jump", "Jump", WiiButtons.WII_BUTTON_1 ), new InputMapping ( "Attack", "Attack", "Fire2", WiiButtons.WII_BUTTON_2 ), new InputMapping ( "Use", "Use", "Fire1", WiiButtons.WII_BUTTON_A ), new InputMapping ( "Run", "Use", "Run", WiiButtons.WII_BUTTON_B ), new InputMapping ( "Pull", "Pull", "Pull", WiiButtons.WII_BUTTON_B // REVIEW ) }; #if UP_USE_WII_INPUT_MANAGER Wiimote remote; #endif public override void Start() { base.Start(); #if UP_USE_WII_INPUT_MANAGER WiimoteManager.FindWiimotes(); // Poll native bluetooth drivers to find Wiimotes foreach(Wiimote r in WiimoteManager.Wiimotes) { remote = r; remote.SendPlayerLED(true, false, false, true); remote.SendDataReportMode(InputDataType.REPORT_BUTTONS); } #endif } public override bool IsActionHeld(string action) { foreach (var i in inputsMap) { if (i.action == action) { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetButton(i.handheld); } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { return GetWiiButton(i.wii); } #endif return Input.GetButton(i.keyboard); } } Debug.LogWarning ("Cannot find action: " + action); return false; } public override bool IsActionDown(string action) { foreach (var i in inputsMap) { if (i.action == action) { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetButtonDown(i.handheld); } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { return GetWiiButton(i.wii); } #endif return Input.GetButtonDown(i.keyboard); } } Debug.LogWarning ("Cannot find action: " + action); return false; } public override bool IsActionUp(string action) { foreach (var i in inputsMap) { if (i.action == action) { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetButtonUp(i.handheld); } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { return !GetWiiButton(i.wii); } #endif return Input.GetButtonUp(i.keyboard); } } Debug.LogWarning ("Cannot find action: " + action); return false; } #if UP_USE_WII_INPUT_MANAGER bool GetWiiButton(WiiButtons btn) { if (remote != null) { switch(btn) { case WiiButtons.WII_BUTTON_1: return remote.Button.one; case WiiButtons.WII_BUTTON_2: return remote.Button.two; case WiiButtons.WII_BUTTON_A: return remote.Button.a; case WiiButtons.WII_BUTTON_B: return remote.Button.b; case WiiButtons.WII_BUTTON_PLUS: return remote.Button.plus; case WiiButtons.WII_BUTTON_MINUS: return remote.Button.minus; case WiiButtons.WII_BUTTON_HOME: return remote.Button.home; } } return false; } #endif public override bool IsLeftDown() { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetAxis("Horizontal") > 0; } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { //return remote.Button.d_left; return remote.Button.d_up; } #endif return Input.GetAxisRaw("Horizontal") > 0; } public override bool IsRightDown() { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetAxis("Horizontal") < 0; } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { //return remote.Button.d_right; return remote.Button.d_down; } #endif return Input.GetAxisRaw("Horizontal") < 0; } public override bool IsUpDown() { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetAxis("Vertical") > 0; } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { //return remote.Button.d_up; return remote.Button.d_right; } #endif return Input.GetAxisRaw("Vertical") > 0; } public override bool IsDownDown() { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetAxis("Vertical") < 0; } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { //return remote.Button.d_down; return remote.Button.d_left; } #endif return Input.GetAxisRaw("Vertical") < 0; } public override float GetAxisRawX() { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetAxis("Horizontal") < 0; } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { //return remote.Button.d_left ? -1 : (remote.Button.d_right ? 1 : 0); return remote.Button.d_up ? -1 : (remote.Button.d_down ? 1 : 0); } #endif return Input.GetAxisRaw ("Horizontal"); } public override float GetAxisRawY() { #if UP_USE_CN_INPUT_MANAGER if (SystemInfo.deviceType == DeviceType.Handheld) { return CnInputManager.GetAxis("Vertical") < 0; } #endif #if UP_USE_WII_INPUT_MANAGER if (remote != null) { return remote.Button.d_left ? -1 : (remote.Button.d_down ? 1 : 0); } #endif return Input.GetAxisRaw ("Vertical"); } public override Vector2 GetAxisRaw() { return new Vector2(GetAxisRawX(), GetAxisRawY()); } public override void Update() { #if UP_USE_WII_INPUT_MANAGER int ret; do { ret = remote.ReadWiimoteData(); } while (ret > 0); // ReadWiimoteData() returns 0 when nothing is left to read. So by doing this we continue to // update the Wiimote until it is "up to date." #endif base.Update(); } } }
// 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! namespace Google.Cloud.ArtifactRegistry.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedArtifactRegistryClientSnippets { /// <summary>Snippet for ListDockerImages</summary> public void ListDockerImagesRequestObject() { // Snippet: ListDockerImages(ListDockerImagesRequest, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create(); // Initialize request argument(s) ListDockerImagesRequest request = new ListDockerImagesRequest { Parent = "", }; // Make the request PagedEnumerable<ListDockerImagesResponse, DockerImage> response = artifactRegistryClient.ListDockerImages(request); // Iterate over all response items, lazily performing RPCs as required foreach (DockerImage item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDockerImagesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (DockerImage item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<DockerImage> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (DockerImage item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDockerImagesAsync</summary> public async Task ListDockerImagesRequestObjectAsync() { // Snippet: ListDockerImagesAsync(ListDockerImagesRequest, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = await ArtifactRegistryClient.CreateAsync(); // Initialize request argument(s) ListDockerImagesRequest request = new ListDockerImagesRequest { Parent = "", }; // Make the request PagedAsyncEnumerable<ListDockerImagesResponse, DockerImage> response = artifactRegistryClient.ListDockerImagesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((DockerImage item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDockerImagesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (DockerImage item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<DockerImage> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (DockerImage item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDockerImages</summary> public void ListDockerImages() { // Snippet: ListDockerImages(string, string, int?, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create(); // Initialize request argument(s) string parent = ""; // Make the request PagedEnumerable<ListDockerImagesResponse, DockerImage> response = artifactRegistryClient.ListDockerImages(parent); // Iterate over all response items, lazily performing RPCs as required foreach (DockerImage item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListDockerImagesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (DockerImage item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<DockerImage> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (DockerImage item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListDockerImagesAsync</summary> public async Task ListDockerImagesAsync() { // Snippet: ListDockerImagesAsync(string, string, int?, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = await ArtifactRegistryClient.CreateAsync(); // Initialize request argument(s) string parent = ""; // Make the request PagedAsyncEnumerable<ListDockerImagesResponse, DockerImage> response = artifactRegistryClient.ListDockerImagesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((DockerImage item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListDockerImagesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (DockerImage item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<DockerImage> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (DockerImage item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListRepositories</summary> public void ListRepositoriesRequestObject() { // Snippet: ListRepositories(ListRepositoriesRequest, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create(); // Initialize request argument(s) ListRepositoriesRequest request = new ListRepositoriesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedEnumerable<ListRepositoriesResponse, Repository> response = artifactRegistryClient.ListRepositories(request); // Iterate over all response items, lazily performing RPCs as required foreach (Repository item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListRepositoriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Repository item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Repository> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Repository item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListRepositoriesAsync</summary> public async Task ListRepositoriesRequestObjectAsync() { // Snippet: ListRepositoriesAsync(ListRepositoriesRequest, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = await ArtifactRegistryClient.CreateAsync(); // Initialize request argument(s) ListRepositoriesRequest request = new ListRepositoriesRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), }; // Make the request PagedAsyncEnumerable<ListRepositoriesResponse, Repository> response = artifactRegistryClient.ListRepositoriesAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Repository item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListRepositoriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Repository item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Repository> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Repository item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListRepositories</summary> public void ListRepositories() { // Snippet: ListRepositories(string, string, int?, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListRepositoriesResponse, Repository> response = artifactRegistryClient.ListRepositories(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Repository item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListRepositoriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Repository item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Repository> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Repository item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListRepositoriesAsync</summary> public async Task ListRepositoriesAsync() { // Snippet: ListRepositoriesAsync(string, string, int?, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = await ArtifactRegistryClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListRepositoriesResponse, Repository> response = artifactRegistryClient.ListRepositoriesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Repository item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListRepositoriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Repository item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Repository> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Repository item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListRepositories</summary> public void ListRepositoriesResourceNames() { // Snippet: ListRepositories(LocationName, string, int?, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListRepositoriesResponse, Repository> response = artifactRegistryClient.ListRepositories(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Repository item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListRepositoriesResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Repository item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Repository> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Repository item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListRepositoriesAsync</summary> public async Task ListRepositoriesResourceNamesAsync() { // Snippet: ListRepositoriesAsync(LocationName, string, int?, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = await ArtifactRegistryClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListRepositoriesResponse, Repository> response = artifactRegistryClient.ListRepositoriesAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Repository item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListRepositoriesResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Repository item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Repository> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Repository item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetRepository</summary> public void GetRepositoryRequestObject() { // Snippet: GetRepository(GetRepositoryRequest, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create(); // Initialize request argument(s) GetRepositoryRequest request = new GetRepositoryRequest { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), }; // Make the request Repository response = artifactRegistryClient.GetRepository(request); // End snippet } /// <summary>Snippet for GetRepositoryAsync</summary> public async Task GetRepositoryRequestObjectAsync() { // Snippet: GetRepositoryAsync(GetRepositoryRequest, CallSettings) // Additional: GetRepositoryAsync(GetRepositoryRequest, CancellationToken) // Create client ArtifactRegistryClient artifactRegistryClient = await ArtifactRegistryClient.CreateAsync(); // Initialize request argument(s) GetRepositoryRequest request = new GetRepositoryRequest { RepositoryName = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"), }; // Make the request Repository response = await artifactRegistryClient.GetRepositoryAsync(request); // End snippet } /// <summary>Snippet for GetRepository</summary> public void GetRepository() { // Snippet: GetRepository(string, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/repositories/[REPOSITORY]"; // Make the request Repository response = artifactRegistryClient.GetRepository(name); // End snippet } /// <summary>Snippet for GetRepositoryAsync</summary> public async Task GetRepositoryAsync() { // Snippet: GetRepositoryAsync(string, CallSettings) // Additional: GetRepositoryAsync(string, CancellationToken) // Create client ArtifactRegistryClient artifactRegistryClient = await ArtifactRegistryClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/repositories/[REPOSITORY]"; // Make the request Repository response = await artifactRegistryClient.GetRepositoryAsync(name); // End snippet } /// <summary>Snippet for GetRepository</summary> public void GetRepositoryResourceNames() { // Snippet: GetRepository(RepositoryName, CallSettings) // Create client ArtifactRegistryClient artifactRegistryClient = ArtifactRegistryClient.Create(); // Initialize request argument(s) RepositoryName name = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"); // Make the request Repository response = artifactRegistryClient.GetRepository(name); // End snippet } /// <summary>Snippet for GetRepositoryAsync</summary> public async Task GetRepositoryResourceNamesAsync() { // Snippet: GetRepositoryAsync(RepositoryName, CallSettings) // Additional: GetRepositoryAsync(RepositoryName, CancellationToken) // Create client ArtifactRegistryClient artifactRegistryClient = await ArtifactRegistryClient.CreateAsync(); // Initialize request argument(s) RepositoryName name = RepositoryName.FromProjectLocationRepository("[PROJECT]", "[LOCATION]", "[REPOSITORY]"); // Make the request Repository response = await artifactRegistryClient.GetRepositoryAsync(name); // End snippet } } }
// 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.Globalization; using System.Threading; namespace System.Globalization { // This calendar recognizes two era values: // 0 CurrentEra (AD) // 1 BeforeCurrentEra (BC) public class GregorianCalendar : Calendar { /* A.D. = anno Domini */ public const int ADEra = 1; // // This is the min Gregorian year can be represented by the DateTime class. // The limitation is derived from the DateTime class. // internal const int MinYear = 1; // // This is the max Gregorian year can be represented by the DateTime class. // The limitation is derived from the DateTime class. // internal const int MaxYear = 9999; internal GregorianCalendarTypes m_type; internal static readonly int[] DaysToMonth365 = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; internal static readonly int[] DaysToMonth366 = { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }; private static volatile Calendar s_defaultInstance; public override DateTime MinSupportedDateTime { get { return (DateTime.MinValue); } } public override DateTime MaxSupportedDateTime { get { return (DateTime.MaxValue); } } public override CalendarAlgorithmType AlgorithmType { get { return CalendarAlgorithmType.SolarCalendar; } } /*=================================GetDefaultInstance========================== **Action: Internal method to provide a default intance of GregorianCalendar. Used by NLS+ implementation ** and other calendars. **Returns: **Arguments: **Exceptions: ============================================================================*/ internal static Calendar GetDefaultInstance() { if (s_defaultInstance == null) { s_defaultInstance = new GregorianCalendar(); } return (s_defaultInstance); } // Construct an instance of gregorian calendar. public GregorianCalendar() : this(GregorianCalendarTypes.Localized) { } public GregorianCalendar(GregorianCalendarTypes type) { if ((int)type < (int)GregorianCalendarTypes.Localized || (int)type > (int)GregorianCalendarTypes.TransliteratedFrench) { throw new ArgumentOutOfRangeException( nameof(type), SR.Format(SR.ArgumentOutOfRange_Range, GregorianCalendarTypes.Localized, GregorianCalendarTypes.TransliteratedFrench)); } this.m_type = type; } public virtual GregorianCalendarTypes CalendarType { get { return (m_type); } set { VerifyWritable(); switch (value) { case GregorianCalendarTypes.Localized: case GregorianCalendarTypes.USEnglish: case GregorianCalendarTypes.MiddleEastFrench: case GregorianCalendarTypes.Arabic: case GregorianCalendarTypes.TransliteratedEnglish: case GregorianCalendarTypes.TransliteratedFrench: m_type = value; break; default: throw new ArgumentOutOfRangeException("m_type", SR.ArgumentOutOfRange_Enum); } } } internal override CalendarId ID { get { // By returning different ID for different variations of GregorianCalendar, // we can support the Transliterated Gregorian calendar. // DateTimeFormatInfo will use this ID to get formatting information about // the calendar. return ((CalendarId)m_type); } } /*=================================GetAbsoluteDate========================== **Action: Gets the absolute date for the given Gregorian date. The absolute date means ** the number of days from January 1st, 1 A.D. **Returns: the absolute date **Arguments: ** year the Gregorian year ** month the Gregorian month ** day the day **Exceptions: ** ArgumentOutOfRangException if year, month, day value is valid. **Note: ** This is an internal method used by DateToTicks() and the calculations of Hijri and Hebrew calendars. ** Number of Days in Prior Years (both common and leap years) + ** Number of Days in Prior Months of Current Year + ** Number of Days in Current Month ** ============================================================================*/ internal static long GetAbsoluteDate(int year, int month, int day) { if (year >= 1 && year <= MaxYear && month >= 1 && month <= 12) { int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))) ? DaysToMonth366 : DaysToMonth365; if (day >= 1 && (day <= days[month] - days[month - 1])) { int y = year - 1; int absoluteDate = y * 365 + y / 4 - y / 100 + y / 400 + days[month - 1] + day - 1; return (absoluteDate); } } throw new ArgumentOutOfRangeException(null, SR.ArgumentOutOfRange_BadYearMonthDay); } // Returns the tick count corresponding to the given year, month, and day. // Will check the if the parameters are valid. internal virtual long DateToTicks(int year, int month, int day) { return (GetAbsoluteDate(year, month, day) * TicksPerDay); } // Returns the DateTime resulting from adding the given number of // months to the specified DateTime. The result is computed by incrementing // (or decrementing) the year and month parts of the specified DateTime by // value months, and, if required, adjusting the day part of the // resulting date downwards to the last day of the resulting month in the // resulting year. The time-of-day part of the result is the same as the // time-of-day part of the specified DateTime. // // In more precise terms, considering the specified DateTime to be of the // form y / m / d + t, where y is the // year, m is the month, d is the day, and t is the // time-of-day, the result is y1 / m1 / d1 + t, // where y1 and m1 are computed by adding value months // to y and m, and d1 is the largest value less than // or equal to d that denotes a valid day in month m1 of year // y1. // public override DateTime AddMonths(DateTime time, int months) { if (months < -120000 || months > 120000) { throw new ArgumentOutOfRangeException( nameof(months), string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, -120000, 120000)); } time.GetDatePart(out int y, out int m, out int d); int i = m - 1 + months; if (i >= 0) { m = i % 12 + 1; y = y + i / 12; } else { m = 12 + (i + 1) % 12; y = y + (i - 11) / 12; } int[] daysArray = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; int days = (daysArray[m] - daysArray[m - 1]); if (d > days) { d = days; } long ticks = DateToTicks(y, m, d) + time.Ticks % TicksPerDay; Calendar.CheckAddResult(ticks, MinSupportedDateTime, MaxSupportedDateTime); return (new DateTime(ticks)); } // Returns the DateTime resulting from adding the given number of // years to the specified DateTime. The result is computed by incrementing // (or decrementing) the year part of the specified DateTime by value // years. If the month and day of the specified DateTime is 2/29, and if the // resulting year is not a leap year, the month and day of the resulting // DateTime becomes 2/28. Otherwise, the month, day, and time-of-day // parts of the result are the same as those of the specified DateTime. // public override DateTime AddYears(DateTime time, int years) { return (AddMonths(time, years * 12)); } // Returns the day-of-month part of the specified DateTime. The returned // value is an integer between 1 and 31. // public override int GetDayOfMonth(DateTime time) { return time.Day; } // Returns the day-of-week part of the specified DateTime. The returned value // is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates // Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates // Thursday, 5 indicates Friday, and 6 indicates Saturday. // public override DayOfWeek GetDayOfWeek(DateTime time) { return ((DayOfWeek)((int)(time.Ticks / TicksPerDay + 1) % 7)); } // Returns the day-of-year part of the specified DateTime. The returned value // is an integer between 1 and 366. // public override int GetDayOfYear(DateTime time) { return time.DayOfYear; } // Returns the number of days in the month given by the year and // month arguments. // public override int GetDaysInMonth(int year, int month, int era) { if (era == CurrentEra || era == ADEra) { if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException(nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.ArgumentOutOfRange_Month); } int[] days = ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365); return (days[month] - days[month - 1]); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the number of days in the year given by the year argument for the current era. // public override int GetDaysInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return ((year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 366 : 365); } throw new ArgumentOutOfRangeException( nameof(year), string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the era for the specified DateTime value. public override int GetEra(DateTime time) { return (ADEra); } public override int[] Eras { get { return (new int[] { ADEra }); } } // Returns the month part of the specified DateTime. The returned value is an // integer between 1 and 12. // public override int GetMonth(DateTime time) { return time.Month; } // Returns the number of months in the specified year and era. public override int GetMonthsInYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (12); } throw new ArgumentOutOfRangeException( nameof(year), string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the year part of the specified DateTime. The returned value is an // integer between 1 and 9999. // public override int GetYear(DateTime time) { return time.Year; } internal override bool IsValidYear(int year, int era) => year >= 1 && year <= MaxYear; internal override bool IsValidDay(int year, int month, int day, int era) { if ((era != CurrentEra && era != ADEra) || year < 1 || year > MaxYear || month < 1 || month > 12 || day < 1) { return false; } int[] days = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? DaysToMonth366 : DaysToMonth365; return day <= (days[month] - days[month - 1]); } // Checks whether a given day in the specified era is a leap day. This method returns true if // the date is a leap day, or false if not. // public override bool IsLeapDay(int year, int month, int day, int era) { if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), SR.Format(SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (day < 1 || day > GetDaysInMonth(year, month)) { throw new ArgumentOutOfRangeException(nameof(day), SR.Format(SR.ArgumentOutOfRange_Range, 1, GetDaysInMonth(year, month))); } if (!IsLeapYear(year)) { return (false); } if (month == 2 && day == 29) { return (true); } return (false); } // Returns the leap month in a calendar year of the specified era. This method returns 0 // if this calendar does not have leap month, or this year is not a leap year. // public override int GetLeapMonth(int year, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } return (0); } // Checks whether a given month in the specified era is a leap month. This method returns true if // month is a leap month, or false if not. // public override bool IsLeapMonth(int year, int month, int era) { if (era != CurrentEra && era != ADEra) { throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } if (year < 1 || year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } if (month < 1 || month > 12) { throw new ArgumentOutOfRangeException(nameof(month), SR.Format(SR.ArgumentOutOfRange_Range, 1, 12)); } return (false); } // Checks whether a given year in the specified era is a leap year. This method returns true if // year is a leap year, or false if not. // public override bool IsLeapYear(int year, int era) { if (era == CurrentEra || era == ADEra) { if (year >= 1 && year <= MaxYear) { return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); } throw new ArgumentOutOfRangeException( nameof(year), string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } // Returns the date and time converted to a DateTime value. Throws an exception if the n-tuple is invalid. // public override DateTime ToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era) { if (era == CurrentEra || era == ADEra) { return new DateTime(year, month, day, hour, minute, second, millisecond); } throw new ArgumentOutOfRangeException(nameof(era), SR.ArgumentOutOfRange_InvalidEraValue); } internal override bool TryToDateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, int era, out DateTime result) { if (era == CurrentEra || era == ADEra) { return DateTime.TryCreate(year, month, day, hour, minute, second, millisecond, out result); } result = DateTime.MinValue; return false; } private const int DEFAULT_TWO_DIGIT_YEAR_MAX = 2029; public override int TwoDigitYearMax { get { if (twoDigitYearMax == -1) { twoDigitYearMax = GetSystemTwoDigitYearSetting(ID, DEFAULT_TWO_DIGIT_YEAR_MAX); } return (twoDigitYearMax); } set { VerifyWritable(); if (value < 99 || value > MaxYear) { throw new ArgumentOutOfRangeException( "year", string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 99, MaxYear)); } twoDigitYearMax = value; } } public override int ToFourDigitYear(int year) { if (year < 0) { throw new ArgumentOutOfRangeException(nameof(year), SR.ArgumentOutOfRange_NeedNonNegNum); } if (year > MaxYear) { throw new ArgumentOutOfRangeException( nameof(year), string.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 1, MaxYear)); } return (base.ToFourDigitYear(year)); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 OpenSimulator Project 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 DEVELOPERS ``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 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.Drawing; using System.Drawing.Imaging; using Nini.Config; using OpenMetaverse; using OpenMetaverse.Imaging; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using log4net; using System.Reflection; namespace OpenSim.Region.CoreModules.Scripting.DynamicTexture { public class DynamicTextureModule : IRegionModule, IDynamicTextureManager { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private const int ALL_SIDES = -1; public const int DISP_EXPIRE = 1; public const int DISP_TEMP = 2; private Dictionary<UUID, Scene> RegisteredScenes = new Dictionary<UUID, Scene>(); private Dictionary<string, IDynamicTextureRender> RenderPlugins = new Dictionary<string, IDynamicTextureRender>(); private Dictionary<UUID, DynamicTextureUpdater> Updaters = new Dictionary<UUID, DynamicTextureUpdater>(); #region IDynamicTextureManager Members public void RegisterRender(string handleType, IDynamicTextureRender render) { if (!RenderPlugins.ContainsKey(handleType)) { RenderPlugins.Add(handleType, render); } } /// <summary> /// Called by code which actually renders the dynamic texture to supply texture data. /// </summary> /// <param name="id"></param> /// <param name="data"></param> public void ReturnData(UUID id, byte[] data) { DynamicTextureUpdater updater = null; lock (Updaters) { if (Updaters.ContainsKey(id)) { updater = Updaters[id]; } } if (updater != null) { if (RegisteredScenes.ContainsKey(updater.SimUUID)) { Scene scene = RegisteredScenes[updater.SimUUID]; updater.DataReceived(data, scene); } } if (updater.UpdateTimer == 0) { lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Remove(updater.UpdaterID); } } } } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer) { return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { return AddDynamicTextureURL(simID, primID, contentType, url, extraParams, updateTimer, SetBlending, (int)(DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES); } public UUID AddDynamicTextureURL(UUID simID, UUID primID, string contentType, string url, string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face) { if (RenderPlugins.ContainsKey(contentType)) { DynamicTextureUpdater updater = new DynamicTextureUpdater(); updater.SimUUID = simID; updater.PrimID = primID; updater.ContentType = contentType; updater.Url = url; updater.UpdateTimer = updateTimer; updater.UpdaterID = UUID.Random(); updater.Params = extraParams; updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; updater.Face = face; updater.Disp = disp; lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Add(updater.UpdaterID, updater); } } RenderPlugins[contentType].AsyncConvertUrl(updater.UpdaterID, url, extraParams); return updater.UpdaterID; } return UUID.Zero; } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer) { return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, false, 255); } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer, bool SetBlending, byte AlphaValue) { return AddDynamicTextureData(simID, primID, contentType, data, extraParams, updateTimer, SetBlending, (int) (DISP_TEMP|DISP_EXPIRE), AlphaValue, ALL_SIDES); } public UUID AddDynamicTextureData(UUID simID, UUID primID, string contentType, string data, string extraParams, int updateTimer, bool SetBlending, int disp, byte AlphaValue, int face) { if (RenderPlugins.ContainsKey(contentType)) { DynamicTextureUpdater updater = new DynamicTextureUpdater(); updater.SimUUID = simID; updater.PrimID = primID; updater.ContentType = contentType; updater.BodyData = data; updater.UpdateTimer = updateTimer; updater.UpdaterID = UUID.Random(); updater.Params = extraParams; updater.BlendWithOldTexture = SetBlending; updater.FrontAlpha = AlphaValue; updater.Face = face; updater.Url = "Local image"; updater.Disp = disp; lock (Updaters) { if (!Updaters.ContainsKey(updater.UpdaterID)) { Updaters.Add(updater.UpdaterID, updater); } } RenderPlugins[contentType].AsyncConvertData(updater.UpdaterID, data, extraParams); return updater.UpdaterID; } return UUID.Zero; } public void GetDrawStringSize(string contentType, string text, string fontName, int fontSize, out double xSize, out double ySize) { xSize = 0; ySize = 0; if (RenderPlugins.ContainsKey(contentType)) { RenderPlugins[contentType].GetDrawStringSize(text, fontName, fontSize, out xSize, out ySize); } } #endregion #region IRegionModule Members public void Initialise(Scene scene, IConfigSource config) { if (!RegisteredScenes.ContainsKey(scene.RegionInfo.RegionID)) { RegisteredScenes.Add(scene.RegionInfo.RegionID, scene); scene.RegisterModuleInterface<IDynamicTextureManager>(this); } } public void PostInitialise() { } public void Close() { } public string Name { get { return "DynamicTextureModule"; } } public bool IsSharedModule { get { return true; } } #endregion #region Nested type: DynamicTextureUpdater public class DynamicTextureUpdater { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public bool BlendWithOldTexture = false; public string BodyData; public string ContentType; public byte FrontAlpha = 255; public UUID LastAssetID; public string Params; public UUID PrimID; public bool SetNewFrontAlpha = false; public UUID SimUUID; public UUID UpdaterID; public int UpdateTimer; public int Face; public int Disp; public string Url; public DynamicTextureUpdater() { LastAssetID = UUID.Zero; UpdateTimer = 0; BodyData = null; } /// <summary> /// Called once new texture data has been received for this updater. /// </summary> public void DataReceived(byte[] data, Scene scene) { SceneObjectPart part = scene.GetSceneObjectPart(PrimID); if (part == null || data == null || data.Length <= 1) { string msg = String.Format("DynamicTextureModule: Error preparing image using URL {0}", Url); scene.SimChat(Utils.StringToBytes(msg), ChatTypeEnum.Say, 0, part.ParentGroup.RootPart.AbsolutePosition, part.Name, part.UUID, false); return; } byte[] assetData = null; AssetBase oldAsset = null; if (BlendWithOldTexture) { Primitive.TextureEntryFace defaultFace = part.Shape.Textures.DefaultTexture; if (defaultFace != null) { oldAsset = scene.AssetService.Get(defaultFace.TextureID.ToString()); if (oldAsset != null) assetData = BlendTextures(data, oldAsset.Data, SetNewFrontAlpha, FrontAlpha); } } if (assetData == null) { assetData = new byte[data.Length]; Array.Copy(data, assetData, data.Length); } // Create a new asset for user AssetBase asset = new AssetBase(UUID.Random(), "DynamicImage" + Util.RandomClass.Next(1, 10000), (sbyte)AssetType.Texture, scene.RegionInfo.RegionID.ToString()); asset.Data = assetData; asset.Description = String.Format("URL image : {0}", Url); asset.Local = false; asset.Temporary = ((Disp & DISP_TEMP) != 0); scene.AssetService.Store(asset); // scene.CommsManager.AssetCache.AddAsset(asset); IJ2KDecoder cacheLayerDecode = scene.RequestModuleInterface<IJ2KDecoder>(); if (cacheLayerDecode != null) { cacheLayerDecode.Decode(asset.FullID, asset.Data); cacheLayerDecode = null; LastAssetID = asset.FullID; } UUID oldID = UUID.Zero; lock (part) { // mostly keep the values from before Primitive.TextureEntry tmptex = part.Shape.Textures; // remove the old asset from the cache oldID = tmptex.DefaultTexture.TextureID; if (Face == ALL_SIDES) { tmptex.DefaultTexture.TextureID = asset.FullID; } else { try { Primitive.TextureEntryFace texface = tmptex.CreateFace((uint)Face); texface.TextureID = asset.FullID; tmptex.FaceTextures[Face] = texface; } catch (Exception) { tmptex.DefaultTexture.TextureID = asset.FullID; } } // I'm pretty sure we always want to force this to true // I'm pretty sure noone whats to set fullbright true if it wasn't true before. // tmptex.DefaultTexture.Fullbright = true; part.UpdateTexture(tmptex); } if (oldID != UUID.Zero && ((Disp & DISP_EXPIRE) != 0)) { if (oldAsset == null) oldAsset = scene.AssetService.Get(oldID.ToString()); if (oldAsset != null) { if (oldAsset.Temporary == true) { scene.AssetService.Delete(oldID.ToString()); } } } } private byte[] BlendTextures(byte[] frontImage, byte[] backImage, bool setNewAlpha, byte newAlpha) { ManagedImage managedImage; Image image; if (OpenJPEG.DecodeToImage(frontImage, out managedImage, out image)) { Bitmap image1 = new Bitmap(image); if (OpenJPEG.DecodeToImage(backImage, out managedImage, out image)) { Bitmap image2 = new Bitmap(image); if (setNewAlpha) SetAlpha(ref image1, newAlpha); Bitmap joint = MergeBitMaps(image1, image2); byte[] result = new byte[0]; try { result = OpenJPEG.EncodeFromImage(joint, true); } catch (Exception) { m_log.Error("[DYNAMICTEXTUREMODULE]: OpenJpeg Encode Failed. Empty byte data returned!"); } return result; } } return null; } public Bitmap MergeBitMaps(Bitmap front, Bitmap back) { Bitmap joint; Graphics jG; joint = new Bitmap(back.Width, back.Height, PixelFormat.Format32bppArgb); jG = Graphics.FromImage(joint); jG.DrawImage(back, 0, 0, back.Width, back.Height); jG.DrawImage(front, 0, 0, back.Width, back.Height); return joint; } private void SetAlpha(ref Bitmap b, byte alpha) { for (int w = 0; w < b.Width; w++) { for (int h = 0; h < b.Height; h++) { b.SetPixel(w, h, Color.FromArgb(alpha, b.GetPixel(w, h))); } } } } #endregion } }
using System.Collections.Concurrent; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Reactive; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Text; using Autofac; using Miningcore.Banning; using Miningcore.Configuration; using Miningcore.Extensions; using Miningcore.JsonRpc; using Miningcore.Messaging; using Miningcore.Notifications.Messages; using Miningcore.Time; using Miningcore.Util; using Newtonsoft.Json; using NLog; using Contract = Miningcore.Contracts.Contract; using static Miningcore.Util.ActionUtils; namespace Miningcore.Stratum; public abstract class StratumServer { protected StratumServer( IComponentContext ctx, IMessageBus messageBus, IMasterClock clock) { Contract.RequiresNonNull(ctx, nameof(ctx)); Contract.RequiresNonNull(messageBus, nameof(messageBus)); Contract.RequiresNonNull(clock, nameof(clock)); this.ctx = ctx; this.messageBus = messageBus; this.clock = clock; } static StratumServer() { if(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { ignoredSocketErrors = new HashSet<int> { (int) SocketError.ConnectionReset, (int) SocketError.ConnectionAborted, (int) SocketError.OperationAborted }; } else if(RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { // see: http://www.virtsync.com/c-error-codes-include-errno ignoredSocketErrors = new HashSet<int> { 104, // ECONNRESET 125, // ECANCELED 103, // ECONNABORTED 110, // ETIMEDOUT 32, // EPIPE }; } } protected readonly ConcurrentDictionary<string, StratumConnection> connections = new(); protected static readonly ConcurrentDictionary<string, X509Certificate2> certs = new(); protected static readonly HashSet<int> ignoredSocketErrors; protected static readonly MethodBase streamWriterCtor = typeof(StreamWriter).GetConstructor( new[] { typeof(Stream), typeof(Encoding), typeof(int), typeof(bool) }); protected readonly IComponentContext ctx; protected readonly IMessageBus messageBus; protected readonly IMasterClock clock; protected ClusterConfig clusterConfig; protected PoolConfig poolConfig; protected IBanManager banManager; protected ILogger logger; public Task RunAsync(CancellationToken ct, params StratumEndpoint[] endpoints) { Contract.RequiresNonNull(endpoints, nameof(endpoints)); logger.Info(() => $"Stratum ports {string.Join(", ", endpoints.Select(x => $"{x.IPEndPoint.Address}:{x.IPEndPoint.Port}").ToArray())} online"); var tasks = endpoints.Select(port => { var server = new Socket(SocketType.Stream, ProtocolType.Tcp); server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); server.Bind(port.IPEndPoint); server.Listen(); return Task.Run(()=> Listen(server, port, ct), ct); }).ToArray(); return Task.WhenAll(tasks); } private async Task Listen(Socket server, StratumEndpoint port, CancellationToken ct) { var cert = GetTlsCert(port); while(!ct.IsCancellationRequested) { try { var socket = await server.AcceptAsync(); AcceptConnection(socket, port, cert, ct); } catch(ObjectDisposedException) { // ignored break; } catch(Exception ex) { logger.Error(ex); } } } private void AcceptConnection(Socket socket, StratumEndpoint port, X509Certificate2 cert, CancellationToken ct) { Task.Run(() => Guard(() => { var remoteEndpoint = (IPEndPoint) socket.RemoteEndPoint; // dispose of banned clients as early as possible if (DisconnectIfBanned(socket, remoteEndpoint)) return; // init connection var connection = new StratumConnection(logger, clock, CorrelationIdGenerator.GetNextId()); logger.Info(() => $"[{connection.ConnectionId}] Accepting connection from {remoteEndpoint.Address}:{remoteEndpoint.Port} ..."); RegisterConnection(connection); OnConnect(connection, port.IPEndPoint); connection.DispatchAsync(socket, ct, port, remoteEndpoint, cert, OnRequestAsync, OnConnectionComplete, OnConnectionError); }, ex=> logger.Error(ex)), ct); } protected virtual void RegisterConnection(StratumConnection connection) { var result = connections.TryAdd(connection.ConnectionId, connection); Debug.Assert(result); PublishTelemetry(TelemetryCategory.Connections, TimeSpan.Zero, true, connections.Count); } protected virtual void UnregisterConnection(StratumConnection connection) { var result = connections.TryRemove(connection.ConnectionId, out _); Debug.Assert(result); PublishTelemetry(TelemetryCategory.Connections, TimeSpan.Zero, true, connections.Count); } protected abstract void OnConnect(StratumConnection connection, IPEndPoint portItem1); protected async Task OnRequestAsync(StratumConnection connection, JsonRpcRequest request, CancellationToken ct) { // boot pre-connected clients if(banManager?.IsBanned(connection.RemoteEndpoint.Address) == true) { logger.Info(() => $"[{connection.ConnectionId}] Disconnecting banned client @ {connection.RemoteEndpoint.Address}"); CloseConnection(connection); return; } logger.Debug(() => $"[{connection.ConnectionId}] Dispatching request '{request.Method}' [{request.Id}]"); await OnRequestAsync(connection, new Timestamped<JsonRpcRequest>(request, clock.Now), ct); } protected virtual void OnConnectionError(StratumConnection connection, Exception ex) { if(ex is AggregateException) ex = ex.InnerException; if(ex is IOException && ex.InnerException != null) ex = ex.InnerException; switch(ex) { case SocketException sockEx: if(!ignoredSocketErrors.Contains(sockEx.ErrorCode)) logger.Error(() => $"[{connection.ConnectionId}] Connection error state: {ex}"); break; case JsonException jsonEx: // junk received (invalid json) logger.Error(() => $"[{connection.ConnectionId}] Connection json error state: {jsonEx.Message}"); if(clusterConfig.Banning?.BanOnJunkReceive.HasValue == false || clusterConfig.Banning?.BanOnJunkReceive == true) { logger.Info(() => $"[{connection.ConnectionId}] Banning client for sending junk"); banManager?.Ban(connection.RemoteEndpoint.Address, TimeSpan.FromMinutes(3)); } break; case AuthenticationException authEx: // junk received (SSL handshake) logger.Error(() => $"[{connection.ConnectionId}] Connection json error state: {authEx.Message}"); if(clusterConfig.Banning?.BanOnJunkReceive.HasValue == false || clusterConfig.Banning?.BanOnJunkReceive == true) { logger.Info(() => $"[{connection.ConnectionId}] Banning client for failing SSL handshake"); banManager?.Ban(connection.RemoteEndpoint.Address, TimeSpan.FromMinutes(3)); } break; case IOException ioEx: // junk received (SSL handshake) logger.Error(() => $"[{connection.ConnectionId}] Connection json error state: {ioEx.Message}"); if(ioEx.Source == "System.Net.Security") { if(clusterConfig.Banning?.BanOnJunkReceive.HasValue == false || clusterConfig.Banning?.BanOnJunkReceive == true) { logger.Info(() => $"[{connection.ConnectionId}] Banning client for failing SSL handshake"); banManager?.Ban(connection.RemoteEndpoint.Address, TimeSpan.FromMinutes(3)); } } break; case ObjectDisposedException odEx: // socket disposed break; case ArgumentException argEx: if(argEx.TargetSite != streamWriterCtor || argEx.ParamName != "stream") logger.Error(() => $"[{connection.ConnectionId}] Connection error state: {ex}"); break; case InvalidOperationException invOpEx: // The source completed without providing data to receive break; default: logger.Error(() => $"[{connection.ConnectionId}] Connection error state: {ex}"); break; } UnregisterConnection(connection); } protected virtual void OnConnectionComplete(StratumConnection connection) { logger.Debug(() => $"[{connection.ConnectionId}] Received EOF"); UnregisterConnection(connection); } protected virtual void CloseConnection(StratumConnection connection) { Contract.RequiresNonNull(connection, nameof(connection)); connection.Disconnect(); UnregisterConnection(connection); } private X509Certificate2 GetTlsCert(StratumEndpoint port) { if(!port.PoolEndpoint.Tls) return null; if(!certs.TryGetValue(port.PoolEndpoint.TlsPfxFile, out var cert)) { cert = Guard(()=> new X509Certificate2(port.PoolEndpoint.TlsPfxFile, port.PoolEndpoint.TlsPfxPassword), ex => { logger.Info(() => $"Failed to load TLS certificate {port.PoolEndpoint.TlsPfxFile}: {ex.Message}"); throw ex; }); certs[port.PoolEndpoint.TlsPfxFile] = cert; } return cert; } private bool DisconnectIfBanned(Socket socket, IPEndPoint remoteEndpoint) { if(remoteEndpoint == null || banManager == null) return false; if (banManager.IsBanned(remoteEndpoint.Address)) { logger.Debug(() => $"Disconnecting banned ip {remoteEndpoint.Address}"); socket.Close(); return true; } return false; } protected IEnumerable<Task> ForEachConnection(Func<StratumConnection, Task> func) { var tmp = connections.Values.ToArray(); return tmp.Select(func); } protected void PublishTelemetry(TelemetryCategory cat, TimeSpan elapsed, bool? success = null, int? total = null) { messageBus.SendTelemetry(poolConfig.Id, cat, elapsed, success, null, total); } protected abstract Task OnRequestAsync(StratumConnection connection, Timestamped<JsonRpcRequest> request, CancellationToken ct); }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Drawing; using System.Linq; using System.Text; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.IoC; using Sitecore.Common; using Sitecore.Configuration; using Sitecore.Collections; using Sitecore.Data; using Sitecore.Data.Fields; using Sitecore.Data.Items; using Sitecore.Globalization; using Sitecore.Links; using Sitecore.Resources.Media; using Sitecore.Xml.Xsl; namespace Glass.Mapper.Sc { /// <summary> /// Class Utilities /// </summary> public class Utilities : Mapper.Utilities { public static bool IsPageEditor { get { #if SC82 return Sitecore.Context.PageMode.IsExperienceEditor; #else return Sitecore.Context.PageMode.IsPageEditor; #endif } } public static bool IsPageEditorEditing { get { #if SC82 return Sitecore.Context.PageMode.IsExperienceEditorEditing; #else return Sitecore.Context.PageMode.IsPageEditorEditing; #endif } } /// <summary> /// Converts a NameValueCollection into HTML attributes /// </summary> /// <param name="attributes">A list of attributes to convert</param> /// <returns>System.String.</returns> public static string ConvertAttributes(NameValueCollection attributes) { if (attributes == null || attributes.Count == 0) return ""; StringBuilder sb = new StringBuilder(); foreach (var key in attributes.AllKeys) { sb.AppendFormat("{0}='{1}' ".Formatted(key, attributes[key] ?? "")); } return sb.ToString(); } /// <summary> /// Converts a SafeDictionary into HTML attributes /// </summary> /// <param name="attributes">A list of attributes to convert</param> /// <returns>System.String.</returns> public static string ConvertAttributes(SafeDictionary<string> attributes, string quotationMark) { if (attributes == null || attributes.Count == 0) return ""; StringBuilder sb = new StringBuilder(); foreach (var pair in attributes) { sb.AppendFormat("{0}={2}{1}{2} ".Formatted(pair.Key, pair.Value ??"", quotationMark)); } return sb.ToString(); } /// <summary> /// Gets the field. /// </summary> /// <param name="item">The item.</param> /// <param name="fieldId">The field id.</param> /// <param name="fieldName">Name of the field.</param> /// <returns>Field.</returns> public static Field GetField(Item item, ID fieldId, string fieldName = "") { if (item == null) throw new NullReferenceException("Item is null"); Field field; if (ID.IsNullOrEmpty(fieldId)) { field = item.Fields[fieldName]; } else { field = item.Fields[fieldId]; } return field; } public static Item CreateFakeItem(Dictionary<Guid, string> fields, string name = "itemName") { return CreateFakeItem(fields, new ID(Guid.NewGuid()), Factory.GetDatabase("master"), name); } public static Item CreateFakeItem(Dictionary<Guid, string> fields, ID templateId, Database database, string name = "ItemName") { var id = new ID(Guid.NewGuid()); var language = Language.Current; var version = Sitecore.Data.Version.Latest; var itemDefinition = new ItemDefinition(id, name, templateId, ID.Null); var fieldList = new FieldList(); if (fields != null) { foreach (var fieldId in fields.Keys) { fieldList.Add(new ID(fieldId), fields[fieldId]); } } var itemData = new ItemData(itemDefinition, language, version, fieldList); var item = new Item(id, itemData, database); return item; } public static Size ResizeImage(int imageW, int imageH, float imageScale, int w, int h, int maxW, int maxH) { Size size = new Size(w, h); Size imageSize = new Size(imageW, imageH); Size maxSize = new Size(maxW, maxH); if (imageW == 0 || imageH == 0) return size; return new GlassImageRender().GetFinalImageSize(imageSize, imageScale, size, maxSize); } /// <summary> /// Constructs the query string. /// </summary> /// <param name="parameters">The parameters.</param> /// <returns>System.String.</returns> public static string ConstructQueryString(NameValueCollection parameters) { var sb = new StringBuilder(); foreach (String name in parameters) sb.Append(String.Concat(name, "=", System.Web.HttpUtility.UrlEncode(parameters[name]), "&")); if (sb.Length > 0) return sb.ToString(0, sb.Length - 1); return String.Empty; } /// <summary> /// Gets the generic outer. /// </summary> /// <param name="type">The type.</param> /// <returns>Type.</returns> public static Type GetGenericOuter(Type type) { return type.GetGenericTypeDefinition(); } /// <summary> /// Gets the language item. /// </summary> /// <param name="foundItem">The found item.</param> /// <param name="language">The language.</param> /// <returns>Item.</returns> public static Item GetLanguageItem(Item foundItem, Language language, IItemVersionHandler versionHandler) { if (foundItem == null) return null; var item = foundItem.Database.GetItem(foundItem.ID, language); if (item == null || !versionHandler.VersionCountEnabledAndHasVersions(item)) { return null; } return item; } /// <summary> /// Gets the language items. /// </summary> /// <param name="foundItems">The found items.</param> /// <param name="language">The language.</param> /// <param name="config"></param> /// <returns>IEnumerable{Item}.</returns> public static IEnumerable<Item> GetLanguageItems(IEnumerable<Item> foundItems, Language language, IItemVersionHandler versionHandler) { if (foundItems == null) return Enumerable.Empty<Item>(); return foundItems.Select(x => GetLanguageItem(x, language, versionHandler)).Where(x => x != null); } public class GlassImageRender : ImageRenderer { public Size GetFinalImageSize(Size imageSize, float imageScale, Size size, Size maxSize ) { return base.GetFinalImageSize(base.GetInitialImageSize(imageSize, imageScale, size), size, maxSize); } } } }
using System; using System.Diagnostics; using i64 = System.Int64; namespace System.Data.SQLite { internal partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains the sqlite3_get_table() and //sqlite3_free_table() ** interface routines. These are just wrappers around the main ** interface routine of sqlite3_exec(). ** ** These routines are in a separate files so that they will not be linked ** if they are not used. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3 ** ************************************************************************* */ //#include "sqliteInt.h" //#include <stdlib.h> //#include <string.h> #if !SQLITE_OMIT_GET_TABLE /* ** This structure is used to pass data from sqlite3_get_table() through ** to the callback function is uses to build the result. */ class TabResult { public string[] azResult; public string zErrMsg; public int nResult; public int nAlloc; public int nRow; public int nColumn; public int nData; public int rc; }; /* ** This routine is called once for each row in the result table. Its job ** is to fill in the TabResult structure appropriately, allocating new ** memory as necessary. */ static public int sqlite3_get_table_cb( object pArg, i64 nCol, object Oargv, object Ocolv ) { string[] argv = (string[])Oargv; string[]colv = (string[])Ocolv; TabResult p = (TabResult)pArg; int need; int i; string z; /* Make sure there is enough space in p.azResult to hold everything ** we need to remember from this invocation of the callback. */ if( p.nRow==0 && argv!=null ){ need = (int)nCol*2; }else{ need = (int)nCol; } if( p.nData + need >= p.nAlloc ){ string[] azNew; p.nAlloc = p.nAlloc*2 + need + 1; azNew = new string[p.nAlloc];//sqlite3_realloc( p.azResult, sizeof(char*)*p.nAlloc ); if( azNew==null ) goto malloc_failed; p.azResult = azNew; } /* If this is the first row, then generate an extra row containing ** the names of all columns. */ if( p.nRow==0 ){ p.nColumn = (int)nCol; for(i=0; i<nCol; i++){ z = sqlite3_mprintf("%s", colv[i]); if( z==null ) goto malloc_failed; p.azResult[p.nData++ -1] = z; } }else if( p.nColumn!=nCol ){ //sqlite3_free(ref p.zErrMsg); p.zErrMsg = sqlite3_mprintf( "sqlite3_get_table() called with two or more incompatible queries" ); p.rc = SQLITE_ERROR; return 1; } /* Copy over the row data */ if( argv!=null ){ for(i=0; i<nCol; i++){ if( argv[i]==null ){ z = null; }else{ int n = sqlite3Strlen30(argv[i])+1; //z = sqlite3_malloc( n ); //if( z==0 ) goto malloc_failed; z= argv[i];//memcpy(z, argv[i], n); } p.azResult[p.nData++ -1] = z; } p.nRow++; } return 0; malloc_failed: p.rc = SQLITE_NOMEM; return 1; } /* ** Query the database. But instead of invoking a callback for each row, ** malloc() for space to hold the result and return the entire results ** at the conclusion of the call. ** ** The result that is written to ***pazResult is held in memory obtained ** from malloc(). But the caller cannot free this memory directly. ** Instead, the entire table should be passed to //sqlite3_free_table() when ** the calling procedure is finished using it. */ static public int sqlite3_get_table( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ ref string[] pazResult, /* Write the result table here */ ref int pnRow, /* Write the number of rows in the result here */ ref int pnColumn, /* Write the number of columns of result here */ ref string pzErrMsg /* Write error messages here */ ){ int rc; TabResult res = new TabResult(); pazResult = null; pnColumn = 0; pnRow = 0; pzErrMsg = ""; res.zErrMsg = ""; res.nResult = 0; res.nRow = 0; res.nColumn = 0; res.nData = 1; res.nAlloc = 20; res.rc = SQLITE_OK; res.azResult = new string[res.nAlloc];// sqlite3_malloc( sizeof( char* ) * res.nAlloc ); if( res.azResult==null ){ db.errCode = SQLITE_NOMEM; return SQLITE_NOMEM; } res.azResult[0] = null; rc = sqlite3_exec(db, zSql, (dxCallback) sqlite3_get_table_cb, res, ref pzErrMsg); //Debug.Assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); //res.azResult = SQLITE_INT_TO_PTR( res.nData ); if( (rc&0xff)==SQLITE_ABORT ){ //sqlite3_free_table(ref res.azResult[1] ); if( res.zErrMsg !=""){ if( pzErrMsg !=null ){ //sqlite3_free(ref pzErrMsg); pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); } //sqlite3_free(ref res.zErrMsg); } db.errCode = res.rc; /* Assume 32-bit assignment is atomic */ return res.rc; } //sqlite3_free(ref res.zErrMsg); if( rc!=SQLITE_OK ){ //sqlite3_free_table(ref res.azResult[1]); return rc; } if( res.nAlloc>res.nData ){ string[] azNew; Array.Resize(ref res.azResult, res.nData-1);//sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) ); //if( azNew==null ){ // //sqlite3_free_table(ref res.azResult[1]); // db.errCode = SQLITE_NOMEM; // return SQLITE_NOMEM; //} res.nAlloc = res.nData+1; //res.azResult = azNew; } pazResult = res.azResult; pnColumn = res.nColumn; pnRow = res.nRow; return rc; } /* ** This routine frees the space the sqlite3_get_table() malloced. */ static void //sqlite3_free_table( ref string azResult /* Result returned from from sqlite3_get_table() */ ){ if( azResult !=null){ int i, n; //azResult--; //Debug.Assert( azResult!=0 ); //n = SQLITE_PTR_TO_INT(azResult[0]); //for(i=1; i<n; i++){ if( azResult[i] ) //sqlite3_free(azResult[i]); } //sqlite3_free(ref azResult); } } #endif //* SQLITE_OMIT_GET_TABLE */ } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Factotum { public partial class CalBlockView : Form { // ---------------------------------------------------------------------- // Initialization // ---------------------------------------------------------------------- // Form constructor public CalBlockView() { InitializeComponent(); // Take care of settings that are not easily managed in the designer. InitializeControls(); } // Take care of settings that are not easily managed in the designer. private void InitializeControls() { } // Set the status filter to show active tools by default // and update the tool selector combo box private void CalBlockView_Load(object sender, EventArgs e) { // Set the status combo first. The selector DataGridView depends on it. cboStatusFilter.SelectedIndex = (int)FilterActiveStatus.ShowActive; // Apply the current filters and set the selector row. // Passing a null selects the first row if there are any rows. UpdateSelector(null); // Now that we have some rows and columns, we can do some customization. CustomizeGrid(); // Need to do this because the customization clears the row selection. SelectGridRow(null); // Wire up the handler for the Entity changed event ECalBlock.Changed += new EventHandler<EntityChangedEventArgs>(ECalBlock_Changed); } private void CalBlockView_FormClosed(object sender, FormClosedEventArgs e) { ECalBlock.Changed -= new EventHandler<EntityChangedEventArgs>(ECalBlock_Changed); } // ---------------------------------------------------------------------- // Event Handlers // ---------------------------------------------------------------------- // If any of this type of entity object was saved or deleted, we want to update the selector // The event args contain the ID of the entity that was added, mofified or deleted. void ECalBlock_Changed(object sender, EntityChangedEventArgs e) { UpdateSelector(e.ID); } // Handle the user's decision to edit the current tool private void EditCurrentSelection() { // Make sure there's a row selected if (dgvCalBlocks.SelectedRows.Count != 1) return; Guid? currentEditItem = (Guid?)(dgvCalBlocks.SelectedRows[0].Cells["ID"].Value); // First check to see if an instance of the form set to the selected ID already exists if (!Globals.CanActivateForm(this, "CalBlockEdit",currentEditItem)) { // Open the edit form with the currently selected ID. CalBlockEdit frm = new CalBlockEdit(currentEditItem); frm.MdiParent = this.MdiParent; frm.Show(); } } // This handles the datagridview double-click as well as button click void btnEdit_Click(object sender, System.EventArgs e) { EditCurrentSelection(); } private void dgvCalBlocks_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) EditCurrentSelection(); } // Handle the user's decision to add a new tool private void btnAdd_Click(object sender, EventArgs e) { CalBlockEdit frm = new CalBlockEdit(); frm.MdiParent = this.MdiParent; frm.Show(); } // Handle the user's decision to delete the selected tool private void btnDelete_Click(object sender, EventArgs e) { if (dgvCalBlocks.SelectedRows.Count != 1) { MessageBox.Show("Please select a Calibration Block to delete first.", "Factotum"); return; } Guid? currentEditItem = (Guid?)(dgvCalBlocks.SelectedRows[0].Cells["ID"].Value); if (Globals.IsFormOpen(this,"CalBlockEdit",currentEditItem)) { MessageBox.Show("Can't delete because that item is currently being edited.", "Factotum"); return; } ECalBlock CalBlock = new ECalBlock(currentEditItem); CalBlock.Delete(true); if (CalBlock.CalBlockErrMsg != null) { MessageBox.Show(CalBlock.CalBlockErrMsg, "Factotum"); CalBlock.CalBlockErrMsg = null; } } // The user changed the status filter setting, so update the selector combo. private void cboStatus_SelectedIndexChanged(object sender, EventArgs e) { ApplyFilters(); } private void btnClose_Click(object sender, EventArgs e) { Close(); } // ---------------------------------------------------------------------- // Private utilities // ---------------------------------------------------------------------- // Update the tool selector combo box by filling its items based on current data and filters. // Then set the currently displayed item to that of the supplied ID. // If the supplied ID isn't on the list because of the current filter state, just show the // first item if there is one. private void UpdateSelector(Guid? id) { // Save the sort specs if there are any, so we can re-apply them SortOrder sortOrder = dgvCalBlocks.SortOrder; int sortCol = -1; if (sortOrder != SortOrder.None) sortCol = dgvCalBlocks.SortedColumn.Index; // Update the grid view selector DataView dv = ECalBlock.GetDefaultDataView(); dgvCalBlocks.DataSource = dv; ApplyFilters(); // Re-apply the sort specs if (sortOrder == SortOrder.Ascending) dgvCalBlocks.Sort(dgvCalBlocks.Columns[sortCol], ListSortDirection.Ascending); else if (sortOrder == SortOrder.Descending) dgvCalBlocks.Sort(dgvCalBlocks.Columns[sortCol], ListSortDirection.Descending); // Select the current row SelectGridRow(id); } private void CustomizeGrid() { // Apply a default sort dgvCalBlocks.Sort(dgvCalBlocks.Columns["CalBlockSerialNumber"], ListSortDirection.Ascending); // Fix up the column headings dgvCalBlocks.Columns["CalBlockSerialNumber"].HeaderText = "Serial Number"; dgvCalBlocks.Columns["CalBlockKitName"].HeaderText = "Kit"; dgvCalBlocks.Columns["CalBlockIsActive"].HeaderText = "Active"; dgvCalBlocks.Columns["CalBlockCalMin"].HeaderText = "Min Cal"; dgvCalBlocks.Columns["CalBlockCalMax"].HeaderText = "Max Cal"; dgvCalBlocks.Columns["CalBlockMaterialType"].HeaderText = "Material"; dgvCalBlocks.Columns["CalBlockType"].HeaderText = "Type"; // Hide some columns dgvCalBlocks.Columns["ID"].Visible = false; dgvCalBlocks.Columns["CalBlockIsActive"].Visible = false; dgvCalBlocks.Columns["CalBlockIsLclChg"].Visible = false; dgvCalBlocks.Columns["CalBlockUsedInOutage"].Visible = false; dgvCalBlocks.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); } // Apply the current filters to the DataView. The DataGridView will auto-refresh. private void ApplyFilters() { if (dgvCalBlocks.DataSource == null) return; StringBuilder sb = new StringBuilder("CalBlockIsActive = ", 255); sb.Append(cboStatusFilter.SelectedIndex == (int)FilterActiveStatus.ShowActive ? "'Yes'" : "'No'"); DataView dv = (DataView)dgvCalBlocks.DataSource; dv.RowFilter = sb.ToString(); } // Select the row with the specified ID if it is currently displayed and scroll to it. // If the ID is not in the list, private void SelectGridRow(Guid? id) { bool found = false; int rows = dgvCalBlocks.Rows.Count; if (rows == 0) return; int r = 0; DataGridViewCell firstCell = dgvCalBlocks.FirstDisplayedCell; if (id != null) { // Find the row with the specified key id and select it. for (r = 0; r < rows; r++) { if ((Guid?)dgvCalBlocks.Rows[r].Cells["ID"].Value == id) { dgvCalBlocks.CurrentCell = dgvCalBlocks[firstCell.ColumnIndex, r]; dgvCalBlocks.Rows[r].Selected = true; found = true; break; } } } if (found) { if (!dgvCalBlocks.Rows[r].Displayed) { // Scroll to the selected row if the ID was in the list. dgvCalBlocks.FirstDisplayedScrollingRowIndex = r; } } else { // Select the first item dgvCalBlocks.CurrentCell = firstCell; dgvCalBlocks.Rows[0].Selected = true; } } } }
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 Vegvesen.Web.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; } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Globalization; using System.IO; using System.Net; using System.ServiceModel; using System.Web; using System.Web.Hosting; using System.Web.Routing; using Adxstudio.Xrm.AspNet; using Adxstudio.Xrm.AspNet.Cms; using Adxstudio.Xrm.AspNet.Identity; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Core.Telemetry; using Adxstudio.Xrm.Search; using Adxstudio.Xrm.Globalization; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Portal.Web; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Metadata; namespace Adxstudio.Xrm.Web { public static class Extensions { /// <summary> /// Responds with a 403 status code. /// </summary> /// <param name="response"></param> public static void ForbiddenAndEndResponse(this HttpResponse response) { response.Clear(); response.StatusCode = (int)HttpStatusCode.Forbidden; response.End(); } /// <summary> /// Calls the Redirect and CompleteRequest operations. /// </summary> /// <param name="application"></param> /// <param name="url"></param> public static void RedirectAndEndResponse(this HttpApplication application, string url) { RedirectAndEndResponse(application, application.Response, url); } /// <summary> /// Calls the Redirect and CompleteRequest operations. /// </summary> /// <param name="context"></param> /// <param name="url"></param> public static void RedirectAndEndResponse(this HttpContext context, string url) { RedirectAndEndResponse(context.ApplicationInstance, context.Response, url); } /// <summary> /// Calls the Redirect and CompleteRequest operations. /// </summary> /// <param name="context"></param> /// <param name="url"></param> public static void RedirectAndEndResponse(this HttpContextBase context, string url) { RedirectAndEndResponse(context.ApplicationInstance, url); } /// <summary> /// Adds the 'Access-Control-Allow-Origin' header to the response or updates an existing header on the response. /// </summary> /// <param name="context">Current request context</param> /// <param name="allowOrigin">The origin value to be assigned to the 'Access-Control-Allow-Origin' header.</param> public static void SetAccessControlAllowOriginHeader(HttpContextBase context, string allowOrigin) { if (context == null || string.IsNullOrWhiteSpace(allowOrigin)) { return; } if (string.IsNullOrWhiteSpace(context.Response.Headers.Get("Access-Control-Allow-Origin"))) { context.Response.AppendHeader("Access-Control-Allow-Origin", allowOrigin); } else { context.Response.Headers["Access-Control-Allow-Origin"] = allowOrigin; } } /// <summary> /// Calls the Redirect and CompleteRequest operations. Validates the URL prior to redirect to ensure it is local to prevent an Open Redirection Attack. /// </summary> /// <param name="application"></param> /// <param name="response"></param> /// <param name="url"></param> private static void RedirectAndEndResponse(HttpApplication application, HttpResponse response, string url) { // Prevent an Open Redirection Attack. Any web application that redirects to a URL that is specified via the request such as the querystring or form data can potentially be tampered with to redirect users to an external, malicious URL. if (System.Web.WebPages.RequestExtensions.IsUrlLocalToHost(new HttpRequestWrapper(application.Request), url)) { response.Redirect(url, false); } else { response.Redirect("~/"); } application.CompleteRequest(); } /// <summary> /// Attempts to restart the application, first by touching web.config, or if that fails, calling UnloadAppDomain. /// </summary> public static void RestartWebApplication() { if (!TryTouchWebConfig()) { TelemetryState.ApplicationEndInfo |= ApplicationEndFlags.UnloadAppDomain; WebEventSource.Log.WriteApplicationLifecycleEvent(ApplicationLifecycleEventCategory.Restart, "Touching WebConfig Failed, Unloading AppDomain"); HttpRuntime.UnloadAppDomain(); } } /// <summary> /// Resets the last updated date for web.config, effectively forcing an app restart. /// </summary> private static bool TryTouchWebConfig() { try { TelemetryState.ApplicationEndInfo |= ApplicationEndFlags.TouchWebConfig; WebEventSource.Log.WriteApplicationLifecycleEvent(ApplicationLifecycleEventCategory.Restart, "Touching WebConfig"); var configPath = GetWebConfigPath(); File.SetLastWriteTimeUtc(configPath, DateTime.UtcNow); return true; } catch { TelemetryState.ApplicationEndInfo &= ~ApplicationEndFlags.TouchWebConfig; return false; } } internal static string LocalizeRecordTypeName(string logicalName) { if (string.IsNullOrEmpty(logicalName)) { return string.Empty; } EntityMetadata entityMetadata = null; var portalContext = PortalCrmConfigurationManager.CreatePortalContext(); try { entityMetadata = portalContext.ServiceContext.GetEntityMetadata(logicalName); } catch (FaultException<OrganizationServiceFault> fe) { // an exception occurs when trying to retrieve a non-existing entity if (!fe.Message.EndsWith("Could not find entity")) { throw new ApplicationException(string.Format("Error getting EntityMetadata for {0}", logicalName), fe); } } return entityMetadata == null ? logicalName : entityMetadata.DisplayCollectionName.GetLocalizedLabel().Label; } private static string GetWebConfigPath() { return HostingEnvironment.MapPath("~/web.config"); } #region IOwinContext public static IOwinContext Set<T>(this RequestContext request, T value) { return Set(request.HttpContext, value); } public static IOwinContext Set<T>(this HttpContextBase context, T value) { return Set(context.GetOwinContext(), value); } public static IOwinContext Set<T>(this IOwinContext context, T value) { return context.Set(typeof(T).FullName, value); } public static IOrganizationService GetOrganizationService(this HttpContext context) { return GetOrganizationService(context.GetOwinContext()); } public static IOrganizationService GetOrganizationService(this HttpContextBase context) { return GetOrganizationService(context.GetOwinContext()); } public static IOrganizationService GetOrganizationService(this IOwinContext context) { var dbContext = context.Get<CrmDbContext>(); return dbContext.Service; } public static CrmWebsite GetWebsite(this HttpContext context) { return GetWebsite(context.GetOwinContext()); } public static CrmWebsite GetWebsite(this HttpContextBase context) { return GetWebsite(context.GetOwinContext()); } public static CrmWebsite GetWebsite(this IOwinContext context) { return context.Get<CrmWebsite>(); } public static CrmUser GetUser(this HttpContext context) { return GetUser(context.GetOwinContext()); } public static CrmUser GetUser(this HttpContextBase context) { return GetUser(context.GetOwinContext()); } public static CrmUser GetUser(this IOwinContext context) { return context.Get<CrmUser>(); } public static CrmSiteMapNode GetNode(this HttpContext context) { return GetNode(context.GetOwinContext()); } public static CrmSiteMapNode GetNode(this HttpContextBase context) { return GetNode(context.GetOwinContext()); } public static CrmSiteMapNode GetNode(this IOwinContext context) { return context.Get<CrmSiteMapNode>(typeof(CrmSiteMapNode).FullName); } public static Entity GetEntity(this HttpContext context) { var node = GetNode(context); return node != null ? node.Entity : null; } public static Entity GetEntity(this HttpContextBase context) { var node = GetNode(context); return node != null ? node.Entity : null; } public static Entity GetEntity(this IOwinContext context) { var node = GetNode(context); return node != null ? node.Entity : null; } public static IContentMapProvider GetContentMapProvider(this HttpContext context) { return GetContentMapProvider(context.GetOwinContext()); } public static IContentMapProvider GetContentMapProvider(this HttpContextBase context) { return GetContentMapProvider(context.GetOwinContext()); } public static IContentMapProvider GetContentMapProvider(this IOwinContext context) { return context.Get<ContentMapProvider>(); } public static T GetSiteSetting<T>(this HttpContext context, string name) { return GetSiteSetting<T>(context.GetOwinContext(), name); } public static T GetSiteSetting<T>(this HttpContextBase context, string name) { return GetSiteSetting<T>(context.GetOwinContext(), name); } public static T GetSiteSetting<T>(this IOwinContext context, string name) { var website = GetWebsite(context); return website.Settings.Get<T>(name); } public static string GetSiteSetting(this HttpContext context, string name) { return GetSiteSetting(context.GetOwinContext(), name); } public static string GetSiteSetting(this HttpContextBase context, string name) { return GetSiteSetting(context.GetOwinContext(), name); } public static string GetSiteSetting(this IOwinContext context, string name) { var website = GetWebsite(context); return website.Settings.Get<string>(name); } public static ContextLanguageInfo GetContextLanguageInfo(this HttpContext context) { return GetContextLanguageInfo(context.GetOwinContext()); } public static ContextLanguageInfo GetContextLanguageInfo(this HttpContextBase context) { return GetContextLanguageInfo(context.GetOwinContext()); } public static ContextLanguageInfo GetContextLanguageInfo(this IOwinContext context) { return context.Get<ContextLanguageInfo>(); } /// <summary> /// Gets the LCID of current CRM language. Ex: if current language is en-CA (4105), then 1033 (en-US) will be returned because that is the associated CRM language. /// </summary> /// <param name="context">Current Http context.</param> /// <returns>LCID of current CRM language.</returns> public static int GetCrmLcid(this HttpContext context) { return GetCrmLcid(context?.GetOwinContext()); } /// <summary> /// Gets the LCID of current CRM language. Ex: if current language is en-CA (4105), then 1033 (en-US) will be returned because that is the associated CRM language. /// </summary> /// <param name="context">Current Http context.</param> /// <returns>LCID of current CRM language.</returns> public static int GetCrmLcid(this HttpContextBase context) { return GetCrmLcid(context?.GetOwinContext()); } /// <summary> /// Gets the LCID of current CRM language. Ex: if current language is en-CA (4105), then 1033 (en-US) will be returned because that is the associated CRM language. /// </summary> /// <param name="context">Current Owin context.</param> /// <returns>LCID of current CRM language.</returns> public static int GetCrmLcid(this IOwinContext context) { return GetCrmLcid(context?.GetContextLanguageInfo()); } /// <summary> /// Gets the LCID of current CRM language. Ex: if current language is en-CA (4105), then 1033 (en-US) will be returned because that is the associated CRM language. /// </summary> /// <param name="languageInfo">ContextLanguageInfo to extract language info from.</param> /// <returns>LCID of current CRM language.</returns> public static int GetCrmLcid(this ContextLanguageInfo languageInfo) { return languageInfo?.ContextLanguage?.CrmLcid ?? CultureInfo.CurrentCulture.LCID; } public static PortalSolutions GetPortalSolutionsDetails(this HttpContext context) { return GetPortalSolutionsDetails(context.GetOwinContext()); } public static PortalSolutions GetPortalSolutionsDetails(this HttpContextBase context) { return GetPortalSolutionsDetails(context.GetOwinContext()); } public static PortalSolutions GetPortalSolutionsDetails(this IOwinContext context) { return context.Get<PortalSolutions>(); } public static string ToFilterLikeString(this string metadataFilter) { return !metadataFilter.Contains("*") ? metadataFilter : metadataFilter.Replace('*', '%'); } #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; using System.Collections.Generic; #if ES_BUILD_STANDALONE namespace Microsoft.Diagnostics.Tracing.Internal #else namespace System.Diagnostics.Tracing.Internal #endif { #if ES_BUILD_AGAINST_DOTNET_V35 using Microsoft.Internal; #endif using Microsoft.Reflection; using System.Reflection; internal static class Environment { public static readonly string NewLine = System.Environment.NewLine; public static int TickCount { get { return System.Environment.TickCount; } } public static string GetResourceString(string key, params object[] args) { string fmt = rm.GetString(key); if (fmt != null) return string.Format(fmt, args); string sargs = String.Empty; foreach(var arg in args) { if (sargs != String.Empty) sargs += ", "; sargs += arg.ToString(); } return key + " (" + sargs + ")"; } public static string GetRuntimeResourceString(string key, params object[] args) { return GetResourceString(key, args); } private static System.Resources.ResourceManager rm = new System.Resources.ResourceManager("Microsoft.Diagnostics.Tracing.Messages", typeof(Environment).Assembly()); } } #if ES_BUILD_AGAINST_DOTNET_V35 namespace Microsoft.Diagnostics.Contracts.Internal { internal class Contract { public static void Assert(bool invariant) { Assert(invariant, string.Empty); } public static void Assert(bool invariant, string message) { if (!invariant) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); throw new Exception("Assertion failed: " + message); } } public static void EndContractBlock() { } } } namespace Microsoft.Internal { using System.Text; internal static class Tuple { public static Tuple<T1> Create<T1>(T1 item1) { return new Tuple<T1>(item1); } public static Tuple<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Tuple<T1, T2>(item1, item2); } } [Serializable] internal class Tuple<T1> { private readonly T1 m_Item1; public T1 Item1 { get { return m_Item1; } } public Tuple(T1 item1) { m_Item1 = item1; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(")"); return sb.ToString(); } int Size { get { return 1; } } } [Serializable] public class Tuple<T1, T2> { private readonly T1 m_Item1; private readonly T2 m_Item2; public T1 Item1 { get { return m_Item1; } } public T2 Item2 { get { return m_Item2; } } public Tuple(T1 item1, T2 item2) { m_Item1 = item1; m_Item2 = item2; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("("); sb.Append(m_Item1); sb.Append(", "); sb.Append(m_Item2); sb.Append(")"); return sb.ToString(); } int Size { get { return 2; } } } } #endif namespace Microsoft.Reflection { using System.Reflection; #if (ES_BUILD_PCL || PROJECTN) [Flags] public enum BindingFlags { DeclaredOnly = 0x02, // Only look at the members declared on the Type Instance = 0x04, // Include Instance members in search Static = 0x08, // Include Static members in search Public = 0x10, // Include Public members in search NonPublic = 0x20, // Include Non-Public members in search } public enum TypeCode { Empty = 0, // Null reference Object = 1, // Instance that isn't a value DBNull = 2, // Database null value Boolean = 3, // Boolean Char = 4, // Unicode character SByte = 5, // Signed 8-bit integer Byte = 6, // Unsigned 8-bit integer Int16 = 7, // Signed 16-bit integer UInt16 = 8, // Unsigned 16-bit integer Int32 = 9, // Signed 32-bit integer UInt32 = 10, // Unsigned 32-bit integer Int64 = 11, // Signed 64-bit integer UInt64 = 12, // Unsigned 64-bit integer Single = 13, // IEEE 32-bit float Double = 14, // IEEE 64-bit double Decimal = 15, // Decimal DateTime = 16, // DateTime String = 18, // Unicode character string } #endif static class ReflectionExtensions { #if (!ES_BUILD_PCL && !PROJECTN) // // Type extension methods // public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsAbstract(this Type type) { return type.IsAbstract; } public static bool IsSealed(this Type type) { return type.IsSealed; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static Type BaseType(this Type type) { return type.BaseType; } public static Assembly Assembly(this Type type) { return type.Assembly; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static bool ReflectionOnly(this Assembly assm) { return assm.ReflectionOnly; } #else // ES_BUILD_PCL // // Type extension methods // public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool IsGenericType(this Type type) { return type.IsConstructedGenericType; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static Assembly Assembly(this Type type) { return type.GetTypeInfo().Assembly; } public static IEnumerable<PropertyInfo> GetProperties(this Type type) { return type.GetTypeInfo().DeclaredProperties; } public static MethodInfo GetGetMethod(this PropertyInfo propInfo) { return propInfo.GetMethod; } public static Type[] GetGenericArguments(this Type type) { return type.GenericTypeArguments; } public static MethodInfo[] GetMethods(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly|BindingFlags.Instance|BindingFlags.Static|BindingFlags.Public|BindingFlags.NonPublic)) == 0); Func<MethodInfo, bool> visFilter; Func<MethodInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = mi => false; break; case BindingFlags.Public: visFilter = mi => mi.IsPublic; break; case BindingFlags.NonPublic: visFilter = mi => !mi.IsPublic; break; default: visFilter = mi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = mi => false; break; case BindingFlags.Instance: instFilter = mi => !mi.IsStatic; break; case BindingFlags.Static: instFilter = mi => mi.IsStatic; break; default: instFilter = mi => true; break; } List<MethodInfo> methodInfos = new List<MethodInfo>(); foreach (var declaredMethod in type.GetTypeInfo().DeclaredMethods) { if (visFilter(declaredMethod) && instFilter(declaredMethod)) methodInfos.Add(declaredMethod); } return methodInfos.ToArray(); } public static FieldInfo[] GetFields(this Type type, BindingFlags flags) { // Minimal implementation to cover only the cases we need System.Diagnostics.Debug.Assert((flags & BindingFlags.DeclaredOnly) != 0); System.Diagnostics.Debug.Assert((flags & ~(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) == 0); Func<FieldInfo, bool> visFilter; Func<FieldInfo, bool> instFilter; switch (flags & (BindingFlags.Public | BindingFlags.NonPublic)) { case 0: visFilter = fi => false; break; case BindingFlags.Public: visFilter = fi => fi.IsPublic; break; case BindingFlags.NonPublic: visFilter = fi => !fi.IsPublic; break; default: visFilter = fi => true; break; } switch (flags & (BindingFlags.Instance | BindingFlags.Static)) { case 0: instFilter = fi => false; break; case BindingFlags.Instance: instFilter = fi => !fi.IsStatic; break; case BindingFlags.Static: instFilter = fi => fi.IsStatic; break; default: instFilter = fi => true; break; } List<FieldInfo> fieldInfos = new List<FieldInfo>(); foreach (var declaredField in type.GetTypeInfo().DeclaredFields) { if (visFilter(declaredField) && instFilter(declaredField)) fieldInfos.Add(declaredField); } return fieldInfos.ToArray(); } public static Type GetNestedType(this Type type, string nestedTypeName) { TypeInfo ti = null; foreach(var nt in type.GetTypeInfo().DeclaredNestedTypes) { if (nt.Name == nestedTypeName) { ti = nt; break; } } return ti == null ? null : ti.AsType(); } public static TypeCode GetTypeCode(this Type type) { if (type == typeof(bool)) return TypeCode.Boolean; else if (type == typeof(byte)) return TypeCode.Byte; else if (type == typeof(char)) return TypeCode.Char; else if (type == typeof(ushort)) return TypeCode.UInt16; else if (type == typeof(uint)) return TypeCode.UInt32; else if (type == typeof(ulong)) return TypeCode.UInt64; else if (type == typeof(sbyte)) return TypeCode.SByte; else if (type == typeof(short)) return TypeCode.Int16; else if (type == typeof(int)) return TypeCode.Int32; else if (type == typeof(long)) return TypeCode.Int64; else if (type == typeof(string)) return TypeCode.String; else if (type == typeof(float)) return TypeCode.Single; else if (type == typeof(double)) return TypeCode.Double; else if (type == typeof(DateTime)) return TypeCode.DateTime; else if (type == (typeof(Decimal))) return TypeCode.Decimal; else return TypeCode.Object; } // // FieldInfo extension methods // public static object GetRawConstantValue(this FieldInfo fi) { return fi.GetValue(null); } // // Assembly extension methods // public static bool ReflectionOnly(this Assembly assm) { // In PCL we can't load in reflection-only context return false; } #endif } } // Defining some no-ops in PCL builds #if ES_BUILD_PCL || PROJECTN namespace System.Security { class SuppressUnmanagedCodeSecurityAttribute : Attribute { } enum SecurityAction { Demand } } namespace System.Security.Permissions { class HostProtectionAttribute : Attribute { public bool MayLeakOnAbort { get; set; } } class PermissionSetAttribute : Attribute { public PermissionSetAttribute(System.Security.SecurityAction action) { } public bool Unrestricted { get; set; } } } #endif #if PROJECTN namespace System { public static class AppDomain { public static int GetCurrentThreadId() { return (int)Interop.mincore.GetCurrentThreadId(); } } } #endif
using UnityEngine; using UnityEditor; using System.IO; public class TrackBuildRExport { private static Transform CURRENT_TRANSFORM; private const string COLLIDER_SUFFIX = "_Collider"; private const string PROGRESSBAR_TEXT = "Exporting Track"; private static string FILE_EXTENTION = ".obj"; private const string ROOT_FOLDER = "Assets/TrackBuildR/Exported/"; public static void InspectorGUI(TrackBuildR track) { TrackBuildRTrack trackData = track.track; const int guiWidth = 400; const int textWidth = 348; const int toggleWidth = 25; const int helpWidth = 20; CURRENT_TRANSFORM = track.transform; EditorGUILayout.Space(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Filename", GUILayout.Width(225)); track.exportFilename = EditorGUILayout.TextField(track.exportFilename, GUILayout.Width(175)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Filetype", GUILayout.Width(350)); track.fileType = (TrackBuildR.fileTypes)EditorGUILayout.EnumPopup(track.fileType, GUILayout.Width(50)); switch (track.fileType) { case TrackBuildR.fileTypes.Obj: FILE_EXTENTION = ".obj"; break; case TrackBuildR.fileTypes.Fbx: FILE_EXTENTION = ".fbx"; break; } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Copy Textures into Export Folder", GUILayout.Width(textWidth)); track.copyTexturesIntoExportFolder = EditorGUILayout.Toggle(track.copyTexturesIntoExportFolder, GUILayout.Width(toggleWidth)); if (GUILayout.Button("?", GUILayout.Width(helpWidth))) { string helpTitle = "Help - Copy Textures into Export Folder"; string helpBody = "Check this box if you want to copy the textures you are using into the export folder." + "\nThis is useful if you plan to use the exported model elsewhere. Having the model and the textures in one folder will allow you to move this model with ease."; EditorUtility.DisplayDialog(helpTitle, helpBody, "close"); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Export Collider"); // track.exportSimpleCollider = EditorGUILayout.Toggle(track.exportSimpleCollider, GUILayout.Width(toggleWidth)); track.exportCollider = EditorGUILayout.Toggle(track.exportCollider, GUILayout.Width(toggleWidth)); if (GUILayout.Button("?", GUILayout.Width(helpWidth))) { string helpTitle = "Help - Export Collider Mesh"; string helpBody = "Check this box if you wish to generate a trackCollider mesh for your model." + "\nThis will generate a mesh to be used with colliders."; EditorUtility.DisplayDialog(helpTitle, helpBody, "close"); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Export as Prefab", GUILayout.Width(textWidth)); track.createPrefabOnExport = EditorGUILayout.Toggle(track.createPrefabOnExport, GUILayout.Width(toggleWidth)); if (GUILayout.Button("?", GUILayout.Width(helpWidth))) { string helpTitle = "Help - Export as Prefab"; string helpBody = "Select this if you wish to create a prefab of your model." + "\nThis is recommended if you're exporting a trackCollider so they will get packaged together."; EditorUtility.DisplayDialog(helpTitle, helpBody, "close"); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Export with tangents", GUILayout.Width(textWidth)); track.includeTangents = EditorGUILayout.Toggle(track.includeTangents, GUILayout.Width(toggleWidth)); if (GUILayout.Button("?", GUILayout.Width(helpWidth))) { string helpTitle = "Help - with tangents"; string helpBody = "Export the models with calculated tangents." + "\nSome shaders require tangents to be calculated on the model." + "\nUnity will do this automatically on all imported meshes so it's not neccessary here." + "/nBut you might want them if you're taking them to another program."; EditorUtility.DisplayDialog(helpTitle, helpBody, "close"); } EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); bool usingSubstances = false; int numberOfTextures = trackData.numberOfTextures; for(int i = 0; i < numberOfTextures; i++) { TrackBuildRTexture texture = trackData.Texture(i); if(texture.type == TrackBuildRTexture.Types.Substance) { usingSubstances = true; break; } } if (usingSubstances) { EditorGUILayout.HelpBox("Model uses Substance textures." + "\nExporting model to " + track.fileType + " will lose references to this texture and it will be rendered white.", MessageType.Warning); } if (GUILayout.Button("Export", GUILayout.Width(guiWidth), GUILayout.Height(40))) { ExportModel(track); } EditorGUILayout.Space(); if(GUILayout.Button("Export to XML")) { string defaultName = track.name; defaultName.Replace(" ", "_"); string filepath = EditorUtility.SaveFilePanel("Export Track BuildR Track to XML", "Assets/TrackBuildR", defaultName, "xml"); if (filepath != "") { using (StreamWriter sw = new StreamWriter(filepath)) { sw.Write(track.ToXML());//write out contents of data to XML } } AssetDatabase.Refresh(); } if (GUILayout.Button("Import from XML")) { string xmlpath = EditorUtility.OpenFilePanel("Import Track BuildR Track from XML", "Assets/TrackBuildR/", "xml"); if (xmlpath != "") track.FromXML(xmlpath); } if (GUILayout.Button("Import from KML")) { string xmlpath = EditorUtility.OpenFilePanel("Import Google Earth KML", "Assets/TrackBuildR/", "kml"); if (xmlpath != "") track.FromKML(xmlpath); } CURRENT_TRANSFORM = null; } private static void ExportModel(TrackBuildR track) { GameObject baseObject = new GameObject(track.exportFilename); baseObject.transform.position = CURRENT_TRANSFORM.position; baseObject.transform.rotation = CURRENT_TRANSFORM.rotation; EditorUtility.DisplayCancelableProgressBar(PROGRESSBAR_TEXT, "", 0.0f); track.ForceFullRecalculation(); EditorUtility.DisplayCancelableProgressBar(PROGRESSBAR_TEXT, "", 0.1f); try { TrackBuildRTrack trackData = track.track; //check overwrites... string newDirectory = ROOT_FOLDER + track.exportFilename; if(!CreateFolder(newDirectory)) { EditorUtility.ClearProgressBar(); return; } EditorUtility.DisplayCancelableProgressBar(PROGRESSBAR_TEXT, "", 0.15f); int numberOfCurves = trackData.numberOfCurves; float exportProgress = 0.75f / (numberOfCurves*6.0f); ExportMaterial[] exportMaterials = new ExportMaterial[1]; ExportMaterial exportTexture = new ExportMaterial(); string[] dynNames = new []{"track","bumper","boundary","bottom","offread","trackCollider"}; for(int c = 0; c < numberOfCurves; c++) { TrackBuildRPoint curve = trackData[c]; int numberOfDynMeshes = 6; DynamicMeshGenericMultiMaterialMesh[] dynMeshes = new DynamicMeshGenericMultiMaterialMesh[6]; dynMeshes[0] = curve.dynamicTrackMesh; dynMeshes[1] = curve.dynamicBumperMesh; dynMeshes[2] = curve.dynamicBoundaryMesh; dynMeshes[3] = curve.dynamicBottomMesh; dynMeshes[4] = curve.dynamicOffroadMesh; dynMeshes[5] = curve.dynamicColliderMesh; int[] textureIndeices = new int[] { curve.trackTextureStyleIndex ,curve.bumperTextureStyleIndex, curve.boundaryTextureStyleIndex, curve.bottomTextureStyleIndex, curve.offroadTextureStyleIndex, 0}; for(int d = 0; d < numberOfDynMeshes; d++) { if(EditorUtility.DisplayCancelableProgressBar(PROGRESSBAR_TEXT, "Exporting Track Curve " + c + " " + dynNames[d], 0.15f + exportProgress * (c * 6 + d))) { EditorUtility.ClearProgressBar(); return; } DynamicMeshGenericMultiMaterialMesh exportDynMesh = dynMeshes[d]; if(track.includeTangents || exportDynMesh.isEmpty) exportDynMesh.Build(track.includeTangents);//rebuild with tangents TrackBuildRTexture texture = trackData.Texture(textureIndeices[d]); exportTexture.name = texture.customName; exportTexture.material = texture.material; exportTexture.generated = false; exportTexture.filepath = texture.filePath; exportMaterials[0] = exportTexture; int meshCount = exportDynMesh.meshCount; for (int i = 0; i < meshCount; i++) { Mesh exportMesh = exportDynMesh[i].mesh; MeshUtility.Optimize(exportMesh); string filenameSuffix = trackModelName(dynNames[d], c, (meshCount > 1) ? i : -1);// "trackCurve" + c + ((meshCount > 1) ? "_" + i.ToString() : ""); string filename = track.exportFilename + filenameSuffix; Export(filename, ROOT_FOLDER + track.exportFilename + "/", track, exportMesh, exportMaterials); if(track.createPrefabOnExport) { AssetDatabase.Refresh();//ensure the database is up to date... string modelFilePath = ROOT_FOLDER + track.exportFilename + "/" + filename + FILE_EXTENTION; if(d < numberOfDynMeshes - 1) { GameObject newModel = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadMainAssetAtPath(modelFilePath)); newModel.name = filename; newModel.transform.parent = baseObject.transform; newModel.transform.localPosition = Vector3.zero; newModel.transform.localRotation = Quaternion.identity; } else { GameObject colliderObject = new GameObject("trackCollider"); colliderObject.AddComponent<MeshCollider>().sharedMesh = (Mesh)AssetDatabase.LoadAssetAtPath(modelFilePath, typeof(Mesh)); colliderObject.transform.parent = baseObject.transform; colliderObject.transform.localPosition = Vector3.zero; colliderObject.transform.localRotation = Quaternion.identity; } } } } } if(track.createPrefabOnExport) { string prefabPath = ROOT_FOLDER + track.exportFilename + "/" + track.exportFilename + ".prefab"; Object prefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)); if(prefab == null) prefab = PrefabUtility.CreateEmptyPrefab(prefabPath); PrefabUtility.ReplacePrefab(baseObject, prefab, ReplacePrefabOptions.ConnectToPrefab); } EditorUtility.DisplayCancelableProgressBar(PROGRESSBAR_TEXT, "", 0.70f); AssetDatabase.Refresh();//ensure the database is up to date... } catch(System.Exception e) { Debug.LogError("BuildR Export Error: "+e); EditorUtility.ClearProgressBar(); } Object.DestroyImmediate(baseObject); EditorUtility.ClearProgressBar(); EditorUtility.UnloadUnusedAssets(); AssetDatabase.Refresh(); } private static void ExportCollider(TrackBuildR data) { DynamicMeshGenericMultiMaterialMesh COL_MESH = new DynamicMeshGenericMultiMaterialMesh(); // COL_MESH.subMeshCount = data.textures.Count; // BuildrBuildingCollider.Build(COL_MESH, data); // COL_MESH.CollapseSubmeshes(); COL_MESH.Build(false); ExportMaterial[] exportTextures = new ExportMaterial[1]; ExportMaterial newTexture = new ExportMaterial(); newTexture.name = "blank"; newTexture.filepath = ""; newTexture.generated = true; exportTextures[0] = newTexture; int numberOfColliderMeshes = COL_MESH.meshCount; for (int i = 0; i < numberOfColliderMeshes; i++) { MeshUtility.Optimize(COL_MESH[i].mesh); string ColliderSuffixIndex = ((numberOfColliderMeshes > 1) ? "_" + i : ""); string ColliderFileName = data.exportFilename + COLLIDER_SUFFIX + ColliderSuffixIndex; string ColliderFolder = ROOT_FOLDER + data.exportFilename + "/"; Export(ColliderFileName, ColliderFolder, data, COL_MESH[i].mesh, exportTextures); } //string newDirectory = rootFolder+track.exportFilename; //if(!CreateFolder(newDirectory)) // return; // ExportMaterial[] exportTextures = new ExportMaterial[1]; // ExportMaterial newTexture = new ExportMaterial(); // newTexture.customName = ""; // newTexture.filepath = ""; // newTexture.generated = true; // exportTextures[0] = newTexture; // Export(track.exportFilename + COLLIDER_SUFFIX, ROOT_FOLDER + track.exportFilename + "/", track, EXPORT_MESH, exportTextures); // // COL_MESH = null; // EXPORT_MESH = null; } private static void Export(string filename, string folder, TrackBuildR data, Mesh exportMesh, ExportMaterial[] exportTextures) { Debug.Log("Export "+filename+" "+folder); switch (data.fileType) { case TrackBuildR.fileTypes.Obj: OBJExporter.Export(folder, filename, exportMesh, exportTextures, data.copyTexturesIntoExportFolder); break; case TrackBuildR.fileTypes.Fbx: FBXExporter.Export(folder, filename, exportMesh, exportTextures, data.copyTexturesIntoExportFolder); break; } } private static bool CreateFolder(string newDirectory) { if (Directory.Exists(newDirectory)) { if (EditorUtility.DisplayDialog("File directory exists", "Are you sure you want to overwrite the contents of this file?", "Cancel", "Overwrite")) { return false; } } try { Directory.CreateDirectory(newDirectory); } catch { EditorUtility.DisplayDialog("Error!", "Failed to create target folder!", ""); return false; } return true; } private static string trackModelName(string type, int curve, int mesh) { return "_" + type + "_" + curve + ((mesh > -1) ? "_" + mesh.ToString() : ""); } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 OpenSimulator Project 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 DEVELOPERS ``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 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.Drawing; using System.Drawing.Imaging; using System.IO; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.CoreModules.World.Terrain.FileLoaders { /// <summary> /// A virtual class designed to have methods overloaded, /// this class provides an interface for a generic image /// saving and loading mechanism, but does not specify the /// format. It should not be insubstantiated directly. /// </summary> public class GenericSystemDrawing : ITerrainLoader { #region ITerrainLoader Members public string FileExtension { get { return ".gsd"; } } /// <summary> /// Loads a file from a specified filename on the disk, /// parses the image using the System.Drawing parsers /// then returns a terrain channel. Values are /// returned based on HSL brightness between 0m and 128m /// </summary> /// <param name="filename">The target image to load</param> /// <returns>A terrain channel generated from the image.</returns> public virtual ITerrainChannel LoadFile(string filename) { return LoadBitmap(new Bitmap(filename)); } public virtual ITerrainChannel LoadFile(string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int w, int h) { Bitmap bitmap = new Bitmap(filename); ITerrainChannel retval = new TerrainChannel(true); for (int x = 0; x < retval.Width; x++) { for (int y = 0; y < retval.Height; y++) { retval[x, y] = bitmap.GetPixel(offsetX * retval.Width + x, (bitmap.Height - (retval.Height * (offsetY + 1))) + retval.Height - y - 1).GetBrightness() * 128; } } return retval; } public virtual ITerrainChannel LoadStream(Stream stream) { return LoadBitmap(new Bitmap(stream)); } protected virtual ITerrainChannel LoadBitmap(Bitmap bitmap) { ITerrainChannel retval = new TerrainChannel(bitmap.Width, bitmap.Height); int x; for (x = 0; x < bitmap.Width; x++) { int y; for (y = 0; y < bitmap.Height; y++) { retval[x, y] = bitmap.GetPixel(x, bitmap.Height - y - 1).GetBrightness() * 128; } } return retval; } /// <summary> /// Exports a file to a image on the disk using a System.Drawing exporter. /// </summary> /// <param name="filename">The target filename</param> /// <param name="map">The terrain channel being saved</param> public virtual void SaveFile(string filename, ITerrainChannel map) { Bitmap colours = CreateGrayscaleBitmapFromMap(map); colours.Save(filename, ImageFormat.Png); } /// <summary> /// Exports a stream using a System.Drawing exporter. /// </summary> /// <param name="stream">The target stream</param> /// <param name="map">The terrain channel being saved</param> public virtual void SaveStream(Stream stream, ITerrainChannel map) { Bitmap colours = CreateGrayscaleBitmapFromMap(map); colours.Save(stream, ImageFormat.Png); } public virtual void SaveFile(ITerrainChannel m_channel, string filename, int offsetX, int offsetY, int fileWidth, int fileHeight, int regionSizeX, int regionSizeY) { // We need to do this because: // "Saving the image to the same file it was constructed from is not allowed and throws an exception." string tempName = offsetX + "_ " + offsetY + "_" + filename; Bitmap entireBitmap = null; Bitmap thisBitmap = null; if (File.Exists(filename)) { File.Copy(filename, tempName); entireBitmap = new Bitmap(tempName); if (entireBitmap.Width != fileWidth * regionSizeX || entireBitmap.Height != fileHeight * regionSizeY) { // old file, let's overwrite it entireBitmap = new Bitmap(fileWidth * regionSizeX, fileHeight * regionSizeY); } } else { entireBitmap = new Bitmap(fileWidth * regionSizeX, fileHeight * regionSizeY); } thisBitmap = CreateGrayscaleBitmapFromMap(m_channel); Console.WriteLine("offsetX=" + offsetX + " offsetY=" + offsetY); for (int x = 0; x < regionSizeX; x++) for (int y = 0; y < regionSizeY; y++) entireBitmap.SetPixel(x + offsetX * regionSizeX, y + (fileHeight - 1 - offsetY) * regionSizeY, thisBitmap.GetPixel(x, y)); Save(entireBitmap, filename); thisBitmap.Dispose(); entireBitmap.Dispose(); if (File.Exists(tempName)) File.Delete(tempName); } protected virtual void Save(Bitmap bmp, string filename) { bmp.Save(filename, ImageFormat.Png); } #endregion public override string ToString() { return "SYS.DRAWING"; } /// <summary> /// Protected method, generates a grayscale bitmap /// image from a specified terrain channel. /// </summary> /// <param name="map">The terrain channel to export to bitmap</param> /// <returns>A System.Drawing.Bitmap containing a grayscale image</returns> protected static Bitmap CreateGrayscaleBitmapFromMap(ITerrainChannel map) { Bitmap bmp = new Bitmap(map.Width, map.Height); const int pallete = 256; Color[] grays = new Color[pallete]; for (int i = 0; i < grays.Length; i++) { grays[i] = Color.FromArgb(i, i, i); } for (int y = 0; y < map.Height; y++) { for (int x = 0; x < map.Width; x++) { // 512 is the largest possible height before colours clamp int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 128.0), 0.0) * (pallete - 1)); // Handle error conditions if (colorindex > pallete - 1 || colorindex < 0) bmp.SetPixel(x, map.Height - y - 1, Color.Red); else bmp.SetPixel(x, map.Height - y - 1, grays[colorindex]); } } return bmp; } /// <summary> /// Protected method, generates a coloured bitmap /// image from a specified terrain channel. /// </summary> /// <param name="map">The terrain channel to export to bitmap</param> /// <returns>A System.Drawing.Bitmap containing a coloured image</returns> protected static Bitmap CreateBitmapFromMap(ITerrainChannel map) { Bitmap gradientmapLd = new Bitmap("defaultstripe.png"); int pallete = gradientmapLd.Height; Bitmap bmp = new Bitmap(map.Width, map.Height); Color[] colours = new Color[pallete]; for (int i = 0; i < pallete; i++) { colours[i] = gradientmapLd.GetPixel(0, i); } for (int y = 0; y < map.Height; y++) { for (int x = 0; x < map.Width; x++) { // 512 is the largest possible height before colours clamp int colorindex = (int) (Math.Max(Math.Min(1.0, map[x, y] / 512.0), 0.0) * (pallete - 1)); // Handle error conditions if (colorindex > pallete - 1 || colorindex < 0) bmp.SetPixel(x, map.Height - y - 1, Color.Red); else bmp.SetPixel(x, map.Height - y - 1, colours[colorindex]); } } return bmp; } } }
'From Squeak 1.3 of Jan 16, 1998 on 26 January 1998 at 9:22:44 pm'! MouseMenuController subclass: #SSAScrollBarController instanceVariableNames: 'unitScrollDelay ' classVariableNames: '' poolDictionaries: '' category: 'PowerTools'! View subclass: #SSAScrollBarView instanceVariableNames: 'scrollBarWidth scrollBarBox upButtonBox downButtonBox elevatorShaft elevatorCache upButtonCache downButtonCache ' classVariableNames: '' poolDictionaries: '' category: 'PowerTools'! !Pen methodsFor: 'accessing' stamp: 'ssa 1/15/98 15:53'! destForm: aForm "2/14/97 ssa added for compatibility." self flag:#compatibility. destForm _ aForm ! ! !ScrollController methodsFor: 'basic control sequence' stamp: 'ssa 12/10/97 15:24'! controlInitialize "Recompute scroll bars. Save underlying image unless it is already saved." "Hacked to disable flop-out scroll bars when inside an SSAScrollBarView - ssa 12/10/97 15:21" super controlInitialize. scrollBar region: (0 @ 0 extent: 24 @ view apparentDisplayBox height). scrollBar insideColor: view backgroundColor. marker region: self computeMarkerRegion. scrollBar _ scrollBar align: scrollBar topRight with: view apparentDisplayBox topLeft. marker _ marker align: marker topCenter with: self upDownLine @ (scrollBar top + 2). savedArea isNil ifTrue: [savedArea _ Form fromDisplay: scrollBar]. (self view superView isKindOf: SSAScrollBarView) "_______HERE IS THE HACK" ifFalse:[scrollBar displayOn: Display]. "Show a border around yellow-button (menu) region" " yellowBar _ Rectangle left: self yellowLine right: scrollBar right + 1 top: scrollBar top bottom: scrollBar bottom. Display border: yellowBar width: 1 mask: Form veryLightGray. " self moveMarker ! ! !ScrollController methodsFor: 'control defaults' stamp: 'ssa 12/10/97 17:10'! controlActivity "Hacked to supprt SSAScrollBarView - ssa 12/10/97 17:07" (self view superView isKindOf: SSAScrollBarView) ifFalse:[ self scrollBarContainsCursor ifTrue: [self scroll] ifFalse: [super controlActivity]] ifTrue:[super controlActivity]! ! !ScrollController methodsFor: 'control defaults' stamp: 'ssa 1/8/98 16:26'! isControlActive "Viva la Junta!!" "HACKED to ignore scrollbar in the activity test if contained in a ScrollbarView - ssa 1/8/98 16:24" view isNil ifTrue: [^ false]. (self view superView isKindOf: SSAScrollBarView) "_______HERE IS THE HACK" ifFalse:["original code" ^(view insetDisplayBox merge: scrollBar inside) containsPoint: sensor cursorPoint] ifTrue:[^view insetDisplayBox containsPoint: sensor cursorPoint]! ! !ScrollController methodsFor: 'marker adjustment' stamp: 'ssa 12/10/97 15:25'! moveMarker "The view window has changed. Update the marker." "Hacked to suppress flop-out scrollbar updates when the view is encapsulated by an SSAScrollBarView - ssa 12/10/97 15:24" (self view superView isKindOf: SSAScrollBarView) "_______HERE IS THE HACK" ifFalse:[self moveMarker: self markerDelta negated anchorMarker: nil]! ! !ScrollController methodsFor: 'marker adjustment' stamp: 'ssa 12/10/97 15:26'! moveMarkerTo: aRectangle "Same as markerRegion: aRectangle; moveMarker, except a no-op if the marker would not move." "Hacked to suppress flop-out scrollbar updates when the view is encapsulated by an SSAScrollBarView - ssa 12/10/97 15:24" (self view superView isKindOf: SSAScrollBarView) "_______HERE IS THE HACK" ifFalse:[ (aRectangle height = marker height and: [self viewDelta = 0]) ifFalse: [self markerRegion: aRectangle. self moveMarker]]! ! !ParagraphEditor methodsFor: 'controlling' stamp: 'ssa 12/11/97 15:36'! controlActivity "Hacked to supprt SSAScrollBarView - ssa 12/10/97 17:07" self scrollBarContainsCursor ifTrue: [(self view superView isKindOf: SSAScrollBarView) ifFalse:[self scroll]] ifFalse: [self processKeyboard. self processMouseButtons]! ! !ParagraphEditor methodsFor: 'scrolling' stamp: 'ssa 1/15/98 15:28'! scrollView: anInteger "Paragraph scrolling uses opposite polarity" "Adjusted to keep text from scrolling off the view - ssa 1/15/98 15:22. The - 30 below is the hack to allow for some empty space to show at the bottom." | maximumAmount minimumAmount amount | maximumAmount _ paragraph clippingRectangle top - paragraph compositionRectangle top max: 0. minimumAmount _ paragraph clippingRectangle bottom - paragraph compositionRectangle bottom - 30 min: 0. amount _ (anInteger min: maximumAmount) max: minimumAmount. ^ self scrollBy: amount negated! ! !ParagraphEditor methodsFor: 'scrolling' stamp: 'ssa 12/5/97 16:27'! updateMarker "Hacked to catch this scrolling 'event'. ssa 12/5/97 16:22" "A variation of computeMarkerRegion--only redisplay the marker in the scrollbar if an actual change has occurred in the positioning of the paragraph." self moveMarkerTo: self computeMarkerRegion. "A hack to notify the SSAScrollBarController" (self view superView isKindOf: SSAScrollBarView) ifTrue:[self view superView updateElevator]! ! !SSAScrollBarController reorganize! ('delays' defaultUnitScrollDelay wait) ('accessing' elevatorBox scroller unitScrollDelay unitScrollDelay: viewToScroll) ('scrolling' pageDown pageHeight pageUp scrollAbsolute unitDown unitHeight unitUp) ('control activity' controlActivity redButtonActivity) ! !SSAScrollBarController methodsFor: 'delays' stamp: 'ssa 1/15/98 13:51'! defaultUnitScrollDelay "Answer the delay to use when unit scrolling, i.e., pressing the up or down button." ^Delay forMilliseconds: 50! ! !SSAScrollBarController methodsFor: 'delays' stamp: 'ssa 1/15/98 13:52'! wait self defaultUnitScrollDelay wait! ! !SSAScrollBarController methodsFor: 'accessing' stamp: 'ssa 12/10/97 15:50'! elevatorBox "Compute this each time since the view content my change." | box originY extentY | box _ self view elevatorShaft. extentY _ self viewToScroll percentVisibleContent * box height. originY _ (self viewToScroll percentPreceedingContent * box height) min: box height - extentY. ^(box origin x asInteger @ (box origin y + originY) asInteger max: box origin) extent: ((box extent x asInteger @ extentY asInteger) min: box extent)! ! !SSAScrollBarController methodsFor: 'accessing' stamp: 'ssa 12/5/97 16:00'! scroller ^self viewToScroll controller! ! !SSAScrollBarController methodsFor: 'accessing' stamp: 'ssa 1/15/98 13:50'! unitScrollDelay "<^hOf Delay>" "ssa 1/15/98 13:50 - Answer the instance variable, unitScrollDelay" unitScrollDelay isNil ifTrue:[self unitScrollDelay: self defaultUnitScrollDelay]. ^unitScrollDelay! ! !SSAScrollBarController methodsFor: 'accessing' stamp: 'ssa 1/15/98 13:50'! unitScrollDelay: aDelay "<aDelay: hOf Delay, ^self>" "ssa 1/15/98 13:50 - Set unitScrollDelay to be aDelay." unitScrollDelay _ aDelay! ! !SSAScrollBarController methodsFor: 'accessing' stamp: 'ssa 12/5/97 14:40'! viewToScroll ^self view subViews first! ! !SSAScrollBarController methodsFor: 'scrolling' stamp: 'ssa 12/5/97 16:07'! pageDown "Scroll down by one page length." self scroller scrollView: self pageHeight negated. self view updateElevator! ! !SSAScrollBarController methodsFor: 'scrolling' stamp: 'ssa 12/5/97 16:00'! pageHeight "Answer the height of a page for the scrolling view." ^self viewToScroll displayBox height! ! !SSAScrollBarController methodsFor: 'scrolling' stamp: 'ssa 12/5/97 16:07'! pageUp "Scroll up by one page length." self scroller scrollView: self pageHeight. self view updateElevator! ! !SSAScrollBarController methodsFor: 'scrolling' stamp: 'ssa 1/20/98 13:45'! scrollAbsolute | box offset height center | box _ self view elevatorShaft. height _ box height. [Sensor redButtonPressed] whileTrue: [center _ self view elevatorBox center y. offset _ (center - Sensor cursorPoint y). (self viewToScroll percentPreceedingContent ~= 0.0 or:[self viewToScroll percentVisibleContent < 1.0]) ifTrue:[self scroller scrollView: ((offset / height) * (self scroller view totalContentHeight * self scroller view unitContentHeight)) asInteger. self view updateElevator]] ! ! !SSAScrollBarController methodsFor: 'scrolling' stamp: 'ssa 1/15/98 13:54'! unitDown "Scroll down by one content unit." self view displayDownButtonPressed. [Sensor redButtonPressed] whileTrue:[ self scroller scrollView: self unitHeight negated. self view updateElevator. self wait]. self view displayDownButton. ! ! !SSAScrollBarController methodsFor: 'scrolling' stamp: 'ssa 12/5/97 16:00'! unitHeight "Answer the height of a content unit for the scrolling view." ^self viewToScroll unitContentHeight! ! !SSAScrollBarController methodsFor: 'scrolling' stamp: 'ssa 1/15/98 13:54'! unitUp "Scroll up by one content unit." self view displayUpButtonPressed. [Sensor redButtonPressed] whileTrue:[ self scroller scrollView: self unitHeight. self view updateElevator. self wait]. self view displayUpButton. ! ! !SSAScrollBarController methodsFor: 'control activity' stamp: 'ssa 1/8/98 16:28'! controlActivity "Refer to the comment in Controller|controlActivity." (Sensor redButtonPressed and:[self view scrollBarBox containsPoint: Sensor cursorPoint]) ifTrue: [^self redButtonActivity]. super controlActivity ! ! !SSAScrollBarController methodsFor: 'control activity' stamp: 'ssa 1/20/98 13:39'! redButtonActivity | point | " self scroller view visibleContentHeight >= (self scroller view totalContentHeight + 2) ifTrue:[^self]." point _ Sensor cursorPoint. (self view upButtonBox containsPoint: point) ifTrue:[^self unitUp]. (self view downButtonBox containsPoint: point) ifTrue:[^self unitDown]. (self view elevatorBox containsPoint: point) ifTrue:[^self scrollAbsolute]. self view elevatorBox center y > point y ifTrue:[self pageUp] ifFalse:[self pageDown]. ! ! !SSAScrollBarView class reorganize! ('examples' exampleBrowser exampleWithListView exampleWithSILView exampleWithStringView exampleWithTextView) ('instance creation' on:) ! !SSAScrollBarView class methodsFor: 'instance creation' stamp: 'ssa 12/11/97 12:24'! on: aScrollingView "<aScrollingView: {hOf ListView | hOf TextView | hOf StringHolderView | hOf ParagraphEditor | hOf CodeView | hOf PPSListView | hOf SelectionInListView}, ^iOf self>" "Answer an instance of me that encapsulates aScrollingView by providing Windows-style scroll bars" ^self new on: aScrollingView! ! !View methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 16:00'! percentContentVisible "Answer the percent of my content that is visible. ssa 12/5/97 15:37" ^self visibleContentHeight / self totalContentHeight! ! !View methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 16:00'! percentPrecedingContent "Answer the percent of my content that not visible since it has been scrolled of the top of the screen. ssa 12/5/97 15:37" ^0.0! ! !View methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 16:31'! percentPreceedingContent "Answer the percent of my content that not visible since it has been scrolled of the top of the screen. ssa 12/5/97 15:37" ^0.0! ! !View methodsFor: 'scrolling support' stamp: 'ssa 1/15/98 15:19'! percentVisibleContent "Answer the percent of my content that is visible. ssa 12/5/97 15:37" ^self totalContentHeight = 0 ifTrue:[0.0] ifFalse:[self visibleContentHeight / self totalContentHeight]! ! !View methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 15:15'! totalContentHeight "Answer the height of my content, visible or not. ssa 12/5/97 15:04" ^100 / self unitContentHeight! ! !View methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 15:15'! unitContentHeight "Answer the unit height of my content. ssa 12/5/97 15:04" ^10.0! ! !View methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 15:15'! visibleContentHeight "Answer the height of my visible content. ssa 12/5/97 15:04" ^100 / self unitContentHeight! ! !ListView methodsFor: 'updating' stamp: 'ssa 12/11/97 17:19'! update: aSymbol "Refer to the comment in View|update:." "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" aSymbol == #list ifTrue: [self list: model list. self displayView] ifFalse:[ aSymbol == #listIndex ifTrue: [self moveSelectionBox: model listIndex]]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !ListView methodsFor: 'scrolling support' stamp: 'ssa 12/10/97 16:09'! percentPreceedingContent "Answer the percent of my content that not visible since it has been scrolled of the top of the screen. ssa 12/5/97 15:37" | para lineIndex | para _ self list. lineIndex _ para lineIndexOfTop: para visibleRectangle top. lineIndex = 1 ifTrue:[^0.0]. ^lineIndex / para numberOfLines asFloat ! ! !ListView methodsFor: 'scrolling support' stamp: 'ssa 12/10/97 16:26'! scrollBy: anInteger "Scroll up by this amount adjusted by lineSpacing and list limits" "Hacked to support SSAScrollBarView - ssa 12/10/97 16:26" | maximumAmount minimumAmount amount | maximumAmount _ 0 max: list clippingRectangle top - list compositionRectangle top. minimumAmount _ 0 min: list clippingRectangle bottom - list compositionRectangle bottom. amount _ (anInteger min: maximumAmount) max: minimumAmount. amount ~= 0 ifTrue: [list scrollBy: amount negated. (self superView isKindOf: SSAScrollBarView) "______HERE IS THE HACK" ifTrue:[self superView updateElevator]. ^ true] ifFalse: [^ false] "Return false if no scrolling took place"! ! !ListView methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 15:16'! totalContentHeight "Answer the total height of my contents. ssa 12/5/97 15:16" ^ self list compositionRectangle height / self unitContentHeight! ! !ListView methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 16:00'! unitContentHeight "Answer the unit height of my contents. ssa 12/5/97 15:16" ^ self list lineGrid asFloat! ! !ListView methodsFor: 'scrolling support' stamp: 'ssa 12/10/97 16:04'! visibleContentHeight "Answer the total height of my contents. ssa 12/5/97 15:16" ^ self list clippingRectangle height / self unitContentHeight! ! !ClassListView methodsFor: 'updating' stamp: 'ssa 12/11/97 17:01'! update: aSymbol "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" (aSymbol == #systemCategorySelectionChanged) | (aSymbol == #editSystemCategories) | (aSymbol == #classListChanged) ifTrue: [self updateClassList]. (aSymbol == #classSelectionChanged) ifTrue: [self updateClassSelection]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !ContextStackListView methodsFor: 'updating' stamp: 'ssa 12/11/97 17:01'! update: aSymbol "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" aSymbol == #contextStackIndex ifTrue: [self moveSelectionBox: model contextStackIndex]. aSymbol == #contextStackList ifTrue: [self list: model contextStackList. self displayView]. aSymbol == #notChanged ifTrue: [self flash]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !FileListView methodsFor: 'as yet unclassified' stamp: 'ssa 12/11/97 17:02'! update: aSymbol "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" aSymbol = #relabel ifTrue: [^ self]. aSymbol == #fileList ifTrue: [self list: model fileList. self displayView]. aSymbol == #fileListIndex ifTrue: [self moveSelectionBox: model fileListIndex]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !InspectListView methodsFor: 'updating' stamp: 'ssa 12/11/97 17:02'! update: aSymbol "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" aSymbol == #inspectObject ifTrue: [self list: model fieldList. selection _ model selectionIndex. self displayView]. aSymbol == #selection ifTrue: [self moveSelectionBox: model selectionIndex]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !MessageCategoryListView methodsFor: 'updating' stamp: 'ssa 12/11/97 17:04'! update: aSymbol "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" (aSymbol == #systemCategorySelectionChanged) | (aSymbol == #editSystemCategories) ifTrue: [self resetAndDisplayView]. (aSymbol == #classSelectionChanged) ifTrue: [self getListAndDisplayView]. (aSymbol == #messageCategorySelectionChanged) ifTrue: [self moveSelectionBox: model messageCategoryListIndex]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !MessageListView methodsFor: 'updating' stamp: 'ssa 12/11/97 17:06'! update: aSymbol "What to do to the message list when Browser changes. If there is only one item, select and show it. : as part of adding a new feature that was subsequently removed, simplified the code here enough to justify using it" "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" aSymbol == #messageSelectionChanged ifTrue: [self updateMessageSelection] ifFalse:[ (#(systemCategorySelectionChanged editSystemCategories editClass editMessageCategories) includes: aSymbol) ifTrue: [self resetAndDisplayView] ifFalse:[ (aSymbol == #messageCategorySelectionChanged) | (aSymbol == #messageListChanged) ifTrue: [self updateMessageList.] ifFalse:[ (aSymbol == #classSelectionChanged) ifTrue: [model messageCategoryListIndex = 1 ifTrue: ["self updateMessageList."] ifFalse: [self resetAndDisplayView]]]]]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !PluggableListView methodsFor: 'updating' stamp: 'ssa 12/11/97 17:07'! update: aSymbol "Refer to the comment in View|update:." "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" | oldIndex newIndex | aSymbol == getListSelector ifTrue: [ oldIndex _ self getCurrentSelectionIndex. self list: self getList. newIndex _ self getCurrentSelectionIndex. (oldIndex > 0 and: [newIndex = 0]) ifTrue: [ "new list did not include the old selection; deselecting" self changeModelSelection: newIndex]. self displayView. self displaySelectionBox]. aSymbol == getSelectionSelector ifTrue: [ self moveSelectionBox: self getCurrentSelectionIndex]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !SSAScrollBarView reorganize! ('displaying' deEmphasizeView displayDownButton displayDownButtonPressed displayElevator displayElevatorShaft displayUpButton displayUpButtonPressed displayView drawDownButton drawElevator drawUpButton emphasizeView updateElevator) ('lock access' unlock) ('display box access' determineDownButtonBox determineElevatorBox determineElevatorShaft determineScrollBarBox determineUpButtonBox displayBox insetDisplayBox realInsetDisplayBox) ('subview additions' addSubView:in:borderWidth: on: on:borderWidth:) ('display transformation' displayTransform: displayTransformation realDisplayTransformation) ('delegation' doesNotUnderstand:) ('accessing' downButtonBox downButtonBox: downButtonCache downButtonCache: elevatorBox elevatorCache elevatorCache: elevatorShaft elevatorShaft: getWindow scrollBarBox scrollBarBox: scrollBarWidth scrollBarWidth: scrollingView upButtonBox upButtonBox: upButtonCache upButtonCache: window) ('control defaults' defaultControllerClass) ('testing' containsPoint:) ('bordering' borderWidth:) ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/11/97 16:49'! deEmphasizeView self displayView. super deEmphasizeView! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/11/97 13:13'! displayDownButton | box | box _ self downButtonBox. self downButtonCache extent = box extent ifFalse:[self drawDownButton]. self downButtonCache displayOn: Display at: box origin! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 1/20/98 21:45'! displayDownButtonPressed | box cf bb | box _ self downButtonBox. Display fill: box fillColor: Color darkGray. Display fill: (box origin + (2 @ 2) corner: box corner - (1 @ 1)) fillColor: Color gray. cf _ ColorForm mappingWhiteToTransparentFrom: (Form extent: 13 @ 13 depth: 1 fromArray: #(0 0 0 0 0 260046848 117440512 33554432 0 0 0 0 0 ) offset: 0 @ 0). bb _ BitBlt destForm: Display sourceForm: cf fillColor: Color black combinationRule: Form paint destOrigin: box origin + 2 sourceOrigin: 0 @ 0 extent: cf extent clipRect: box truncated. bb copyBits! ]style[(24 197 30 363)f1b,f1,f1b,f1! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/11/97 13:19'! displayElevator | box | box _ self elevatorBox. self elevatorCache extent = box extent ifFalse:[self drawElevator]. self elevatorCache displayOn: Display at: box origin! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/10/97 15:13'! displayElevatorShaft | box | box _ self elevatorShaft. Display fill: box fillColor: Color lightGray. ! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/11/97 13:18'! displayUpButton | box | box _ self upButtonBox. self upButtonCache extent = box extent ifFalse:[self drawUpButton]. self upButtonCache displayOn: Display at: box origin! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 1/20/98 21:45'! displayUpButtonPressed | box cf bb | box _ self upButtonBox. Display fill: box fillColor: Color darkGray. Display fill: (box origin + (2 @ 2) corner: box corner - (1 @ 1)) fillColor: Color gray. cf _ ColorForm mappingWhiteToTransparentFrom: (Form extent: 13 @ 13 depth: 1 fromArray: #(0 0 0 0 0 33554432 117440512 260046848 0 0 0 0 0 ) offset: 0 @ 0). bb _ BitBlt destForm: Display sourceForm: cf fillColor: Color black combinationRule: Form paint destOrigin: box origin + 2 sourceOrigin: 0 @ 0 extent: cf extent clipRect: box truncated. bb copyBits! ]style[(22 195 30 363)f1b,f1,f1b,f1! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/5/97 14:50'! displayView self displayElevatorShaft. self displayUpButton. self displayDownButton. self displayElevator ! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 1/20/98 21:45'! drawDownButton | box pen cf bb form | form _ Form extent: self downButtonBox extent depth: Display depth. box _ form boundingBox. pen _ Pen new. pen destForm: form. pen color: Color gray. pen place: box bottomLeft. pen goto: box topLeft. pen goto: box topRight. pen color: Color veryLightGray. pen place: box bottomLeft + (1 @ 0). pen goto: box topLeft + 1. pen goto: box topRight + (0 @ 1). pen color: Color darkGray. pen place: box bottomLeft + (1 @ 1 negated). pen goto: box bottomRight - (1 @ 1). pen goto: box topRight + (1 negated @ 1). pen color: Color black. pen place: box bottomLeft. pen goto: box bottomRight. pen goto: box topRight. form fill: (box origin + (2 @ 2) corner: box corner - (1 @ 1)) fillColor: Color gray. cf _ ColorForm mappingWhiteToTransparentFrom: (Form extent: 13 @ 13 depth: 1 fromArray: #(0 0 0 0 0 260046848 117440512 33554432 0 0 0 0 0 ) offset: 0 @ 0). bb _ BitBlt destForm: form sourceForm: cf fillColor: Color black combinationRule: Form paint destOrigin: box origin + 1 sourceOrigin: 0 @ 0 extent: cf extent clipRect: box truncated. bb copyBits. self downButtonCache: form! ]style[(14 758 30 389)f1b,f1,f1b,f1! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/11/97 13:20'! drawElevator | box pen form | form _ Form extent: self controller elevatorBox extent depth: Display depth. box _ form boundingBox. pen _ Pen new. pen destForm: form. pen color: Color gray. pen place: box bottomLeft. pen goto: box topLeft. pen goto: box topRight. pen color: Color veryLightGray. pen place: box bottomLeft + (1 @ 0). pen goto: box topLeft + 1. pen goto: box topRight + (0 @ 1). pen color: Color darkGray. pen place: box bottomLeft + (1 @ 1 negated). pen goto: box bottomRight - (1 @ 1). pen goto: box topRight + (1 negated @ 1). pen color: Color black. pen place: box bottomLeft. pen goto: box bottomRight. pen goto: box topRight. form fill: (box origin + (2 @ 2) corner: box corner - (1 @ 1)) fillColor: Color gray. self elevatorCache: form! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 1/20/98 21:45'! drawUpButton | box pen cf bb form | form _ Form extent: self upButtonBox extent depth: Display depth. box _ form boundingBox. pen _ Pen new. pen destForm: form. pen color: Color gray. pen place: box bottomLeft. pen goto: box topLeft. pen goto: box topRight. pen color: Color veryLightGray. pen place: box bottomLeft + (1 @ 0). pen goto: box topLeft + 1. pen goto: box topRight + (0 @ 1). pen color: Color darkGray. pen place: box bottomLeft + (1 @ 1 negated). pen goto: box bottomRight - (1 @ 1). pen goto: box topRight + (1 negated @ 1). pen color: Color black. pen place: box bottomLeft. pen goto: box bottomRight. pen goto: box topRight. form fill: (box origin + (2 @ 2) corner: box corner - (1 @ 1)) fillColor: Color gray. cf _ ColorForm mappingWhiteToTransparentFrom: (Form extent: 13 @ 13 depth: 1 fromArray: #(0 0 0 0 0 33554432 117440512 260046848 0 0 0 0 0 ) offset: 0 @ 0). bb _ BitBlt destForm: form sourceForm: cf fillColor: Color black combinationRule: Form paint destOrigin: box origin + 1 sourceOrigin: 0 @ 0 extent: cf extent clipRect: box truncated. bb copyBits. self upButtonCache: form! ]style[(12 756 30 387)f1b,f1,f1b,f1! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/5/97 14:49'! emphasizeView self displayView. super emphasizeView! ! !SSAScrollBarView methodsFor: 'displaying' stamp: 'ssa 12/5/97 16:08'! updateElevator self displayElevatorShaft. self displayElevator! ! !SSAScrollBarView methodsFor: 'lock access' stamp: 'ssa 12/5/97 16:10'! unlock "Flush the cache." self scrollBarBox: nil. self upButtonBox: nil. self downButtonBox: nil. self elevatorShaft: nil. super unlock! ! !SSAScrollBarView methodsFor: 'display box access' stamp: 'ssa 12/5/97 12:48'! determineDownButtonBox "Answer the rectangle for the scroll bar down button." ^self scrollBarBox corner - self scrollBarBox width asPoint extent: self scrollBarBox width asPoint! ! !SSAScrollBarView methodsFor: 'display box access' stamp: 'ssa 12/5/97 12:38'! determineElevatorBox "Answer the rectangle for the scroll bar elevator." ^self scrollBarBox center - (self scrollBarWidth asPoint // 2) extent: self scrollBarWidth asPoint! ! !SSAScrollBarView methodsFor: 'display box access' stamp: 'ssa 12/5/97 14:19'! determineElevatorShaft "Answer the rectangle for the scroll bar down button." ^self upButtonBox bottomLeft corner: self downButtonBox topRight! ! !SSAScrollBarView methodsFor: 'display box access' stamp: 'ssa 12/5/97 12:47'! determineScrollBarBox "Answer the rectangle for the scroll bar region." ^(self realInsetDisplayBox areasOutside: self insetDisplayBox) first! ! !SSAScrollBarView methodsFor: 'display box access' stamp: 'ssa 12/5/97 12:52'! determineUpButtonBox "Answer the rectangle for the scroll bar up button." ^self scrollBarBox origin extent: self scrollBarBox width asPoint! ! !SSAScrollBarView methodsFor: 'display box access'! displayBox "tah -- (17 July 1989 6:37:46 pm ) -- Answer the real displayBox" ^self realInsetDisplayBox expandBy: borderWidth! ! !SSAScrollBarView methodsFor: 'display box access' stamp: 'ssa 12/5/97 12:00'! insetDisplayBox "Answer the inset displayBox reduced by the horizontal space for the scroll bar" | box | box _ self realInsetDisplayBox. ^box origin extent: box width - (self borderWidth left + self scrollBarWidth) @ box height ! ! !SSAScrollBarView methodsFor: 'display box access' stamp: 'ssa 12/15/97 14:50'! realInsetDisplayBox "tah -- (17 July 1989 6:05:48 pm ) -- answer the real inset displayBox " ^super insetDisplayBox! ! !SSAScrollBarView methodsFor: 'subview additions' stamp: 'ssa 1/15/98 15:50'! addSubView: aView in: aRelativeRectangle borderWidth: width "11/3/96 ssa - added for compatibility." "Make 'aView' into a subview. Use 'aRelativeRectangle' and the super view's window to compute (1) a viewport within the superview for 'aView' and (2) the window extent for 'aView'. Note: defining the windowing transformation and deriving the viewport is logically equivalent but does not seem to be easily done" | subViewPort myWindow myExtent myOrigin | self addSubView: aView ifCyclic: [self error: 'cycle in subView structure.']. aView borderWidth: width. myWindow _ self window. myExtent _ myWindow extent. myOrigin _ myWindow origin. subViewPort _ myExtent * aRelativeRectangle origin + myOrigin corner: myExtent * aRelativeRectangle corner + myOrigin. aView window: aView window viewport: subViewPort ! ! !SSAScrollBarView methodsFor: 'subview additions'! on: aView "tah -- (17 July 1989 7:17:34 pm ) -- Add a subview to this view" self on: aView borderWidth: 0! ! !SSAScrollBarView methodsFor: 'subview additions'! on: aView borderWidth: aBorderWidth "tah -- (17 July 1989 7:17:34 pm ) -- Add a subview to this view" self addSubView: aView in: (0@0 extent: (1@1)) borderWidth: aBorderWidth! ! !SSAScrollBarView methodsFor: 'display transformation'! displayTransform: anObject "Apply the display transformation of the receiver to anObject (see View|displayTransformation) and answer the resulting scaled, translated object. It is normally applied to Rectangles, Points, and other objects with coordinates defined in the View's local coordinate system in order to get a corresponding object in display coordinates." ^(self realDisplayTransformation applyTo: anObject) rounded! ! !SSAScrollBarView methodsFor: 'display transformation' stamp: 'ssa 12/15/97 14:49'! displayTransformation "This is a hook for to get the real displayTransformation" ^self scrollBarWidth = 0 ifTrue: [self realDisplayTransformation] ifFalse: [WindowingTransformation window: self getWindow viewport: (self realInsetDisplayBox expandBy: self borderWidth)]! ! !SSAScrollBarView methodsFor: 'display transformation'! realDisplayTransformation "This is a hook for labeledView to get the real displayTransformation" ^super displayTransformation! ! !SSAScrollBarView methodsFor: 'delegation' stamp: 'ssa 1/23/98 14:56'! doesNotUnderstand: aMessage "Here it comes, the dreaded doesNotUnderstand: HACK ssa 1/23/98 14:55" ^self scrollingView perform: aMessage selector withArguments: aMessage arguments! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 12:24'! downButtonBox "<^hOf Rectangle>" "ssa 12/5/97 11:15 - Answer the instance variable, downButtonBox" downButtonBox isNil ifTrue:[self downButtonBox: self determineDownButtonBox]. ^downButtonBox! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 11:15'! downButtonBox: aRectangle "<aRectangle: hOf Rectangle, ^self>" "ssa 12/5/97 11:15 - Set downButtonBox to be aRectangle." downButtonBox _ aRectangle! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/11/97 11:46'! downButtonCache "<^hOf Form>" "ssa 12/11/97 11:43 - Answer the instance variable, downButtonCache" downButtonCache isNil ifTrue:[self downButtonCache: (Form extent:1@1)]. ^downButtonCache! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/11/97 11:43'! downButtonCache: aColorForm "<aColorForm: hOf ColorForm, ^self>" "ssa 12/11/97 11:43 - Set downButtonCache to be aColorForm." downButtonCache _ aColorForm! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 16:29'! elevatorBox "Answer the rectangle for the elevator." ^self controller elevatorBox! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/11/97 11:46'! elevatorCache "<^hOf Form>" "ssa 12/10/97 16:32 - Answer the instance variable, elevatorCache" elevatorCache isNil ifTrue:[self elevatorCache: (Form extent:1@1)]. ^elevatorCache! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/10/97 16:32'! elevatorCache: aForm "<aForm: hOf Form, ^self>" "ssa 12/10/97 16:32 - Set elevatorCache to be aForm." elevatorCache _ aForm! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 14:18'! elevatorShaft "<^hOf Rectangle>" "ssa 12/5/97 14:18 - Answer the instance variable, elevatorShaft" elevatorShaft isNil ifTrue:[self elevatorShaft: self determineElevatorShaft]. ^elevatorShaft! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 14:18'! elevatorShaft: aRectangle "<aRectangle: hOf Rectangle, ^self>" "ssa 12/5/97 14:18 - Set elevatorShaft to be aRectangle." elevatorShaft _ aRectangle! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/11/97 12:43'! getWindow "This is here to break a recursive loop caused by the indirection of my display transformation." self window isNil ifTrue:[self window: Display boundingBox]. ^self window! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 11:28'! scrollBarBox "<^hOf Rectangle>" "ssa 12/5/97 11:15 - Answer the instance variable, scrollBarBox" scrollBarBox isNil ifTrue:[self scrollBarBox: self determineScrollBarBox]. ^scrollBarBox! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 11:15'! scrollBarBox: aRectangle "<aRectangle: hOf Rectangle, ^self>" "ssa 12/5/97 11:15 - Set scrollBarBox to be aRectangle." scrollBarBox _ aRectangle! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/10/97 14:05'! scrollBarWidth "<^hOf Integer>" "ssa 12/5/97 11:27 - Answer the instance variable, scrollBarWidth" scrollBarWidth isNil ifTrue:[self scrollBarWidth: 12]. ^scrollBarWidth! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 11:27'! scrollBarWidth: anInteger "<anInteger: hOf Integer, ^self>" "ssa 12/5/97 11:27 - Set scrollBarWidth to be anInteger." scrollBarWidth _ anInteger! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 1/24/98 16:06'! scrollingView ^self subViews isEmpty ifTrue:[nil] ifFalse:[self subViews first]! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 13:59'! upButtonBox "<^hOf Rectangle>" "ssa 12/5/97 11:15 - Answer the instance variable, upButtonBox" upButtonBox isNil ifTrue:[self upButtonBox: self determineUpButtonBox]. ^upButtonBox! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/5/97 11:15'! upButtonBox: aRectangle "<aRectangle: hOf Rectangle, ^self>" "ssa 12/5/97 11:15 - Set upButtonBox to be aRectangle." upButtonBox _ aRectangle! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/11/97 11:46'! upButtonCache "<^hOf Form>" "ssa 12/11/97 11:43 - Answer the instance variable, upButtonCache" upButtonCache isNil ifTrue:[self upButtonCache: (Form extent:1@1)]. ^upButtonCache! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/11/97 11:43'! upButtonCache: aColorForm "<aColorForm: hOf ColorForm, ^self>" "ssa 12/11/97 11:43 - Set upButtonCache to be aColorForm." upButtonCache _ aColorForm! ! !SSAScrollBarView methodsFor: 'accessing' stamp: 'ssa 12/11/97 12:44'! window "This is here to break a recursive loop caused by the indirection of my display transformation." window isNil ifTrue:[self window: Display boundingBox]. ^window! ! !SSAScrollBarView methodsFor: 'control defaults' stamp: 'ssa 12/5/97 12:16'! defaultControllerClass ^SSAScrollBarController! ! !SSAScrollBarView methodsFor: 'testing' stamp: 'ssa 1/8/98 16:13'! containsPoint: aPoint "Overriden to access my real insetDsiplayBox" ^ self realInsetDisplayBox containsPoint: aPoint! ! !SSAScrollBarView methodsFor: 'bordering' stamp: 'ssa 1/24/98 16:05'! borderWidth: anything super borderWidth:1. ! ! !StringHolderView methodsFor: 'updating' stamp: 'ssa 1/15/98 14:39'! updateDisplayContents "Make the text that is displayed be the contents of the receiver's model." "VIVA LA JUNTA!!!! hack this to update the scroll bar when the contents changes - ssa 1/15/98 14:39" self editString: model contents. self displayView. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !StringHolderView methodsFor: 'scrolling support' stamp: 'ssa 12/10/97 14:49'! percentPreceedingContent "Answer the percent of my content that not visible since it has been scrolled of the top of the screen. ssa 12/5/97 15:37" | para lineIndex | para _ self displayContents. lineIndex _ para lineIndexOfTop: para visibleRectangle top. lineIndex = 1 ifTrue:[^0.0]. ^lineIndex / para numberOfLines asFloat ! ! !StringHolderView methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 15:17'! totalContentHeight "Answer the total height of my contents. ssa 12/5/97 15:16" ^ self displayContents compositionRectangle height / self unitContentHeight! ! !StringHolderView methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 16:00'! unitContentHeight "Answer the unit height of my contents. ssa 12/5/97 15:16" ^ self displayContents lineGrid asFloat! ! !StringHolderView methodsFor: 'scrolling support' stamp: 'ssa 12/5/97 16:00'! visibleContentHeight "Answer the total height of my contents. ssa 12/5/97 15:16" ^ self displayContents clippingRectangle height / self unitContentHeight! ! !BrowserCodeView methodsFor: 'updating' stamp: 'ssa 1/15/98 14:47'! updateDisplayContents "Refer to the comment in StringHolderView|updateDisplayContents." "VIVA LA JUNTA!!!! hack this to update the scroll bar when the contents changes - ssa 1/15/98 14:39" | contents | contents _ model contents. displayContents asString ~= contents ifTrue: [model messageListIndex ~= 0 ifTrue: [contents _ contents asText makeSelectorBoldIn: model selectedClassOrMetaClass]. self editString: contents. self displayView. model editSelection == #newMessage ifTrue: [controller selectFrom: 1 to: contents size]]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !ContextStackCodeView methodsFor: 'updating' stamp: 'ssa 1/15/98 15:34'! updateDisplayContents "Refer to the comment in StringHolderView|updateDisplayContents." "VIVA LA JUNTA!!!! hack this to update the scroll bar when the contents changes - ssa 1/15/98 14:39" | contents | contents _ model contents. displayContents string ~= contents ifTrue: [displayContents _ (contents asText makeSelectorBoldIn: model selectedClassOrMetaClass) asParagraph. self positionDisplayContents. self controller changeParagraph: displayContents. self displayView. self highlightPC]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !SystemCategoryListView methodsFor: 'updating' stamp: 'ssa 12/11/97 17:09'! update: aSymbol "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" aSymbol == #systemCategorySelectionChanged ifTrue: [self updateSystemCategorySelection]. aSymbol == #systemCategoriesChanged ifTrue: [self updateSystemCategoryList]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]! ! !TextCollectorView methodsFor: 'updating' stamp: 'ssa 1/15/98 15:06'! update: aParameter "Transcript cr; show: 'qwre'. Transcript clear." "Hacked to support SSAScrollBars - ssa 12/11/97 16:42" aParameter == #appendEntry ifTrue: [controller doOccluded: [controller appendEntry]]. aParameter == #update ifTrue: [controller doOccluded: [controller changeText: model contents asText]]. (self superView isKindOf: SSAScrollBarView) ifTrue:[self superView updateElevator]. (aParameter == #update) | (aParameter == #appendEntry) ifFalse:[^ super update: aParameter]! !
// 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.Diagnostics; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Text; using System.Security.Authentication; using System.Security.Permissions; namespace System.DirectoryServices.AccountManagement { abstract public class PrincipalException : SystemException { internal PrincipalException() : base() { } internal PrincipalException(string message) : base(message) { } internal PrincipalException(string message, Exception innerException) : base(message, innerException) { } protected PrincipalException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class MultipleMatchesException : PrincipalException { public MultipleMatchesException() : base() { } public MultipleMatchesException(string message) : base(message) { } public MultipleMatchesException(string message, Exception innerException) : base(message, innerException) { } protected MultipleMatchesException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class NoMatchingPrincipalException : PrincipalException { public NoMatchingPrincipalException() : base() { } public NoMatchingPrincipalException(string message) : base(message) { } public NoMatchingPrincipalException(string message, Exception innerException) : base(message, innerException) { } protected NoMatchingPrincipalException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class PasswordException : PrincipalException { public PasswordException() : base() { } public PasswordException(string message) : base(message) { } public PasswordException(string message, Exception innerException) : base(message, innerException) { } protected PasswordException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class PrincipalExistsException : PrincipalException { public PrincipalExistsException() : base() { } public PrincipalExistsException(string message) : base(message) { } public PrincipalExistsException(string message, Exception innerException) : base(message, innerException) { } protected PrincipalExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { } } public class PrincipalServerDownException : PrincipalException { private int _errorCode = 0; private string _serverName = null; public PrincipalServerDownException() : base() { } public PrincipalServerDownException(string message) : base(message) { } public PrincipalServerDownException(string message, Exception innerException) : base(message, innerException) { } public PrincipalServerDownException(string message, int errorCode) : base(message) { _errorCode = errorCode; } public PrincipalServerDownException(string message, Exception innerException, int errorCode) : base(message, innerException) { _errorCode = errorCode; } public PrincipalServerDownException(string message, Exception innerException, int errorCode, string serverName) : base(message, innerException) { _errorCode = errorCode; _serverName = serverName; } protected PrincipalServerDownException(SerializationInfo info, StreamingContext context) : base(info, context) { _errorCode = info.GetInt32("errorCode"); _serverName = (string)info.GetValue("serverName", typeof(String)); } [System.Security.SecurityCritical] [SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("errorCode", _errorCode); info.AddValue("serverName", _serverName, typeof(String)); base.GetObjectData(info, context); } } public class PrincipalOperationException : PrincipalException { private int _errorCode = 0; public PrincipalOperationException() : base() { } public PrincipalOperationException(string message) : base(message) { } public PrincipalOperationException(string message, Exception innerException) : base(message, innerException) { } public PrincipalOperationException(string message, int errorCode) : base(message) { _errorCode = errorCode; } public PrincipalOperationException(string message, Exception innerException, int errorCode) : base(message, innerException) { _errorCode = errorCode; } protected PrincipalOperationException(SerializationInfo info, StreamingContext context) : base(info, context) { _errorCode = info.GetInt32("errorCode"); } [System.Security.SecurityCritical] [SecurityPermission(System.Security.Permissions.SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("errorCode", _errorCode); base.GetObjectData(info, context); } public int ErrorCode { get { return _errorCode; } } } internal class ExceptionHelper { // Put a private constructor because this class should only be used as static methods private ExceptionHelper() { } private static int s_ERROR_NOT_ENOUGH_MEMORY = 8; // map to outofmemory exception private static int s_ERROR_OUTOFMEMORY = 14; // map to outofmemory exception private static int s_ERROR_DS_DRA_OUT_OF_MEM = 8446; // map to outofmemory exception private static int s_ERROR_NO_SUCH_DOMAIN = 1355; // map to ActiveDirectoryServerDownException private static int s_ERROR_ACCESS_DENIED = 5; // map to UnauthorizedAccessException private static int s_ERROR_NO_LOGON_SERVERS = 1311; // map to ActiveDirectoryServerDownException private static int s_ERROR_DS_DRA_ACCESS_DENIED = 8453; // map to UnauthorizedAccessException private static int s_RPC_S_OUT_OF_RESOURCES = 1721; // map to outofmemory exception internal static int RPC_S_SERVER_UNAVAILABLE = 1722; // map to ActiveDirectoryServerDownException internal static int RPC_S_CALL_FAILED = 1726; // map to ActiveDirectoryServerDownException // internal static int ERROR_DS_DRA_BAD_DN = 8439; //fix error CS0414: Warning as Error: is assigned but its value is never used // internal static int ERROR_DS_NAME_UNPARSEABLE = 8350; //fix error CS0414: Warning as Error: is assigned but its value is never used // internal static int ERROR_DS_UNKNOWN_ERROR = 8431; //fix error CS0414: Warning as Error: is assigned but its value is never used // public static uint ERROR_HRESULT_ACCESS_DENIED = 0x80070005; //fix error CS0414: Warning as Error: is assigned but its value is never used public static uint ERROR_HRESULT_LOGON_FAILURE = 0x8007052E; public static uint ERROR_HRESULT_CONSTRAINT_VIOLATION = 0x8007202f; public static uint ERROR_LOGON_FAILURE = 0x31; // public static uint ERROR_LDAP_INVALID_CREDENTIALS = 49; //fix error CS0414: Warning as Error: is assigned but its value is never used // // This method maps some common COM Hresults to // existing clr exceptions // internal static Exception GetExceptionFromCOMException(COMException e) { Exception exception; int errorCode = e.ErrorCode; string errorMessage = e.Message; // // Check if we can throw a more specific exception // if (errorCode == unchecked((int)0x80070005)) { // // Access Denied // exception = new UnauthorizedAccessException(errorMessage, e); } else if (errorCode == unchecked((int)0x800708c5) || errorCode == unchecked((int)0x80070056) || errorCode == unchecked((int)0x8007052)) { // // Password does not meet complexity requirements or old password does not match or policy restriction has been enforced. // exception = new PasswordException(errorMessage, e); } else if (errorCode == unchecked((int)0x800708b0) || errorCode == unchecked((int)0x80071392)) { // // Principal already exists // exception = new PrincipalExistsException(errorMessage, e); } else if (errorCode == unchecked((int)0x8007052e)) { // // Logon Failure // exception = new AuthenticationException(errorMessage, e); } else if (errorCode == unchecked((int)0x8007202f)) { // // Constraint Violation // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked((int)0x80072035)) { // // Unwilling to perform // exception = new InvalidOperationException(errorMessage, e); } else if (errorCode == unchecked((int)0x80070008)) { // // No Memory // exception = new OutOfMemoryException(); } else if ((errorCode == unchecked((int)0x8007203a)) || (errorCode == unchecked((int)0x8007200e)) || (errorCode == unchecked((int)0x8007200f))) { exception = new PrincipalServerDownException(errorMessage, e, errorCode, null); } else { // // Wrap the exception in a generic OperationException // exception = new PrincipalOperationException(errorMessage, e, errorCode); } return exception; } [System.Security.SecuritySafeCritical] internal static Exception GetExceptionFromErrorCode(int errorCode) { return GetExceptionFromErrorCode(errorCode, null); } [System.Security.SecurityCritical] internal static Exception GetExceptionFromErrorCode(int errorCode, string targetName) { string errorMsg = GetErrorMessage(errorCode, false); if ((errorCode == s_ERROR_ACCESS_DENIED) || (errorCode == s_ERROR_DS_DRA_ACCESS_DENIED)) return new UnauthorizedAccessException(errorMsg); else if ((errorCode == s_ERROR_NOT_ENOUGH_MEMORY) || (errorCode == s_ERROR_OUTOFMEMORY) || (errorCode == s_ERROR_DS_DRA_OUT_OF_MEM) || (errorCode == s_RPC_S_OUT_OF_RESOURCES)) return new OutOfMemoryException(); else if ((errorCode == s_ERROR_NO_LOGON_SERVERS) || (errorCode == s_ERROR_NO_SUCH_DOMAIN) || (errorCode == RPC_S_SERVER_UNAVAILABLE) || (errorCode == RPC_S_CALL_FAILED)) { return new PrincipalServerDownException(errorMsg, errorCode); } else { return new PrincipalOperationException(errorMsg, errorCode); } } [System.Security.SecurityCritical] internal static string GetErrorMessage(int errorCode, bool hresult) { uint temp = (uint)errorCode; if (!hresult) { temp = ((((temp) & 0x0000FFFF) | (7 << 16) | 0x80000000)); } string errorMsg = ""; StringBuilder sb = new StringBuilder(256); int result = UnsafeNativeMethods.FormatMessageW(UnsafeNativeMethods.FORMAT_MESSAGE_IGNORE_INSERTS | UnsafeNativeMethods.FORMAT_MESSAGE_FROM_SYSTEM | UnsafeNativeMethods.FORMAT_MESSAGE_ARGUMENT_ARRAY, IntPtr.Zero, (int)temp, 0, sb, sb.Capacity + 1, IntPtr.Zero); if (result != 0) { errorMsg = sb.ToString(0, result); } else { errorMsg = StringResources.DSUnknown + Convert.ToString(temp, 16); } return errorMsg; } } }
using Microsoft.IdentityModel; using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace SharePointSiteCreator.SharePoint { public static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm, string targetClientId, string targetClientSecret) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(targetClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, targetClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registerd for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate(object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Environment Constants // private static string GlobalEndPointPrefix = "accounts"; private static string AcsHostUrl = "accesscontrol.windows.net"; // // Hosted app configuration // private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
namespace android.content { [global::MonoJavaBridge.JavaClass(typeof(global::android.content.AsyncQueryHandler_))] public abstract partial class AsyncQueryHandler : android.os.Handler { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected AsyncQueryHandler(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] protected sealed partial class WorkerArgs : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal WorkerArgs(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.FieldId _uri1607; public global::android.net.Uri uri { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _uri1607)) as android.net.Uri; } set { } } internal static global::MonoJavaBridge.FieldId _handler1608; public global::android.os.Handler handler { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _handler1608)) as android.os.Handler; } set { } } internal static global::MonoJavaBridge.FieldId _projection1609; public global::java.lang.String[] projection { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _projection1609)) as java.lang.String[]; } set { } } internal static global::MonoJavaBridge.FieldId _selection1610; public global::java.lang.String selection { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _selection1610)) as java.lang.String; } set { } } internal static global::MonoJavaBridge.FieldId _selectionArgs1611; public global::java.lang.String[] selectionArgs { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _selectionArgs1611)) as java.lang.String[]; } set { } } internal static global::MonoJavaBridge.FieldId _orderBy1612; public global::java.lang.String orderBy { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _orderBy1612)) as java.lang.String; } set { } } internal static global::MonoJavaBridge.FieldId _result1613; public global::java.lang.Object result { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _result1613)) as java.lang.Object; } set { } } internal static global::MonoJavaBridge.FieldId _cookie1614; public global::java.lang.Object cookie { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.GetObjectField(this.JvmHandle, _cookie1614)) as java.lang.Object; } set { } } internal static global::MonoJavaBridge.FieldId _values1615; public global::android.content.ContentValues values { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.content.ContentValues>(@__env.GetObjectField(this.JvmHandle, _values1615)) as android.content.ContentValues; } set { } } static WorkerArgs() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.AsyncQueryHandler.WorkerArgs.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/AsyncQueryHandler$WorkerArgs")); global::android.content.AsyncQueryHandler.WorkerArgs._uri1607 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "uri", "Landroid/net/Uri;"); global::android.content.AsyncQueryHandler.WorkerArgs._handler1608 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "handler", "Landroid/os/Handler;"); global::android.content.AsyncQueryHandler.WorkerArgs._projection1609 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "projection", "[Ljava/lang/String;"); global::android.content.AsyncQueryHandler.WorkerArgs._selection1610 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "selection", "Ljava/lang/String;"); global::android.content.AsyncQueryHandler.WorkerArgs._selectionArgs1611 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "selectionArgs", "[Ljava/lang/String;"); global::android.content.AsyncQueryHandler.WorkerArgs._orderBy1612 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "orderBy", "Ljava/lang/String;"); global::android.content.AsyncQueryHandler.WorkerArgs._result1613 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "result", "Ljava/lang/Object;"); global::android.content.AsyncQueryHandler.WorkerArgs._cookie1614 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "cookie", "Ljava/lang/Object;"); global::android.content.AsyncQueryHandler.WorkerArgs._values1615 = @__env.GetFieldIDNoThrow(global::android.content.AsyncQueryHandler.WorkerArgs.staticClass, "values", "Landroid/content/ContentValues;"); } } [global::MonoJavaBridge.JavaClass()] protected partial class WorkerHandler : android.os.Handler { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected WorkerHandler(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override void handleMessage(android.os.Message arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.WorkerHandler.staticClass, "handleMessage", "(Landroid/os/Message;)V", ref global::android.content.AsyncQueryHandler.WorkerHandler._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; public WorkerHandler(android.content.AsyncQueryHandler arg0, android.os.Looper arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.content.AsyncQueryHandler.WorkerHandler._m1.native == global::System.IntPtr.Zero) global::android.content.AsyncQueryHandler.WorkerHandler._m1 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.WorkerHandler.staticClass, "<init>", "(Landroid/content/AsyncQueryHandler;Landroid/os/Looper;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.AsyncQueryHandler.WorkerHandler.staticClass, global::android.content.AsyncQueryHandler.WorkerHandler._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } static WorkerHandler() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.AsyncQueryHandler.WorkerHandler.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/AsyncQueryHandler$WorkerHandler")); } } private static global::MonoJavaBridge.MethodId _m0; public override void handleMessage(android.os.Message arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "handleMessage", "(Landroid/os/Message;)V", ref global::android.content.AsyncQueryHandler._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m1; protected virtual global::android.os.Handler createHandler(android.os.Looper arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.content.AsyncQueryHandler.staticClass, "createHandler", "(Landroid/os/Looper;)Landroid/os/Handler;", ref global::android.content.AsyncQueryHandler._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.Handler; } private static global::MonoJavaBridge.MethodId _m2; public virtual void startQuery(int arg0, java.lang.Object arg1, android.net.Uri arg2, java.lang.String[] arg3, java.lang.String arg4, java.lang.String[] arg5, java.lang.String arg6) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "startQuery", "(ILjava/lang/Object;Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;Ljava/lang/String;)V", ref global::android.content.AsyncQueryHandler._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg6)); } private static global::MonoJavaBridge.MethodId _m3; public virtual void cancelOperation(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "cancelOperation", "(I)V", ref global::android.content.AsyncQueryHandler._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void startInsert(int arg0, java.lang.Object arg1, android.net.Uri arg2, android.content.ContentValues arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "startInsert", "(ILjava/lang/Object;Landroid/net/Uri;Landroid/content/ContentValues;)V", ref global::android.content.AsyncQueryHandler._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m5; public virtual void startUpdate(int arg0, java.lang.Object arg1, android.net.Uri arg2, android.content.ContentValues arg3, java.lang.String arg4, java.lang.String[] arg5) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "startUpdate", "(ILjava/lang/Object;Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)V", ref global::android.content.AsyncQueryHandler._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg5)); } private static global::MonoJavaBridge.MethodId _m6; public virtual void startDelete(int arg0, java.lang.Object arg1, android.net.Uri arg2, java.lang.String arg3, java.lang.String[] arg4) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "startDelete", "(ILjava/lang/Object;Landroid/net/Uri;Ljava/lang/String;[Ljava/lang/String;)V", ref global::android.content.AsyncQueryHandler._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4)); } private static global::MonoJavaBridge.MethodId _m7; protected virtual void onQueryComplete(int arg0, java.lang.Object arg1, android.database.Cursor arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "onQueryComplete", "(ILjava/lang/Object;Landroid/database/Cursor;)V", ref global::android.content.AsyncQueryHandler._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m8; protected virtual void onInsertComplete(int arg0, java.lang.Object arg1, android.net.Uri arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "onInsertComplete", "(ILjava/lang/Object;Landroid/net/Uri;)V", ref global::android.content.AsyncQueryHandler._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m9; protected virtual void onUpdateComplete(int arg0, java.lang.Object arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "onUpdateComplete", "(ILjava/lang/Object;I)V", ref global::android.content.AsyncQueryHandler._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m10; protected virtual void onDeleteComplete(int arg0, java.lang.Object arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.content.AsyncQueryHandler.staticClass, "onDeleteComplete", "(ILjava/lang/Object;I)V", ref global::android.content.AsyncQueryHandler._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m11; public AsyncQueryHandler(android.content.ContentResolver arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.content.AsyncQueryHandler._m11.native == global::System.IntPtr.Zero) global::android.content.AsyncQueryHandler._m11 = @__env.GetMethodIDNoThrow(global::android.content.AsyncQueryHandler.staticClass, "<init>", "(Landroid/content/ContentResolver;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.content.AsyncQueryHandler.staticClass, global::android.content.AsyncQueryHandler._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } static AsyncQueryHandler() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.AsyncQueryHandler.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/AsyncQueryHandler")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::android.content.AsyncQueryHandler))] internal sealed partial class AsyncQueryHandler_ : android.content.AsyncQueryHandler { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal AsyncQueryHandler_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } static AsyncQueryHandler_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.content.AsyncQueryHandler_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/content/AsyncQueryHandler")); } } }
// 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.Runtime.CompilerServices; using System.Runtime.InteropServices; using Xunit; using static System.Buffers.Binary.BinaryPrimitives; namespace System.Buffers.Binary.Tests { public class BinaryReaderUnitTests { [Fact] public void SpanRead() { Assert.True(BitConverter.IsLittleEndian); ulong value = 0x8877665544332211; // [11 22 33 44 55 66 77 88] Span<byte> span; unsafe { span = new Span<byte>(&value, 8); } Assert.Equal<byte>(0x11, MemoryMarshal.Read<byte>(span)); Assert.True(MemoryMarshal.TryRead(span, out byte byteValue)); Assert.Equal(0x11, byteValue); Assert.Equal<sbyte>(0x11, MemoryMarshal.Read<sbyte>(span)); Assert.True(MemoryMarshal.TryRead(span, out byte sbyteValue)); Assert.Equal(0x11, byteValue); Assert.Equal<ushort>(0x1122, ReadUInt16BigEndian(span)); Assert.True(TryReadUInt16BigEndian(span, out ushort ushortValue)); Assert.Equal(0x1122, ushortValue); Assert.Equal<ushort>(0x2211, ReadUInt16LittleEndian(span)); Assert.True(TryReadUInt16LittleEndian(span, out ushortValue)); Assert.Equal(0x2211, ushortValue); Assert.Equal<short>(0x1122, ReadInt16BigEndian(span)); Assert.True(TryReadInt16BigEndian(span, out short shortValue)); Assert.Equal(0x1122, shortValue); Assert.Equal<short>(0x2211, ReadInt16LittleEndian(span)); Assert.True(TryReadInt16LittleEndian(span, out shortValue)); Assert.Equal(0x2211, ushortValue); Assert.Equal<uint>(0x11223344, ReadUInt32BigEndian(span)); Assert.True(TryReadUInt32BigEndian(span, out uint uintValue)); Assert.Equal<uint>(0x11223344, uintValue); Assert.Equal<uint>(0x44332211, ReadUInt32LittleEndian(span)); Assert.True(TryReadUInt32LittleEndian(span, out uintValue)); Assert.Equal<uint>(0x44332211, uintValue); Assert.Equal<int>(0x11223344, ReadInt32BigEndian(span)); Assert.True(TryReadInt32BigEndian(span, out int intValue)); Assert.Equal<int>(0x11223344, intValue); Assert.Equal<int>(0x44332211, ReadInt32LittleEndian(span)); Assert.True(TryReadInt32LittleEndian(span, out intValue)); Assert.Equal<int>(0x44332211, intValue); Assert.Equal<ulong>(0x1122334455667788, ReadUInt64BigEndian(span)); Assert.True(TryReadUInt64BigEndian(span, out ulong ulongValue)); Assert.Equal<ulong>(0x1122334455667788, ulongValue); Assert.Equal<ulong>(0x8877665544332211, ReadUInt64LittleEndian(span)); Assert.True(TryReadUInt64LittleEndian(span, out ulongValue)); Assert.Equal<ulong>(0x8877665544332211, ulongValue); Assert.Equal<long>(0x1122334455667788, ReadInt64BigEndian(span)); Assert.True(TryReadInt64BigEndian(span, out long longValue)); Assert.Equal<long>(0x1122334455667788, longValue); Assert.Equal<long>(unchecked((long)0x8877665544332211), ReadInt64LittleEndian(span)); Assert.True(TryReadInt64LittleEndian(span, out longValue)); Assert.Equal<long>(unchecked((long)0x8877665544332211), longValue); } [Fact] public void ReadOnlySpanRead() { Assert.True(BitConverter.IsLittleEndian); ulong value = 0x8877665544332211; // [11 22 33 44 55 66 77 88] ReadOnlySpan<byte> span; unsafe { span = new ReadOnlySpan<byte>(&value, 8); } Assert.Equal<byte>(0x11, MemoryMarshal.Read<byte>(span)); Assert.True(MemoryMarshal.TryRead(span, out byte byteValue)); Assert.Equal(0x11, byteValue); Assert.Equal<sbyte>(0x11, MemoryMarshal.Read<sbyte>(span)); Assert.True(MemoryMarshal.TryRead(span, out byte sbyteValue)); Assert.Equal(0x11, byteValue); Assert.Equal<ushort>(0x1122, ReadUInt16BigEndian(span)); Assert.True(TryReadUInt16BigEndian(span, out ushort ushortValue)); Assert.Equal(0x1122, ushortValue); Assert.Equal<ushort>(0x2211, ReadUInt16LittleEndian(span)); Assert.True(TryReadUInt16LittleEndian(span, out ushortValue)); Assert.Equal(0x2211, ushortValue); Assert.Equal<short>(0x1122, ReadInt16BigEndian(span)); Assert.True(TryReadInt16BigEndian(span, out short shortValue)); Assert.Equal(0x1122, shortValue); Assert.Equal<short>(0x2211, ReadInt16LittleEndian(span)); Assert.True(TryReadInt16LittleEndian(span, out shortValue)); Assert.Equal(0x2211, ushortValue); Assert.Equal<uint>(0x11223344, ReadUInt32BigEndian(span)); Assert.True(TryReadUInt32BigEndian(span, out uint uintValue)); Assert.Equal<uint>(0x11223344, uintValue); Assert.Equal<uint>(0x44332211, ReadUInt32LittleEndian(span)); Assert.True(TryReadUInt32LittleEndian(span, out uintValue)); Assert.Equal<uint>(0x44332211, uintValue); Assert.Equal<int>(0x11223344, ReadInt32BigEndian(span)); Assert.True(TryReadInt32BigEndian(span, out int intValue)); Assert.Equal<int>(0x11223344, intValue); Assert.Equal<int>(0x44332211, ReadInt32LittleEndian(span)); Assert.True(TryReadInt32LittleEndian(span, out intValue)); Assert.Equal<int>(0x44332211, intValue); Assert.Equal<ulong>(0x1122334455667788, ReadUInt64BigEndian(span)); Assert.True(TryReadUInt64BigEndian(span, out ulong ulongValue)); Assert.Equal<ulong>(0x1122334455667788, ulongValue); Assert.Equal<ulong>(0x8877665544332211, ReadUInt64LittleEndian(span)); Assert.True(TryReadUInt64LittleEndian(span, out ulongValue)); Assert.Equal<ulong>(0x8877665544332211, ulongValue); Assert.Equal<long>(0x1122334455667788, ReadInt64BigEndian(span)); Assert.True(TryReadInt64BigEndian(span, out long longValue)); Assert.Equal<long>(0x1122334455667788, longValue); Assert.Equal<long>(unchecked((long)0x8877665544332211), ReadInt64LittleEndian(span)); Assert.True(TryReadInt64LittleEndian(span, out longValue)); Assert.Equal<long>(unchecked((long)0x8877665544332211), longValue); } [Fact] public void SpanReadFail() { Span<byte> span = new byte[] { 1 }; Assert.Equal<byte>(1, MemoryMarshal.Read<byte>(span)); Assert.True(MemoryMarshal.TryRead(span, out byte byteValue)); Assert.Equal(1, byteValue); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<short>(_span)); Assert.False(MemoryMarshal.TryRead(span, out short shortValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<int>(_span)); Assert.False(MemoryMarshal.TryRead(span, out int intValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<long>(_span)); Assert.False(MemoryMarshal.TryRead(span, out long longValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<ushort>(_span)); Assert.False(MemoryMarshal.TryRead(span, out ushort ushortValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<uint>(_span)); Assert.False(MemoryMarshal.TryRead(span, out uint uintValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<ulong>(_span)); Assert.False(MemoryMarshal.TryRead(span, out ulong ulongValue)); Span<byte> largeSpan = new byte[100]; TestHelpers.AssertThrows<ArgumentException, byte>(largeSpan, (_span) => MemoryMarshal.Read<TestHelpers.TestValueTypeWithReference>(_span)); TestHelpers.AssertThrows<ArgumentException, byte>(largeSpan, (_span) => MemoryMarshal.TryRead(_span, out TestHelpers.TestValueTypeWithReference stringValue)); } [Fact] public void ReadOnlySpanReadFail() { ReadOnlySpan<byte> span = new byte[] { 1 }; Assert.Equal<byte>(1, MemoryMarshal.Read<byte>(span)); Assert.True(MemoryMarshal.TryRead(span, out byte byteValue)); Assert.Equal(1, byteValue); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<short>(_span)); Assert.False(MemoryMarshal.TryRead(span, out short shortValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<int>(_span)); Assert.False(MemoryMarshal.TryRead(span, out int intValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<long>(_span)); Assert.False(MemoryMarshal.TryRead(span, out long longValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<ushort>(_span)); Assert.False(MemoryMarshal.TryRead(span, out ushort ushortValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<uint>(_span)); Assert.False(MemoryMarshal.TryRead(span, out uint uintValue)); TestHelpers.AssertThrows<ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Read<ulong>(_span)); Assert.False(MemoryMarshal.TryRead(span, out ulong ulongValue)); ReadOnlySpan<byte> largeSpan = new byte[100]; TestHelpers.AssertThrows<ArgumentException, byte>(largeSpan, (_span) => MemoryMarshal.Read<TestHelpers.TestValueTypeWithReference>(_span)); TestHelpers.AssertThrows<ArgumentException, byte>(largeSpan, (_span) => MemoryMarshal.TryRead(_span, out TestHelpers.TestValueTypeWithReference stringValue)); } [Fact] public void SpanWriteAndReadBigEndianHeterogeneousStruct() { Assert.True(BitConverter.IsLittleEndian); Span<byte> spanBE = new byte[Unsafe.SizeOf<TestStruct>()]; WriteInt16BigEndian(spanBE, s_testStruct.S0); WriteInt32BigEndian(spanBE.Slice(2), s_testStruct.I0); WriteInt64BigEndian(spanBE.Slice(6), s_testStruct.L0); WriteUInt16BigEndian(spanBE.Slice(14), s_testStruct.US0); WriteUInt32BigEndian(spanBE.Slice(16), s_testStruct.UI0); WriteUInt64BigEndian(spanBE.Slice(20), s_testStruct.UL0); WriteInt16BigEndian(spanBE.Slice(28), s_testStruct.S1); WriteInt32BigEndian(spanBE.Slice(30), s_testStruct.I1); WriteInt64BigEndian(spanBE.Slice(34), s_testStruct.L1); WriteUInt16BigEndian(spanBE.Slice(42), s_testStruct.US1); WriteUInt32BigEndian(spanBE.Slice(44), s_testStruct.UI1); WriteUInt64BigEndian(spanBE.Slice(48), s_testStruct.UL1); ReadOnlySpan<byte> readOnlySpanBE = new ReadOnlySpan<byte>(spanBE.ToArray()); var readStruct = new TestStruct { S0 = ReadInt16BigEndian(spanBE), I0 = ReadInt32BigEndian(spanBE.Slice(2)), L0 = ReadInt64BigEndian(spanBE.Slice(6)), US0 = ReadUInt16BigEndian(spanBE.Slice(14)), UI0 = ReadUInt32BigEndian(spanBE.Slice(16)), UL0 = ReadUInt64BigEndian(spanBE.Slice(20)), S1 = ReadInt16BigEndian(spanBE.Slice(28)), I1 = ReadInt32BigEndian(spanBE.Slice(30)), L1 = ReadInt64BigEndian(spanBE.Slice(34)), US1 = ReadUInt16BigEndian(spanBE.Slice(42)), UI1 = ReadUInt32BigEndian(spanBE.Slice(44)), UL1 = ReadUInt64BigEndian(spanBE.Slice(48)) }; var readStructFromReadOnlySpan = new TestStruct { S0 = ReadInt16BigEndian(readOnlySpanBE), I0 = ReadInt32BigEndian(readOnlySpanBE.Slice(2)), L0 = ReadInt64BigEndian(readOnlySpanBE.Slice(6)), US0 = ReadUInt16BigEndian(readOnlySpanBE.Slice(14)), UI0 = ReadUInt32BigEndian(readOnlySpanBE.Slice(16)), UL0 = ReadUInt64BigEndian(readOnlySpanBE.Slice(20)), S1 = ReadInt16BigEndian(readOnlySpanBE.Slice(28)), I1 = ReadInt32BigEndian(readOnlySpanBE.Slice(30)), L1 = ReadInt64BigEndian(readOnlySpanBE.Slice(34)), US1 = ReadUInt16BigEndian(readOnlySpanBE.Slice(42)), UI1 = ReadUInt32BigEndian(readOnlySpanBE.Slice(44)), UL1 = ReadUInt64BigEndian(readOnlySpanBE.Slice(48)) }; Assert.Equal(s_testStruct, readStruct); Assert.Equal(s_testStruct, readStructFromReadOnlySpan); } [Fact] public void SpanWriteAndReadLittleEndianHeterogeneousStruct() { Assert.True(BitConverter.IsLittleEndian); Span<byte> spanLE = new byte[Unsafe.SizeOf<TestStruct>()]; WriteInt16LittleEndian(spanLE, s_testStruct.S0); WriteInt32LittleEndian(spanLE.Slice(2), s_testStruct.I0); WriteInt64LittleEndian(spanLE.Slice(6), s_testStruct.L0); WriteUInt16LittleEndian(spanLE.Slice(14), s_testStruct.US0); WriteUInt32LittleEndian(spanLE.Slice(16), s_testStruct.UI0); WriteUInt64LittleEndian(spanLE.Slice(20), s_testStruct.UL0); WriteInt16LittleEndian(spanLE.Slice(28), s_testStruct.S1); WriteInt32LittleEndian(spanLE.Slice(30), s_testStruct.I1); WriteInt64LittleEndian(spanLE.Slice(34), s_testStruct.L1); WriteUInt16LittleEndian(spanLE.Slice(42), s_testStruct.US1); WriteUInt32LittleEndian(spanLE.Slice(44), s_testStruct.UI1); WriteUInt64LittleEndian(spanLE.Slice(48), s_testStruct.UL1); ReadOnlySpan<byte> readOnlySpanLE = new ReadOnlySpan<byte>(spanLE.ToArray()); var readStruct = new TestStruct { S0 = ReadInt16LittleEndian(spanLE), I0 = ReadInt32LittleEndian(spanLE.Slice(2)), L0 = ReadInt64LittleEndian(spanLE.Slice(6)), US0 = ReadUInt16LittleEndian(spanLE.Slice(14)), UI0 = ReadUInt32LittleEndian(spanLE.Slice(16)), UL0 = ReadUInt64LittleEndian(spanLE.Slice(20)), S1 = ReadInt16LittleEndian(spanLE.Slice(28)), I1 = ReadInt32LittleEndian(spanLE.Slice(30)), L1 = ReadInt64LittleEndian(spanLE.Slice(34)), US1 = ReadUInt16LittleEndian(spanLE.Slice(42)), UI1 = ReadUInt32LittleEndian(spanLE.Slice(44)), UL1 = ReadUInt64LittleEndian(spanLE.Slice(48)) }; var readStructFromReadOnlySpan = new TestStruct { S0 = ReadInt16LittleEndian(readOnlySpanLE), I0 = ReadInt32LittleEndian(readOnlySpanLE.Slice(2)), L0 = ReadInt64LittleEndian(readOnlySpanLE.Slice(6)), US0 = ReadUInt16LittleEndian(readOnlySpanLE.Slice(14)), UI0 = ReadUInt32LittleEndian(readOnlySpanLE.Slice(16)), UL0 = ReadUInt64LittleEndian(readOnlySpanLE.Slice(20)), S1 = ReadInt16LittleEndian(readOnlySpanLE.Slice(28)), I1 = ReadInt32LittleEndian(readOnlySpanLE.Slice(30)), L1 = ReadInt64LittleEndian(readOnlySpanLE.Slice(34)), US1 = ReadUInt16LittleEndian(readOnlySpanLE.Slice(42)), UI1 = ReadUInt32LittleEndian(readOnlySpanLE.Slice(44)), UL1 = ReadUInt64LittleEndian(readOnlySpanLE.Slice(48)) }; Assert.Equal(s_testStruct, readStruct); Assert.Equal(s_testStruct, readStructFromReadOnlySpan); } [Fact] public void ReadingStructFieldByFieldOrReadAndReverseEndianness() { Assert.True(BitConverter.IsLittleEndian); Span<byte> spanBE = new byte[Unsafe.SizeOf<TestHelpers.TestStructExplicit>()]; var testExplicitStruct = new TestHelpers.TestStructExplicit { S0 = short.MaxValue, I0 = int.MaxValue, L0 = long.MaxValue, US0 = ushort.MaxValue, UI0 = uint.MaxValue, UL0 = ulong.MaxValue, S1 = short.MinValue, I1 = int.MinValue, L1 = long.MinValue, US1 = ushort.MinValue, UI1 = uint.MinValue, UL1 = ulong.MinValue }; WriteInt16BigEndian(spanBE, testExplicitStruct.S0); WriteInt32BigEndian(spanBE.Slice(2), testExplicitStruct.I0); WriteInt64BigEndian(spanBE.Slice(6), testExplicitStruct.L0); WriteUInt16BigEndian(spanBE.Slice(14), testExplicitStruct.US0); WriteUInt32BigEndian(spanBE.Slice(16), testExplicitStruct.UI0); WriteUInt64BigEndian(spanBE.Slice(20), testExplicitStruct.UL0); WriteInt16BigEndian(spanBE.Slice(28), testExplicitStruct.S1); WriteInt32BigEndian(spanBE.Slice(30), testExplicitStruct.I1); WriteInt64BigEndian(spanBE.Slice(34), testExplicitStruct.L1); WriteUInt16BigEndian(spanBE.Slice(42), testExplicitStruct.US1); WriteUInt32BigEndian(spanBE.Slice(44), testExplicitStruct.UI1); WriteUInt64BigEndian(spanBE.Slice(48), testExplicitStruct.UL1); Assert.Equal(56, spanBE.Length); ReadOnlySpan<byte> readOnlySpanBE = new ReadOnlySpan<byte>(spanBE.ToArray()); TestHelpers.TestStructExplicit readStructAndReverse = MemoryMarshal.Read<TestHelpers.TestStructExplicit>(spanBE); if (BitConverter.IsLittleEndian) { readStructAndReverse.S0 = ReverseEndianness(readStructAndReverse.S0); readStructAndReverse.I0 = ReverseEndianness(readStructAndReverse.I0); readStructAndReverse.L0 = ReverseEndianness(readStructAndReverse.L0); readStructAndReverse.US0 = ReverseEndianness(readStructAndReverse.US0); readStructAndReverse.UI0 = ReverseEndianness(readStructAndReverse.UI0); readStructAndReverse.UL0 = ReverseEndianness(readStructAndReverse.UL0); readStructAndReverse.S1 = ReverseEndianness(readStructAndReverse.S1); readStructAndReverse.I1 = ReverseEndianness(readStructAndReverse.I1); readStructAndReverse.L1 = ReverseEndianness(readStructAndReverse.L1); readStructAndReverse.US1 = ReverseEndianness(readStructAndReverse.US1); readStructAndReverse.UI1 = ReverseEndianness(readStructAndReverse.UI1); readStructAndReverse.UL1 = ReverseEndianness(readStructAndReverse.UL1); } var readStructFieldByField = new TestHelpers.TestStructExplicit { S0 = ReadInt16BigEndian(spanBE), I0 = ReadInt32BigEndian(spanBE.Slice(2)), L0 = ReadInt64BigEndian(spanBE.Slice(6)), US0 = ReadUInt16BigEndian(spanBE.Slice(14)), UI0 = ReadUInt32BigEndian(spanBE.Slice(16)), UL0 = ReadUInt64BigEndian(spanBE.Slice(20)), S1 = ReadInt16BigEndian(spanBE.Slice(28)), I1 = ReadInt32BigEndian(spanBE.Slice(30)), L1 = ReadInt64BigEndian(spanBE.Slice(34)), US1 = ReadUInt16BigEndian(spanBE.Slice(42)), UI1 = ReadUInt32BigEndian(spanBE.Slice(44)), UL1 = ReadUInt64BigEndian(spanBE.Slice(48)) }; TestHelpers.TestStructExplicit readStructAndReverseFromReadOnlySpan = MemoryMarshal.Read<TestHelpers.TestStructExplicit>(readOnlySpanBE); if (BitConverter.IsLittleEndian) { readStructAndReverseFromReadOnlySpan.S0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.S0); readStructAndReverseFromReadOnlySpan.I0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.I0); readStructAndReverseFromReadOnlySpan.L0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.L0); readStructAndReverseFromReadOnlySpan.US0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.US0); readStructAndReverseFromReadOnlySpan.UI0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.UI0); readStructAndReverseFromReadOnlySpan.UL0 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.UL0); readStructAndReverseFromReadOnlySpan.S1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.S1); readStructAndReverseFromReadOnlySpan.I1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.I1); readStructAndReverseFromReadOnlySpan.L1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.L1); readStructAndReverseFromReadOnlySpan.US1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.US1); readStructAndReverseFromReadOnlySpan.UI1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.UI1); readStructAndReverseFromReadOnlySpan.UL1 = ReverseEndianness(readStructAndReverseFromReadOnlySpan.UL1); } var readStructFieldByFieldFromReadOnlySpan = new TestHelpers.TestStructExplicit { S0 = ReadInt16BigEndian(readOnlySpanBE), I0 = ReadInt32BigEndian(readOnlySpanBE.Slice(2)), L0 = ReadInt64BigEndian(readOnlySpanBE.Slice(6)), US0 = ReadUInt16BigEndian(readOnlySpanBE.Slice(14)), UI0 = ReadUInt32BigEndian(readOnlySpanBE.Slice(16)), UL0 = ReadUInt64BigEndian(readOnlySpanBE.Slice(20)), S1 = ReadInt16BigEndian(readOnlySpanBE.Slice(28)), I1 = ReadInt32BigEndian(readOnlySpanBE.Slice(30)), L1 = ReadInt64BigEndian(readOnlySpanBE.Slice(34)), US1 = ReadUInt16BigEndian(readOnlySpanBE.Slice(42)), UI1 = ReadUInt32BigEndian(readOnlySpanBE.Slice(44)), UL1 = ReadUInt64BigEndian(readOnlySpanBE.Slice(48)) }; Assert.Equal(testExplicitStruct, readStructAndReverse); Assert.Equal(testExplicitStruct, readStructFieldByField); Assert.Equal(testExplicitStruct, readStructAndReverseFromReadOnlySpan); Assert.Equal(testExplicitStruct, readStructFieldByFieldFromReadOnlySpan); } private static TestStruct s_testStruct = new TestStruct { S0 = short.MaxValue, I0 = int.MaxValue, L0 = long.MaxValue, US0 = ushort.MaxValue, UI0 = uint.MaxValue, UL0 = ulong.MaxValue, S1 = short.MinValue, I1 = int.MinValue, L1 = long.MinValue, US1 = ushort.MinValue, UI1 = uint.MinValue, UL1 = ulong.MinValue }; [StructLayout(LayoutKind.Sequential)] private struct TestStruct { public short S0; public int I0; public long L0; public ushort US0; public uint UI0; public ulong UL0; public short S1; public int I1; public long L1; public ushort US1; public uint UI1; public ulong UL1; } } }
//------------------------------------------------------------------------------ // <copyright file="SoapCodeExporter.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Serialization { using System; using System.Collections; using System.IO; using System.ComponentModel; using System.Xml.Schema; using System.CodeDom; using System.CodeDom.Compiler; using System.Reflection; using System.Diagnostics; using System.Xml; using System.Security.Permissions; /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="SoapCodeExporter"]/*' /> /// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class SoapCodeExporter : CodeExporter { /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="SoapCodeExporter.SoapCodeExporter"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapCodeExporter(CodeNamespace codeNamespace) : base(codeNamespace, null, null, CodeGenerationOptions.GenerateProperties, null) {} /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="SoapCodeExporter.SoapCodeExporter1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit) : base(codeNamespace, codeCompileUnit, null, CodeGenerationOptions.GenerateProperties, null) {} /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="SoapCodeExporter.SoapCodeExporter2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeGenerationOptions options) : base(codeNamespace, codeCompileUnit, null, CodeGenerationOptions.GenerateProperties, null) {} /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.SoapCodeExporter3"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeGenerationOptions options, Hashtable mappings) : base(codeNamespace, codeCompileUnit, null, options, mappings) {} /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="XmlCodeExporter.SoapCodeExporter4"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public SoapCodeExporter(CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings) : base(codeNamespace, codeCompileUnit, codeProvider, options, mappings) {} /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="SoapCodeExporter.ExportTypeMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ExportTypeMapping(XmlTypeMapping xmlTypeMapping) { xmlTypeMapping.CheckShallow(); CheckScope(xmlTypeMapping.Scope); ExportElement(xmlTypeMapping.Accessor); } /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="SoapCodeExporter.ExportMembersMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping) { xmlMembersMapping.CheckShallow(); CheckScope(xmlMembersMapping.Scope); for (int i = 0; i < xmlMembersMapping.Count; i++) { ExportElement((ElementAccessor)xmlMembersMapping[i].Accessor); } } void ExportElement(ElementAccessor element) { ExportType(element.Mapping); } void ExportType(TypeMapping mapping) { if (mapping.IsReference) return; if (ExportedMappings[mapping] == null) { CodeTypeDeclaration codeClass = null; ExportedMappings.Add(mapping, mapping); if (mapping is EnumMapping) { codeClass = ExportEnum((EnumMapping)mapping, typeof(SoapEnumAttribute)); } else if (mapping is StructMapping) { codeClass = ExportStruct((StructMapping)mapping); } else if (mapping is ArrayMapping) { EnsureTypesExported(((ArrayMapping)mapping).Elements, null); } if (codeClass != null) { // Add [GeneratedCodeAttribute(Tool=.., Version=..)] codeClass.CustomAttributes.Add(GeneratedCodeAttribute); // Add [SerializableAttribute] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(SerializableAttribute).FullName)); if (!codeClass.IsEnum) { // Add [DebuggerStepThrough] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DebuggerStepThroughAttribute).FullName)); // Add [DesignerCategory("code")] codeClass.CustomAttributes.Add(new CodeAttributeDeclaration(typeof(DesignerCategoryAttribute).FullName, new CodeAttributeArgument[] {new CodeAttributeArgument(new CodePrimitiveExpression("code"))})); } AddTypeMetadata(codeClass.CustomAttributes, typeof(SoapTypeAttribute), mapping.TypeDesc.Name, Accessor.UnescapeName(mapping.TypeName), mapping.Namespace, mapping.IncludeInSchema); ExportedClasses.Add(mapping, codeClass); } } } CodeTypeDeclaration ExportStruct(StructMapping mapping) { if (mapping.TypeDesc.IsRoot) { ExportRoot(mapping, typeof(SoapIncludeAttribute)); return null; } if (!mapping.IncludeInSchema) return null; string className = mapping.TypeDesc.Name; string baseName = mapping.TypeDesc.BaseTypeDesc == null ? string.Empty : mapping.TypeDesc.BaseTypeDesc.Name; CodeTypeDeclaration codeClass = new CodeTypeDeclaration(className); codeClass.IsPartial = CodeProvider.Supports(GeneratorSupport.PartialTypes); codeClass.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); CodeNamespace.Types.Add(codeClass); if (baseName != null && baseName.Length > 0) { codeClass.BaseTypes.Add(baseName); } else AddPropertyChangedNotifier(codeClass); codeClass.TypeAttributes |= TypeAttributes.Public; if (mapping.TypeDesc.IsAbstract) codeClass.TypeAttributes |= TypeAttributes.Abstract; CodeExporter.AddIncludeMetadata(codeClass.CustomAttributes, mapping, typeof(SoapIncludeAttribute)); if (GenerateProperties) { for (int i = 0; i < mapping.Members.Length; i++) { ExportProperty(codeClass, mapping.Members[i], mapping.Scope); } } else { for (int i = 0; i < mapping.Members.Length; i++) { ExportMember(codeClass, mapping.Members[i]); } } for (int i = 0; i < mapping.Members.Length; i++) { EnsureTypesExported(mapping.Members[i].Elements, null); } if (mapping.BaseMapping != null) ExportType(mapping.BaseMapping); ExportDerivedStructs(mapping); CodeGenerator.ValidateIdentifiers(codeClass); return codeClass; } [PermissionSet(SecurityAction.InheritanceDemand, Name="FullTrust")] internal override void ExportDerivedStructs(StructMapping mapping) { for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) ExportType(derived); } /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="SoapCodeExporter.AddMappingMetadata"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddMappingMetadata(CodeAttributeDeclarationCollection metadata, XmlMemberMapping member, bool forceUseMemberName) { AddMemberMetadata(metadata, member.Mapping, forceUseMemberName); } /// <include file='doc\SoapCodeExporter.uex' path='docs/doc[@for="SoapCodeExporter.AddMappingMetadata1"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void AddMappingMetadata(CodeAttributeDeclarationCollection metadata, XmlMemberMapping member) { AddMemberMetadata(metadata, member.Mapping, false); } void AddElementMetadata(CodeAttributeDeclarationCollection metadata, string elementName, TypeDesc typeDesc, bool isNullable) { CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(SoapElementAttribute).FullName); if (elementName != null) { attribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(elementName))); } if (typeDesc != null && typeDesc.IsAmbiguousDataType) { attribute.Arguments.Add(new CodeAttributeArgument("DataType", new CodePrimitiveExpression(typeDesc.DataType.Name))); } if (isNullable) { attribute.Arguments.Add(new CodeAttributeArgument("IsNullable", new CodePrimitiveExpression(true))); } metadata.Add(attribute); } void AddMemberMetadata(CodeAttributeDeclarationCollection metadata, MemberMapping member, bool forceUseMemberName) { if (member.Elements.Length == 0) return; ElementAccessor element = member.Elements[0]; TypeMapping mapping = (TypeMapping)element.Mapping; string elemName = Accessor.UnescapeName(element.Name); bool sameName = ((elemName == member.Name) && !forceUseMemberName); if (!sameName || mapping.TypeDesc.IsAmbiguousDataType || element.IsNullable) { AddElementMetadata(metadata, sameName ? null : elemName, mapping.TypeDesc.IsAmbiguousDataType ? mapping.TypeDesc : null, element.IsNullable); } } void ExportMember(CodeTypeDeclaration codeClass, MemberMapping member) { string fieldType = member.GetTypeName(CodeProvider); CodeMemberField field = new CodeMemberField(fieldType, member.Name); field.Attributes = (field.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; field.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); codeClass.Members.Add(field); AddMemberMetadata(field.CustomAttributes, member, false); if (member.CheckSpecified != SpecifiedAccessor.None) { field = new CodeMemberField(typeof(bool).FullName, member.Name + "Specified"); field.Attributes = (field.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public; field.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(SoapIgnoreAttribute).FullName); field.CustomAttributes.Add(attribute); codeClass.Members.Add(field); } } void ExportProperty(CodeTypeDeclaration codeClass, MemberMapping member, CodeIdentifiers memberScope) { string fieldName = memberScope.AddUnique(CodeExporter.MakeFieldName(member.Name), member); string fieldType = member.GetTypeName(CodeProvider); // need to create a private field CodeMemberField field = new CodeMemberField(fieldType, fieldName); field.Attributes = MemberAttributes.Private; codeClass.Members.Add(field); CodeMemberProperty prop = CreatePropertyDeclaration(field, member.Name, fieldType); prop.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); AddMemberMetadata(prop.CustomAttributes, member, false); codeClass.Members.Add(prop); if (member.CheckSpecified != SpecifiedAccessor.None) { field = new CodeMemberField(typeof(bool).FullName, fieldName + "Specified"); field.Attributes = MemberAttributes.Private; codeClass.Members.Add(field); prop = CreatePropertyDeclaration(field, member.Name + "Specified", typeof(bool).FullName); prop.Comments.Add(new CodeCommentStatement(Res.GetString(Res.XmlRemarks), true)); CodeAttributeDeclaration attribute = new CodeAttributeDeclaration(typeof(SoapIgnoreAttribute).FullName); prop.CustomAttributes.Add(attribute); codeClass.Members.Add(prop); } } internal override void EnsureTypesExported(Accessor[] accessors, string ns) { if (accessors == null) return; for (int i = 0; i < accessors.Length; i++) ExportType(accessors[i].Mapping); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: This class will encapsulate an uint and ** provide an Object representation of it. ** ** ===========================================================*/ using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics.Contracts; namespace System { // * Wrapper for unsigned 32 bit integers. [CLSCompliant(false)] [System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)] public struct UInt32 : IComparable, IFormattable, IComparable<UInt32>, IEquatable<UInt32>, IConvertible { private uint _value; public const uint MaxValue = (uint)0xffffffff; public const uint MinValue = 0U; // 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 UInt32, this method throws an ArgumentException. // public int CompareTo(Object value) { if (value == null) { return 1; } if (value is UInt32) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. uint i = (uint)value; if (_value < i) return -1; if (_value > i) return 1; return 0; } throw new ArgumentException(SR.Arg_MustBeUInt32); } public int CompareTo(UInt32 value) { // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. if (_value < value) return -1; if (_value > value) return 1; return 0; } public override bool Equals(Object obj) { if (!(obj is UInt32)) { return false; } return _value == ((UInt32)obj)._value; } [NonVersionable] public bool Equals(UInt32 obj) { return _value == obj; } // The absolute value of the int contained. public override int GetHashCode() { return ((int)_value); } // The base 10 representation of the number with no extra padding. public override String ToString() { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt32(_value, null, null); } public String ToString(IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt32(_value, null, provider); } public String ToString(String format) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt32(_value, format, null); } public String ToString(String format, IFormatProvider provider) { Contract.Ensures(Contract.Result<String>() != null); return FormatProvider.FormatUInt32(_value, format, provider); } [CLSCompliant(false)] public static uint Parse(String s) { return FormatProvider.ParseUInt32(s, NumberStyles.Integer, null); } internal static void ValidateParseStyleInteger(NumberStyles style) { // Check for undefined flags if ((style & Decimal.InvalidNumberStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, nameof(style)); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { throw new ArgumentException(SR.Arg_InvalidHexStyle); } } } [CLSCompliant(false)] public static uint Parse(String s, NumberStyles style) { ValidateParseStyleInteger(style); return FormatProvider.ParseUInt32(s, style, null); } [CLSCompliant(false)] public static uint Parse(String s, IFormatProvider provider) { return FormatProvider.ParseUInt32(s, NumberStyles.Integer, provider); } [CLSCompliant(false)] public static uint Parse(String s, NumberStyles style, IFormatProvider provider) { ValidateParseStyleInteger(style); return FormatProvider.ParseUInt32(s, style, provider); } [CLSCompliant(false)] public static bool TryParse(String s, out UInt32 result) { return FormatProvider.TryParseUInt32(s, NumberStyles.Integer, null, out result); } [CLSCompliant(false)] public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out UInt32 result) { ValidateParseStyleInteger(style); return FormatProvider.TryParseUInt32(s, style, provider, out result); } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt32; } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(_value); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return _value; } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(_value); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(String.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Globalization; using System.Threading; using Microsoft.Practices.Prism.Properties; using Microsoft.Practices.ServiceLocation; namespace Microsoft.Practices.Prism.Regions { /// <summary> /// Class that creates a fluent interface for the <see cref="IRegionManager"/> class, with respect to /// adding views to regions (View Injection pattern), registering view types to regions (View Discovery pattern) /// </summary> public static class RegionManagerExtensions { /// <summary> /// Add a view to the Views collection of a Region. Note that the region must already exist in this regionmanager. /// </summary> /// <param name="regionManager">The regionmanager that this extension method effects.</param> /// <param name="regionName">The name of the region to add a view to</param> /// <param name="view">The view to add to the views collection</param> /// <returns>The RegionManager, to easily add several views. </returns> public static IRegionManager AddToRegion(this IRegionManager regionManager, string regionName, object view) { if (regionManager == null) throw new ArgumentNullException("regionManager"); if (!regionManager.Regions.ContainsRegionWithName(regionName)) { throw new ArgumentException( string.Format(Thread.CurrentThread.CurrentCulture, Resources.RegionNotFound, regionName), "regionName"); } IRegion region = regionManager.Regions[regionName]; return region.Add(view); } /// <summary> /// Associate a view with a region, by registering a type. When the region get's displayed /// this type will be resolved using the ServiceLocator into a concrete instance. The instance /// will be added to the Views collection of the region /// </summary> /// <param name="regionManager">The regionmanager that this extension method effects.</param> /// <param name="regionName">The name of the region to associate the view with.</param> /// <param name="viewType">The type of the view to register with the </param> /// <returns>The regionmanager, for adding several views easily</returns> public static IRegionManager RegisterViewWithRegion(this IRegionManager regionManager, string regionName, Type viewType) { var regionViewRegistry = ServiceLocator.Current.GetInstance<IRegionViewRegistry>(); regionViewRegistry.RegisterViewWithRegion(regionName, viewType); return regionManager; } /// <summary> /// Associate a view with a region, using a delegate to resolve a concreate instance of the view. /// When the region get's displayed, this delelgate will be called and the result will be added to the /// views collection of the region. /// </summary> /// <param name="regionManager">The regionmanager that this extension method effects.</param> /// <param name="regionName">The name of the region to associate the view with.</param> /// <param name="getContentDelegate">The delegate used to resolve a concreate instance of the view.</param> /// <returns>The regionmanager, for adding several views easily</returns> public static IRegionManager RegisterViewWithRegion(this IRegionManager regionManager, string regionName, Func<object> getContentDelegate) { var regionViewRegistry = ServiceLocator.Current.GetInstance<IRegionViewRegistry>(); regionViewRegistry.RegisterViewWithRegion(regionName, getContentDelegate); return regionManager; } /// <summary> /// Adds a region to the regionmanager with the name received as argument. /// </summary> /// <param name="regionCollection">The regionmanager's collection of regions.</param> /// <param name="regionName">The name to be given to the region.</param> /// <param name="region">The region to be added to the regionmanager.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="region"/> or <paramref name="regionCollection"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="regionName"/> and <paramref name="region"/>'s name do not match and the <paramref name="region"/> <see cref="IRegion.Name"/> is not <see langword="null"/>.</exception> public static void Add(this IRegionCollection regionCollection, string regionName, IRegion region) { if (region == null) throw new ArgumentNullException("region"); if (regionCollection == null) throw new ArgumentNullException("regionCollection"); if (region.Name != null && region.Name != regionName) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.RegionManagerWithDifferentNameException, region.Name, regionName), "regionName"); } if (region.Name == null) { region.Name = regionName; } regionCollection.Add(region); } /// <summary> /// Navigates the specified region manager. /// </summary> /// <param name="regionManager">The regionmanager that this extension method effects.</param> /// <param name="regionName">The name of the region to call Navigate on.</param> /// <param name="source">The URI of the content to display.</param> /// <param name="navigationCallback">The navigation callback.</param> public static void RequestNavigate(this IRegionManager regionManager, string regionName, Uri source, Action<NavigationResult> navigationCallback) { if (regionManager == null) throw new ArgumentNullException("regionManager"); if (navigationCallback == null) throw new ArgumentNullException("navigationCallback"); if (regionManager.Regions.ContainsRegionWithName(regionName)) { regionManager.Regions[regionName].RequestNavigate(source, navigationCallback); } else { navigationCallback(new NavigationResult(new NavigationContext(null, source), false)); } } /// <summary> /// Navigates the specified region manager. /// </summary> /// <param name="regionManager">The regionmanager that this extension method effects.</param> /// <param name="regionName">The name of the region to call Navigate on.</param> /// <param name="source">The URI of the content to display.</param> public static void RequestNavigate(this IRegionManager regionManager, string regionName, Uri source) { RequestNavigate(regionManager, regionName, source, nr => { }); } /// <summary> /// Navigates the specified region manager. /// </summary> /// <param name="regionManager">The regionmanager that this extension method effects.</param> /// <param name="regionName">The name of the region to call Navigate on.</param> /// <param name="source">The URI of the content to display.</param> /// <param name="navigationCallback">The navigation callback.</param> public static void RequestNavigate(this IRegionManager regionManager, string regionName, string source, Action<NavigationResult> navigationCallback) { if (source == null) throw new ArgumentNullException("source"); RequestNavigate(regionManager, regionName, new Uri(source, UriKind.RelativeOrAbsolute), navigationCallback); } /// <summary> /// Navigates the specified region manager. /// </summary> /// <param name="regionManager">The regionmanager that this extension method effects.</param> /// <param name="regionName">The name of the region to call Navigate on.</param> /// <param name="source">The URI of the content to display.</param> public static void RequestNavigate(this IRegionManager regionManager, string regionName, string source) { RequestNavigate(regionManager, regionName, source, nr => { }); } /// <summary> /// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target Uri, passing a navigation callback and an instance of NavigationParameters, which holds a collection of object parameters. /// </summary> /// <param name="regionManager">The IRegionManager instance that is extended by this method.</param> /// <param name="regionName">The name of the region where the navigation will occur.</param> /// <param name="target">A Uri that represents the target where the region will navigate.</param> /// <param name="navigationCallback">The navigation callback that will be executed after the navigation is completed.</param> /// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param> public static void RequestNavigate(this IRegionManager regionManager, string regionName, Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { if (regionManager == null) { return; } if (regionManager.Regions.ContainsRegionWithName(regionName)) { regionManager.Regions[regionName].RequestNavigate(target, navigationCallback, navigationParameters); } } /// <summary> /// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target string, passing a navigation callback and an instance of NavigationParameters, which holds a collection of object parameters. /// </summary> /// <param name="regionManager">The IRegionManager instance that is extended by this method.</param> /// <param name="regionName">The name of the region where the navigation will occur.</param> /// <param name="target">A string that represents the target where the region will navigate.</param> /// <param name="navigationCallback">The navigation callback that will be executed after the navigation is completed.</param> /// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param> public static void RequestNavigate(this IRegionManager regionManager, string regionName, string target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { RequestNavigate(regionManager, regionName, new Uri(target, UriKind.RelativeOrAbsolute), navigationCallback, navigationParameters); } /// <summary> /// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target Uri, passing an instance of NavigationParameters, which holds a collection of object parameters. /// </summary> /// <param name="regionManager">The IRegionManager instance that is extended by this method.</param> /// <param name="regionName">The name of the region where the navigation will occur.</param> /// <param name="target">A Uri that represents the target where the region will navigate.</param> /// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param> public static void RequestNavigate(this IRegionManager regionManager, string regionName, Uri target, NavigationParameters navigationParameters) { RequestNavigate(regionManager, regionName, target, nr => { }, navigationParameters); } /// <summary> /// This method allows an IRegionManager to locate a specified region and navigate in it to the specified target string, passing an instance of NavigationParameters, which holds a collection of object parameters. /// </summary> /// <param name="regionManager">The IRegionManager instance that is extended by this method.</param> /// <param name="regionName">The name of the region where the navigation will occur.</param> /// <param name="target">A string that represents the target where the region will navigate.</param> /// <param name="navigationParameters">An instance of NavigationParameters, which holds a collection of object parameters.</param> public static void RequestNavigate(this IRegionManager regionManager, string regionName, string target, NavigationParameters navigationParameters) { RequestNavigate(regionManager, regionName, new Uri(target, UriKind.RelativeOrAbsolute), nr => { }, navigationParameters); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Wilson.Companies.Core.Entities; using Wilson.Companies.Data.DataAccess; using Wilson.Web.Areas.Admin.Models.ControlPanelViewModels; using Wilson.Web.Events.Interfaces; namespace Wilson.Web.Areas.Admin.Controllers { public class ControlPanelController : AdminBaseController { private readonly UserManager<ApplicationUser> userManager; private readonly RoleManager<ApplicationRole> roleManager; private ILogger logger; public ControlPanelController( ICompanyWorkData companyWorkData, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager, ILoggerFactory loggerFactory, IMapper mapperr, IEventsFactory eventsFactory) : base(companyWorkData, mapperr, eventsFactory) { this.userManager = userManager; this.roleManager = roleManager; this.logger = loggerFactory.CreateLogger<ControlPanelController>(); } // // GET: /Admin/Index [HttpGet] public IActionResult Index() { return View(); } // // GET: /Admin/Register [HttpGet] public async Task<IActionResult> Register() { return View(await RegisterViewModel.CreateAsync(this.roleManager, this.CompanyWorkData)); } // // POST: /Admin/Register [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model) { if (!ModelState.IsValid) { return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData)); } var settings = await this.GetSettings(); if (settings == null && string.IsNullOrEmpty(settings.HomeCompanyId) && !settings.IsDatabaseInstalled) { ModelState.AddModelError( string.Empty, "Application settings can not be found. Try again and if the problem persist contact the administrator."); ModelState.Values.ToList() .ForEach(m => m.Errors.ToList() .ForEach(e => this.logger.LogError(2, e.ErrorMessage))); return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData)); } var role = await this.roleManager.FindByNameAsync(model.User.ApplicationRoleName); if (role == null) { ModelState.AddModelError(nameof(model.User.ApplicationRoleName), "Application role not found!"); ModelState.Values.ToList() .ForEach(m => m.Errors.ToList() .ForEach(e => this.logger.LogError(2, e.ErrorMessage))); return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData)); } var employee = await this.CompanyWorkData.Employees.GetById(model.EmployeeId); if (employee == null) { ModelState.AddModelError( string.Empty, "Employee not found. Please try again."); ModelState.Values.ToList() .ForEach(m => m.Errors.ToList() .ForEach(e => this.logger.LogError(2, e.ErrorMessage))); return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData)); } // Create user from the employee. var user = ApplicationUser.Create(employee, employee.Email); var result = await this.userManager.CreateAsync(user, model.User.Password); if (!result.Succeeded) { this.logger.LogError(2, "Failed to create user."); result.Errors.ToList().ForEach(e => this.logger.LogError(2, $"{e.Code} -- {e.Description}")); this.AddErrors(result); return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData)); } var addToRoleResult = await userManager.AddToRoleAsync(user, role.Name); if (!addToRoleResult.Succeeded) { this.logger.LogError(2, $"Failed to add user to role. {role.Name}"); addToRoleResult.Errors.ToList().ForEach(e => this.logger.LogError(2, $"{e.Code} -- {e.Description}")); this.AddErrors(addToRoleResult); return View(await RegisterViewModel.ReBuildAsync(model, this.roleManager, this.userManager, this.CompanyWorkData)); } this.logger.LogInformation(3, "Admin created new User account with password."); return RedirectToAction(nameof(ShowAllUsers)); } // // GET: /Admin/ShowAllUsers [HttpGet] public async Task<IActionResult> ShowAllUsers() { var users = await this.CompanyWorkData.Users.GetAllAsync(); var models = this.Mapper.Map<IEnumerable<ApplicationUser>, IEnumerable<ShortUserViewModel>>(users); return View(models); } // // GET: /Admin/EditUser [HttpGet] public async Task<IActionResult> EditUser(string id) { var user = await this.CompanyWorkData.Users.GetById(id); if (user == null) { this.logger.LogError(2, $"User with Id {id} not found."); return NotFound($"User with Id {id} not found."); } return View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper)); } // // POST: /Admin/EditUser [HttpPost] public async Task<IActionResult> EditUser(EditUserViewModel model) { var user = await this.userManager.FindByIdAsync(model.Id); if (user == null) { this.logger.LogError(2, $"User with Id {model.Id} not found."); return NotFound($"User with Id {model.Id} not found."); } if (!ModelState.IsValid) { return View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper)); } if (!(await this.userManager.IsInRoleAsync(user, model.ApplicationRoleName))) { var newRole = await this.roleManager.FindByNameAsync(model.ApplicationRoleName); if (newRole == null) { ModelState.AddModelError( string.Empty, $"Application role {model.ApplicationRoleName} not found."); ModelState.Values.ToList() .ForEach(m => m.Errors.ToList() .ForEach(e => this.logger.LogError(2, e.ErrorMessage))); return View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper)); } var oldRoles = await this.userManager.GetRolesAsync(user); await this.userManager.RemoveFromRolesAsync(user, oldRoles); await this.userManager.AddToRoleAsync(user, newRole.Name); } user.UpdatePhone(model.PhoneNumber); var result = await this.userManager.UpdateAsync(user); if (!result.Succeeded) { this.AddErrors(result); return View(await EditUserViewModel.Create(user, this.roleManager, this.userManager, this.Mapper)); } this.logger.LogInformation(3, string.Format("Admin edited User with Id {0}.", user.Id)); return RedirectToAction(nameof(ShowAllUsers)); } // // POST: /Admin/ActivateUser [HttpPost] public async Task<IActionResult> ActivateUser(string id) { var user = await this.CompanyWorkData.Users.GetById(id); if (user == null) { this.logger.LogError(2, $"User with Id {id} not found."); return NotFound($"User with Id {id} not found."); } user.Activate(); await this.CompanyWorkData.CompleteAsync(); this.logger.LogInformation(3, string.Format("Admin activated User with Id {0}.", id)); return RedirectToAction(nameof(ShowAllUsers)); } // // POST: /Admin/DeactivateUser [HttpPost] public async Task<IActionResult> DeactivateUser(string id) { var user = await this.CompanyWorkData.Users.GetById(id); if (user == null) { this.logger.LogError(2, $"User with Id {id} not found."); return NotFound($"User with Id {id} not found."); } var isAdmin = await this.userManager.IsInRoleAsync(user, Constants.Roles.Administrator); if (isAdmin) { return BadRequest($"Can not deactivate Administrator."); } user.Deactivate(); await this.CompanyWorkData.CompleteAsync(); this.logger.LogInformation(3, string.Format("Admin deactivated User with Id {0}.", id.ToString())); return RedirectToAction(nameof(ShowAllUsers)); } } }
// 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.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Threading; using System.Windows.Forms; using System.Runtime.InteropServices; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.CoreServices; using OpenLiveWriter.CoreServices.UI; using OpenLiveWriter.Localization; using OpenLiveWriter.Interop.Windows; using Timer=System.Windows.Forms.Timer; namespace OpenLiveWriter.ApplicationFramework.Skinning { [Obsolete("not needed", true)] public class FramelessManager : IFrameManager { private static event EventHandler AlwaysShowFrameChanged; private SatelliteApplicationForm _form; private UITheme _uiTheme; private MinMaxClose minMaxClose; private SizeBorderHitTester _sizeBorderHitTester = new SizeBorderHitTester(new Size(15, 15), new Size(16,16)); private ColorizedResources res = ColorizedResources.Instance; private Timer _mouseFrameTimer; private int _activationCount = 0; private bool _inMenuLoop; private bool _forceFrame = false; private bool _alwaysShowFrame; private Size _overrideSize = Size.Empty; private Command _commandShowMenu; private const int SYSICON_TOP = 6; private const int SYSICON_LEFT = 5; const int SIZE_RESTORED =0; const int SIZE_MINIMIZED =1; const int SIZE_MAXIMIZED =2; const int SIZE_MAXSHOW =3; const int SIZE_MAXHIDE =4; public FramelessManager(SatelliteApplicationForm form) { _alwaysShowFrame = AlwaysShowFrame; _form = form; minMaxClose = new MinMaxClose(); minMaxClose.Anchor = AnchorStyles.Top | AnchorStyles.Right; _form.Controls.Add(minMaxClose); _mouseFrameTimer = new Timer(); _mouseFrameTimer.Interval = 100; _mouseFrameTimer.Tick += new EventHandler(_mouseFrameTimer_Tick); _commandShowMenu = new Command(CommandId.ShowMenu); _commandShowMenu.Latched = AlwaysShowFrame; _commandShowMenu.Execute += new EventHandler(commandShowMenu_Execute); // JJA: no longer provide a frameless option //ApplicationManager.CommandManager.Add(_commandShowMenu); ColorizedResources.GlobalColorizationChanged += new EventHandler(ColorizedResources_GlobalColorizationChanged); _form.Layout += new LayoutEventHandler(_form_Layout); _form.Activated += new EventHandler(_form_Activated); _form.Deactivate += new EventHandler(_form_Deactivate); _form.SizeChanged += new EventHandler(_form_SizeChanged); _form.MouseDown +=new MouseEventHandler(_form_MouseDown); _form.DoubleClick +=new EventHandler(_form_DoubleClick); _form.Disposed += new EventHandler(_form_Disposed); AlwaysShowFrameChanged += new EventHandler(FramelessManager_AlwaysShowFrameChanged); _uiTheme = new UITheme(form); } private void commandShowMenu_Execute(object sender, EventArgs e) { AlwaysShowFrame = !_commandShowMenu.Latched; } public bool WndProc(ref Message m) { switch ((uint)m.Msg) { case 0x031E: // WM_DWMCOMPOSITIONCHANGED { // Aero was enabled or disabled. Force the UI to switch to // the glass or non-glass style. DisplayHelper.IsCompositionEnabled(true); ColorizedResources.FireColorChanged(); break; } case WM.SIZE: { uint size = (uint) m.LParam.ToInt32(); switch (m.WParam.ToInt32()) { case SIZE_RESTORED: _overrideSize = new Size((int) (size & 0xFFFF), (int) (size >> 16)); UpdateFrame(); break; case SIZE_MAXIMIZED: UpdateFrame(); break; case SIZE_MAXHIDE: case SIZE_MINIMIZED: case SIZE_MAXSHOW: break; } break; } case WM.NCHITTEST: { // Handling this message gives us an easy way to make // areas of the client region behave as elements of the // non-client region. For example, the edges of the form // can act as sizers. Point p = _form.PointToClient(new Point(m.LParam.ToInt32())); if (_form.ClientRectangle.Contains(p)) { // only override the behavior if the mouse is within the client area if (Frameless) { int result = _sizeBorderHitTester.Test(_form.ClientSize, p); if (result != -1) { m.Result = new IntPtr(result); return true; } } if ( !PointInSystemIcon(p) ) { // The rest of the visible areas of the form act like // the caption (click and drag to move, double-click to // maximize/restore). m.Result = new IntPtr(HT.CAPTION); return true; } } break; } case WM.ENTERMENULOOP: if ( Control.MouseButtons == MouseButtons.None ) { _inMenuLoop = true; ForceFrame = true; } break; case WM.EXITMENULOOP: if (_inMenuLoop) { _inMenuLoop = false; if (!IsMouseInFrame()) ForceFrame = false; else _mouseFrameTimer.Start(); } break; } return false; } private bool PointInSystemIcon(Point clientPoint) { return false; //return new Rectangle(SYSICON_LEFT, SYSICON_TOP, res.LogoImage.Width, res.LogoImage.Height).Contains(clientPoint) ; } private bool ForceFrame { get { return _forceFrame; } set { if (_forceFrame != value) { _forceFrame = value; UpdateFrame(); _form.Update(); } } } public static bool AlwaysShowFrame { // JJA: no longer provide a frameless option get { return true; } //get { return ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("Appearance").GetBoolean(SatelliteApplicationForm.SHOW_FRAME_KEY, false); } set { ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("Appearance").SetBoolean(SatelliteApplicationForm.SHOW_FRAME_KEY, value); if (AlwaysShowFrameChanged != null) AlwaysShowFrameChanged(null, EventArgs.Empty); } } public bool Frameless { // JJA: no longer provide a frameless option get { return false; } //get { return !_alwaysShowFrame && !_forceFrame && _form.WindowState != FormWindowState.Maximized && !_uiTheme.ForceShowFrame; } } private void _form_Layout(object sender, LayoutEventArgs e) { // align the min/max/close button to the top-right of the form minMaxClose.Left = _form.ClientSize.Width - minMaxClose.Width - 6; minMaxClose.Top = 0; } private void UpdateFrame() { minMaxClose.Visible = Frameless; if (Frameless) { SetRoundedRegion(_form, _overrideSize); _wasFrameless = true ; } else { // don't set a null region if we were never frameless // to begin with (eliminates the black corners that // appear when you set the region ot null) if ( _wasFrameless ) _form.Region = null; } _form.UpdateFramelessState(Frameless) ; _form.PerformLayout(); _form.Invalidate(false); } private bool _wasFrameless = false ; public static void SetRoundedRegion(Form form, Size overrideSize) { int width, height; if (overrideSize == Size.Empty) { width = form.ClientSize.Width; height = form.ClientSize.Height; } else { width = overrideSize.Width; height = overrideSize.Height; } Region r = new Region(new Rectangle(3, 0, width - 6, height)); r.Union(new Rectangle(2, 1, width - 4, height - 2)); r.Union(new Rectangle(1, 2, width - 2, height - 4)); r.Union(new Rectangle(0, 3, width, height - 6)); RECT rect = new RECT(); User32.GetWindowRect(form.Handle, ref rect); Point windowScreenPos = RectangleHelper.Convert(rect).Location; Point clientScreenPos = form.PointToScreen(new Point(0, 0)); r.Translate(clientScreenPos.X - windowScreenPos.X, clientScreenPos.Y - windowScreenPos.Y); form.Region = r; } public void PaintBackground(PaintEventArgs e) { //using (new QuickTimer("Paint frameless app window. Clip: " + e.ClipRectangle.ToString())) { Graphics g = e.Graphics; g.InterpolationMode = InterpolationMode.Low; g.CompositingMode = CompositingMode.SourceCopy; Color light = res.FrameGradientLight; int width = _form.ClientSize.Width; int height = _form.ClientSize.Height; using (Brush b = new SolidBrush(light)) g.FillRectangle(b, 0, 0, width, height); // border if ( Frameless ) res.AppOutlineBorder.DrawBorder(g, _form.ClientRectangle); g.CompositingMode = CompositingMode.SourceOver; g.CompositingQuality = CompositingQuality.HighSpeed; Rectangle footerRect = new Rectangle( 0, _form.ClientSize.Height - _form.DockPadding.Bottom, _form.ClientSize.Width, _form.DockPadding.Bottom); if (e.ClipRectangle.IntersectsWith(footerRect)) res.AppFooterBackground.DrawBorder(g, footerRect); //GraphicsHelper.TileFillUnscaledImageHorizontally(g, res.FooterBackground, footerRect); Rectangle toolbarRect = new Rectangle( _form.DockPadding.Left, _form.DockPadding.Top, _form.ClientSize.Width - _form.DockPadding.Left - _form.DockPadding.Right, res.ToolbarBorder.MinimumHeight ); if (e.ClipRectangle.IntersectsWith(toolbarRect)) { res.ToolbarBorder.DrawBorder(g, toolbarRect); } // draw vapor #if VAPOR Rectangle appVapor = AppVaporRectangle; if (e.ClipRectangle.IntersectsWith(appVapor)) { if (appVapor.Width == res.VaporImage.Width) { // NOTE: Try to bring Gdi painting back for performance (check with Joe on this) //GdiPaint.BitBlt(g, minMaxClose.Faded ? res.VaporImageFadedHbitmap : res.VaporImageHbitmap, new Rectangle(Point.Empty, appVapor.Size), appVapor.Location); g.DrawImage(minMaxClose.Faded ? res.VaporImageFaded : res.VaporImage, appVapor); } else { g.DrawImage(minMaxClose.Faded ? res.VaporImageFaded : res.VaporImage, appVapor); } } #endif g.CompositingQuality = CompositingQuality.HighQuality; /* if (Frameless) { // gripper g.DrawImage(res.GripperImage, width - 15, height - 15, res.GripperImage.Width, res.GripperImage.Height); // draw window caption //g.DrawIcon(ApplicationEnvironment.ProductIconSmall, 5, 6); g.DrawImage(res.LogoImage, SYSICON_LEFT, SYSICON_TOP, res.LogoImage.Width, res.LogoImage.Height); // determine caption font NONCLIENTMETRICS metrics = new NONCLIENTMETRICS(); metrics.cbSize = Marshal.SizeOf(metrics); User32.SystemParametersInfo(SPI.GETNONCLIENTMETRICS, 0, ref metrics, 0); using ( Font font = new Font( metrics.lfCaptionFont.lfFaceName, Math.Min(-metrics.lfCaptionFont.lfHeight, 13), (metrics.lfCaptionFont.lfItalic > 0 ? FontStyle.Italic : FontStyle.Regular) | (metrics.lfCaptionFont.lfWeight >= 700 ? FontStyle.Bold : FontStyle.Regular), GraphicsUnit.World)) { using ( Brush brush = new SolidBrush(!minMaxClose.Faded ? Color.White : Color.FromArgb(140, Color.White)) ) { // draw caption g.DrawString( ApplicationEnvironment.ProductName, font, brush, 22, 5 ); } } } */ } } private void _form_Activated(object sender, EventArgs e) { if (++_activationCount == 1) { minMaxClose.Faded = false; _form.Invalidate(false); } } private void _form_Deactivate(object sender, EventArgs e) { if (--_activationCount == 0) { minMaxClose.Faded = true; _form.Invalidate(false); } } private void _mouseFrameTimer_Tick(object sender, EventArgs e) { if (_inMenuLoop) { _mouseFrameTimer.Stop(); } else if (!IsMouseInFrame()) { ForceFrame = false; _mouseFrameTimer.Stop(); } } private bool IsMouseInFrame() { return false; /* RECT rect = new RECT(); User32.GetWindowRect(_form.Handle, ref rect); Rectangle windowRect = RectangleHelper.Convert(rect); return windowRect.Contains(Control.MousePosition) && !_form.ClientRectangle.Contains(_form.PointToClient(Control.MousePosition)); */ } private void _form_SizeChanged(object sender, EventArgs e) { _overrideSize = Size.Empty; } private void ColorizedResources_GlobalColorizationChanged(object sender, EventArgs e) { try { if ( ControlHelper.ControlCanHandleInvoke(_form) ) { _form.BeginInvoke(new ThreadStart(RefreshColors)); } } catch (Exception ex) { Trace.Fail(ex.ToString()); } } private void RefreshColors() { ColorizedResources colRes = ColorizedResources.Instance; colRes.Refresh(); colRes.FireColorizationChanged(); User32.SendMessage(_form.Handle, WM.NCPAINT, new UIntPtr(1), IntPtr.Zero ) ; _form.Invalidate(true); _form.Update(); } private void _form_Disposed(object sender, EventArgs e) { ColorizedResources.GlobalColorizationChanged -= new EventHandler(ColorizedResources_GlobalColorizationChanged); AlwaysShowFrameChanged -= new EventHandler(FramelessManager_AlwaysShowFrameChanged); } private void FramelessManager_AlwaysShowFrameChanged(object sender, EventArgs e) { if (_form.IsDisposed) { return; } if (_form.InvokeRequired) { _form.BeginInvoke(new EventHandler(FramelessManager_AlwaysShowFrameChanged), new object[] {sender, e}); return; } _alwaysShowFrame = ApplicationEnvironment.PreferencesSettingsRoot.GetSubSettings("Appearance").GetBoolean(SatelliteApplicationForm.SHOW_FRAME_KEY, false); UpdateFrame(); _form.Update(); _commandShowMenu.Latched = _alwaysShowFrame; Command commandMenu = ApplicationManager.CommandManager.Get(CommandId.Menu); if (commandMenu != null) commandMenu.On = !_alwaysShowFrame; } private void _hideFrame_Click(object sender, EventArgs e) { AlwaysShowFrame = false; } /// <summary> /// Prevents the vapor from appearing faded while the mini form is visible. /// This should only be used if the mini form will disappear when it loses /// focus (deactivated), otherwise the main form will be painted as activated /// even when it may not be. /// </summary> public void AddOwnedForm(Form f) { _form_Activated(this, EventArgs.Empty); } /// <summary> /// Restore normal painting. /// </summary> public void RemoveOwnedForm(Form f) { _form_Deactivate(this, EventArgs.Empty); } private void _form_MouseDown(object sender, MouseEventArgs e) { /* JJA: Couldn't get both single and double-click working (would almost never * get the second click, presumably because the menu was up). We have decided * for the time being that double-click to close is a more important gesture * (for what it is worth, Windows Media Player also supports ONLY double-click * and not single-click). If we want to support both it is probably possible * however it will take some WndProc hacking. * if ( PointInSystemIcon( _form.PointToClient(Control.MousePosition) ) ) { // handle single-click Point menuPoint = _form.PointToScreen(new Point(0, _form.DockPadding.Top)) ; IntPtr hSystemMenu = User32.GetSystemMenu(_form.Handle, false) ; int iCmd = User32.TrackPopupMenu(hSystemMenu, TPM.RETURNCMD | TPM.LEFTBUTTON, menuPoint.X, menuPoint.Y, 0, _form.Handle, IntPtr.Zero ) ; if ( iCmd != 0 ) { User32.SendMessage(_form.Handle, WM.SYSCOMMAND, new IntPtr(iCmd), MessageHelper.MAKELONG(Control.MousePosition.X, Control.MousePosition.Y)) ; } } */ } private void _form_DoubleClick(object sender, EventArgs e) { if ( PointInSystemIcon( _form.PointToClient(Control.MousePosition) ) ) _form.Close() ; } private class UITheme : ControlUITheme { public bool ForceShowFrame; //private FramelessManager _framelessManager; // public UITheme(Control control, FramelessManager framelessManager) : base(control, false) public UITheme(Control control) : base(control, false) { //_framelessManager = framelessManager; ApplyTheme(); } protected override void ApplyTheme(bool highContrast) { ForceShowFrame = highContrast; //if(_framelessManager._form.Created) //{ // _framelessManager.UpdateFrame(); // _framelessManager._form.Update(); //} } } } }
// Copyright 2021, Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Ads.Common.Lib; using System; using System.Collections.Generic; using System.Reflection; namespace Google.Api.Ads.AdManager.Lib { /// <summary> /// Lists all the services available through this library. /// </summary> public partial class AdManagerService : AdsService { /// <summary> /// All the services available in v202202. /// </summary> public class v202202 { /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ActivityGroupService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ActivityGroupService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ActivityService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ActivityService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/AdjustmentRuleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdjustmentService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/AdRuleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AdRuleService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/AudienceSegmentService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature AudienceSegmentService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CdnConfigurationService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CdnConfigurationService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CmsMetadataService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CmsMetadataService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ContactService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ContactService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CompanyService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature CompanyService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ContentBundleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ContentBundleService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ContentService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ContentService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CreativeService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CreativeReviewService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeReviewService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CreativeSetService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeSetService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CreativeTemplateService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeTemplateService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CreativeWrapperService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CreativeWrapperService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CustomFieldService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CustomFieldService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/CustomTargetingService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature CustomTargetingService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/DaiAuthenticationKeyService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature DaiAuthenticationKeyService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/DaiEncodingProfileService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature DaiEncodingProfileService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ForecastService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ForecastService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/InventoryService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature InventoryService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/LabelService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LabelService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/LineItemTemplateService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LineItemTemplateService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/LineItemService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LineItemService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/LineItemCreativeAssociationService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LineItemCreativeAssociationService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/LiveStreamEventService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature LiveStreamEventService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/MobileApplicationService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature MobileApplicationService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/NativeStyleService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature NativeStyleService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/NetworkService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature NetworkService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/OrderService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature OrderService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/PlacementService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature PlacementService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ProposalService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature ProposalService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ProposalLineItemService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature ProposalLineItemService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/PublisherQueryLanguageService"> /// this page </a> for details. /// </summary> public static readonly ServiceSignature PublisherQueryLanguageService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/ReportService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature ReportService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/SiteService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SiteService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/StreamActivityMonitorService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature StreamActivityMonitorService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/SuggestedAdUnitService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature SuggestedAdUnitService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/TargetingPresetService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TargetingPresetService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/TeamService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature TeamService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/UserService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature UserService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/UserTeamAssociationService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature UserTeamAssociationService; /// <summary> /// See <a href="https://developers.google.com/doubleclick-publishers/docs/reference/v202202/YieldGroupService"> /// this page</a> for details. /// </summary> public static readonly ServiceSignature YieldGroupService; /// <summary> /// Factory type for v202202 services. /// </summary> public static readonly Type factoryType = typeof(AdManagerServiceFactory); /// <summary> /// Static constructor to initialize the service constants. /// </summary> static v202202() { ActivityGroupService = AdManagerService.MakeServiceSignature("v202202", "ActivityGroupService"); ActivityService = AdManagerService.MakeServiceSignature("v202202", "ActivityService"); AdjustmentService = AdManagerService.MakeServiceSignature("v202202", "AdjustmentService"); AdRuleService = AdManagerService.MakeServiceSignature("v202202", "AdRuleService"); AudienceSegmentService = AdManagerService.MakeServiceSignature("v202202", "AudienceSegmentService"); CdnConfigurationService = AdManagerService.MakeServiceSignature("v202202", "CdnConfigurationService"); CmsMetadataService = AdManagerService.MakeServiceSignature("v202202", "CmsMetadataService"); CompanyService = AdManagerService.MakeServiceSignature("v202202", "CompanyService"); ContactService = AdManagerService.MakeServiceSignature("v202202", "ContactService"); ContentBundleService = AdManagerService.MakeServiceSignature("v202202", "ContentBundleService"); ContentService = AdManagerService.MakeServiceSignature("v202202", "ContentService"); CreativeService = AdManagerService.MakeServiceSignature("v202202", "CreativeService"); CreativeReviewService = AdManagerService.MakeServiceSignature("v202202", "CreativeReviewService"); CreativeSetService = AdManagerService.MakeServiceSignature("v202202", "CreativeSetService"); CreativeTemplateService = AdManagerService.MakeServiceSignature("v202202", "CreativeTemplateService"); CreativeWrapperService = AdManagerService.MakeServiceSignature("v202202", "CreativeWrapperService"); CustomTargetingService = AdManagerService.MakeServiceSignature("v202202", "CustomTargetingService"); CustomFieldService = AdManagerService.MakeServiceSignature("v202202", "CustomFieldService"); DaiAuthenticationKeyService = AdManagerService.MakeServiceSignature("v202202", "DaiAuthenticationKeyService"); DaiEncodingProfileService = AdManagerService.MakeServiceSignature("v202202", "DaiEncodingProfileService"); ForecastService = AdManagerService.MakeServiceSignature("v202202", "ForecastService"); InventoryService = AdManagerService.MakeServiceSignature("v202202", "InventoryService"); LabelService = AdManagerService.MakeServiceSignature("v202202", "LabelService"); LineItemTemplateService = AdManagerService.MakeServiceSignature("v202202", "LineItemTemplateService"); LineItemService = AdManagerService.MakeServiceSignature("v202202", "LineItemService"); LineItemCreativeAssociationService = AdManagerService.MakeServiceSignature("v202202", "LineItemCreativeAssociationService"); LiveStreamEventService = AdManagerService.MakeServiceSignature("v202202", "LiveStreamEventService"); MobileApplicationService = AdManagerService.MakeServiceSignature("v202202", "MobileApplicationService"); NativeStyleService = AdManagerService.MakeServiceSignature("v202202", "NativeStyleService"); NetworkService = AdManagerService.MakeServiceSignature("v202202", "NetworkService"); OrderService = AdManagerService.MakeServiceSignature("v202202", "OrderService"); PlacementService = AdManagerService.MakeServiceSignature("v202202", "PlacementService"); ProposalService = AdManagerService.MakeServiceSignature("v202202", "ProposalService"); ProposalLineItemService = AdManagerService.MakeServiceSignature("v202202", "ProposalLineItemService"); PublisherQueryLanguageService = AdManagerService.MakeServiceSignature("v202202", "PublisherQueryLanguageService"); ReportService = AdManagerService.MakeServiceSignature("v202202", "ReportService"); SiteService = AdManagerService.MakeServiceSignature("v202202", "SiteService"); StreamActivityMonitorService = AdManagerService.MakeServiceSignature("v202202", "StreamActivityMonitorService"); SuggestedAdUnitService = AdManagerService.MakeServiceSignature("v202202", "SuggestedAdUnitService"); TargetingPresetService = AdManagerService.MakeServiceSignature("v202202", "TargetingPresetService"); TeamService = AdManagerService.MakeServiceSignature("v202202", "TeamService"); UserService = AdManagerService.MakeServiceSignature("v202202", "UserService"); UserTeamAssociationService = AdManagerService.MakeServiceSignature("v202202", "UserTeamAssociationService"); YieldGroupService = AdManagerService.MakeServiceSignature("v202202", "YieldGroupService"); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.NetCore.Analyzers.Runtime { /// <summary> /// CA1305: Specify IFormatProvider /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class SpecifyIFormatProviderAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1305"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.SpecifyIFormatProviderTitle), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageIFormatProviderAlternateString = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.SpecifyIFormatProviderMessageIFormatProviderAlternateString), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageIFormatProviderAlternate = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.SpecifyIFormatProviderMessageIFormatProviderAlternate), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageUICultureString = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.SpecifyIFormatProviderMessageUICultureString), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableMessageUICulture = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.SpecifyIFormatProviderMessageUICulture), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftNetCoreAnalyzersResources.SpecifyIFormatProviderDescription), MicrosoftNetCoreAnalyzersResources.ResourceManager, typeof(MicrosoftNetCoreAnalyzersResources)); internal static DiagnosticDescriptor IFormatProviderAlternateStringRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageIFormatProviderAlternateString, DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor IFormatProviderAlternateRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageIFormatProviderAlternate, DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor UICultureStringRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageUICultureString, DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor UICultureRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageUICulture, DiagnosticCategory.Globalization, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); private static readonly ImmutableArray<string> s_dateInvariantFormats = ImmutableArray.Create("o", "O", "r", "R", "s", "u"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(IFormatProviderAlternateStringRule, IFormatProviderAlternateRule, UICultureStringRule, UICultureRule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterCompilationStartAction(csaContext => { #region "Get All the WellKnown Types and Members" var iformatProviderType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIFormatProvider); var cultureInfoType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemGlobalizationCultureInfo); if (iformatProviderType == null || cultureInfoType == null) { return; } var objectType = csaContext.Compilation.GetSpecialType(SpecialType.System_Object); var stringType = csaContext.Compilation.GetSpecialType(SpecialType.System_String); if (objectType == null || stringType == null) { return; } var charType = csaContext.Compilation.GetSpecialType(SpecialType.System_Char); var boolType = csaContext.Compilation.GetSpecialType(SpecialType.System_Boolean); var guidType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemGuid); var builder = ImmutableHashSet.CreateBuilder<INamedTypeSymbol>(); builder.AddIfNotNull(charType); builder.AddIfNotNull(boolType); builder.AddIfNotNull(stringType); builder.AddIfNotNull(guidType); var invariantToStringTypes = builder.ToImmutableHashSet(); var dateTimeType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDateTime); var dateTimeOffsetType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDateTimeOffset); var timeSpanType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTimeSpan); var stringFormatMembers = stringType.GetMembers("Format").OfType<IMethodSymbol>(); var stringFormatMemberWithStringAndObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(objectType)); var stringFormatMemberWithStringObjectAndObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(objectType), GetParameterInfo(objectType)); var stringFormatMemberWithStringObjectObjectAndObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(objectType), GetParameterInfo(objectType), GetParameterInfo(objectType)); var stringFormatMemberWithStringAndParamsObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(stringType), GetParameterInfo(objectType, isArray: true, arrayRank: 1, isParams: true)); var stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter = stringFormatMembers.GetFirstOrDefaultMemberWithParameterInfos( GetParameterInfo(iformatProviderType), GetParameterInfo(stringType), GetParameterInfo(objectType, isArray: true, arrayRank: 1, isParams: true)); var currentCultureProperty = cultureInfoType?.GetMembers("CurrentCulture").OfType<IPropertySymbol>().FirstOrDefault(); var invariantCultureProperty = cultureInfoType?.GetMembers("InvariantCulture").OfType<IPropertySymbol>().FirstOrDefault(); var currentUICultureProperty = cultureInfoType?.GetMembers("CurrentUICulture").OfType<IPropertySymbol>().FirstOrDefault(); var installedUICultureProperty = cultureInfoType?.GetMembers("InstalledUICulture").OfType<IPropertySymbol>().FirstOrDefault(); var threadType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingThread); var currentThreadCurrentUICultureProperty = threadType?.GetMembers("CurrentUICulture").OfType<IPropertySymbol>().FirstOrDefault(); var activatorType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemActivator); var resourceManagerType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemResourcesResourceManager); var computerInfoType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualBasicDevicesComputerInfo); var installedUICulturePropertyOfComputerInfoType = computerInfoType?.GetMembers("InstalledUICulture").OfType<IPropertySymbol>().FirstOrDefault(); var obsoleteAttributeType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); #endregion csaContext.RegisterOperationAction(oaContext => { var invocationExpression = (IInvocationOperation)oaContext.Operation; var targetMethod = invocationExpression.TargetMethod; #region "Exceptions" if (targetMethod.IsGenericMethod || targetMethod.ContainingType.IsErrorType() || (activatorType != null && activatorType.Equals(targetMethod.ContainingType)) || (resourceManagerType != null && resourceManagerType.Equals(targetMethod.ContainingType)) || IsValidToStringCall(invocationExpression, invariantToStringTypes, dateTimeType, dateTimeOffsetType, timeSpanType)) { return; } #endregion #region "IFormatProviderAlternateStringRule Only" if (stringType != null && cultureInfoType != null && stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter != null && (targetMethod.Equals(stringFormatMemberWithStringAndObjectParameter) || targetMethod.Equals(stringFormatMemberWithStringObjectAndObjectParameter) || targetMethod.Equals(stringFormatMemberWithStringObjectObjectAndObjectParameter) || targetMethod.Equals(stringFormatMemberWithStringAndParamsObjectParameter))) { // Sample message for IFormatProviderAlternateStringRule: Because the behavior of string.Format(string, object) could vary based on the current user's locale settings, // replace this call in IFormatProviderStringTest.M() with a call to string.Format(IFormatProvider, string, params object[]). oaContext.ReportDiagnostic( invocationExpression.Syntax.CreateDiagnostic( IFormatProviderAlternateStringRule, targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), stringFormatMemberWithIFormatProviderStringAndParamsObjectParameter.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat))); return; } #endregion #region "IFormatProviderAlternateStringRule & IFormatProviderAlternateRule" IEnumerable<IMethodSymbol> methodsWithSameNameAsTargetMethod = targetMethod.ContainingType.GetMembers(targetMethod.Name).OfType<IMethodSymbol>().WhereMethodDoesNotContainAttribute(obsoleteAttributeType).ToList(); if (methodsWithSameNameAsTargetMethod.HasMoreThan(1)) { var correctOverloads = methodsWithSameNameAsTargetMethod.GetMethodOverloadsWithDesiredParameterAtLeadingOrTrailing(targetMethod, iformatProviderType).ToList(); // If there are two matching overloads, one with CultureInfo as the first parameter and one with CultureInfo as the last parameter, // report the diagnostic on the overload with CultureInfo as the last parameter, to match the behavior of FxCop. var correctOverload = correctOverloads.FirstOrDefault(overload => overload.Parameters.Last().Type.Equals(iformatProviderType)) ?? correctOverloads.FirstOrDefault(); // Sample message for IFormatProviderAlternateRule: Because the behavior of Convert.ToInt64(string) could vary based on the current user's locale settings, // replace this call in IFormatProviderStringTest.TestMethod() with a call to Convert.ToInt64(string, IFormatProvider). if (correctOverload != null) { oaContext.ReportDiagnostic( invocationExpression.Syntax.CreateDiagnostic( targetMethod.ReturnType.Equals(stringType) ? IFormatProviderAlternateStringRule : IFormatProviderAlternateRule, targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), correctOverload.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat))); } } #endregion #region "UICultureStringRule & UICultureRule" IEnumerable<int> IformatProviderParameterIndices = GetIndexesOfParameterType(targetMethod, iformatProviderType); foreach (var index in IformatProviderParameterIndices) { var argument = invocationExpression.Arguments[index]; if (argument != null && currentUICultureProperty != null && installedUICultureProperty != null && currentThreadCurrentUICultureProperty != null) { var semanticModel = argument.SemanticModel; var symbol = semanticModel.GetSymbolInfo(argument.Value.Syntax, oaContext.CancellationToken).Symbol; if (symbol != null && (symbol.Equals(currentUICultureProperty) || symbol.Equals(installedUICultureProperty) || symbol.Equals(currentThreadCurrentUICultureProperty) || (installedUICulturePropertyOfComputerInfoType != null && symbol.Equals(installedUICulturePropertyOfComputerInfoType)))) { // Sample message // 1. UICultureStringRule - 'TestClass.TestMethod()' passes 'Thread.CurrentUICulture' as the 'IFormatProvider' parameter to 'TestClass.CalleeMethod(string, IFormatProvider)'. // This property returns a culture that is inappropriate for formatting methods. // 2. UICultureRule -'TestClass.TestMethod()' passes 'CultureInfo.CurrentUICulture' as the 'IFormatProvider' parameter to 'TestClass.Callee(IFormatProvider, string)'. // This property returns a culture that is inappropriate for formatting methods. oaContext.ReportDiagnostic( invocationExpression.Syntax.CreateDiagnostic( targetMethod.ReturnType.Equals(stringType) ? UICultureStringRule : UICultureRule, oaContext.ContainingSymbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), symbol.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat), targetMethod.ToDisplayString(SymbolDisplayFormats.ShortSymbolDisplayFormat))); } } } #endregion }, OperationKind.Invocation); }); } private static IEnumerable<int> GetIndexesOfParameterType(IMethodSymbol targetMethod, INamedTypeSymbol formatProviderType) { return targetMethod.Parameters .Select((Parameter, Index) => (Parameter, Index)) .Where(x => x.Parameter.Type.Equals(formatProviderType)) .Select(x => x.Index); } private static ParameterInfo GetParameterInfo(INamedTypeSymbol type, bool isArray = false, int arrayRank = 0, bool isParams = false) { return ParameterInfo.GetParameterInfo(type, isArray, arrayRank, isParams); } private static bool IsValidToStringCall(IInvocationOperation invocationOperation, ImmutableHashSet<INamedTypeSymbol> invariantToStringTypes, INamedTypeSymbol? dateTimeType, INamedTypeSymbol? dateTimeOffsetType, INamedTypeSymbol? timeSpanType) { var targetMethod = invocationOperation.TargetMethod; if (targetMethod.Name != "ToString") { return false; } if (invariantToStringTypes.Contains(targetMethod.ContainingType)) { return true; } if (invocationOperation.Arguments.Length != 1 || !invocationOperation.Arguments[0].Value.ConstantValue.HasValue || !(invocationOperation.Arguments[0].Value.ConstantValue.Value is string format)) { return false; } // Handle invariant format specifiers, see https://github.com/dotnet/roslyn-analyzers/issues/3507 if ((dateTimeType != null && targetMethod.ContainingType.Equals(dateTimeType)) || (dateTimeOffsetType != null && targetMethod.ContainingType.Equals(dateTimeOffsetType))) { return s_dateInvariantFormats.Contains(format); } if (timeSpanType != null && targetMethod.ContainingType.Equals(timeSpanType)) { return format == "c"; } return false; } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace DocuSign.eSign.Model { /// <summary> /// DocumentUpdateInfo /// </summary> [DataContract] public partial class DocumentUpdateInfo : IEquatable<DocumentUpdateInfo>, IValidatableObject { public DocumentUpdateInfo() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="DocumentUpdateInfo" /> class. /// </summary> /// <param name="Data">.</param> /// <param name="DocumentId">Specifies the document ID number that the tab is placed on. This must refer to an existing Document&#39;s ID attribute..</param> /// <param name="DocumentSecurityStore">DocumentSecurityStore.</param> /// <param name="Name">.</param> /// <param name="ReturnFormat">.</param> /// <param name="SignatureDataInfos">.</param> /// <param name="TimeStampField">TimeStampField.</param> public DocumentUpdateInfo(string Data = default(string), string DocumentId = default(string), DocumentSecurityStore DocumentSecurityStore = default(DocumentSecurityStore), string Name = default(string), string ReturnFormat = default(string), List<SignatureDataInfo> SignatureDataInfos = default(List<SignatureDataInfo>), TimeStampField TimeStampField = default(TimeStampField)) { this.Data = Data; this.DocumentId = DocumentId; this.DocumentSecurityStore = DocumentSecurityStore; this.Name = Name; this.ReturnFormat = ReturnFormat; this.SignatureDataInfos = SignatureDataInfos; this.TimeStampField = TimeStampField; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="data", EmitDefaultValue=false)] public string Data { get; set; } /// <summary> /// Specifies the document ID number that the tab is placed on. This must refer to an existing Document&#39;s ID attribute. /// </summary> /// <value>Specifies the document ID number that the tab is placed on. This must refer to an existing Document&#39;s ID attribute.</value> [DataMember(Name="documentId", EmitDefaultValue=false)] public string DocumentId { get; set; } /// <summary> /// Gets or Sets DocumentSecurityStore /// </summary> [DataMember(Name="documentSecurityStore", EmitDefaultValue=false)] public DocumentSecurityStore DocumentSecurityStore { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="returnFormat", EmitDefaultValue=false)] public string ReturnFormat { get; set; } /// <summary> /// /// </summary> /// <value></value> [DataMember(Name="signatureDataInfos", EmitDefaultValue=false)] public List<SignatureDataInfo> SignatureDataInfos { get; set; } /// <summary> /// Gets or Sets TimeStampField /// </summary> [DataMember(Name="timeStampField", EmitDefaultValue=false)] public TimeStampField TimeStampField { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DocumentUpdateInfo {\n"); sb.Append(" Data: ").Append(Data).Append("\n"); sb.Append(" DocumentId: ").Append(DocumentId).Append("\n"); sb.Append(" DocumentSecurityStore: ").Append(DocumentSecurityStore).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" ReturnFormat: ").Append(ReturnFormat).Append("\n"); sb.Append(" SignatureDataInfos: ").Append(SignatureDataInfos).Append("\n"); sb.Append(" TimeStampField: ").Append(TimeStampField).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as DocumentUpdateInfo); } /// <summary> /// Returns true if DocumentUpdateInfo instances are equal /// </summary> /// <param name="other">Instance of DocumentUpdateInfo to be compared</param> /// <returns>Boolean</returns> public bool Equals(DocumentUpdateInfo other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Data == other.Data || this.Data != null && this.Data.Equals(other.Data) ) && ( this.DocumentId == other.DocumentId || this.DocumentId != null && this.DocumentId.Equals(other.DocumentId) ) && ( this.DocumentSecurityStore == other.DocumentSecurityStore || this.DocumentSecurityStore != null && this.DocumentSecurityStore.Equals(other.DocumentSecurityStore) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.ReturnFormat == other.ReturnFormat || this.ReturnFormat != null && this.ReturnFormat.Equals(other.ReturnFormat) ) && ( this.SignatureDataInfos == other.SignatureDataInfos || this.SignatureDataInfos != null && this.SignatureDataInfos.SequenceEqual(other.SignatureDataInfos) ) && ( this.TimeStampField == other.TimeStampField || this.TimeStampField != null && this.TimeStampField.Equals(other.TimeStampField) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Data != null) hash = hash * 59 + this.Data.GetHashCode(); if (this.DocumentId != null) hash = hash * 59 + this.DocumentId.GetHashCode(); if (this.DocumentSecurityStore != null) hash = hash * 59 + this.DocumentSecurityStore.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.ReturnFormat != null) hash = hash * 59 + this.ReturnFormat.GetHashCode(); if (this.SignatureDataInfos != null) hash = hash * 59 + this.SignatureDataInfos.GetHashCode(); if (this.TimeStampField != null) hash = hash * 59 + this.TimeStampField.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
// Project : ACTORS // Contacts : Pixeye - ask@pixeye.games using System.Collections.Generic; namespace Pixeye.Actors{ ///<summary> /// Mutable String class, optimized for speed and memory allocations while retrieving the final result as a string. /// Similar use than StringBuilder, but avoid a lot of allocations done by StringBuilder (conversion of int and float to string, frequent capacity change, etc.) /// Author: Nicolas Gadenne contact@gaddygames.com ///</summary> public class FastString { ///<summary>Immutable string. Generated at last moment, only if needed</summary> private string m_stringGenerated = ""; ///<summary>Is m_stringGenerated is up to date ?</summary> private bool m_isStringGenerated = false; ///<summary>Working mutable string</summary> private char[] m_buffer = null; private int m_bufferPos = 0; private int m_charsCapacity = 0; ///<summary>Temporary string used for the Replace method</summary> private List<char> m_replacement = null; private object m_valueControl = null; private int m_valueControlInt = int.MinValue; public FastString( int initialCapacity = 32 ) { m_buffer = new char[ m_charsCapacity = initialCapacity ]; } public bool IsEmpty() { return (m_isStringGenerated ? (m_stringGenerated == null) : (m_bufferPos == 0)); } ///<summary>Return the string</summary> public override string ToString() { if( !m_isStringGenerated ) // Regenerate the immutable string if needed { m_stringGenerated = new string( m_buffer, 0, m_bufferPos ); m_isStringGenerated = true; } return m_stringGenerated; } // Value controls methods: use a value to check if the string has to be regenerated. ///<summary>Return true if the valueControl has changed (and update it)</summary> public bool IsModified( int newControlValue ) { bool changed = (newControlValue != m_valueControlInt); if( changed ) m_valueControlInt = newControlValue; return changed; } ///<summary>Return true if the valueControl has changed (and update it)</summary> public bool IsModified( object newControlValue ) { bool changed = !(newControlValue.Equals( m_valueControl )); if( changed ) m_valueControl = newControlValue; return changed; } // Set methods: ///<summary>Set a string, no memorry allocation</summary> public void Set( string str ) { // We fill the m_chars list to manage future appends, but we also directly set the final stringGenerated Clear(); Append( str ); m_stringGenerated = str; m_isStringGenerated = true; } ///<summary>Caution, allocate some memory</summary> public void Set( object str ) { Set( str.ToString() ); } ///<summary>Append several params: no memory allocation unless params are of object type</summary> public void Set<T1, T2>( T1 str1, T2 str2 ) { Clear(); Append( str1 ); Append( str2 ); } public void Set<T1, T2, T3>( T1 str1, T2 str2, T3 str3 ) { Clear(); Append( str1 ); Append( str2 ); Append( str3 ); } public void Set<T1, T2, T3, T4>( T1 str1, T2 str2, T3 str3, T4 str4 ) { Clear(); Append( str1 ); Append( str2 ); Append( str3 ); Append( str4 ); } ///<summary>Allocate a little memory (20 byte)</summary> public void Set( params object[] str ) { Clear(); for( int i=0; i<str.Length; i++ ) Append( str[ i ] ); } // Append methods, to build the string without allocation ///<summary>Reset the m_char array</summary> public FastString Clear() { m_bufferPos = 0; m_isStringGenerated = false; return this; } ///<summary>Append a string without memory allocation</summary> public FastString Append( string value ) { ReallocateIFN( value.Length ); int n = value.Length; for( int i=0; i<n; i++ ) m_buffer[ m_bufferPos + i ] = value[ i ]; m_bufferPos += n; m_isStringGenerated = false; return this; } ///<summary>Append an object.ToString(), allocate some memory</summary> public FastString Append( object value ) { Append( value.ToString() ); return this; } ///<summary>Append an int without memory allocation</summary> public FastString Append( int value ) { // Allocate enough memory to handle any int number ReallocateIFN( 16 ); // Handle the negative case if( value < 0 ) { value = -value; m_buffer[ m_bufferPos++ ] = '-'; } // Copy the digits in reverse order int nbChars = 0; do { m_buffer[ m_bufferPos++ ] = (char)('0' + value%10); value /= 10; nbChars++; } while( value != 0 ); // Reverse the result for( int i=nbChars/2-1; i>=0; i-- ) { char c = m_buffer[ m_bufferPos-i-1 ]; m_buffer[ m_bufferPos-i-1 ] = m_buffer[ m_bufferPos-nbChars+i ]; m_buffer[ m_bufferPos-nbChars+i ] = c; } m_isStringGenerated = false; return this; } ///<summary>Append a float without memory allocation.</summary> public FastString Append( float valueF ) { double value = valueF; m_isStringGenerated = false; ReallocateIFN( 32 ); // Check we have enough buffer allocated to handle any float number // Handle the 0 case if( value == 0 ) { m_buffer[ m_bufferPos++ ] = '0'; return this; } // Handle the negative case if( value < 0 ) { value = -value; m_buffer[ m_bufferPos++ ] = '-'; } // Get the 7 meaningful digits as a long int nbDecimals = 0; while( value < 1000000 ) { value *= 10; nbDecimals++; } long valueLong = (long)System.Math.Round( value ); // Parse the number in reverse order int nbChars = 0; bool isLeadingZero = true; while( valueLong != 0 || nbDecimals >= 0 ) { // We stop removing leading 0 when non-0 or decimal digit if( valueLong%10 != 0 || nbDecimals <= 0 ) isLeadingZero = false; // Write the last digit (unless a leading zero) if( !isLeadingZero ) m_buffer[ m_bufferPos + (nbChars++) ] = (char)('0' + valueLong%10); // Add the decimal point if( --nbDecimals == 0 && !isLeadingZero ) m_buffer[ m_bufferPos + (nbChars++) ] = '.'; valueLong /= 10; } m_bufferPos += nbChars; // Reverse the result for( int i=nbChars/2-1; i>=0; i-- ) { char c = m_buffer[ m_bufferPos-i-1 ]; m_buffer[ m_bufferPos-i-1 ] = m_buffer[ m_bufferPos-nbChars+i ]; m_buffer[ m_bufferPos-nbChars+i ] = c; } return this; } ///<summary>Replace all occurences of a string by another one</summary> public FastString Replace( string oldStr, string newStr ) { if( m_bufferPos == 0 ) return this; if( m_replacement == null ) m_replacement = new List<char>(); // Create the new string into m_replacement for( int i=0; i<m_bufferPos; i++ ) { bool isToReplace = false; if( m_buffer[ i ] == oldStr[ 0 ] ) // If first character found, check for the rest of the string to replace { int k=1; while( k < oldStr.Length && m_buffer[ i+k ] == oldStr[ k ] ) k++; isToReplace = (k >= oldStr.Length); } if( isToReplace ) // Do the replacement { i += oldStr.Length-1; if (newStr == null) continue; for( int k=0; k<newStr.Length; k++ ) m_replacement.Add( newStr[ k ] ); } else // No replacement, copy the old character m_replacement.Add( m_buffer[ i ] ); } // Copy back the new string into m_chars ReallocateIFN( m_replacement.Count - m_bufferPos ); for( int k=0; k<m_replacement.Count; k++ ) m_buffer[ k ] = m_replacement[ k ]; m_bufferPos = m_replacement.Count; m_replacement.Clear(); m_isStringGenerated = false; return this; } private void ReallocateIFN( int nbCharsToAdd ) { if( m_bufferPos + nbCharsToAdd > m_charsCapacity ) { m_charsCapacity = System.Math.Max( m_charsCapacity + nbCharsToAdd, m_charsCapacity * 2 ); var newChars = new char[ m_charsCapacity ]; m_buffer.CopyTo( newChars, 0 ); m_buffer = newChars; } } } }
/* Copyright (c) 2004-2006 Tomas Matousek, Vaclav Novak and Martin Maly. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.Reflection.Emit; using System.Diagnostics; using PHP.Core.AST; using PHP.Core.Emit; using PHP.Core.Parsers; using PHP.Core.Reflection; namespace PHP.Core.Compiler.AST { partial class NodeCompilers { #region ConstantUse abstract class ConstantUseCompiler<T> : ExpressionCompiler<T> where T : ConstantUse { protected DConstant constant; internal abstract void ResolveName(T/*!*/node, Analyzer/*!*/ analyzer); /// <summary> /// Determines behavior on assignment. /// </summary> /// <returns>Always <B>false</B>, since constants contain immutable objects only.</returns> public override bool IsDeeplyCopied(T node, CopyReason reason, int nestingLevel) { return false; } public override Evaluation Analyze(T node, Analyzer analyzer, ExInfoFromParent info) { bool already_resolved = constant != null; if (!already_resolved) { access = info.Access; ResolveName(node, analyzer); } if (constant.IsUnknown) return new Evaluation(node); KnownConstant known_const = (KnownConstant)constant; if (known_const.HasValue) { // constant value is known: return new Evaluation(node, known_const.Value); } else if (already_resolved) { // circular definition: constant.ReportCircularDefinition(analyzer.ErrorSink); return new Evaluation(node); } else { // value is not known yet, try to resolve it: if (known_const.Node != null) known_const.Node.Analyze(analyzer); return (known_const.HasValue) ? new Evaluation(node, known_const.Value) : new Evaluation(node); } } } #endregion #region GlobalConstUse [NodeCompiler(typeof(GlobalConstUse))] sealed class GlobalConstUseCompiler : ConstantUseCompiler<GlobalConstUse> { public override Evaluation EvaluatePriorAnalysis(GlobalConstUse node, CompilationSourceUnit sourceUnit) { constant = sourceUnit.TryResolveGlobalConstantGlobally(node.Name); return (constant != null && constant.HasValue) ? new Evaluation(node, constant.Value) : new Evaluation(node); } internal override void ResolveName(GlobalConstUse/*!*/node, Analyzer/*!*/ analyzer) { if (constant == null) constant = analyzer.ResolveGlobalConstantName(node.Name, node.Span); } /// <include file='Doc/Nodes.xml' path='doc/method[@name="Emit"]/*'/> /// <param name="node">Instance.</param> /// <remarks> /// Emits IL instructions to load the value of the constant. If the value is known at compile /// time (constant is system), its value is loaded on the stack. Otherwise the value is /// obtained at runtime by calling <see cref="PHP.Core.ScriptContext.GetConstantValue"/>. /// </remarks> public override PhpTypeCode Emit(GlobalConstUse node, CodeGenerator codeGenerator) { Debug.Assert(access == AccessType.Read || access == AccessType.None); Statistics.AST.AddNode("ConstantUse.Global"); // loads constant only if its value is read: if (access == AccessType.Read) { return constant.EmitGet(codeGenerator, null, false, node.FallbackName.HasValue ? node.FallbackName.Value.ToString() : null); } else { // to satisfy debugger; sequence point has already been defined: if (codeGenerator.Context.Config.Compiler.Debug) codeGenerator.IL.Emit(OpCodes.Nop); } return PhpTypeCode.Void; } } #endregion #region ClassConstUse /// <summary> /// Class constant use. /// </summary> [NodeCompiler(typeof(ClassConstUse))] class ClassConstUseCompiler<T> : ConstantUseCompiler<T> where T : ClassConstUse { protected DType/*!A*/type; bool runtimeVisibilityCheck; public override Evaluation EvaluatePriorAnalysis(T node, CompilationSourceUnit sourceUnit) { var className = node.ClassName; if (!string.IsNullOrEmpty(className.QualifiedName.Name.Value)) constant = sourceUnit.TryResolveClassConstantGlobally(className, node.Name); return (constant != null && constant.HasValue) ? new Evaluation(node, constant.Value) : new Evaluation(node); } internal override void ResolveName(T node, Analyzer analyzer) { var typeRef = node.TypeRef; TypeRefHelper.Analyze(typeRef, analyzer); this.type = TypeRefHelper.ResolvedTypeOrUnknown(typeRef); // analyze constructed type (we are in the full analysis): analyzer.AnalyzeConstructedType(type); constant = analyzer.ResolveClassConstantName(type, node.Name, node.Span, analyzer.CurrentType, analyzer.CurrentRoutine, out runtimeVisibilityCheck); } public override PhpTypeCode Emit(T node, CodeGenerator codeGenerator) { Debug.Assert(access == AccessType.None || access == AccessType.Read); Statistics.AST.AddNode("ConstantUse.Class"); if (access == AccessType.Read) { return constant.EmitGet(codeGenerator, type as ConstructedType, runtimeVisibilityCheck, null); } else { // to satisfy debugger; sequence point has already been defined: if (codeGenerator.Context.Config.Compiler.Debug) codeGenerator.IL.Emit(OpCodes.Nop); } return PhpTypeCode.Void; } } #endregion #region PseudoClassConstUseCompiler [NodeCompiler(typeof(PseudoClassConstUse))] sealed class PseudoClassConstUseCompiler : ClassConstUseCompiler<PseudoClassConstUse> { private string TryGetValue(PseudoClassConstUse/*!*/node) { switch (node.Type) { case PseudoClassConstUse.Types.Class: var className = node.ClassName; if (string.IsNullOrEmpty(className.QualifiedName.Name.Value) || className.QualifiedName.IsStaticClassName || className.QualifiedName.IsSelfClassName) return null; return className.QualifiedName.ToString(); default: throw new InvalidOperationException(); } } internal override void ResolveName(PseudoClassConstUse node, Analyzer analyzer) { if (this.type != null) return; var typeRef = node.TypeRef; typeRef.Analyze(analyzer); this.type = typeRef.ResolvedTypeOrUnknown(); // analyze constructed type (we are in the full analysis): analyzer.AnalyzeConstructedType(type); // this.constant = null; } public override Evaluation EvaluatePriorAnalysis(PseudoClassConstUse node, CompilationSourceUnit sourceUnit) { var value = TryGetValue(node); if (value != null) return new Evaluation(node, value); else return base.EvaluatePriorAnalysis(node, sourceUnit); } public override Evaluation Analyze(PseudoClassConstUse node, Analyzer analyzer, ExInfoFromParent info) { access = info.access; var value = TryGetValue(node); if (value != null) return new Evaluation(node, value); // this.ResolveName(node, analyzer); // return new Evaluation(node); } public override PhpTypeCode Emit(PseudoClassConstUse node, CodeGenerator codeGenerator) { switch (node.Type) { case PseudoClassConstUse.Types.Class: this.type.EmitLoadTypeDesc(codeGenerator, ResolveTypeFlags.ThrowErrors | ResolveTypeFlags.UseAutoload); codeGenerator.IL.Emit(OpCodes.Call, Methods.Operators.GetFullyQualifiedName); return PhpTypeCode.String; default: throw new InvalidOperationException(); } } } #endregion #region PseudoConstUse [NodeCompiler(typeof(PseudoConstUse))] sealed class PseudoConstUseCompiler : ExpressionCompiler<PseudoConstUse> { #region Analysis /// <summary> /// Get the value indicating if the given constant is evaluable in compile time. /// </summary> /// <param name="type"></param> /// <returns></returns> private bool IsEvaluable(PseudoConstUse.Types type) { switch (type) { case PseudoConstUse.Types.File: case PseudoConstUse.Types.Dir: return false; default: return true; } } public override Evaluation Analyze(PseudoConstUse node, Analyzer analyzer, ExInfoFromParent info) { access = info.access; if (IsEvaluable(node.Type)) return new Evaluation(node, Evaluate(node, analyzer)); else return new Evaluation(node); } /// <summary> /// Gets value of __LINE__, __FUNCTION__, __METHOD__, __CLASS__, __NAMESPACE__ used in source code. /// Doesn't get value for __FILE__ and __DIR__. This value is combined from relative path and the current source root /// at run-time. /// </summary> /// <remarks> /// Analyzer maintains during AST walk information about its position in AST /// and that information uses (among others) to provide values of the pseudo constants. /// </remarks> private object Evaluate(PseudoConstUse node, Analyzer/*!*/ analyzer) { switch (node.Type) { case PseudoConstUse.Types.Line: return (int)new Text.TextPoint(analyzer.SourceUnit, node.Span.Start).Line; // __LINE__ is of type Integer in PHP case PseudoConstUse.Types.Class: if (analyzer.CurrentType != null) return analyzer.CurrentType.FullName; return string.Empty; case PseudoConstUse.Types.Trait: if (analyzer.CurrentType != null && analyzer.CurrentType.TypeDesc.IsTrait) return analyzer.CurrentType.FullName; return string.Empty; case PseudoConstUse.Types.Function: if (analyzer.CurrentRoutine != null) return analyzer.CurrentRoutine.FullName; return string.Empty; case PseudoConstUse.Types.Method: if (analyzer.CurrentRoutine != null) { if (analyzer.CurrentRoutine.IsMethod) { return ((KnownType)analyzer.CurrentRoutine.DeclaringType).QualifiedName.ToString( ((PhpMethod)analyzer.CurrentRoutine).Name, false); } else return analyzer.CurrentRoutine.FullName; } return string.Empty; case PseudoConstUse.Types.Namespace: return analyzer.CurrentNamespace.HasValue ? analyzer.CurrentNamespace.Value.NamespacePhpName : string.Empty; case PseudoConstUse.Types.File: case PseudoConstUse.Types.Dir: Debug.Fail("Evaluated at run-time."); return null; default: throw null; } } #endregion /// <summary> /// Emit /// CALL Operators.ToAbsoluteSourcePath(relative source path level, remaining relative source path); /// </summary> /// <param name="codeGenerator">Code generator.</param> /// <returns>Type code of value that is on the top of the evaluation stack as the result of call of emitted code.</returns> private PhpTypeCode EmitToAbsoluteSourcePath(CodeGenerator/*!*/ codeGenerator) { ILEmitter il = codeGenerator.IL; // CALL Operators.ToAbsoluteSourcePath(<relative source path level>, <remaining relative source path>); RelativePath relative_path = codeGenerator.SourceUnit.SourceFile.RelativePath; il.LdcI4(relative_path.Level); il.Emit(OpCodes.Ldstr, relative_path.Path); il.Emit(OpCodes.Call, Methods.Operators.ToAbsoluteSourcePath); // return PhpTypeCode.String; } public override PhpTypeCode Emit(PseudoConstUse node, CodeGenerator codeGenerator) { switch (node.Type) { case PseudoConstUse.Types.File: EmitToAbsoluteSourcePath(codeGenerator); break; case PseudoConstUse.Types.Dir: ILEmitter il = codeGenerator.IL; // CALL Path.GetDirectory( Operators.ToAbsoluteSourcePath(...) ) EmitToAbsoluteSourcePath(codeGenerator); il.Emit(OpCodes.Call, Methods.Path.GetDirectoryName); break; default: Debug.Fail("Pseudo constant " + node.Type.ToString() + " expected to be already evaluated."); throw null; } return PhpTypeCode.String; } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Abstractions.Mount; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Utils; namespace Microsoft.TemplateEngine.Core.Util { public class Orchestrator : IOrchestrator, IOrchestrator2 { public void Run(string runSpecPath, IDirectory sourceDir, string targetDir) { IGlobalRunSpec spec; using (Stream stream = sourceDir.MountPoint.EnvironmentSettings.Host.FileSystem.OpenRead(runSpecPath)) { spec = RunSpecLoader(stream); EngineConfig config = new EngineConfig(sourceDir.MountPoint.EnvironmentSettings, EngineConfig.DefaultWhitespaces, EngineConfig.DefaultLineEndings, spec.RootVariableCollection); IProcessor processor = Processor.Create(config, spec.Operations); stream.Position = 0; using (MemoryStream ms = new MemoryStream()) { processor.Run(stream, ms); ms.Position = 0; spec = RunSpecLoader(ms); } } RunInternal(sourceDir.MountPoint.EnvironmentSettings, sourceDir, targetDir, spec); } public IReadOnlyList<IFileChange2> GetFileChanges(string runSpecPath, IDirectory sourceDir, string targetDir) { IGlobalRunSpec spec; using (Stream stream = sourceDir.MountPoint.EnvironmentSettings.Host.FileSystem.OpenRead(runSpecPath)) { spec = RunSpecLoader(stream); EngineConfig config = new EngineConfig(sourceDir.MountPoint.EnvironmentSettings, EngineConfig.DefaultWhitespaces, EngineConfig.DefaultLineEndings, spec.RootVariableCollection); IProcessor processor = Processor.Create(config, spec.Operations); stream.Position = 0; using (MemoryStream ms = new MemoryStream()) { processor.Run(stream, ms); ms.Position = 0; spec = RunSpecLoader(ms); } } return GetFileChangesInternal(sourceDir.MountPoint.EnvironmentSettings, sourceDir, targetDir, spec); } public void Run(IGlobalRunSpec spec, IDirectory sourceDir, string targetDir) { RunInternal(sourceDir.MountPoint.EnvironmentSettings, sourceDir, targetDir, spec); } public IReadOnlyList<IFileChange2> GetFileChanges(IGlobalRunSpec spec, IDirectory sourceDir, string targetDir) { return GetFileChangesInternal(sourceDir.MountPoint.EnvironmentSettings, sourceDir, targetDir, spec); } IReadOnlyList<IFileChange> IOrchestrator.GetFileChanges(string runSpecPath, IDirectory sourceDir, string targetDir) { return GetFileChanges(runSpecPath, sourceDir, targetDir); } IReadOnlyList<IFileChange> IOrchestrator.GetFileChanges(IGlobalRunSpec spec, IDirectory sourceDir, string targetDir) { return GetFileChanges(spec, sourceDir, targetDir); } protected virtual IGlobalRunSpec RunSpecLoader(Stream runSpec) { return null; } protected virtual bool TryGetBufferSize(IFile sourceFile, out int bufferSize) { bufferSize = -1; return false; } protected virtual bool TryGetFlushThreshold(IFile sourceFile, out int threshold) { threshold = -1; return false; } private static List<KeyValuePair<IPathMatcher, IProcessor>> CreateFileGlobProcessors(IEngineEnvironmentSettings environmentSettings, IGlobalRunSpec spec) { List<KeyValuePair<IPathMatcher, IProcessor>> processorList = new List<KeyValuePair<IPathMatcher, IProcessor>>(); if (spec.Special != null) { foreach (KeyValuePair<IPathMatcher, IRunSpec> runSpec in spec.Special) { IReadOnlyList<IOperationProvider> operations = runSpec.Value.GetOperations(spec.Operations); EngineConfig config = new EngineConfig(environmentSettings, EngineConfig.DefaultWhitespaces, EngineConfig.DefaultLineEndings, spec.RootVariableCollection, runSpec.Value.VariableFormatString); IProcessor processor = Processor.Create(config, operations); processorList.Add(new KeyValuePair<IPathMatcher, IProcessor>(runSpec.Key, processor)); } } return processorList; } private IReadOnlyList<IFileChange2> GetFileChangesInternal(IEngineEnvironmentSettings environmentSettings, IDirectory sourceDir, string targetDir, IGlobalRunSpec spec) { EngineConfig cfg = new EngineConfig(environmentSettings, EngineConfig.DefaultWhitespaces, EngineConfig.DefaultLineEndings, spec.RootVariableCollection); IProcessor fallback = Processor.Create(cfg, spec.Operations); List<IFileChange2> changes = new List<IFileChange2>(); List<KeyValuePair<IPathMatcher, IProcessor>> fileGlobProcessors = CreateFileGlobProcessors(sourceDir.MountPoint.EnvironmentSettings, spec); foreach (IFile file in sourceDir.EnumerateFiles("*", SearchOption.AllDirectories)) { string sourceRel = file.PathRelativeTo(sourceDir); string fileName = Path.GetFileName(sourceRel); bool checkingDirWithPlaceholderFile = false; if (spec.IgnoreFileNames.Contains(fileName)) { // The placeholder file should never get copied / created / processed. It just causes the dir to get created if needed. // The change checking / reporting is different, setting this variable tracks it. checkingDirWithPlaceholderFile = true; } foreach (IPathMatcher include in spec.Include) { if (include.IsMatch(sourceRel)) { bool excluded = false; foreach (IPathMatcher exclude in spec.Exclude) { if (exclude.IsMatch(sourceRel)) { excluded = true; break; } } if (!excluded) { if (!spec.TryGetTargetRelPath(sourceRel, out string targetRel)) { targetRel = sourceRel; } string targetPath = Path.Combine(targetDir, targetRel); if (checkingDirWithPlaceholderFile) { targetPath = Path.GetDirectoryName(targetPath); targetRel = Path.GetDirectoryName(targetRel); if (environmentSettings.Host.FileSystem.DirectoryExists(targetPath)) { changes.Add(new FileChange(sourceRel, targetRel, ChangeKind.Overwrite)); } else { changes.Add(new FileChange(sourceRel, targetRel, ChangeKind.Create)); } } else if (environmentSettings.Host.FileSystem.FileExists(targetPath)) { changes.Add(new FileChange(sourceRel, targetRel, ChangeKind.Overwrite)); } else { changes.Add(new FileChange(sourceRel, targetRel, ChangeKind.Create)); } } break; } } } return changes; } private void RunInternal(IEngineEnvironmentSettings environmentSettings, IDirectory sourceDir, string targetDir, IGlobalRunSpec spec) { EngineConfig cfg = new EngineConfig(environmentSettings, EngineConfig.DefaultWhitespaces, EngineConfig.DefaultLineEndings, spec.RootVariableCollection); IProcessor fallback = Processor.Create(cfg, spec.Operations); List<KeyValuePair<IPathMatcher, IProcessor>> fileGlobProcessors = CreateFileGlobProcessors(sourceDir.MountPoint.EnvironmentSettings, spec); foreach (IFile file in sourceDir.EnumerateFiles("*", SearchOption.AllDirectories)) { string sourceRel = file.PathRelativeTo(sourceDir); string fileName = Path.GetFileName(sourceRel); bool checkingDirWithPlaceholderFile = false; if (spec.IgnoreFileNames.Contains(fileName)) { // The placeholder file should never get copied / created / processed. It just causes the dir to get created if needed. // The change checking / reporting is different, setting this variable tracks it. checkingDirWithPlaceholderFile = true; } foreach (IPathMatcher include in spec.Include) { if (include.IsMatch(sourceRel)) { bool excluded = false; foreach (IPathMatcher exclude in spec.Exclude) { if (exclude.IsMatch(sourceRel)) { excluded = true; break; } } if (!excluded) { bool copy = false; foreach(IPathMatcher copyOnly in spec.CopyOnly) { if (copyOnly.IsMatch(sourceRel)) { copy = true; break; } } spec.LocalizationOperations.TryGetValue(sourceRel, out IReadOnlyList<IOperationProvider> locOperations); if (checkingDirWithPlaceholderFile) { CreateTargetDir(environmentSettings, sourceRel, targetDir, spec); } else if (!copy) { ProcessFile(file, sourceRel, targetDir, spec, fallback, fileGlobProcessors, locOperations); } else { string targetPath = CreateTargetDir(environmentSettings, sourceRel, targetDir, spec); using (Stream sourceStream = file.OpenRead()) using (Stream targetStream = environmentSettings.Host.FileSystem.CreateFile(targetPath)) { sourceStream.CopyTo(targetStream); } } } break; } } } } private static string CreateTargetDir(IEngineEnvironmentSettings environmentSettings, string sourceRel, string targetDir, IGlobalRunSpec spec) { if (!spec.TryGetTargetRelPath(sourceRel, out string targetRel)) { targetRel = sourceRel; } string targetPath = Path.Combine(targetDir, targetRel); string fullTargetDir = Path.GetDirectoryName(targetPath); environmentSettings.Host.FileSystem.CreateDirectory(fullTargetDir); return targetPath; } private void ProcessFile(IFile sourceFile, string sourceRel, string targetDir, IGlobalRunSpec spec, IProcessor fallback, IEnumerable<KeyValuePair<IPathMatcher, IProcessor>> fileGlobProcessors, IReadOnlyList<IOperationProvider> locOperations) { IProcessor runner = fileGlobProcessors.FirstOrDefault(x => x.Key.IsMatch(sourceRel)).Value ?? fallback; if (runner == null) { throw new InvalidOperationException("At least one of [runner] or [fallback] cannot be null"); } if (locOperations != null) { runner = runner.CloneAndAppendOperations(locOperations); } if (!spec.TryGetTargetRelPath(sourceRel, out string targetRel)) { targetRel = sourceRel; } string targetPath = Path.Combine(targetDir, targetRel); //TODO: Update context with the current file & such here bool customBufferSize = TryGetBufferSize(sourceFile, out int bufferSize); bool customFlushThreshold = TryGetFlushThreshold(sourceFile, out int flushThreshold); string fullTargetDir = Path.GetDirectoryName(targetPath); sourceFile.MountPoint.EnvironmentSettings.Host.FileSystem.CreateDirectory(fullTargetDir); try { using (Stream source = sourceFile.OpenRead()) using (Stream target = sourceFile.MountPoint.EnvironmentSettings.Host.FileSystem.CreateFile(targetPath)) { if (!customBufferSize) { runner.Run(source, target); } else { if (!customFlushThreshold) { runner.Run(source, target, bufferSize); } else { runner.Run(source, target, bufferSize, flushThreshold); } } } } catch(Exception ex) { throw new ContentGenerationException($"Error while processing file {sourceFile.FullPath}", ex); } } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.Runtime.Interop { using System; using System.Text; using System.Security; using System.Collections.Generic; using System.Runtime.Versioning; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Diagnostics.CodeAnalysis; using System.Runtime.Diagnostics; [SuppressUnmanagedCodeSecurity] static class UnsafeNativeMethods { public const string KERNEL32 = "kernel32.dll"; public const String ADVAPI32 = "advapi32.dll"; public const int ERROR_INVALID_HANDLE = 6; public const int ERROR_MORE_DATA = 234; public const int ERROR_ARITHMETIC_OVERFLOW = 534; public const int ERROR_NOT_ENOUGH_MEMORY = 8; [StructLayout(LayoutKind.Explicit, Size = 16)] public struct EventData { [FieldOffset(0)] internal UInt64 DataPointer; [FieldOffset(8)] internal uint Size; [FieldOffset(12)] internal int Reserved; } [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(KERNEL32, BestFitMapping = false, CharSet = CharSet.Auto)] [ResourceExposure(ResourceScope.Process)] [SecurityCritical] public static extern SafeWaitHandle CreateWaitableTimer(IntPtr mustBeZero, bool manualReset, string timerName); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(KERNEL32, ExactSpelling = true)] [ResourceExposure(ResourceScope.None)] [SecurityCritical] public static extern bool SetWaitableTimer(SafeWaitHandle handle, ref long dueTime, int period, IntPtr mustBeZero, IntPtr mustBeZeroAlso, bool resume); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [SecurityCritical] public static extern int QueryPerformanceCounter(out long time); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(KERNEL32, SetLastError = false)] [ResourceExposure(ResourceScope.None)] [SecurityCritical] public static extern uint GetSystemTimeAdjustment( [Out] out int adjustment, [Out] out uint increment, [Out] out uint adjustmentDisabled ); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(KERNEL32, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [SecurityCritical] public static extern void GetSystemTimeAsFileTime([Out] out long time); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.SpecifyMarshalingForPInvokeStringArguments, Justification = "")] [DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] [ResourceExposure(ResourceScope.None)] [SecurityCritical] static extern bool GetComputerNameEx ( [In] ComputerNameFormat nameType, [In, Out, MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpBuffer, [In, Out] ref int size ); [SecurityCritical] internal static string GetComputerName(ComputerNameFormat nameType) { int length = 0; if (!GetComputerNameEx(nameType, null, ref length)) { int error = Marshal.GetLastWin32Error(); if (error != ERROR_MORE_DATA) { throw Fx.Exception.AsError(new System.ComponentModel.Win32Exception(error)); } } if (length < 0) { Fx.AssertAndThrow("GetComputerName returned an invalid length: " + length); } StringBuilder stringBuilder = new StringBuilder(length); if (!GetComputerNameEx(nameType, stringBuilder, ref length)) { int error = Marshal.GetLastWin32Error(); throw Fx.Exception.AsError(new System.ComponentModel.Win32Exception(error)); } return stringBuilder.ToString(); } [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(KERNEL32)] [ResourceExposure(ResourceScope.None)] [SecurityCritical] internal static extern bool IsDebuggerPresent(); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(KERNEL32)] [ResourceExposure(ResourceScope.Process)] [SecurityCritical] internal static extern void DebugBreak(); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(KERNEL32, CharSet = CharSet.Unicode)] [ResourceExposure(ResourceScope.Process)] [SecurityCritical] internal static extern void OutputDebugString(string lpOutputString); // // Callback // [SecurityCritical] internal unsafe delegate void EtwEnableCallback( [In] ref Guid sourceId, [In] int isEnabled, [In] byte level, [In] long matchAnyKeywords, [In] long matchAllKeywords, [In] void* filterData, [In] void* callbackContext ); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventRegister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventRegister( [In] ref Guid providerId, [In]EtwEnableCallback enableCallback, [In]void* callbackContext, [In][Out]ref long registrationHandle ); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventUnregister", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern uint EventUnregister([In] long registrationHandle); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventEnabled", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern bool EventEnabled([In] long registrationHandle, [In] ref EventDescriptor eventDescriptor); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWrite", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventWrite( [In] long registrationHandle, [In] ref EventDescriptor eventDescriptor, [In] uint userDataCount, [In] EventData* userData ); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteTransfer", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventWriteTransfer( [In] long registrationHandle, [In] ref EventDescriptor eventDescriptor, [In] ref Guid activityId, [In] ref Guid relatedActivityId, [In] uint userDataCount, [In] EventData* userData ); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventWriteString", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventWriteString( [In] long registrationHandle, [In] byte level, [In] long keywords, [In] char* message ); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, ExactSpelling = true, EntryPoint = "EventActivityIdControl", CharSet = System.Runtime.InteropServices.CharSet.Unicode)] [SecurityCritical] internal static extern unsafe uint EventActivityIdControl([In] int ControlCode, [In][Out] ref Guid ActivityId); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.None)] [SecurityCritical] [Fx.Tag.SecurityNote(Critical = "Accesses security critical type SafeHandle")] internal static extern bool ReportEvent(SafeHandle hEventLog, ushort type, ushort category, uint eventID, byte[] userSID, ushort numStrings, uint dataLen, HandleRef strings, byte[] rawData); [SuppressMessage(FxCop.Category.Security, FxCop.Rule.ReviewSuppressUnmanagedCodeSecurityUsage, Justification = "This PInvoke call has been reviewed")] [DllImport(ADVAPI32, CharSet = System.Runtime.InteropServices.CharSet.Unicode, SetLastError = true)] [ResourceExposure(ResourceScope.Machine)] [Fx.Tag.SecurityNote(Critical = "Returns security critical type SafeEventLogWriteHandle")] [SecurityCritical] internal static extern SafeEventLogWriteHandle RegisterEventSource(string uncServerName, string sourceName); } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using System.Linq; using Glass.Mapper.Umb.CastleWindsor; using Glass.Mapper.Umb.Configuration; using Glass.Mapper.Umb.Configuration.Attributes; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Services; namespace Glass.Mapper.Umb.Integration { [TestFixture] public class UmbracoServiceFixture { private ContentService _contentService; #region Method - GetItem [Test] public void GetItem_UsingItemId_ReturnsItem() { //Assign var context = Context.Create(DependencyResolver.CreateStandardResolver()); context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); var service = new UmbracoService(_contentService, context); var id = new Guid("{24814F74-CE52-4975-B9F3-15ABCBB132D6}"); //Act var result = (StubClass)service.GetItem<StubClass>(id); //Assert Assert.IsNotNull(result); } [Test] public void GetItem_UsingItemIdInt_ReturnsItem() { //Assign var context = Context.Create(DependencyResolver.CreateStandardResolver()); context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); var content = _contentService.GetById(new Guid("{24814F74-CE52-4975-B9F3-15ABCBB132D6}")); var service = new UmbracoService(_contentService, context); //Act var result = (StubClass)service.GetItem<StubClass>(content.Id); //Assert Assert.IsNotNull(result); } [Test] public void GetItem_UsingItemId_ReturnsItemName() { //Assign var context = Context.Create(DependencyResolver.CreateStandardResolver()); context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); var service = new UmbracoService(_contentService, context); var id = new Guid("{24814F74-CE52-4975-B9F3-15ABCBB132D6}"); //Act var result = service.GetItem<StubClassWithProperty>(id); //Assert Assert.IsNotNull(result); Assert.AreEqual("EmptyItem", result.Name); } #endregion //#region Method - Save [Test] public void Save_ItemDisplayNameChanged_SavesName() { //Assign string expected = "new name"; var context = Context.Create(DependencyResolver.CreateStandardResolver()); context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); var currentItem = _contentService.GetById(new Guid("{24814F74-CE52-4975-B9F3-15ABCBB132D6}")); var service = new UmbracoService(_contentService, context); var cls = new StubSaving(); cls.Id = currentItem.Key; //setup item currentItem.Name = "old name"; _contentService.Save(currentItem); //Act cls.Name = expected; service.Save(cls); //Assert var newItem = _contentService.GetById(new Guid("{24814F74-CE52-4975-B9F3-15ABCBB132D6}")); Assert.AreEqual(expected, newItem.Name); } //[Test] //public void Save_ItemDisplayNameChangedUsingProxy_SavesDisplayName() //{ // //Assign // var itemPath = "/Umbraco/content/Tests/UmbracoService/Save/EmptyItem"; // string expected = "new name"; // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var currentItem = db.GetItem(itemPath); // var service = new UmbracoService(db, context); // //setup item // using (new SecurityDisabler()) // { // currentItem.Editing.BeginEdit(); // currentItem[Global.Fields.DisplayName] = "old name"; // currentItem.Editing.EndEdit(); // } // var cls = service.GetItem<StubSaving>(itemPath, true); // using (new SecurityDisabler()) // { // //Act // cls.Name = expected; // service.Save(cls); // //Assert // var newItem = db.GetItem(itemPath); // Assert.AreEqual(expected, newItem[Global.Fields.DisplayName]); // Assert.IsTrue(cls is StubSaving); // Assert.AreNotEqual(typeof(StubSaving), cls.GetType()); // } //} //[Test] //public void Save_ItemDisplayNameChangedUsingProxyUsingInterface_SavesDisplayName() //{ // //Assign // var itemPath = "/Umbraco/content/Tests/UmbracoService/Save/EmptyItem"; // string expected = "new name"; // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var currentItem = db.GetItem(itemPath); // var service = new UmbracoService(db, context); // //setup item // using (new SecurityDisabler()) // { // currentItem.Editing.BeginEdit(); // currentItem[Global.Fields.DisplayName] = "old name"; // currentItem.Editing.EndEdit(); // } // var cls = service.GetItem<IStubSaving>(itemPath); // using (new SecurityDisabler()) // { // //Act // cls.Name = expected; // service.Save(cls); // //Assert // var newItem = db.GetItem(itemPath); // Assert.AreEqual(expected, newItem[Global.Fields.DisplayName]); // Assert.IsTrue(cls is IStubSaving); // Assert.AreNotEqual(typeof(IStubSaving), cls.GetType()); // } //} //#endregion //#region Method - CreateTypes //[Test] //public void CreateTypes_TwoItems_ReturnsTwoClasses() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db, context); // var result1 = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateTypes/Result1"); // var result2 = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateTypes/Result2"); // //Act // var results = // service.CreateTypes(false, false, typeof(StubClass), () => new[] { result1, result2 }) as // IEnumerable<StubClass>; // //Assert // Assert.AreEqual(2, results.Count()); // Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid)); // Assert.IsTrue(results.Any(x => x.Id == result2.ID.Guid)); //} //[Test] //public void CreateTypes_TwoItemsOnly1WithLanguage_ReturnsOneClasses() //{ // //Assign // var language = LanguageManager.GetLanguage("af-ZA"); // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db, context); // var result1 = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateTypes/Result1", language); // var result2 = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateTypes/Result2", language); // //Act // var results = // service.CreateTypes(false, false, typeof(StubClass), () => new[] { result1, result2 }) as // IEnumerable<StubClass>; // //Assert // Assert.AreEqual(1, results.Count()); // Assert.IsTrue(results.Any(x => x.Id == result1.ID.Guid)); //} //#endregion //#region Method - CreateType //[Test] //public void CreateType_NoConstructorArgs_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // //Act // var result = (StubClass)service.CreateType(typeof(StubClass), item, false, false); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); //} //[Test] //public void CreateType_NoConstructorArgsTyped_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // //Act // var result = service.CreateType<StubClass>(item, false, false); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); //} //[Test] //public void CreateType_OneConstructorArgs_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // var param1 = 456; // //Act // var result = (StubClass)service.CreateType(typeof(StubClass), item, false, false, param1); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); // Assert.AreEqual(param1, result.Param1); //} //[Test] //public void CreateType_OneConstructorArgsTyped_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // var param1 = 456; // //Act // var result = service.CreateType<StubClass, int>(item, param1); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); // Assert.AreEqual(param1, result.Param1); //} //[Test] //public void CreateType_TwoConstructorArgs_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // var param1 = 456; // var param2 = "hello world"; // //Act // var result = (StubClass)service.CreateType(typeof(StubClass), item, false, false, param1, param2); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); // Assert.AreEqual(param1, result.Param1); // Assert.AreEqual(param2, result.Param2); //} //[Test] //public void CreateType_TwoConstructorArgsTyped_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // var param1 = 456; // var param2 = "hello world"; // //Act // var result = service.CreateType<StubClass, int, string>(item, param1, param2); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); // Assert.AreEqual(param1, result.Param1); // Assert.AreEqual(param2, result.Param2); //} //[Test] //public void CreateType_ThreeConstructorArgs_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // var param1 = 456; // var param2 = "hello world"; // DateTime param3 = DateTime.Now; // //Act // var result = (StubClass)service.CreateType(typeof(StubClass), item, false, false, param1, param2, param3); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); // Assert.AreEqual(param1, result.Param1); // Assert.AreEqual(param2, result.Param2); // Assert.AreEqual(param3, result.Param3); //} //[Test] //public void CreateType_ThreeConstructorArgsTyped_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // var param1 = 456; // var param2 = "hello world"; // DateTime param3 = DateTime.Now; // //Act // var result = service.CreateType<StubClass, int, string, DateTime>(item, param1, param2, param3, false, false); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); // Assert.AreEqual(param1, result.Param1); // Assert.AreEqual(param2, result.Param2); // Assert.AreEqual(param3, result.Param3); //} //[Test] //public void CreateType_FourConstructorArgs_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // var param1 = 456; // var param2 = "hello world"; // DateTime param3 = DateTime.Now; // var param4 = true; // //Act // var result = (StubClass)service.CreateType(typeof(StubClass), item, false, false, param1, param2, param3, param4); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); // Assert.AreEqual(param1, result.Param1); // Assert.AreEqual(param2, result.Param2); // Assert.AreEqual(param3, result.Param3); // Assert.AreEqual(param4, result.Param4); //} //[Test] //public void CreateType_FourConstructorArgsTyped_ReturnsItem() //{ // //Assign // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var service = new UmbracoService(db); // var item = db.GetItem("/Umbraco/content/Tests/UmbracoService/CreateType/Target"); // var param1 = 456; // var param2 = "hello world"; // DateTime param3 = DateTime.Now; // var param4 = true; // //Act // var result = service.CreateType<StubClass, int, string, DateTime, bool>(item, param1, param2, param3, param4, false, false); // //Assert // Assert.IsNotNull(result); // Assert.AreEqual(item.ID.Guid, result.Id); // Assert.AreEqual(param1, result.Param1); // Assert.AreEqual(param2, result.Param2); // Assert.AreEqual(param3, result.Param3); // Assert.AreEqual(param4, result.Param4); //} //#endregion //#region Method - Create //[Test] //public void Create_CreatesANewItem() //{ // //Assign // string parentPath = "/Umbraco/content/Tests/UmbracoService/Create"; // string childPath = "/Umbraco/content/Tests/UmbracoService/Create/newChild"; // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var service = new UmbracoService(db); // var parent = service.GetItem<StubClass>(parentPath); // var child = new StubClass(); // child.Name = "newChild"; // //Act // using (new SecurityDisabler()) // { // service.Create(parent, child); // } // //Assert // var newItem = db.GetItem(childPath); // newItem.Delete(); // Assert.AreEqual(child.Name, newItem.Name); // Assert.AreEqual(child.Id, newItem.ID.Guid); //} //#endregion //#region Method - Delete //[Test] //public void Delete_RemovesItemFromDatabse() //{ // //Assign // string parentPath = "/Umbraco/content/Tests/UmbracoService/Delete"; // string childPath = "/Umbraco/content/Tests/UmbracoService/Delete/Target"; // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var service = new UmbracoService(db); // var parent = db.GetItem(parentPath); // var child = parent.Add("Target", new TemplateID(new ID(StubClass.TemplateId))); // Assert.IsNotNull(child); // var childClass = service.GetItem<StubClass>(childPath); // Assert.IsNotNull(childClass); // //Act // using (new SecurityDisabler()) // { // service.Delete(childClass); // } // //Assert // var newItem = db.GetItem(childPath); // Assert.IsNull(newItem); //} //#endregion //#region Method - Move //[Test] //public void Move_MovesItemFromParent1ToParent2() //{ // //Assign // string parent1Path = "/Umbraco/content/Tests/UmbracoService/Move/Parent1"; // string parent2Path = "/Umbraco/content/Tests/UmbracoService/Move/Parent2"; // string targetPath = "/Umbraco/content/Tests/UmbracoService/Move/Parent1/Target"; // string targetNewPath = "/Umbraco/content/Tests/UmbracoService/Move/Parent2/Target"; // var db = Umbraco.Configuration.Factory.GetDatabase("master"); // var context = Context.Create(DependencyResolver.CreateStandardResolver()); // context.Load(new UmbracoAttributeConfigurationLoader("Glass.Mapper.Umb.Integration")); // var service = new UmbracoService(db); // var parent1 = db.GetItem(parent1Path); // var parent2 = db.GetItem(parent1Path); // var target = db.GetItem(targetPath); // Assert.AreEqual(parent1.ID, target.Parent.ID); // var parent2Class = service.GetItem<StubClass>(parent2Path); // var targetClass = service.GetItem<StubClass>(targetPath); // //Act // using (new SecurityDisabler()) // { // service.Move(targetClass, parent2Class); // } // //Assert // var targetNew = db.GetItem(targetNewPath); // Assert.IsNotNull(targetNew); // using (new SecurityDisabler()) // { // targetNew.MoveTo(parent1); // } //} //#endregion #region Stubs [TestFixtureSetUp] public void CreateStub() { string name = "EmptyItem"; string contentTypeAlias = "TestType"; string contentTypeName = "Test Type"; var unitOfWork = Global.CreateUnitOfWork(); var repoFactory = new RepositoryFactory(); _contentService = new ContentService(unitOfWork, repoFactory); var contentTypeService = new ContentTypeService(unitOfWork, repoFactory, new ContentService(unitOfWork), new MediaService(unitOfWork, repoFactory)); var dataTypeService = new DataTypeService(unitOfWork, repoFactory); var contentType = new ContentType(-1); contentType.Name = contentTypeName; contentType.Alias = contentTypeAlias; contentType.Thumbnail = string.Empty; contentTypeService.Save(contentType); Assert.Greater(contentType.Id, 0); var definitions = dataTypeService.GetDataTypeDefinitionByControlId(new Guid("ec15c1e5-9d90-422a-aa52-4f7622c63bea")); dataTypeService.Save(definitions.FirstOrDefault()); var propertyType = new PropertyType(definitions.FirstOrDefault()); propertyType.Alias = "Property"; contentType.AddPropertyType(propertyType); contentTypeService.Save(contentType); Assert.Greater(contentType.Id, 0); var content = new Content(name, -1, contentType); content.Key = new Guid("{24814F74-CE52-4975-B9F3-15ABCBB132D6}"); _contentService.Save(content); } [UmbracoType] public class StubSaving { [UmbracoId] public virtual Guid Id { get; set; } [UmbracoInfo(Type = UmbracoInfoType.Name)] public virtual string Name { get; set; } } [UmbracoType] public interface IStubSaving { [UmbracoId] Guid Id { get; set; } [UmbracoInfo(Type = UmbracoInfoType.Name)] string Name { get; set; } } [UmbracoType(ContentTypeAlias = ContentTypeAlias)] public class StubClass { public const string ContentTypeAlias = "TestType"; public DateTime Param3 { get; set; } public bool Param4 { get; set; } public string Param2 { get; set; } public int Param1 { get; set; } public StubClass() { } public StubClass(int param1) { Param1 = param1; } public StubClass(int param1, string param2) : this(param1) { Param2 = param2; } public StubClass(int param1, string param2, DateTime param3) : this(param1, param2) { Param3 = param3; } public StubClass(int param1, string param2, DateTime param3, bool param4) : this(param1, param2, param3) { Param4 = param4; } [UmbracoId] public virtual Guid Id { get; set; } [UmbracoInfo(UmbracoInfoType.Path)] public virtual string Path { get; set; } [UmbracoInfo(UmbracoInfoType.Version)] public virtual Guid Version { get; set; } [UmbracoInfo(UmbracoInfoType.Name)] public virtual string Name { get; set; } } [UmbracoType] public class StubClassWithProperty { [UmbracoInfo(UmbracoInfoType.Name)] public virtual string Name { get; set; } } #endregion } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace BusinessApps.ChatRoomWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
using System; using System.Collections.Generic; using Fairweather.Service; namespace Common { public class Sorted_List_Cursor : Any_List_Cursor { public Sorted_List_Cursor(IDictionary<string, string> idict) { cnt = idict.Count; list1 = new List<Pair<string>>(cnt); list2 = new List<Pair<string>>(cnt); key_indices = new Dictionary<string, Pair<int>>(cnt); Load_Data_Inner(idict); } public void Load_Data(IDictionary<string, string> idict) { cnt = idict.Count; list1.Clear(); list2.Clear(); key_indices.Clear(); list1.Capacity = cnt; list2.Capacity = cnt; Load_Data_Inner(idict); } void Load_Data_Inner(IDictionary<string, string> idict) { var temp_dict1 = new Dictionary<string, int>(cnt); var temp_dict2 = new Dictionary<string, int>(cnt); foreach (var kvp in idict) { var pair1 = new Pair<string>(kvp.Key, kvp.Value); list1.Add(pair1); list2.Add(pair1); } bool do_not_sort = idict is SortedDictionary<string, string> || idict is SortedList<string, string>; if (!do_not_sort) { list1.Sort(Pair.Compare_First<string>); } list2.Sort(Pair.Compare_Second<string>); for (int ii = 0; ii < cnt; ++ii) { var key1 = list1[ii].First; var key2 = list2[ii].First; temp_dict1[key1] = ii; temp_dict2[key2] = ii; } foreach (var kvp in temp_dict1) { var key = kvp.Key; var pos1 = kvp.Value; var pos2 = temp_dict2[key]; key_indices[key] = new Pair<int>(pos1, pos2); } } Sorted_List_Cursor(List<Pair<string>> list1, List<Pair<string>> list2, Dictionary<string, Pair<int>> index) { cnt = list1.Count; (cnt == list2.Count).tiff(); (cnt == index.Count).tiff(); this.list1 = list1; this.list2 = list2; this.key_indices = index; } /// <summary> /// Adding a new key-value pair is required to take effect in all instances constructed /// from this one using GetCopy() /// </summary> public override Records_Cursor Get_Copy() { var ret = new Sorted_List_Cursor(list1, list2, key_indices); return ret; } int cnt; /// <summary> /// List of (key, value) ordered by key /// </summary> readonly List<Pair<string>> list1; /// <summary> /// List of (key, value) ordered by value /// </summary> readonly List<Pair<string>> list2; /// <summary> /// Dictionary of key -> (index of key in list1, index of key in list2) /// </summary> readonly Dictionary<string, Pair<int>> key_indices; public override int Count { get { return cnt; } } Func<int, int> GetComparer(string prefix, bool first_col, StringComparison comparison) { Func<int, int> ret = (int index) => { if (index == -1) return -1; if (!IsValidIndex(index)) true.tift(); var to_compare = GetValue(first_col, index); if (to_compare.StartsWith(prefix, comparison)) return 0; int cmp = String.Compare(prefix, to_compare, comparison); bool before = (cmp < 0); return before ? -1 : +1; }; return ret; } /// Returns a continuous range of elements, beginning with the first element /// whose key or value (specified by "key") start with the specified prefix. /// index and with the specified maximum length. "length" denotes the maximum /// number of returned elements. /// "length" of -1 signifies no upper bound. /// The direction of enumeration is affected by the SortedListCursor::Forward /// property. /// It may also return elements which do not satisfy the condition (at the end of /// the returned collection. //public override List<Pair<string>> GetRange(string prefix, int length, StringComparison comparison) { // bool forward = Forward; // bool first_col = First_Column; // var comparer = GetComparer(prefix, forward, first_col, comparison); // var startIndex = Algorithms.Binary_Range_Search1(0, Count - 1, comparer, forward); // if (startIndex == -1) // return new List<Pair<string>>(); // var ret = GetRange(startIndex, length); // return ret; //} // // /// Returns a continuous range of elements, beginning with the first element /// whose key or value (specified by "key") start with the specified prefix. /// index and with the specified maximum length. "length" denotes the maximum /// number of returned elements. /// "length" of -1 signifies no upper bound. /// The direction of enumeration is affected by the SortedListCursor::Forward /// property. /// It may not return elements which do not satisfy the condition (at the end of /// the returned collection. public override List<Pair<string>> GetPureRange(string prefix, int length, StringComparison comparison) { bool forward = Forward; bool first_col = First_Column; var comparer = GetComparer(prefix, first_col, comparison); var startIndex = Magic.Binary_Range_Search1(0, Count - 1, comparer, forward); var endIndex = Magic.Binary_Range_Search1(0, Count - 1, comparer, !forward); if (startIndex == -1) return new List<Pair<string>>(); if (endIndex == -1) endIndex = forward ? Count - 1 : 0; var length1 = endIndex - startIndex + 1; if (length != -1) length1 = Math.Min(length, length1); var ret = GetRange(startIndex, length1); return ret; } protected override Pair<string> GetPair(bool first_col, int real_index) { var list = first_col ? list1 : list2; var ret = list[real_index]; return ret; } public override bool ContainsKey(string key) { return key_indices.ContainsKey(key); } public override Pair<string>? GetKVP(string key) { Pair<int> tmp; if (!key_indices.TryGetValue(key, out tmp)) return null; var pair = list1[tmp.First]; return pair; } public override int? GetIndex(string prefix, bool partial, StringComparison comparison) { bool forward = Forward; bool first_col = First_Column; var comparer = GetComparer(prefix, first_col, comparison); var startIndex = Magic.Binary_Range_Search1(0, Count - 1, comparer, forward); if (startIndex == -1) return null; var result = GetIndex(forward, startIndex); if (!partial) { var found = GetValue(first_col, result); if (!found.Equals(prefix, comparison)) return null; } return result; } /// <summary> /// Adding a new key-value pair is required to take effect in all instances constructed /// from this one using GetCopy() /// </summary> public override bool Add_New(string key, string value) { if (key_indices.ContainsKey(key)) return false; var pair = new Pair<string>(key, value); int index1 = list1.Insert_Into_Sorted(pair, Pair.Compare_First<string>); int index2 = list2.Insert_Into_Sorted(pair, Pair.Compare_Second<string>); key_indices[key] = new Pair<int>(index1, index2); ++cnt; return true; } public override bool Remove(string key) { Pair<int> pair; if (!key_indices.TryGetValue(key, out pair)) return false; key_indices.Remove(key); list1.RemoveAt(pair.First); list2.RemoveAt(pair.Second); --cnt; return true; } public override bool Supports_Second_Column { get { return true; } } } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="BaseAppDomainIsolatedTask.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright> //------------------------------------------------------------------------------------------------------------------------------------------------------------------- namespace MSBuild.ExtensionPack { using System; using System.Globalization; using System.Management; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; /// <summary> /// Provides a common task for all the MSBuildExtensionPack Tasks that need to be instantiated in their own app domain. /// </summary> public abstract class BaseAppDomainIsolatedTask : AppDomainIsolatedTask { private string machineName; private AuthenticationLevel authenticationLevel = System.Management.AuthenticationLevel.Default; /// <summary> /// Sets the TaskAction. /// </summary> public virtual string TaskAction { get; set; } /// <summary> /// Sets the MachineName. /// </summary> public virtual string MachineName { get { return this.machineName ?? Environment.MachineName; } set { this.machineName = value; } } /// <summary> /// Sets the UserName /// </summary> public virtual string UserName { get; set; } /// <summary> /// Sets the UserPassword. /// </summary> public virtual string UserPassword { get; set; } /// <summary> /// Sets the authority to be used to authenticate the specified user. /// </summary> public string Authority { get; set; } /// <summary> /// Sets the authentication level to be used to connect to WMI. Default is Default. Also supports: Call, Connect, None, Packet, PacketIntegrity, PacketPrivacy, Unchanged /// </summary> public string AuthenticationLevel { get { return this.authenticationLevel.ToString(); } set { this.authenticationLevel = (AuthenticationLevel)Enum.Parse(typeof(AuthenticationLevel), value); } } /// <summary> /// Set to true to log the full Exception Stack to the console. /// </summary> public bool LogExceptionStack { get; set; } /// <summary> /// Set to true to suppress all Message logging by tasks. Errors and Warnings are not affected. /// </summary> public bool SuppressTaskMessages { get; set; } internal ManagementScope Scope { get; set; } /// <summary> /// Executes this instance. /// </summary> /// <returns>bool</returns> public override sealed bool Execute() { this.DetermineLogging(); try { this.InternalExecute(); return !this.Log.HasLoggedErrors; } catch (Exception ex) { this.GetExceptionLevel(); this.Log.LogErrorFromException(ex, this.LogExceptionStack, true, null); return !this.Log.HasLoggedErrors; } } /// <summary> /// Determines whether the task is targeting the local machine /// </summary> /// <returns>bool</returns> internal bool TargetingLocalMachine() { return this.TargetingLocalMachine(false); } /// <summary> /// Determines whether the task is targeting the local machine /// </summary> /// <param name="canExecuteRemotely">True if the current TaskAction can run against a remote machine</param> /// <returns>bool</returns> internal bool TargetingLocalMachine(bool canExecuteRemotely) { if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) != 0) { if (!canExecuteRemotely) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "This task does not support remote execution. Please remove the MachineName: {0}", this.MachineName)); } return false; } return true; } internal void LogTaskWarning(string message) { this.Log.LogWarning(message); } internal void LogTaskMessage(MessageImportance messageImportance, string message) { this.LogTaskMessage(messageImportance, message, null); } internal void LogTaskMessage(string message, object[] arguments) { this.LogTaskMessage(MessageImportance.Normal, message, arguments); } internal void LogTaskMessage(string message) { this.LogTaskMessage(MessageImportance.Normal, message, null); } internal void LogTaskMessage(MessageImportance messageImportance, string message, object[] arguments) { if (!this.SuppressTaskMessages) { if (arguments == null) { this.Log.LogMessage(messageImportance, message); } else { this.Log.LogMessage(messageImportance, message, arguments); } } } internal void GetManagementScope(string wmiNamespace) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "ManagementScope Set: {0}", "\\\\" + this.MachineName + wmiNamespace)); if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0) { this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace); } else { ConnectionOptions options = new ConnectionOptions { Authentication = this.authenticationLevel, Username = this.UserName, Password = this.UserPassword, Authority = this.Authority }; this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace, options); } } internal void GetManagementScope(string wmiNamespace, ConnectionOptions options) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "ManagementScope Set: {0}", "\\\\" + this.MachineName + wmiNamespace)); this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace, options); } /// <summary> /// This is the main InternalExecute method that all tasks should implement /// </summary> /// <remarks> /// LogError should be thrown in the event of errors /// </remarks> protected abstract void InternalExecute(); private void GetExceptionLevel() { string s = Environment.GetEnvironmentVariable("LogExceptionStack", EnvironmentVariableTarget.Machine); if (!string.IsNullOrEmpty(s)) { this.LogExceptionStack = Convert.ToBoolean(s, CultureInfo.CurrentCulture); } } private void DetermineLogging() { string s = Environment.GetEnvironmentVariable("SuppressTaskMessages", EnvironmentVariableTarget.Machine); if (!string.IsNullOrEmpty(s)) { this.SuppressTaskMessages = Convert.ToBoolean(s, CultureInfo.CurrentCulture); } } } }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; namespace Amib.Threading.Internal { #region WorkItemsGroup class /// <summary> /// Summary description for WorkItemsGroup. /// </summary> public class WorkItemsGroup : WorkItemsGroupBase { #region Private members /// <summary> /// Signaled when all of the WorkItemsGroup's work item completed. /// </summary> //private readonly ManualResetEvent _isIdleWaitHandle = new ManualResetEvent(true); private readonly ManualResetEvent _isIdleWaitHandle = EventWaitHandleFactory.CreateManualResetEvent(true); private readonly object _lock = new object(); /// <summary> /// A reference to the SmartThreadPool instance that created this /// WorkItemsGroup. /// </summary> private readonly SmartThreadPool _stp; /// <summary> /// WorkItemsGroup start information /// </summary> private readonly WIGStartInfo _workItemsGroupStartInfo; /// <summary> /// Priority queue to hold work items before they are passed /// to the SmartThreadPool. /// </summary> private readonly PriorityQueue _workItemsQueue; /// <summary> /// A common object for all the work items that this work items group /// generate so we can mark them to cancel in O(1) /// </summary> private CanceledWorkItemsGroup _canceledWorkItemsGroup = new CanceledWorkItemsGroup(); /// <summary> /// Defines how many work items of this WorkItemsGroup can run at once. /// </summary> private int _concurrency; /// <summary> /// A flag to indicate if the Work Items Group is now suspended. /// </summary> private bool _isSuspended; /// <summary> /// Indicate how many work items are currently running in the SmartThreadPool. /// This value is used with the Cancel, to calculate if we can send new /// work items to the STP. /// </summary> private int _workItemsExecutingInStp = 0; /// <summary> /// Indicate how many work items are waiting in the SmartThreadPool /// queue. /// This value is used to apply the concurrency. /// </summary> private int _workItemsInStpQueue; /// <summary> /// The OnIdle event /// </summary> private event WorkItemsGroupIdleHandler _onIdle; #endregion Private members #region Construction public WorkItemsGroup( SmartThreadPool stp, int concurrency, WIGStartInfo wigStartInfo) { if (concurrency <= 0) { throw new ArgumentOutOfRangeException( "concurrency", #if !(_WINDOWS_CE) && !(_SILVERLIGHT) && !(WINDOWS_PHONE) concurrency, #endif "concurrency must be greater than zero"); } _stp = stp; _concurrency = concurrency; _workItemsGroupStartInfo = new WIGStartInfo(wigStartInfo).AsReadOnly(); _workItemsQueue = new PriorityQueue(); Name = "WorkItemsGroup"; // The _workItemsInStpQueue gets the number of currently executing work items, // because once a work item is executing, it cannot be cancelled. _workItemsInStpQueue = _workItemsExecutingInStp; _isSuspended = _workItemsGroupStartInfo.StartSuspended; } #endregion Construction #region WorkItemsGroupBase Overrides public override event WorkItemsGroupIdleHandler OnIdle { add { _onIdle += value; } remove { _onIdle -= value; } } public override int Concurrency { get { return _concurrency; } set { Debug.Assert(value > 0); int diff = value - _concurrency; _concurrency = value; if (diff > 0) { EnqueueToSTPNextNWorkItem(diff); } } } public override int WaitingCallbacks { get { return _workItemsQueue.Count; } } /// <summary> /// WorkItemsGroup start information /// </summary> public override WIGStartInfo WIGStartInfo { get { return _workItemsGroupStartInfo; } } public override void Cancel(bool abortExecution) { lock (_lock) { _canceledWorkItemsGroup.IsCanceled = true; _workItemsQueue.Clear(); _workItemsInStpQueue = 0; _canceledWorkItemsGroup = new CanceledWorkItemsGroup(); } if (abortExecution) { _stp.CancelAbortWorkItemsGroup(this); } } public override object[] GetStates() { lock (_lock) { object[] states = new object[_workItemsQueue.Count]; int i = 0; foreach (WorkItem workItem in _workItemsQueue) { states[i] = workItem.GetWorkItemResult().State; ++i; } return states; } } /// <summary> /// Start the Work Items Group if it was started suspended /// </summary> public override void Start() { // If the Work Items Group already started then quit if (!_isSuspended) { return; } _isSuspended = false; EnqueueToSTPNextNWorkItem(Math.Min(_workItemsQueue.Count, _concurrency)); } /// <summary> /// Wait for the thread pool to be idle /// </summary> public override bool WaitForIdle(int millisecondsTimeout) { SmartThreadPool.ValidateWorkItemsGroupWaitForIdle(this); return STPEventWaitHandle.WaitOne(_isIdleWaitHandle, millisecondsTimeout, false); } #endregion WorkItemsGroupBase Overrides #region Private methods public void EnqueueToSTPNextNWorkItem(int count) { for (int i = 0; i < count; ++i) { EnqueueToSTPNextWorkItem(null, false); } } public void OnSTPIsStarting() { if (_isSuspended) { return; } EnqueueToSTPNextNWorkItem(_concurrency); } internal override void Enqueue(WorkItem workItem) { EnqueueToSTPNextWorkItem(workItem); } private void EnqueueToSTPNextWorkItem(WorkItem workItem) { EnqueueToSTPNextWorkItem(workItem, false); } private void EnqueueToSTPNextWorkItem(WorkItem workItem, bool decrementWorkItemsInStpQueue) { lock (_lock) { // Got here from OnWorkItemCompletedCallback() if (decrementWorkItemsInStpQueue) { --_workItemsInStpQueue; if (_workItemsInStpQueue < 0) { _workItemsInStpQueue = 0; } --_workItemsExecutingInStp; if (_workItemsExecutingInStp < 0) { _workItemsExecutingInStp = 0; } } // If the work item is not null then enqueue it if (null != workItem) { workItem.CanceledWorkItemsGroup = _canceledWorkItemsGroup; RegisterToWorkItemCompletion(workItem.GetWorkItemResult()); _workItemsQueue.Enqueue(workItem); //_stp.IncrementWorkItemsCount(); if ((1 == _workItemsQueue.Count) && (0 == _workItemsInStpQueue)) { _stp.RegisterWorkItemsGroup(this); IsIdle = false; _isIdleWaitHandle.Reset(); } } // If the work items queue of the group is empty than quit if (0 == _workItemsQueue.Count) { if (0 == _workItemsInStpQueue) { _stp.UnregisterWorkItemsGroup(this); IsIdle = true; _isIdleWaitHandle.Set(); if (decrementWorkItemsInStpQueue && _onIdle != null && _onIdle.GetInvocationList().Length > 0) { _stp.QueueWorkItem(new WorkItemCallback(FireOnIdle)); } } return; } if (!_isSuspended) { if (_workItemsInStpQueue < _concurrency) { WorkItem nextWorkItem = _workItemsQueue.Dequeue() as WorkItem; try { _stp.Enqueue(nextWorkItem); } catch (ObjectDisposedException e) { e.GetHashCode(); // The STP has been shutdown } ++_workItemsInStpQueue; } } } } private object FireOnIdle(object state) { FireOnIdleImpl(_onIdle); return null; } [MethodImpl(MethodImplOptions.NoInlining)] private void FireOnIdleImpl(WorkItemsGroupIdleHandler onIdle) { if (null == onIdle) { return; } Delegate[] delegates = onIdle.GetInvocationList(); foreach (WorkItemsGroupIdleHandler eh in delegates) { try { eh(this); } catch { } // Suppress exceptions } } private void OnWorkItemCompletedCallback(WorkItem workItem) { EnqueueToSTPNextWorkItem(null, true); } private void OnWorkItemStartedCallback(WorkItem workItem) { lock (_lock) { ++_workItemsExecutingInStp; } } private void RegisterToWorkItemCompletion(IWorkItemResult wir) { IInternalWorkItemResult iwir = (IInternalWorkItemResult)wir; iwir.OnWorkItemStarted += OnWorkItemStartedCallback; iwir.OnWorkItemCompleted += OnWorkItemCompletedCallback; } #endregion Private methods } #endregion WorkItemsGroup class }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using Infoplus.Client; using Infoplus.Model; namespace Infoplus.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface ILowStockApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search lowStocks by filter /// </summary> /// <remarks> /// Returns the list of lowStocks that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;LowStock&gt;</returns> List<LowStock> GetLowStockByFilter (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search lowStocks by filter /// </summary> /// <remarks> /// Returns the list of lowStocks that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;LowStock&gt;</returns> ApiResponse<List<LowStock>> GetLowStockByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a lowStock by id /// </summary> /// <remarks> /// Returns the lowStock identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="lowStockId">Id of the lowStock to be returned.</param> /// <returns>LowStock</returns> LowStock GetLowStockById (int? lowStockId); /// <summary> /// Get a lowStock by id /// </summary> /// <remarks> /// Returns the lowStock identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="lowStockId">Id of the lowStock to be returned.</param> /// <returns>ApiResponse of LowStock</returns> ApiResponse<LowStock> GetLowStockByIdWithHttpInfo (int? lowStockId); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search lowStocks by filter /// </summary> /// <remarks> /// Returns the list of lowStocks that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;LowStock&gt;</returns> System.Threading.Tasks.Task<List<LowStock>> GetLowStockByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Search lowStocks by filter /// </summary> /// <remarks> /// Returns the list of lowStocks that match the given filter. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;LowStock&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<LowStock>>> GetLowStockByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null); /// <summary> /// Get a lowStock by id /// </summary> /// <remarks> /// Returns the lowStock identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="lowStockId">Id of the lowStock to be returned.</param> /// <returns>Task of LowStock</returns> System.Threading.Tasks.Task<LowStock> GetLowStockByIdAsync (int? lowStockId); /// <summary> /// Get a lowStock by id /// </summary> /// <remarks> /// Returns the lowStock identified by the specified id. /// </remarks> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="lowStockId">Id of the lowStock to be returned.</param> /// <returns>Task of ApiResponse (LowStock)</returns> System.Threading.Tasks.Task<ApiResponse<LowStock>> GetLowStockByIdAsyncWithHttpInfo (int? lowStockId); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class LowStockApi : ILowStockApi { private Infoplus.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="LowStockApi"/> class. /// </summary> /// <returns></returns> public LowStockApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="LowStockApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public LowStockApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = Infoplus.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public Infoplus.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Search lowStocks by filter Returns the list of lowStocks that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>List&lt;LowStock&gt;</returns> public List<LowStock> GetLowStockByFilter (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<LowStock>> localVarResponse = GetLowStockByFilterWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search lowStocks by filter Returns the list of lowStocks that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>ApiResponse of List&lt;LowStock&gt;</returns> public ApiResponse< List<LowStock> > GetLowStockByFilterWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/lowStock/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetLowStockByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<LowStock>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<LowStock>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<LowStock>))); } /// <summary> /// Search lowStocks by filter Returns the list of lowStocks that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of List&lt;LowStock&gt;</returns> public async System.Threading.Tasks.Task<List<LowStock>> GetLowStockByFilterAsync (string filter = null, int? page = null, int? limit = null, string sort = null) { ApiResponse<List<LowStock>> localVarResponse = await GetLowStockByFilterAsyncWithHttpInfo(filter, page, limit, sort); return localVarResponse.Data; } /// <summary> /// Search lowStocks by filter Returns the list of lowStocks that match the given filter. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Query string, used to filter results. (optional)</param> /// <param name="page">Result page number. Defaults to 1. (optional)</param> /// <param name="limit">Maximum results per page. Defaults to 20. Max allowed value is 250. (optional)</param> /// <param name="sort">Sort results by specified field. (optional)</param> /// <returns>Task of ApiResponse (List&lt;LowStock&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<LowStock>>> GetLowStockByFilterAsyncWithHttpInfo (string filter = null, int? page = null, int? limit = null, string sort = null) { var localVarPath = "/v1.0/lowStock/search"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter if (page != null) localVarQueryParams.Add("page", Configuration.ApiClient.ParameterToString(page)); // query parameter if (limit != null) localVarQueryParams.Add("limit", Configuration.ApiClient.ParameterToString(limit)); // query parameter if (sort != null) localVarQueryParams.Add("sort", Configuration.ApiClient.ParameterToString(sort)); // query parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetLowStockByFilter", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<LowStock>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<LowStock>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<LowStock>))); } /// <summary> /// Get a lowStock by id Returns the lowStock identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="lowStockId">Id of the lowStock to be returned.</param> /// <returns>LowStock</returns> public LowStock GetLowStockById (int? lowStockId) { ApiResponse<LowStock> localVarResponse = GetLowStockByIdWithHttpInfo(lowStockId); return localVarResponse.Data; } /// <summary> /// Get a lowStock by id Returns the lowStock identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="lowStockId">Id of the lowStock to be returned.</param> /// <returns>ApiResponse of LowStock</returns> public ApiResponse< LowStock > GetLowStockByIdWithHttpInfo (int? lowStockId) { // verify the required parameter 'lowStockId' is set if (lowStockId == null) throw new ApiException(400, "Missing required parameter 'lowStockId' when calling LowStockApi->GetLowStockById"); var localVarPath = "/v1.0/lowStock/{lowStockId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (lowStockId != null) localVarPathParams.Add("lowStockId", Configuration.ApiClient.ParameterToString(lowStockId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetLowStockById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<LowStock>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (LowStock) Configuration.ApiClient.Deserialize(localVarResponse, typeof(LowStock))); } /// <summary> /// Get a lowStock by id Returns the lowStock identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="lowStockId">Id of the lowStock to be returned.</param> /// <returns>Task of LowStock</returns> public async System.Threading.Tasks.Task<LowStock> GetLowStockByIdAsync (int? lowStockId) { ApiResponse<LowStock> localVarResponse = await GetLowStockByIdAsyncWithHttpInfo(lowStockId); return localVarResponse.Data; } /// <summary> /// Get a lowStock by id Returns the lowStock identified by the specified id. /// </summary> /// <exception cref="Infoplus.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="lowStockId">Id of the lowStock to be returned.</param> /// <returns>Task of ApiResponse (LowStock)</returns> public async System.Threading.Tasks.Task<ApiResponse<LowStock>> GetLowStockByIdAsyncWithHttpInfo (int? lowStockId) { // verify the required parameter 'lowStockId' is set if (lowStockId == null) throw new ApiException(400, "Missing required parameter 'lowStockId' when calling LowStockApi->GetLowStockById"); var localVarPath = "/v1.0/lowStock/{lowStockId}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (lowStockId != null) localVarPathParams.Add("lowStockId", Configuration.ApiClient.ParameterToString(lowStockId)); // path parameter // authentication (api_key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("API-Key"))) { localVarHeaderParams["API-Key"] = Configuration.GetApiKeyWithPrefix("API-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetLowStockById", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<LowStock>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (LowStock) Configuration.ApiClient.Deserialize(localVarResponse, typeof(LowStock))); } } }
/* * Copyright 2011 Software Freedom Conservancy. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.IO; using System.Net; using System.Threading; using System.Collections; using System.Text; using Selenium; namespace Selenium { /// <summary> /// Sends commands and retrieves results via HTTP. /// </summary> public class HttpCommandProcessor : ICommandProcessor { private readonly string url; private string sessionId; private string browserStartCommand; private string browserURL; private string extensionJs; /// <summary> /// The server URL, to whom we send command requests /// </summary> public string Url { get { return url; } } /// <summary> /// Specifies a server host/port, a command to launch the browser, and a starting URL for the browser. /// </summary> /// <param name="serverHost">the host name on which the Selenium Server resides</param> /// <param name="serverPort">the port on which the Selenium Server is listening</param> /// <param name="browserStartCommand">the command string used to launch the browser, e.g. "*firefox" or "c:\\program files\\internet explorer\\iexplore.exe"</param> /// <param name="browserURL">the starting URL including just a domain name. We'll start the browser pointing at the Selenium resources on this URL, /// e.g. "http://www.google.com" would send the browser to "http://www.google.com/selenium-server/RemoteRunner.html"</param> public HttpCommandProcessor(string serverHost, int serverPort, string browserStartCommand, string browserURL) { this.url = "http://" + serverHost + ":"+ serverPort + "/selenium-server/driver/"; this.browserStartCommand = browserStartCommand; this.browserURL = browserURL; this.extensionJs = ""; } /// <summary> /// Specifies the URL to the server, a command to launch the browser, and a starting URL for the browser. /// </summary> /// <param name="serverURL">the URL of the Selenium Server Driver, e.g. "http://localhost:4444/selenium-server/driver/" (don't forget the final slash!)</param> /// <param name="browserStartCommand">the command string used to launch the browser, e.g. "*firefox" or "c:\\program files\\internet explorer\\iexplore.exe"</param> /// <param name="browserURL">the starting URL including just a domain name. We'll start the browser pointing at the Selenium resources on this URL, /// e.g. "http://www.google.com" would send the browser to "http://www.google.com/selenium-server/RemoteRunner.html"</param> public HttpCommandProcessor(string serverURL, string browserStartCommand, string browserURL) { this.url = serverURL; this.browserStartCommand = browserStartCommand; this.browserURL = browserURL; this.extensionJs = ""; } /// <summary> /// Send the specified remote command to the browser to be performed /// </summary> /// <param name="command">the remote command verb</param> /// <param name="args">the arguments to the remote command (depends on the verb)</param> /// <returns>the command result, defined by the remote JavaScript. "getX" style /// commands may return data from the browser</returns> public string DoCommand(string command, string[] args) { IRemoteCommand remoteCommand = new DefaultRemoteCommand(command, args); using (HttpWebResponse response = (HttpWebResponse) CreateWebRequest(remoteCommand).GetResponse()) { if (response.StatusCode != HttpStatusCode.OK) { throw new SeleniumException(response.StatusDescription); } string resultBody = ReadResponse(response); if (!resultBody.StartsWith("OK")) { throw new SeleniumException(resultBody); } return resultBody; } } /// <summary> /// Retrieves the body of the HTTP response /// </summary> /// <param name="response">the response object to read</param> /// <returns>the body of the HTTP response</returns> public virtual string ReadResponse(HttpWebResponse response) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } } /// <summary> /// Builds an HTTP request based on the specified remote Command /// </summary> /// <param name="command">the command we'll send to the server</param> /// <returns>an HTTP request, which will perform this command</returns> public virtual WebRequest CreateWebRequest(IRemoteCommand command) { byte[] data = BuildCommandPostData(command.CommandString); HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded; charset=utf-8"; request.Timeout = Timeout.Infinite; request.ServicePoint.ConnectionLimit = 2000; Stream rs = request.GetRequestStream(); rs.Write(data, 0, data.Length); rs.Close(); return request; } private byte[] BuildCommandPostData(string commandString) { string data = commandString; if (sessionId != null) { data += "&sessionId=" + sessionId; } return (new UTF8Encoding()).GetBytes(data); } /// <summary> /// Sets the extension Javascript to be used in the created session /// </summary> /// <param name="extensionJs">The extension JavaScript to use.</param> public void SetExtensionJs(string extensionJs) { this.extensionJs = extensionJs; } /// <summary> /// Creates a new browser session /// </summary> public void Start() { string result = GetString("getNewBrowserSession", new String[] {browserStartCommand, browserURL, extensionJs}); sessionId = result; } /// <summary> /// Take any extra options that may be needed when creating a browser session /// </summary> /// <param name="optionString">Browser Options</param> public void Start(string optionString) { string result = GetString("getNewBrowserSession", new String[] { browserStartCommand, browserURL, extensionJs, optionString }); sessionId = result; } /// <summary> /// Wraps the version of start() that takes a string parameter, sending it the result /// of calling ToString() on optionsObject, which will likey be a BrowserConfigurationOptions instan /// </summary> /// <param name="optionsObject">Contains BrowserConfigurationOptions </param> public void Start(Object optionsObject) { Start(optionsObject.ToString()); } /// <summary> /// Stops the previous browser session, killing the browser /// </summary> public void Stop() { DoCommand("testComplete", null); sessionId = null; } /// <summary> /// Runs the specified remote accessor (getter) command and returns the retrieved result /// </summary> /// <param name="commandName">the remote Command verb</param> /// <param name="args">the arguments to the remote Command (depends on the verb)</param> /// <returns>the result of running the accessor on the browser</returns> public String GetString(String commandName, String[] args) { return DoCommand(commandName, args).Substring(3); // skip "OK," } /// <summary> /// Runs the specified remote accessor (getter) command and returns the retrieved result /// </summary> /// <param name="commandName">the remote Command verb</param> /// <param name="args">the arguments to the remote Command (depends on the verb)</param> /// <returns>the result of running the accessor on the browser</returns> public String[] GetStringArray(String commandName, String[] args) { String result = GetString(commandName, args); return parseCSV(result); } /// <summary> /// Parse Selenium comma separated values. /// </summary> /// <param name="input">the comma delimited string to parse</param> /// <returns>the parsed comma-separated entries</returns> public static String[] parseCSV(String input) { ArrayList output = new ArrayList(); StringBuilder sb = new StringBuilder(); for(int i = 0; i < input.Length; i++) { char c = input.ToCharArray()[i]; switch (c) { case ',': output.Add(sb.ToString()); sb = new StringBuilder(); continue; case '\\': i++; c = input.ToCharArray()[i]; sb.Append(c); continue; default: sb.Append(c); break; } } output.Add(sb.ToString()); return (String[]) output.ToArray(typeof(String)); } /// <summary> /// Runs the specified remote accessor (getter) command and returns the retrieved result /// </summary> /// <param name="commandName">the remote Command verb</param> /// <param name="args">the arguments to the remote Command (depends on the verb)</param> /// <returns>the result of running the accessor on the browser</returns> public Decimal GetNumber(String commandName, String[] args) { String result = GetString(commandName, args); Decimal d = Decimal.Parse(result); return d; } /// <summary> /// Runs the specified remote accessor (getter) command and returns the retrieved result /// </summary> /// <param name="commandName">the remote Command verb</param> /// <param name="args">the arguments to the remote Command (depends on the verb)</param> /// <returns>the result of running the accessor on the browser</returns> public Decimal[] GetNumberArray(String commandName, String[] args) { String[] result = GetStringArray(commandName, args); Decimal[] d = new Decimal[result.Length]; for (int i = 0; i < result.Length; i++) { d[i] = Decimal.Parse(result[i]); } return d; } /// <summary> /// Runs the specified remote accessor (getter) command and returns the retrieved result /// </summary> /// <param name="commandName">the remote Command verb</param> /// <param name="args">the arguments to the remote Command (depends on the verb)</param> /// <returns>the result of running the accessor on the browser</returns> public bool GetBoolean(String commandName, String[] args) { String result = GetString(commandName, args); bool b; if ("true".Equals(result)) { b = true; return b; } if ("false".Equals(result)) { b = false; return b; } throw new Exception("result was neither 'true' nor 'false': " + result); } /// <summary> /// Runs the specified remote accessor (getter) command and returns the retrieved result /// </summary> /// <param name="commandName">the remote Command verb</param> /// <param name="args">the arguments to the remote Command (depends on the verb)</param> /// <returns>the result of running the accessor on the browser</returns> public bool[] GetBooleanArray(String commandName, String[] args) { String[] result = GetStringArray(commandName, args); bool[] b = new bool[result.Length]; for (int i = 0; i < result.Length; i++) { if ("true".Equals(result)) { b[i] = true; continue; } if ("false".Equals(result)) { b[i] = false; continue; } throw new Exception("result was neither 'true' nor 'false': " + result); } return b; } } }
using System; using System.IO; namespace SilentOrbit.ProtocolBuffers { public static partial class ProtocolParser { /// <summary> /// Reads past a varint for an unknown field. /// </summary> public static void ReadSkipVarInt(Stream stream) { while (true) { int b = stream.ReadByte(); if (b < 0) throw new IOException("Stream ended too early"); if ((b & 0x80) == 0) return; //end of varint } } public static byte[] ReadVarIntBytes(Stream stream) { byte[] buffer = new byte[10]; int offset = 0; while (true) { int b = stream.ReadByte(); if (b < 0) throw new IOException("Stream ended too early"); buffer[offset] = (byte)b; offset += 1; if ((b & 0x80) == 0) break; //end of varint if (offset >= buffer.Length) throw new ProtocolBufferException("VarInt too long, more than 10 bytes"); } byte[] ret = new byte[offset]; Array.Copy(buffer, ret, ret.Length); return ret; } #region VarInt: int32, uint32, sint32 /// <summary> /// Since the int32 format is inefficient for negative numbers we have avoided to implement it. /// The same functionality can be achieved using: (int)ReadUInt64(stream); /// </summary> [Obsolete("Use (int)ReadUInt64(stream); //yes 64")] public static int ReadInt32(Stream stream) { return (int)ReadUInt64(stream); } /// <summary> /// Since the int32 format is inefficient for negative numbers we have avoided to imlplement. /// The same functionality can be achieved using: WriteUInt64(stream, (uint)val); /// Note that 64 must always be used for int32 to generate the ten byte wire format. /// </summary> [Obsolete("Use WriteUInt64(stream, (ulong)val); //yes 64, negative numbers are encoded that way")] public static void WriteInt32(Stream stream, int val) { //signed varint is always encoded as 64 but values! WriteUInt64(stream, (ulong)val); } /// <summary> /// Zig-zag signed VarInt format /// </summary> public static int ReadZInt32(Stream stream) { uint val = ReadUInt32(stream); return (int)(val >> 1) ^ ((int)(val << 31) >> 31); } /// <summary> /// Zig-zag signed VarInt format /// </summary> public static void WriteZInt32(Stream stream, int val) { WriteUInt32(stream, (uint)((val << 1) ^ (val >> 31))); } /// <summary> /// Unsigned VarInt format /// Do not use to read int32, use ReadUint64 for that. /// </summary> public static uint ReadUInt32(Stream stream) { uint val = 0; for (int n = 0; n < 5; n++) { int b = stream.ReadByte(); if (b < 0) throw new IOException("Stream ended too early"); //Check that it fits in 32 bits if ((n == 4) && (b & 0xF0) != 0) throw new ProtocolBufferException("Got larger VarInt than 32bit unsigned"); //End of check if ((b & 0x80) == 0) return val | (uint)b << (7 * n); val |= (uint)(b & 0x7F) << (7 * n); } throw new ProtocolBufferException("Got larger VarInt than 32bit unsigned"); } /// <summary> /// Unsigned VarInt format /// </summary> public static void WriteUInt32(Stream stream, uint val) { while (true) { byte b = (byte)(val & 0x7F); val = val >> 7; if (val == 0) { stream.WriteByte(b); break; } else { b |= 0x80; stream.WriteByte(b); } } } #endregion VarInt: int32, uint32, sint32 #region VarInt: int64, UInt64, SInt64 /// <summary> /// Since the int64 format is inefficient for negative numbers we have avoided to implement it. /// The same functionality can be achieved using: (long)ReadUInt64(stream); /// </summary> [Obsolete("Use (long)ReadUInt64(stream); instead")] public static int ReadInt64(Stream stream) { return (int)ReadUInt64(stream); } /// <summary> /// Since the int64 format is inefficient for negative numbers we have avoided to implement. /// The same functionality can be achieved using: WriteUInt64 (stream, (ulong)val); /// </summary> [Obsolete("Use WriteUInt64 (stream, (ulong)val); instead")] public static void WriteInt64(Stream stream, int val) { WriteUInt64(stream, (ulong)val); } /// <summary> /// Zig-zag signed VarInt format /// </summary> public static long ReadZInt64(Stream stream) { ulong val = ReadUInt64(stream); return (long)(val >> 1) ^ ((long)(val << 63) >> 63); } /// <summary> /// Zig-zag signed VarInt format /// </summary> public static void WriteZInt64(Stream stream, long val) { WriteUInt64(stream, (ulong)((val << 1) ^ (val >> 63))); } /// <summary> /// Unsigned VarInt format /// </summary> public static ulong ReadUInt64(Stream stream) { ulong val = 0; for (int n = 0; n < 10; n++) { int b = stream.ReadByte(); if (b < 0) throw new IOException("Stream ended too early"); //Check that it fits in 64 bits if ((n == 9) && (b & 0xFE) != 0) throw new ProtocolBufferException("Got larger VarInt than 64 bit unsigned"); //End of check if ((b & 0x80) == 0) return val | (ulong)b << (7 * n); val |= (ulong)(b & 0x7F) << (7 * n); } throw new ProtocolBufferException("Got larger VarInt than 64 bit unsigned"); } /// <summary> /// Unsigned VarInt format /// </summary> public static void WriteUInt64(Stream stream, ulong val) { while (true) { byte b = (byte)(val & 0x7F); val = val >> 7; if (val == 0) { stream.WriteByte(b); break; } else { b |= 0x80; stream.WriteByte(b); } } } #endregion VarInt: int64, UInt64, SInt64 #region Varint: bool public static bool ReadBool(Stream stream) { int b = stream.ReadByte(); if (b < 0) throw new IOException("Stream ended too early"); if (b == 1) return true; if (b == 0) return false; throw new ProtocolBufferException("Invalid boolean value"); } public static void WriteBool(Stream stream, bool val) { stream.WriteByte(val ? (byte)1 : (byte)0); } #endregion Varint: bool } }
/* * Infoplus API * * Infoplus API. * * OpenAPI spec version: v1.0 * Contact: api@infopluscommerce.com * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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 NUnit.Framework; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Infoplus.Api; using Infoplus.Model; using Infoplus.Client; using System.Reflection; namespace Infoplus.Test { /// <summary> /// Class for testing ItemReceipt /// </summary> /// <remarks> /// This file is automatically generated by Swagger Codegen. /// Please update the test case below to test the model. /// </remarks> [TestFixture] public class ItemReceiptTests { // TODO uncomment below to declare an instance variable for ItemReceipt //private ItemReceipt instance; /// <summary> /// Setup before each test /// </summary> [SetUp] public void Init() { // TODO uncomment below to create an instance of ItemReceipt //instance = new ItemReceipt(); } /// <summary> /// Clean up after each test /// </summary> [TearDown] public void Cleanup() { } /// <summary> /// Test an instance of ItemReceipt /// </summary> [Test] public void ItemReceiptInstanceTest() { // TODO uncomment below to test "IsInstanceOfType" ItemReceipt //Assert.IsInstanceOfType<ItemReceipt> (instance, "variable 'instance' is a ItemReceipt"); } /// <summary> /// Test the property 'Id' /// </summary> [Test] public void IdTest() { // TODO unit test for the property 'Id' } /// <summary> /// Test the property 'PoNo' /// </summary> [Test] public void PoNoTest() { // TODO unit test for the property 'PoNo' } /// <summary> /// Test the property 'LobId' /// </summary> [Test] public void LobIdTest() { // TODO unit test for the property 'LobId' } /// <summary> /// Test the property 'LegacyPoNo' /// </summary> [Test] public void LegacyPoNoTest() { // TODO unit test for the property 'LegacyPoNo' } /// <summary> /// Test the property 'WarehouseId' /// </summary> [Test] public void WarehouseIdTest() { // TODO unit test for the property 'WarehouseId' } /// <summary> /// Test the property 'OrderDate' /// </summary> [Test] public void OrderDateTest() { // TODO unit test for the property 'OrderDate' } /// <summary> /// Test the property 'FactCost' /// </summary> [Test] public void FactCostTest() { // TODO unit test for the property 'FactCost' } /// <summary> /// Test the property 'MlCost' /// </summary> [Test] public void MlCostTest() { // TODO unit test for the property 'MlCost' } /// <summary> /// Test the property 'Sku' /// </summary> [Test] public void SkuTest() { // TODO unit test for the property 'Sku' } /// <summary> /// Test the property 'OrderQuantity' /// </summary> [Test] public void OrderQuantityTest() { // TODO unit test for the property 'OrderQuantity' } /// <summary> /// Test the property 'RequestedDeliveryDate' /// </summary> [Test] public void RequestedDeliveryDateTest() { // TODO unit test for the property 'RequestedDeliveryDate' } /// <summary> /// Test the property 'UnitCode' /// </summary> [Test] public void UnitCodeTest() { // TODO unit test for the property 'UnitCode' } /// <summary> /// Test the property 'WrapCode' /// </summary> [Test] public void WrapCodeTest() { // TODO unit test for the property 'WrapCode' } /// <summary> /// Test the property 'UnitsPerWrap' /// </summary> [Test] public void UnitsPerWrapTest() { // TODO unit test for the property 'UnitsPerWrap' } /// <summary> /// Test the property 'Cost' /// </summary> [Test] public void CostTest() { // TODO unit test for the property 'Cost' } /// <summary> /// Test the property 'Sell' /// </summary> [Test] public void SellTest() { // TODO unit test for the property 'Sell' } /// <summary> /// Test the property 'PricingPer' /// </summary> [Test] public void PricingPerTest() { // TODO unit test for the property 'PricingPer' } /// <summary> /// Test the property 'MaxFreight' /// </summary> [Test] public void MaxFreightTest() { // TODO unit test for the property 'MaxFreight' } /// <summary> /// Test the property 'ChargeFreight' /// </summary> [Test] public void ChargeFreightTest() { // TODO unit test for the property 'ChargeFreight' } /// <summary> /// Test the property 'MaxOther' /// </summary> [Test] public void MaxOtherTest() { // TODO unit test for the property 'MaxOther' } /// <summary> /// Test the property 'DistDate' /// </summary> [Test] public void DistDateTest() { // TODO unit test for the property 'DistDate' } /// <summary> /// Test the property 'VoidDate' /// </summary> [Test] public void VoidDateTest() { // TODO unit test for the property 'VoidDate' } /// <summary> /// Test the property 'FreezeAction' /// </summary> [Test] public void FreezeActionTest() { // TODO unit test for the property 'FreezeAction' } /// <summary> /// Test the property 'RevDate' /// </summary> [Test] public void RevDateTest() { // TODO unit test for the property 'RevDate' } /// <summary> /// Test the property 'ArtBack' /// </summary> [Test] public void ArtBackTest() { // TODO unit test for the property 'ArtBack' } /// <summary> /// Test the property 'Origin' /// </summary> [Test] public void OriginTest() { // TODO unit test for the property 'Origin' } /// <summary> /// Test the property 'Sample' /// </summary> [Test] public void SampleTest() { // TODO unit test for the property 'Sample' } /// <summary> /// Test the property 'SampleTo' /// </summary> [Test] public void SampleToTest() { // TODO unit test for the property 'SampleTo' } /// <summary> /// Test the property 'MaxOvers' /// </summary> [Test] public void MaxOversTest() { // TODO unit test for the property 'MaxOvers' } /// <summary> /// Test the property 'MaxUnders' /// </summary> [Test] public void MaxUndersTest() { // TODO unit test for the property 'MaxUnders' } /// <summary> /// Test the property 'ReceivedSfp' /// </summary> [Test] public void ReceivedSfpTest() { // TODO unit test for the property 'ReceivedSfp' } /// <summary> /// Test the property 'BudgetCode' /// </summary> [Test] public void BudgetCodeTest() { // TODO unit test for the property 'BudgetCode' } /// <summary> /// Test the property 'AccountingCode' /// </summary> [Test] public void AccountingCodeTest() { // TODO unit test for the property 'AccountingCode' } /// <summary> /// Test the property 'TaxExempt' /// </summary> [Test] public void TaxExemptTest() { // TODO unit test for the property 'TaxExempt' } /// <summary> /// Test the property 'Capitalize' /// </summary> [Test] public void CapitalizeTest() { // TODO unit test for the property 'Capitalize' } /// <summary> /// Test the property 'Accrual' /// </summary> [Test] public void AccrualTest() { // TODO unit test for the property 'Accrual' } /// <summary> /// Test the property 'OddQuantity' /// </summary> [Test] public void OddQuantityTest() { // TODO unit test for the property 'OddQuantity' } /// <summary> /// Test the property 'FreightCost' /// </summary> [Test] public void FreightCostTest() { // TODO unit test for the property 'FreightCost' } /// <summary> /// Test the property 'ReceivedDate' /// </summary> [Test] public void ReceivedDateTest() { // TODO unit test for the property 'ReceivedDate' } /// <summary> /// Test the property 'ReceivedQuantity' /// </summary> [Test] public void ReceivedQuantityTest() { // TODO unit test for the property 'ReceivedQuantity' } /// <summary> /// Test the property 'FromProd' /// </summary> [Test] public void FromProdTest() { // TODO unit test for the property 'FromProd' } /// <summary> /// Test the property 'SfpComplete' /// </summary> [Test] public void SfpCompleteTest() { // TODO unit test for the property 'SfpComplete' } /// <summary> /// Test the property 'EndQuantity' /// </summary> [Test] public void EndQuantityTest() { // TODO unit test for the property 'EndQuantity' } /// <summary> /// Test the property 'EndVal' /// </summary> [Test] public void EndValTest() { // TODO unit test for the property 'EndVal' } /// <summary> /// Test the property 'EndFact' /// </summary> [Test] public void EndFactTest() { // TODO unit test for the property 'EndFact' } /// <summary> /// Test the property 'InterimQuantity' /// </summary> [Test] public void InterimQuantityTest() { // TODO unit test for the property 'InterimQuantity' } /// <summary> /// Test the property 'InterimVal' /// </summary> [Test] public void InterimValTest() { // TODO unit test for the property 'InterimVal' } /// <summary> /// Test the property 'InterimFact' /// </summary> [Test] public void InterimFactTest() { // TODO unit test for the property 'InterimFact' } /// <summary> /// Test the property 'LastAct' /// </summary> [Test] public void LastActTest() { // TODO unit test for the property 'LastAct' } /// <summary> /// Test the property 'WeightPerWrap' /// </summary> [Test] public void WeightPerWrapTest() { // TODO unit test for the property 'WeightPerWrap' } /// <summary> /// Test the property 'Norcs' /// </summary> [Test] public void NorcsTest() { // TODO unit test for the property 'Norcs' } /// <summary> /// Test the property 'VendorId' /// </summary> [Test] public void VendorIdTest() { // TODO unit test for the property 'VendorId' } /// <summary> /// Test the property 'BsVendor' /// </summary> [Test] public void BsVendorTest() { // TODO unit test for the property 'BsVendor' } /// <summary> /// Test the property 'MlVendor' /// </summary> [Test] public void MlVendorTest() { // TODO unit test for the property 'MlVendor' } /// <summary> /// Test the property 'ReceiptNo' /// </summary> [Test] public void ReceiptNoTest() { // TODO unit test for the property 'ReceiptNo' } /// <summary> /// Test the property 'PaidFull' /// </summary> [Test] public void PaidFullTest() { // TODO unit test for the property 'PaidFull' } /// <summary> /// Test the property 'EnteredBy' /// </summary> [Test] public void EnteredByTest() { // TODO unit test for the property 'EnteredBy' } /// <summary> /// Test the property 'ReceivedBy' /// </summary> [Test] public void ReceivedByTest() { // TODO unit test for the property 'ReceivedBy' } /// <summary> /// Test the property 'LineNo' /// </summary> [Test] public void LineNoTest() { // TODO unit test for the property 'LineNo' } /// <summary> /// Test the property 'ProdLot' /// </summary> [Test] public void ProdLotTest() { // TODO unit test for the property 'ProdLot' } /// <summary> /// Test the property 'UnitsPerCase' /// </summary> [Test] public void UnitsPerCaseTest() { // TODO unit test for the property 'UnitsPerCase' } /// <summary> /// Test the property 'CaseWeight' /// </summary> [Test] public void CaseWeightTest() { // TODO unit test for the property 'CaseWeight' } /// <summary> /// Test the property 'Height' /// </summary> [Test] public void HeightTest() { // TODO unit test for the property 'Height' } /// <summary> /// Test the property 'Width' /// </summary> [Test] public void WidthTest() { // TODO unit test for the property 'Width' } /// <summary> /// Test the property 'Length' /// </summary> [Test] public void LengthTest() { // TODO unit test for the property 'Length' } /// <summary> /// Test the property 'DockTime' /// </summary> [Test] public void DockTimeTest() { // TODO unit test for the property 'DockTime' } /// <summary> /// Test the property 'ModifyDate' /// </summary> [Test] public void ModifyDateTest() { // TODO unit test for the property 'ModifyDate' } /// <summary> /// Test the property 'Impressions' /// </summary> [Test] public void ImpressionsTest() { // TODO unit test for the property 'Impressions' } /// <summary> /// Test the property 'AsnLine' /// </summary> [Test] public void AsnLineTest() { // TODO unit test for the property 'AsnLine' } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.BusinessEntities.BusinessEntities File: IConnector.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.BusinessEntities { using System; using System.Collections.Generic; using Ecng.Serialization; using StockSharp.Logging; using StockSharp.Messages; /// <summary> /// The main interface providing the connection to the trading systems. /// </summary> public interface IConnector : IPersistable, ILogReceiver, IMarketDataProvider, ISecurityProvider, INewsProvider, IPortfolioProvider { /// <summary> /// Own trade received. /// </summary> event Action<MyTrade> NewMyTrade; /// <summary> /// Own trades received. /// </summary> event Action<IEnumerable<MyTrade>> NewMyTrades; /// <summary> /// Tick trade received. /// </summary> event Action<Trade> NewTrade; /// <summary> /// Tick trades received. /// </summary> event Action<IEnumerable<Trade>> NewTrades; /// <summary> /// Order received. /// </summary> event Action<Order> NewOrder; /// <summary> /// Orders received. /// </summary> event Action<IEnumerable<Order>> NewOrders; /// <summary> /// Order changed (cancelled, matched). /// </summary> event Action<Order> OrderChanged; /// <summary> /// Orders changed (cancelled, matched). /// </summary> event Action<IEnumerable<Order>> OrdersChanged; /// <summary> /// Order registration error event. /// </summary> event Action<OrderFail> OrderRegisterFailed; /// <summary> /// Order cancellation error event. /// </summary> event Action<OrderFail> OrderCancelFailed; /// <summary> /// Order registration errors event. /// </summary> event Action<IEnumerable<OrderFail>> OrdersRegisterFailed; /// <summary> /// Order cancellation errors event. /// </summary> event Action<IEnumerable<OrderFail>> OrdersCancelFailed; /// <summary> /// Mass order cancellation event. /// </summary> event Action<long> MassOrderCanceled; /// <summary> /// Mass order cancellation errors event. /// </summary> event Action<long, Exception> MassOrderCancelFailed; /// <summary> /// Failed order status request event. /// </summary> event Action<long, Exception> OrderStatusFailed; /// <summary> /// Stop-order registration errors event. /// </summary> event Action<IEnumerable<OrderFail>> StopOrdersRegisterFailed; /// <summary> /// Stop-order cancellation errors event. /// </summary> event Action<IEnumerable<OrderFail>> StopOrdersCancelFailed; /// <summary> /// Stop-orders received. /// </summary> event Action<IEnumerable<Order>> NewStopOrders; /// <summary> /// Stop orders state change event. /// </summary> event Action<IEnumerable<Order>> StopOrdersChanged; /// <summary> /// Stop-order registration error event. /// </summary> event Action<OrderFail> StopOrderRegisterFailed; /// <summary> /// Stop-order cancellation error event. /// </summary> event Action<OrderFail> StopOrderCancelFailed; /// <summary> /// Stop-order received. /// </summary> event Action<Order> NewStopOrder; /// <summary> /// Stop order state change event. /// </summary> event Action<Order> StopOrderChanged; /// <summary> /// Security received. /// </summary> event Action<Security> NewSecurity; /// <summary> /// Securities received. /// </summary> event Action<IEnumerable<Security>> NewSecurities; /// <summary> /// Security changed. /// </summary> event Action<Security> SecurityChanged; /// <summary> /// Securities changed. /// </summary> event Action<IEnumerable<Security>> SecuritiesChanged; /// <summary> /// Portfolios received. /// </summary> event Action<IEnumerable<Portfolio>> NewPortfolios; /// <summary> /// Portfolio changed. /// </summary> event Action<Portfolio> PortfolioChanged; /// <summary> /// Portfolios changed. /// </summary> event Action<IEnumerable<Portfolio>> PortfoliosChanged; /// <summary> /// Position received. /// </summary> event Action<Position> NewPosition; /// <summary> /// Positions received. /// </summary> event Action<IEnumerable<Position>> NewPositions; /// <summary> /// Position changed. /// </summary> event Action<Position> PositionChanged; /// <summary> /// Positions changed. /// </summary> event Action<IEnumerable<Position>> PositionsChanged; /// <summary> /// Order book received. /// </summary> event Action<MarketDepth> NewMarketDepth; /// <summary> /// Order book changed. /// </summary> event Action<MarketDepth> MarketDepthChanged; /// <summary> /// Order books received. /// </summary> event Action<IEnumerable<MarketDepth>> NewMarketDepths; /// <summary> /// Order books changed. /// </summary> event Action<IEnumerable<MarketDepth>> MarketDepthsChanged; /// <summary> /// Order log received. /// </summary> event Action<OrderLogItem> NewOrderLogItem; /// <summary> /// Order log received. /// </summary> event Action<IEnumerable<OrderLogItem>> NewOrderLogItems; /// <summary> /// News received. /// </summary> event Action<News> NewNews; /// <summary> /// News updated (news body received <see cref="StockSharp.BusinessEntities.News.Story"/>). /// </summary> event Action<News> NewsChanged; /// <summary> /// Message processed <see cref="Message"/>. /// </summary> event Action<Message> NewMessage; /// <summary> /// Connected. /// </summary> event Action Connected; /// <summary> /// Disconnected. /// </summary> event Action Disconnected; /// <summary> /// Connection error (for example, the connection was aborted by server). /// </summary> event Action<Exception> ConnectionError; /// <summary> /// Connected. /// </summary> event Action<IMessageAdapter> ConnectedEx; /// <summary> /// Disconnected. /// </summary> event Action<IMessageAdapter> DisconnectedEx; /// <summary> /// Connection error (for example, the connection was aborted by server). /// </summary> event Action<IMessageAdapter, Exception> ConnectionErrorEx; /// <summary> /// Dats process error. /// </summary> event Action<Exception> Error; /// <summary> /// Server time changed <see cref="IConnector.ExchangeBoards"/>. It passed the time difference since the last call of the event. The first time the event passes the value <see cref="TimeSpan.Zero"/>. /// </summary> event Action<TimeSpan> MarketTimeChanged; /// <summary> /// Lookup result <see cref="LookupSecurities(Security)"/> received. /// </summary> event Action<Exception, IEnumerable<Security>> LookupSecuritiesResult; /// <summary> /// Lookup result <see cref="LookupPortfolios"/> received. /// </summary> event Action<Exception, IEnumerable<Portfolio>> LookupPortfoliosResult; /// <summary> /// Successful subscription market-data. /// </summary> event Action<Security, MarketDataMessage> MarketDataSubscriptionSucceeded; /// <summary> /// Error subscription market-data. /// </summary> event Action<Security, MarketDataMessage, Exception> MarketDataSubscriptionFailed; /// <summary> /// Successful unsubscription market-data. /// </summary> event Action<Security, MarketDataMessage> MarketDataUnSubscriptionSucceeded; /// <summary> /// Error unsubscription market-data. /// </summary> event Action<Security, MarketDataMessage, Exception> MarketDataUnSubscriptionFailed; /// <summary> /// Session changed. /// </summary> event Action<ExchangeBoard, SessionStates> SessionStateChanged; /// <summary> /// Get session state for required board. /// </summary> /// <param name="board">Electronic board.</param> /// <returns>Session state. If the information about session state does not exist, then <see langword="null" /> will be returned.</returns> SessionStates? GetSessionState(ExchangeBoard board); /// <summary> /// List of all exchange boards, for which instruments are loaded <see cref="Securities"/>. /// </summary> IEnumerable<ExchangeBoard> ExchangeBoards { get; } /// <summary> /// List of all loaded instruments. It should be called after event <see cref="IConnector.NewSecurities"/> arisen. Otherwise the empty set will be returned. /// </summary> IEnumerable<Security> Securities { get; } /// <summary> /// Get all orders. /// </summary> IEnumerable<Order> Orders { get; } /// <summary> /// Get all stop-orders. /// </summary> IEnumerable<Order> StopOrders { get; } /// <summary> /// Get all registration errors. /// </summary> IEnumerable<OrderFail> OrderRegisterFails { get; } /// <summary> /// Get all cancellation errors. /// </summary> IEnumerable<OrderFail> OrderCancelFails { get; } /// <summary> /// Get all tick trades. /// </summary> IEnumerable<Trade> Trades { get; } /// <summary> /// Get all own trades. /// </summary> IEnumerable<MyTrade> MyTrades { get; } /// <summary> /// Get all positions. /// </summary> IEnumerable<Position> Positions { get; } /// <summary> /// All news. /// </summary> IEnumerable<News> News { get; } /// <summary> /// Connection state. /// </summary> ConnectionStates ConnectionState { get; } ///// <summary> ///// Gets a value indicating whether the re-registration orders via the method <see cref="ReRegisterOrder(StockSharp.BusinessEntities.Order,StockSharp.BusinessEntities.Order)"/> as a single transaction. ///// </summary> //bool IsSupportAtomicReRegister { get; } /// <summary> /// List of all securities, subscribed via <see cref="RegisterSecurity"/>. /// </summary> IEnumerable<Security> RegisteredSecurities { get; } /// <summary> /// List of all securities, subscribed via <see cref="RegisterMarketDepth"/>. /// </summary> IEnumerable<Security> RegisteredMarketDepths { get; } /// <summary> /// List of all securities, subscribed via <see cref="RegisterTrades"/>. /// </summary> IEnumerable<Security> RegisteredTrades { get; } /// <summary> /// List of all securities, subscribed via <see cref="RegisterOrderLog"/>. /// </summary> IEnumerable<Security> RegisteredOrderLogs { get; } /// <summary> /// List of all portfolios, subscribed via <see cref="RegisterPortfolio"/>. /// </summary> IEnumerable<Portfolio> RegisteredPortfolios { get; } /// <summary> /// Transactional adapter. /// </summary> IMessageAdapter TransactionAdapter { get; } /// <summary> /// Market-data adapter. /// </summary> IMessageAdapter MarketDataAdapter { get; } /// <summary> /// Connect to trading system. /// </summary> void Connect(); /// <summary> /// Disconnect from trading system. /// </summary> void Disconnect(); /// <summary> /// To find instruments that match the filter <paramref name="criteria" />. Found instruments will be passed through the event <see cref="LookupSecuritiesResult"/>. /// </summary> /// <param name="criteria">The instrument whose fields will be used as a filter.</param> void LookupSecurities(Security criteria); /// <summary> /// To find instruments that match the filter <paramref name="criteria" />. Found instruments will be passed through the event <see cref="LookupSecuritiesResult"/>. /// </summary> /// <param name="criteria">The criterion which fields will be used as a filter.</param> void LookupSecurities(SecurityLookupMessage criteria); /// <summary> /// To find portfolios that match the filter <paramref name="criteria" />. Found portfolios will be passed through the event <see cref="LookupPortfoliosResult"/>. /// </summary> /// <param name="criteria">The portfolio which fields will be used as a filter.</param> void LookupPortfolios(Portfolio criteria); /// <summary> /// To get the position by portfolio and instrument. /// </summary> /// <param name="portfolio">The portfolio on which the position should be found.</param> /// <param name="security">The instrument on which the position should be found.</param> /// <param name="clientCode">The client code.</param> /// <param name="depoName">The depository name where the stock is located physically. By default, an empty string is passed, which means the total position by all depositories.</param> /// <returns>Position.</returns> Position GetPosition(Portfolio portfolio, Security security, string clientCode = "", string depoName = ""); /// <summary> /// Get filtered order book. /// </summary> /// <param name="security">The instrument by which an order book should be got.</param> /// <returns>Filtered order book.</returns> MarketDepth GetFilteredMarketDepth(Security security); /// <summary> /// Register new order. /// </summary> /// <param name="order">Registration details.</param> void RegisterOrder(Order order); /// <summary> /// Reregister the order. /// </summary> /// <param name="oldOrder">Cancelling order.</param> /// <param name="newOrder">New order to register.</param> void ReRegisterOrder(Order oldOrder, Order newOrder); /// <summary> /// Reregister the order. /// </summary> /// <param name="oldOrder">Changing order.</param> /// <param name="price">Price of the new order.</param> /// <param name="volume">Volume of the new order.</param> /// <returns>New order.</returns> Order ReRegisterOrder(Order oldOrder, decimal price, decimal volume); /// <summary> /// Cancel the order. /// </summary> /// <param name="order">The order which should be canceled.</param> void CancelOrder(Order order); /// <summary> /// Cancel orders by filter. /// </summary> /// <param name="isStopOrder"><see langword="true" />, if cancel only a stop orders, <see langword="false" /> - if regular orders, <see langword="null" /> - both.</param> /// <param name="portfolio">Portfolio. If the value is equal to <see langword="null" />, then the portfolio does not match the orders cancel filter.</param> /// <param name="direction">Order side. If the value is <see langword="null" />, the direction does not use.</param> /// <param name="board">Trading board. If the value is equal to <see langword="null" />, then the board does not match the orders cancel filter.</param> /// <param name="security">Instrument. If the value is equal to <see langword="null" />, then the instrument does not match the orders cancel filter.</param> /// <param name="securityType">Security type. If the value is <see langword="null" />, the type does not use.</param> void CancelOrders(bool? isStopOrder = null, Portfolio portfolio = null, Sides? direction = null, ExchangeBoard board = null, Security security = null, SecurityTypes? securityType = null); /// <summary> /// To sign up to get market data by the instrument. /// </summary> /// <param name="security">The instrument by which new information getting should be started.</param> /// <param name="message">The message that contain subscribe info.</param> void SubscribeMarketData(Security security, MarketDataMessage message); /// <summary> /// To unsubscribe from getting market data by the instrument. /// </summary> /// <param name="security">The instrument by which new information getting should be started.</param> /// <param name="message">The message that contain unsubscribe info.</param> void UnSubscribeMarketData(Security security, MarketDataMessage message); /// <summary> /// To start getting quotes (order book) by the instrument. Quotes values are available through the event <see cref="IConnector.MarketDepthsChanged"/>. /// </summary> /// <param name="security">The instrument by which quotes getting should be started.</param> void RegisterMarketDepth(Security security); /// <summary> /// To stop getting quotes by the instrument. /// </summary> /// <param name="security">The instrument by which quotes getting should be stopped.</param> void UnRegisterMarketDepth(Security security); /// <summary> /// To start getting filtered quotes (order book) by the instrument. Quotes values are available through the event <see cref="GetFilteredMarketDepth"/>. /// </summary> /// <param name="security">The instrument by which quotes getting should be started.</param> void RegisterFilteredMarketDepth(Security security); /// <summary> /// To stop getting filtered quotes by the instrument. /// </summary> /// <param name="security">The instrument by which quotes getting should be stopped.</param> void UnRegisterFilteredMarketDepth(Security security); /// <summary> /// To start getting trades (tick data) by the instrument. New trades will come through the event <see cref="IConnector.NewTrades"/>. /// </summary> /// <param name="security">The instrument by which trades getting should be started.</param> void RegisterTrades(Security security); /// <summary> /// To stop getting trades (tick data) by the instrument. /// </summary> /// <param name="security">The instrument by which trades getting should be stopped.</param> void UnRegisterTrades(Security security); /// <summary> /// To start getting new information (for example, <see cref="Security.LastTrade"/> or <see cref="Security.BestBid"/>) by the instrument. /// </summary> /// <param name="security">The instrument by which new information getting should be started.</param> void RegisterSecurity(Security security); /// <summary> /// To stop getting new information. /// </summary> /// <param name="security">The instrument by which new information getting should be stopped.</param> void UnRegisterSecurity(Security security); /// <summary> /// Subscribe on order log for the security. /// </summary> /// <param name="security">Security for subscription.</param> void RegisterOrderLog(Security security); /// <summary> /// Unsubscribe from order log for the security. /// </summary> /// <param name="security">Security for unsubscription.</param> void UnRegisterOrderLog(Security security); /// <summary> /// Subscribe on the portfolio changes. /// </summary> /// <param name="portfolio">Portfolio for subscription.</param> void RegisterPortfolio(Portfolio portfolio); /// <summary> /// Unsubscribe from the portfolio changes. /// </summary> /// <param name="portfolio">Portfolio for unsubscription.</param> void UnRegisterPortfolio(Portfolio portfolio); /// <summary> /// Subscribe on news. /// </summary> void RegisterNews(); /// <summary> /// Unsubscribe from news. /// </summary> void UnRegisterNews(); } }
namespace Larsu.Hibernate { using System; using System.Reflection; using System.Threading; using Larsu.Hibernate.Policy; using NHibernate; using NHibernate.Engine; using NHibernate.Exceptions; using NHibernate.Hql.Util; using NHibernate.Proxy; using NLog; public class EntityManager : IEntityManager { private static ILogger logger = LogManager.GetCurrentClassLogger(); private ThreadLocal<ISession> sessionThreadLocal; private ThreadLocal<IStatelessSession> statelessSessionThreadLocal; #region Constructors [Obsolete] public EntityManager() { this.Name = SessionManager.DefaultConfigName; this.sessionThreadLocal = SessionManager.GetCurrentSessionThreadLocal(SessionManager.DefaultConfigName); this.statelessSessionThreadLocal = SessionManager.GetCurrentStatelessSessionThreadLocal(SessionManager.DefaultConfigName); } [Obsolete] public EntityManager(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } this.Name = name; this.sessionThreadLocal = SessionManager.GetCurrentSessionThreadLocal(this.Name); this.statelessSessionThreadLocal = SessionManager.GetCurrentStatelessSessionThreadLocal(this.Name); } public EntityManager(string name, ISessionFactory sessionFactory) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (sessionFactory == null) { throw new ArgumentNullException(nameof(sessionFactory)); } this.Name = name; this.SessionFactory = sessionFactory; this.sessionThreadLocal = new ThreadLocal<ISession>(() => sessionFactory.OpenSession()); this.statelessSessionThreadLocal = new ThreadLocal<IStatelessSession>(() => sessionFactory.OpenStatelessSession()); } #endregion #region Properties public string Name { get; protected set; } protected ISessionFactory SessionFactory { get; set; } protected ISession Session { get { return this.sessionThreadLocal.Value; } } protected IStatelessSession StatelessSession { get { return this.statelessSessionThreadLocal.Value; } } #endregion #region Methods public TRepository GetRepository<TRepository>() where TRepository : IRepository { var repo = Activator.CreateInstance(typeof(TRepository)); var sessionProp = repo.GetType().GetProperty("Session", BindingFlags.NonPublic | BindingFlags.Instance); var statelessProp = repo.GetType().GetProperty("StatelessSession", BindingFlags.NonPublic | BindingFlags.Instance); if (sessionProp == null) { throw new PropertyNotFoundException(typeof(TRepository), "Session"); } if (statelessProp == null) { throw new PropertyNotFoundException(typeof(TRepository), "StatelessSession"); } // We do this in order to enable child classes to be free of constructors like MyRepository(session, statelessSession); sessionProp.SetValue(repo, this.Session); statelessProp.SetValue(repo, this.StatelessSession); return (TRepository)repo; } public void FlushSession() { this.Session.Flush(); } public void ClearSession() { this.Session.Clear(); } public ISession OpenSession() { return this.SessionFactory.OpenSession(); } public IStatelessSession OpenStatelessSession() { return this.SessionFactory.OpenStatelessSession(); } public void Evict(IEntity entity) { this.Session.Evict(entity); } public void Evict<TEntity>() where TEntity : IEntity { this.Session.EvictAll<TEntity>(); } public bool? IsTransient(IEntity entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } var sessionFactoryImpl = (ISessionFactoryImplementor)this.Session.SessionFactory; var typeName = entity.GetType().AssemblyQualifiedName; var persister = new SessionFactoryHelper(sessionFactoryImpl).RequireClassPersister(typeName); return persister.IsTransient(entity, (ISessionImplementor)this.Session); } public void Save(IEntity entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } using (var transaction = this.Session.BeginTransaction()) { this.Session.Save(entity); transaction.Commit(); } } public void Save(IEntityCollection collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } using (var transaction = this.Session.BeginTransaction()) { foreach (var entity in collection) { this.Session.Save(entity); } transaction.Commit(); } } public void Save(IEntity entity, IRecoveryPolicy policy) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } if (policy == null) { throw new ArgumentNullException(nameof(policy)); } while (true) { using (var transaction = this.Session.BeginTransaction()) { try { this.Session.Save(entity); transaction.Commit(); break; } catch (Exception ex) { logger.Debug(ex); this.Session.Evict(entity); if (!transaction.WasRolledBack) { try { transaction.Rollback(); } catch (Exception rex) { logger.Debug(rex, "Rollback unsuccessful."); } } var dbException = ADOExceptionHelper.ExtractDbException(ex); if (policy.ShouldPerformRetry(dbException)) { continue; } throw; } } } } public void Save(IEntityCollection collection, IRecoveryPolicy policy) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (policy == null) { throw new ArgumentNullException(nameof(policy)); } while (true) { using (var transaction = this.Session.BeginTransaction()) { try { foreach (var entity in collection) { this.Session.Save(entity); } transaction.Commit(); break; } catch (Exception ex) { logger.Debug(ex); foreach (var entity in collection) { this.Session.Evict(entity); } if (!transaction.WasRolledBack) { try { transaction.Rollback(); } catch (Exception rex) { logger.Debug(rex, "Rollback unsuccessful."); } } var dbException = ADOExceptionHelper.ExtractDbException(ex); if (policy.ShouldPerformRetry(dbException)) { continue; } throw; } } } } public void Delete(IEntity entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } using (var transaction = this.Session.BeginTransaction()) { this.Session.Delete(entity); transaction.Commit(); } } public void Delete(IEntityCollection collection) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } using (var transaction = this.Session.BeginTransaction()) { foreach (var entity in collection) { this.Session.Delete(entity); } transaction.Commit(); } } public void Delete(IEntity entity, IRecoveryPolicy policy) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } if (policy == null) { throw new ArgumentNullException(nameof(policy)); } while (true) { using (var transaction = this.Session.BeginTransaction()) { try { this.Session.Delete(entity); transaction.Commit(); break; } catch (Exception ex) { logger.Debug(ex); this.Session.Evict(entity); if (!transaction.WasRolledBack) { try { transaction.Rollback(); } catch (Exception rex) { logger.Debug(rex, "Rollback unsuccessful."); } } var dbException = ADOExceptionHelper.ExtractDbException(ex); if (policy.ShouldPerformRetry(dbException)) { continue; } throw; } } } } public void Delete(IEntityCollection collection, IRecoveryPolicy policy) { if (collection == null) { throw new ArgumentNullException(nameof(collection)); } if (policy == null) { throw new ArgumentNullException(nameof(policy)); } while (true) { using (var transaction = this.Session.BeginTransaction()) { try { foreach (var entity in collection) { this.Session.Delete(entity); } transaction.Commit(); break; } catch (Exception ex) { logger.Debug(ex); foreach (var entity in collection) { this.Session.Evict(entity); } if (!transaction.WasRolledBack) { try { transaction.Rollback(); } catch (Exception rex) { logger.Debug(rex, "Rollback unsuccessful."); } } var dbException = ADOExceptionHelper.ExtractDbException(ex); if (policy.ShouldPerformRetry(dbException)) { continue; } throw; } } } } public Type UnwrapType(IEntity entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } var type = entity.GetType(); if (entity is INHibernateProxy) { return type.BaseType; } return type; } public TEntity Unwrap<TEntity>(IEntity entity) where TEntity : class, IEntity { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } if (!(entity is INHibernateProxy)) { return (TEntity)entity; } var initializer = (entity as INHibernateProxy).HibernateLazyInitializer; if (initializer.IsUninitialized) { return initializer.GetImplementation() as TEntity; } var impl = this.Session.GetSessionImplementation(); var unwrapped = impl.PersistenceContext.Unproxy(entity); return unwrapped as TEntity; } #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; using System.Linq; using System.Xml; using Xunit; namespace System.ServiceModel.Syndication.Tests { public static partial class BasicScenarioTests { [Fact] public static void SyndicationFeed_Rss_DateTimeParser() { // *** SETUP *** \\ // *** EXECUTE *** \\ SyndicationFeed feed; DateTimeOffset dto = new DateTimeOffset(2017, 1, 2, 3, 4, 5, new TimeSpan(0)); using (XmlReader reader = XmlReader.Create("TestFeeds/RssSpecCustomParser.xml")) { var formatter = new Rss20FeedFormatter(); formatter.DateTimeParser = (XmlDateTimeData xmlDateTimeData, out DateTimeOffset dateTimeOffset) => { dateTimeOffset = dto; return true; }; formatter.ReadFrom(reader); feed = formatter.Feed; } // *** ASSERT *** \\ Assert.True(feed != null, "res was null."); Assert.Equal(dto, feed.LastUpdatedTime); } [Fact] public static void SyndicationFeed_Rss_UriParser() { // *** SETUP *** \\ // *** EXECUTE *** \\ SyndicationFeed feed; using (XmlReader reader = XmlReader.Create("TestFeeds/RssSpecCustomParser.xml")) { var formatter = new Rss20FeedFormatter { UriParser = (XmlUriData xmlUriData, out Uri uri) => { uri = new Uri($"http://value-{xmlUriData.UriString}-kind-{xmlUriData.UriKind}-localName-{xmlUriData.ElementQualifiedName.Name}-ns-{xmlUriData.ElementQualifiedName.Namespace}-end"); return true; } }; formatter.ReadFrom(reader); feed = formatter.Feed; } // *** ASSERT *** \\ Assert.True(feed != null, "res was null."); Assert.Equal(new Uri("http://value-ChannelBase-kind-relativeorabsolute-localName-channel-ns--end"), feed.BaseUri); Assert.Equal(new Uri("http://value-ImageUrl-kind-relativeorabsolute-localName-url-ns--end"), feed.ImageUrl); Assert.NotNull(feed.Links); Assert.Equal(1, feed.Links.Count); Assert.Equal(new Uri("http://value-FeedLink-kind-relativeorabsolute-localName-link-ns--end"), feed.Links.First().Uri); Assert.True(feed.Items != null, "res.Items was null."); Assert.Equal(1, feed.Items.Count()); Assert.Equal(1, feed.Items.First().Links.Count); Assert.Equal(new Uri("http://value-itemlink-kind-relativeorabsolute-localName-link-ns--end"), feed.Items.First().Links.First().Uri); } [Fact] public static void SyndicationFeed_Atom_DateTimeParser() { // *** SETUP *** \\ // *** EXECUTE *** \\ SyndicationFeed feed; DateTimeOffset dto = new DateTimeOffset(2017, 1, 2, 3, 4, 5, new TimeSpan(0)); using (XmlReader reader = XmlReader.Create("TestFeeds/SimpleAtomFeedCustomParser.xml")) { var formatter = new Atom10FeedFormatter { DateTimeParser = (XmlDateTimeData xmlDateTimeData, out DateTimeOffset dateTimeOffset) => { dateTimeOffset = dto; return true; } }; formatter.ReadFrom(reader); feed = formatter.Feed; } // *** ASSERT *** \\ Assert.True(feed != null, "res was null."); Assert.Equal(dto, feed.LastUpdatedTime); Assert.True(feed.Items != null, "res.Items was null."); Assert.Equal(1, feed.Items.Count()); Assert.Equal(dto, feed.Items.First().LastUpdatedTime); } [Fact] public static void SyndicationFeed_Atom_UriParser() { // *** SETUP *** \\ // *** EXECUTE *** \\ SyndicationFeed feed; using (XmlReader reader = XmlReader.Create("TestFeeds/SimpleAtomFeedCustomParser.xml")) { var formatter = new Atom10FeedFormatter { UriParser = (XmlUriData xmlUriData, out Uri uri) => { uri = new Uri($"http://value-{xmlUriData.UriString}-kind-{xmlUriData.UriKind}-localName-{xmlUriData.ElementQualifiedName.Name}-ns-{xmlUriData.ElementQualifiedName.Namespace}-end"); return true; } }; formatter.ReadFrom(reader); feed = formatter.Feed; } // *** ASSERT *** \\ Assert.True(feed != null, "res was null."); Assert.Equal(new Uri("http://value-FeedLogo-kind-relativeorabsolute-localName-logo-ns-http//www.w3.org/2005/Atom-end"), feed.ImageUrl); Assert.True(feed.Items != null, "res.Items was null."); Assert.Equal(1, feed.Items.Count()); Assert.NotNull(feed.Items.First().Links); Assert.Equal(1, feed.Items.First().Links.Count); Assert.Equal(new Uri("http://value-EntryLinkHref-kind-relativeorabsolute-localName-link-ns-http//www.w3.org/2005/Atom-end"), feed.Items.First().Links.First().Uri); Assert.Equal(new Uri("http://value-EntryContentSrc-kind-relativeorabsolute-localName-content-ns-http://www.w3.org/2005/Atom-end"), ((UrlSyndicationContent)feed.Items.First().Content).Url); } [Fact] public static void SyndicationFeed_RSS_Optional_Elements() { using (XmlReader reader = XmlReader.Create("TestFeeds/rssSpecExample.xml")) { SyndicationFeed feed = SyndicationFeed.Load(reader); Assert.NotNull(feed.Documentation); Assert.Equal("http://contoso.com/rss", feed.Documentation.GetAbsoluteUri().ToString()); Assert.NotNull(feed.TimeToLive); Assert.Equal(TimeSpan.FromMinutes(60), feed.TimeToLive.Value); Assert.NotNull(feed.SkipHours); Assert.Equal(3, feed.SkipHours.Count); Assert.NotNull(feed.SkipDays); Assert.Equal(7, feed.SkipDays.Count); Assert.NotNull(feed.TextInput); Assert.Equal("Search Online", feed.TextInput.Description); Assert.Equal("Search", feed.TextInput.Title); Assert.Equal("input Name", feed.TextInput.Name); Assert.Equal("http://www.contoso.no/search?", feed.TextInput.Link.Uri.ToString()); } } [Fact] public static void SyndicationFeed_Load_Write_RSS_With_Optional_Elements() { List<AllowableDifference> allowableDifferences = GetRssFeedPositiveTestAllowableDifferences(); ReadWriteSyndicationFeed( file: "TestFeeds/rssOptionalElements.xml", feedFormatter: (feedObject) => new Rss20FeedFormatter(feedObject), allowableDifferences: allowableDifferences ); } [Fact] public static void SyndicationFeed_Load_Write_RSS_Use_Optional_Element_Properties() { List<AllowableDifference> allowableDifferences = GetRssFeedPositiveTestAllowableDifferences(); ReadWriteSyndicationFeed( file: "TestFeeds/rssOptionalElements.xml", feedFormatter: (feedObject) => new Rss20FeedFormatter(feedObject), allowableDifferences: allowableDifferences, verifySyndicationFeedRead: (feed) => { Assert.NotNull(feed); Assert.NotNull(feed.Documentation); Assert.True(feed.Documentation.GetAbsoluteUri().ToString() == "http://contoso.com/rss"); Assert.NotNull(feed.TimeToLive); Assert.Equal(TimeSpan.FromMinutes(60), feed.TimeToLive.Value); Assert.NotNull(feed.SkipHours); Assert.Equal(3, feed.SkipHours.Count); Assert.NotNull(feed.SkipDays); Assert.Equal(2, feed.SkipDays.Count); Assert.NotNull(feed.TextInput); Assert.Equal("Search Online", feed.TextInput.Description); Assert.Equal("Search", feed.TextInput.Title); Assert.Equal("input Name", feed.TextInput.Name); Assert.Equal("http://www.contoso.no/search?", feed.TextInput.Link.Uri.ToString()); }); } } }
using System; using System.Collections; namespace DocTagger { class StopWordsHandler { private static StopWordsHandler _instance = new StopWordsHandler(); private Hashtable _stopwords = null; public static StopWordsHandler Instance { get { return _instance; } } public object AddElement(IDictionary collection, Object key, object newValue) { object element = collection[key]; collection[key] = newValue; return element; } public bool IsStopWord(string str) { return _stopwords.ContainsKey(str.ToLower()); } private StopWordsHandler() { _stopwords = new Hashtable(); _stopwords.Add("a", null); _stopwords.Add("abaft", null); _stopwords.Add("aboard", null); _stopwords.Add("about", null); _stopwords.Add("above", null); _stopwords.Add("across", null); _stopwords.Add("afore", null); _stopwords.Add("aforesaid", null); _stopwords.Add("after", null); _stopwords.Add("again", null); _stopwords.Add("against", null); _stopwords.Add("agin", null); _stopwords.Add("ago", null); _stopwords.Add("aint", null); _stopwords.Add("albeit", null); _stopwords.Add("all", null); _stopwords.Add("almost", null); _stopwords.Add("alone", null); _stopwords.Add("along", null); _stopwords.Add("alongside", null); _stopwords.Add("already", null); _stopwords.Add("also", null); _stopwords.Add("although", null); _stopwords.Add("always", null); _stopwords.Add("am", null); _stopwords.Add("american", null); _stopwords.Add("amid", null); _stopwords.Add("amidst", null); _stopwords.Add("among", null); _stopwords.Add("amongst", null); _stopwords.Add("an", null); _stopwords.Add("and", null); _stopwords.Add("anent", null); _stopwords.Add("another", null); _stopwords.Add("any", null); _stopwords.Add("anybody", null); _stopwords.Add("anyone", null); _stopwords.Add("anything", null); _stopwords.Add("are", null); _stopwords.Add("aren't", null); _stopwords.Add("around", null); _stopwords.Add("as", null); _stopwords.Add("aslant", null); _stopwords.Add("astride", null); _stopwords.Add("at", null); _stopwords.Add("athwart", null); _stopwords.Add("away", null); _stopwords.Add("b", null); _stopwords.Add("back", null); _stopwords.Add("bar", null); _stopwords.Add("barring", null); _stopwords.Add("be", null); _stopwords.Add("because", null); _stopwords.Add("been", null); _stopwords.Add("before", null); _stopwords.Add("behind", null); _stopwords.Add("being", null); _stopwords.Add("below", null); _stopwords.Add("beneath", null); _stopwords.Add("beside", null); _stopwords.Add("besides", null); _stopwords.Add("best", null); _stopwords.Add("better", null); _stopwords.Add("between", null); _stopwords.Add("betwixt", null); _stopwords.Add("beyond", null); _stopwords.Add("both", null); _stopwords.Add("but", null); _stopwords.Add("by", null); _stopwords.Add("c", null); _stopwords.Add("can", null); _stopwords.Add("cannot", null); _stopwords.Add("can't", null); _stopwords.Add("certain", null); _stopwords.Add("circa", null); _stopwords.Add("close", null); _stopwords.Add("concerning", null); _stopwords.Add("considering", null); _stopwords.Add("cos", null); _stopwords.Add("could", null); _stopwords.Add("couldn't", null); _stopwords.Add("couldst", null); _stopwords.Add("d", null); _stopwords.Add("dare", null); _stopwords.Add("dared", null); _stopwords.Add("daren't", null); _stopwords.Add("dares", null); _stopwords.Add("daring", null); _stopwords.Add("despite", null); _stopwords.Add("did", null); _stopwords.Add("didn't", null); _stopwords.Add("different", null); _stopwords.Add("directly", null); _stopwords.Add("do", null); _stopwords.Add("does", null); _stopwords.Add("doesn't", null); _stopwords.Add("doing", null); _stopwords.Add("done", null); _stopwords.Add("don't", null); _stopwords.Add("dost", null); _stopwords.Add("doth", null); _stopwords.Add("down", null); _stopwords.Add("during", null); _stopwords.Add("durst", null); _stopwords.Add("e", null); _stopwords.Add("each", null); _stopwords.Add("early", null); _stopwords.Add("either", null); _stopwords.Add("em", null); _stopwords.Add("english", null); _stopwords.Add("enough", null); _stopwords.Add("ere", null); _stopwords.Add("even", null); _stopwords.Add("ever", null); _stopwords.Add("every", null); _stopwords.Add("everybody", null); _stopwords.Add("everyone", null); _stopwords.Add("everything", null); _stopwords.Add("except", null); _stopwords.Add("excepting", null); _stopwords.Add("f", null); _stopwords.Add("failing", null); _stopwords.Add("far", null); _stopwords.Add("few", null); _stopwords.Add("first", null); _stopwords.Add("five", null); _stopwords.Add("following", null); _stopwords.Add("for", null); _stopwords.Add("four", null); _stopwords.Add("from", null); _stopwords.Add("g", null); _stopwords.Add("gonna", null); _stopwords.Add("gotta", null); _stopwords.Add("h", null); _stopwords.Add("had", null); _stopwords.Add("hadn't", null); _stopwords.Add("hard", null); _stopwords.Add("has", null); _stopwords.Add("hasn't", null); _stopwords.Add("hast", null); _stopwords.Add("hath", null); _stopwords.Add("have", null); _stopwords.Add("haven't", null); _stopwords.Add("having", null); _stopwords.Add("he", null); _stopwords.Add("he'd", null); _stopwords.Add("he'll", null); _stopwords.Add("her", null); _stopwords.Add("here", null); _stopwords.Add("here's", null); _stopwords.Add("hers", null); _stopwords.Add("herself", null); _stopwords.Add("he's", null); _stopwords.Add("high", null); _stopwords.Add("him", null); _stopwords.Add("himself", null); _stopwords.Add("his", null); _stopwords.Add("home", null); _stopwords.Add("how", null); _stopwords.Add("howbeit", null); _stopwords.Add("however", null); _stopwords.Add("how's", null); _stopwords.Add("i", null); _stopwords.Add("id", null); _stopwords.Add("if", null); _stopwords.Add("ill", null); _stopwords.Add("i'm", null); _stopwords.Add("immediately", null); _stopwords.Add("important", null); _stopwords.Add("in", null); _stopwords.Add("inside", null); _stopwords.Add("instantly", null); _stopwords.Add("into", null); _stopwords.Add("is", null); _stopwords.Add("isn't", null); _stopwords.Add("it", null); _stopwords.Add("it'll", null); _stopwords.Add("it's", null); _stopwords.Add("its", null); _stopwords.Add("itself", null); _stopwords.Add("i've", null); _stopwords.Add("j", null); _stopwords.Add("just", null); _stopwords.Add("k", null); _stopwords.Add("l", null); _stopwords.Add("large", null); _stopwords.Add("last", null); _stopwords.Add("later", null); _stopwords.Add("least", null); _stopwords.Add("left", null); _stopwords.Add("less", null); _stopwords.Add("lest", null); _stopwords.Add("let's", null); _stopwords.Add("like", null); _stopwords.Add("likewise", null); _stopwords.Add("little", null); _stopwords.Add("living", null); _stopwords.Add("long", null); _stopwords.Add("m", null); _stopwords.Add("many", null); _stopwords.Add("may", null); _stopwords.Add("mayn't", null); _stopwords.Add("me", null); _stopwords.Add("mid", null); _stopwords.Add("midst", null); _stopwords.Add("might", null); _stopwords.Add("mightn't", null); _stopwords.Add("mine", null); _stopwords.Add("minus", null); _stopwords.Add("more", null); _stopwords.Add("most", null); _stopwords.Add("much", null); _stopwords.Add("must", null); _stopwords.Add("mustn't", null); _stopwords.Add("my", null); _stopwords.Add("myself", null); _stopwords.Add("n", null); _stopwords.Add("near", null); _stopwords.Add("'neath", null); _stopwords.Add("need", null); _stopwords.Add("needed", null); _stopwords.Add("needing", null); _stopwords.Add("needn't", null); _stopwords.Add("needs", null); _stopwords.Add("neither", null); _stopwords.Add("never", null); _stopwords.Add("nevertheless", null); _stopwords.Add("new", null); _stopwords.Add("next", null); _stopwords.Add("nigh", null); _stopwords.Add("nigher", null); _stopwords.Add("nighest", null); _stopwords.Add("nisi", null); _stopwords.Add("no", null); _stopwords.Add("no-one", null); _stopwords.Add("nobody", null); _stopwords.Add("none", null); _stopwords.Add("nor", null); _stopwords.Add("not", null); _stopwords.Add("nothing", null); _stopwords.Add("notwithstanding", null); _stopwords.Add("now", null); _stopwords.Add("o", null); _stopwords.Add("o'er", null); _stopwords.Add("of", null); _stopwords.Add("off", null); _stopwords.Add("often", null); _stopwords.Add("on", null); _stopwords.Add("once", null); _stopwords.Add("one", null); _stopwords.Add("oneself", null); _stopwords.Add("only", null); _stopwords.Add("onto", null); _stopwords.Add("open", null); _stopwords.Add("or", null); _stopwords.Add("other", null); _stopwords.Add("otherwise", null); _stopwords.Add("ought", null); _stopwords.Add("oughtn't", null); _stopwords.Add("our", null); _stopwords.Add("ours", null); _stopwords.Add("ourselves", null); _stopwords.Add("out", null); _stopwords.Add("outside", null); _stopwords.Add("over", null); _stopwords.Add("own", null); _stopwords.Add("p", null); _stopwords.Add("past", null); _stopwords.Add("pending", null); _stopwords.Add("per", null); _stopwords.Add("perhaps", null); _stopwords.Add("plus", null); _stopwords.Add("possible", null); _stopwords.Add("present", null); _stopwords.Add("probably", null); _stopwords.Add("provided", null); _stopwords.Add("providing", null); _stopwords.Add("public", null); _stopwords.Add("q", null); _stopwords.Add("qua", null); _stopwords.Add("quite", null); _stopwords.Add("r", null); _stopwords.Add("rather", null); _stopwords.Add("re", null); _stopwords.Add("real", null); _stopwords.Add("really", null); _stopwords.Add("respecting", null); _stopwords.Add("right", null); _stopwords.Add("round", null); _stopwords.Add("s", null); _stopwords.Add("same", null); _stopwords.Add("sans", null); _stopwords.Add("save", null); _stopwords.Add("saving", null); _stopwords.Add("second", null); _stopwords.Add("several", null); _stopwords.Add("shall", null); _stopwords.Add("shalt", null); _stopwords.Add("shan't", null); _stopwords.Add("she", null); _stopwords.Add("shed", null); _stopwords.Add("shell", null); _stopwords.Add("she's", null); _stopwords.Add("short", null); _stopwords.Add("should", null); _stopwords.Add("shouldn't", null); _stopwords.Add("since", null); _stopwords.Add("six", null); _stopwords.Add("small", null); _stopwords.Add("so", null); _stopwords.Add("some", null); _stopwords.Add("somebody", null); _stopwords.Add("someone", null); _stopwords.Add("something", null); _stopwords.Add("sometimes", null); _stopwords.Add("soon", null); _stopwords.Add("special", null); _stopwords.Add("still", null); _stopwords.Add("such", null); _stopwords.Add("summat", null); _stopwords.Add("supposing", null); _stopwords.Add("sure", null); _stopwords.Add("t", null); _stopwords.Add("than", null); _stopwords.Add("that", null); _stopwords.Add("that'd", null); _stopwords.Add("that'll", null); _stopwords.Add("that's", null); _stopwords.Add("the", null); _stopwords.Add("thee", null); _stopwords.Add("their", null); _stopwords.Add("theirs", null); _stopwords.Add("their's", null); _stopwords.Add("them", null); _stopwords.Add("themselves", null); _stopwords.Add("then", null); _stopwords.Add("there", null); _stopwords.Add("there's", null); _stopwords.Add("these", null); _stopwords.Add("they", null); _stopwords.Add("they'd", null); _stopwords.Add("they'll", null); _stopwords.Add("they're", null); _stopwords.Add("they've", null); _stopwords.Add("thine", null); _stopwords.Add("this", null); _stopwords.Add("tho", null); _stopwords.Add("those", null); _stopwords.Add("thou", null); _stopwords.Add("though", null); _stopwords.Add("three", null); _stopwords.Add("thro'", null); _stopwords.Add("through", null); _stopwords.Add("throughout", null); _stopwords.Add("thru", null); _stopwords.Add("thyself", null); _stopwords.Add("till", null); _stopwords.Add("to", null); _stopwords.Add("today", null); _stopwords.Add("together", null); _stopwords.Add("too", null); _stopwords.Add("touching", null); _stopwords.Add("toward", null); _stopwords.Add("towards", null); _stopwords.Add("true", null); _stopwords.Add("'twas", null); _stopwords.Add("'tween", null); _stopwords.Add("'twere", null); _stopwords.Add("'twill", null); _stopwords.Add("'twixt", null); _stopwords.Add("two", null); _stopwords.Add("'twould", null); _stopwords.Add("u", null); _stopwords.Add("under", null); _stopwords.Add("underneath", null); _stopwords.Add("unless", null); _stopwords.Add("unlike", null); _stopwords.Add("until", null); _stopwords.Add("unto", null); _stopwords.Add("up", null); _stopwords.Add("upon", null); _stopwords.Add("us", null); _stopwords.Add("used", null); _stopwords.Add("usually", null); _stopwords.Add("v", null); _stopwords.Add("versus", null); _stopwords.Add("very", null); _stopwords.Add("via", null); _stopwords.Add("vice", null); _stopwords.Add("vis-a-vis", null); _stopwords.Add("w", null); _stopwords.Add("wanna", null); _stopwords.Add("wanting", null); _stopwords.Add("was", null); _stopwords.Add("wasn't", null); _stopwords.Add("way", null); _stopwords.Add("we", null); _stopwords.Add("we'd", null); _stopwords.Add("well", null); _stopwords.Add("were", null); _stopwords.Add("weren't", null); _stopwords.Add("wert", null); _stopwords.Add("we've", null); _stopwords.Add("what", null); _stopwords.Add("whatever", null); _stopwords.Add("what'll", null); _stopwords.Add("what's", null); _stopwords.Add("when", null); _stopwords.Add("whencesoever", null); _stopwords.Add("whenever", null); _stopwords.Add("when's", null); _stopwords.Add("whereas", null); _stopwords.Add("where's", null); _stopwords.Add("whether", null); _stopwords.Add("which", null); _stopwords.Add("whichever", null); _stopwords.Add("whichsoever", null); _stopwords.Add("while", null); _stopwords.Add("whilst", null); _stopwords.Add("who", null); _stopwords.Add("who'd", null); _stopwords.Add("whoever", null); _stopwords.Add("whole", null); _stopwords.Add("who'll", null); _stopwords.Add("whom", null); _stopwords.Add("whore", null); _stopwords.Add("who's", null); _stopwords.Add("whose", null); _stopwords.Add("whoso", null); _stopwords.Add("whosoever", null); _stopwords.Add("will", null); _stopwords.Add("with", null); _stopwords.Add("within", null); _stopwords.Add("without", null); _stopwords.Add("wont", null); _stopwords.Add("would", null); _stopwords.Add("wouldn't", null); _stopwords.Add("wouldst", null); _stopwords.Add("x", null); _stopwords.Add("y", null); _stopwords.Add("ye", null); _stopwords.Add("yet", null); _stopwords.Add("you", null); _stopwords.Add("you'd", null); _stopwords.Add("you'll", null); _stopwords.Add("your", null); _stopwords.Add("you're", null); _stopwords.Add("yours", null); _stopwords.Add("yourself", null); _stopwords.Add("yourselves", null); _stopwords.Add("you've", null); _stopwords.Add("z", null); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; using System.Text; // Include Silverlight's managed resources #if SILVERLIGHT using System.Core; #endif //SILVERLIGHT namespace System.Linq { public interface IQueryable : IEnumerable { Expression Expression { get; } Type ElementType { get; } // the provider that created this query IQueryProvider Provider { get; } } public interface IQueryable<out T> : IEnumerable<T>, IQueryable { } public interface IQueryProvider{ IQueryable CreateQuery(Expression expression); IQueryable<TElement> CreateQuery<TElement>(Expression expression); object Execute(Expression expression); TResult Execute<TResult>(Expression expression); } public interface IOrderedQueryable : IQueryable { } public interface IOrderedQueryable<out T> : IQueryable<T>, IOrderedQueryable { } public static class Queryable { #region Helper methods to obtain MethodInfo in a safe way private static MethodInfo GetMethodInfo<T1, T2>(Func<T1, T2> f, T1 unused1) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3>(Func<T1, T2, T3> f, T1 unused1, T2 unused2) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f, T1 unused1, T2 unused2, T3 unused3) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3, T4, T5>(Func<T1, T2, T3, T4, T5> f, T1 unused1, T2 unused2, T3 unused3, T4 unused4) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3, T4, T5, T6>(Func<T1, T2, T3, T4, T5, T6> f, T1 unused1, T2 unused2, T3 unused3, T4 unused4, T5 unused5) { return f.Method; } private static MethodInfo GetMethodInfo<T1, T2, T3, T4, T5, T6, T7>(Func<T1, T2, T3, T4, T5, T6, T7> f, T1 unused1, T2 unused2, T3 unused3, T4 unused4, T5 unused5, T6 unused6) { return f.Method; } #endregion public static IQueryable<TElement> AsQueryable<TElement>(this IEnumerable<TElement> source) { if (source == null) throw Error.ArgumentNull("source"); if (source is IQueryable<TElement>) return (IQueryable<TElement>)source; return new EnumerableQuery<TElement>(source); } public static IQueryable AsQueryable(this IEnumerable source) { if (source == null) throw Error.ArgumentNull("source"); if (source is IQueryable) return (IQueryable)source; Type enumType = TypeHelper.FindGenericType(typeof(IEnumerable<>), source.GetType()); if (enumType == null) throw Error.ArgumentNotIEnumerableGeneric("source"); return EnumerableQuery.Create(enumType.GetGenericArguments()[0], source); } public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Where, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Where, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static IQueryable<TResult> OfType<TResult>(this IQueryable source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.OfType<TResult>, source), new Expression[] { source.Expression } )); } public static IQueryable<TResult> Cast<TResult>(this IQueryable source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Cast<TResult>, source), new Expression[] { source.Expression } )); } public static IQueryable<TResult> Select<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TResult>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Select, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static IQueryable<TResult> Select<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, int, TResult>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Select, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static IQueryable<TResult> SelectMany<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, IEnumerable<TResult>>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.SelectMany, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static IQueryable<TResult> SelectMany<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, int, IEnumerable<TResult>>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.SelectMany, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static IQueryable<TResult> SelectMany<TSource, TCollection, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, int, IEnumerable<TCollection>>> collectionSelector, Expression<Func<TSource, TCollection, TResult>> resultSelector){ if (source == null) throw Error.ArgumentNull("source"); if (collectionSelector == null) throw Error.ArgumentNull("collectionSelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.SelectMany, source, collectionSelector, resultSelector), new Expression[] { source.Expression, Expression.Quote(collectionSelector), Expression.Quote(resultSelector) } )); } public static IQueryable<TResult> SelectMany<TSource,TCollection,TResult>(this IQueryable<TSource> source, Expression<Func<TSource, IEnumerable<TCollection>>> collectionSelector, Expression<Func<TSource, TCollection, TResult>> resultSelector) { if (source == null) throw Error.ArgumentNull("source"); if (collectionSelector == null) throw Error.ArgumentNull("collectionSelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.SelectMany, source, collectionSelector, resultSelector), new Expression[] { source.Expression, Expression.Quote(collectionSelector), Expression.Quote(resultSelector) } )); } private static Expression GetSourceExpression<TSource>(IEnumerable<TSource> source) { IQueryable<TSource> q = source as IQueryable<TSource>; if (q != null) return q.Expression; return Expression.Constant(source, typeof(IEnumerable<TSource>)); } public static IQueryable<TResult> Join<TOuter,TInner,TKey,TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter,TKey>> outerKeySelector, Expression<Func<TInner,TKey>> innerKeySelector, Expression<Func<TOuter,TInner,TResult>> resultSelector) { if (outer == null) throw Error.ArgumentNull("outer"); if (inner == null) throw Error.ArgumentNull("inner"); if (outerKeySelector == null) throw Error.ArgumentNull("outerKeySelector"); if (innerKeySelector == null) throw Error.ArgumentNull("innerKeySelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return outer.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Join, outer, inner, outerKeySelector, innerKeySelector, resultSelector), new Expression[] { outer.Expression, GetSourceExpression(inner), Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector) } )); } public static IQueryable<TResult> Join<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, TInner, TResult>> resultSelector, IEqualityComparer<TKey> comparer) { if (outer == null) throw Error.ArgumentNull("outer"); if (inner == null) throw Error.ArgumentNull("inner"); if (outerKeySelector == null) throw Error.ArgumentNull("outerKeySelector"); if (innerKeySelector == null) throw Error.ArgumentNull("innerKeySelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return outer.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Join, outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer), new Expression[] { outer.Expression, GetSourceExpression(inner), Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) } )); } public static IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, IEnumerable<TInner>, TResult>> resultSelector) { if (outer == null) throw Error.ArgumentNull("outer"); if (inner == null) throw Error.ArgumentNull("inner"); if (outerKeySelector == null) throw Error.ArgumentNull("outerKeySelector"); if (innerKeySelector == null) throw Error.ArgumentNull("innerKeySelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return outer.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.GroupJoin, outer, inner, outerKeySelector, innerKeySelector, resultSelector), new Expression[] { outer.Expression, GetSourceExpression(inner), Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector) } )); } public static IQueryable<TResult> GroupJoin<TOuter, TInner, TKey, TResult>(this IQueryable<TOuter> outer, IEnumerable<TInner> inner, Expression<Func<TOuter, TKey>> outerKeySelector, Expression<Func<TInner, TKey>> innerKeySelector, Expression<Func<TOuter, IEnumerable<TInner>, TResult>> resultSelector, IEqualityComparer<TKey> comparer) { if (outer == null) throw Error.ArgumentNull("outer"); if (inner == null) throw Error.ArgumentNull("inner"); if (outerKeySelector == null) throw Error.ArgumentNull("outerKeySelector"); if (innerKeySelector == null) throw Error.ArgumentNull("innerKeySelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return outer.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.GroupJoin, outer, inner, outerKeySelector, innerKeySelector, resultSelector, comparer), new Expression[] { outer.Expression, GetSourceExpression(inner), Expression.Quote(outerKeySelector), Expression.Quote(innerKeySelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) } )); } public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.OrderBy, source, keySelector), new Expression[] { source.Expression, Expression.Quote(keySelector) } )); } public static IOrderedQueryable<TSource> OrderBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.OrderBy, source, keySelector, comparer), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer<TKey>)) } )); } public static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return (IOrderedQueryable<TSource>)source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.OrderByDescending, source, keySelector), new Expression[] { source.Expression, Expression.Quote(keySelector) } )); } public static IOrderedQueryable<TSource> OrderByDescending<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.OrderByDescending, source, keySelector, comparer), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer<TKey>)) } )); } public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.ThenBy, source, keySelector), new Expression[] { source.Expression, Expression.Quote(keySelector) } )); } public static IOrderedQueryable<TSource> ThenBy<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.ThenBy, source, keySelector, comparer), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer<TKey>)) } )); } public static IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.ThenByDescending, source, keySelector), new Expression[] { source.Expression, Expression.Quote(keySelector) } )); } public static IOrderedQueryable<TSource> ThenByDescending<TSource, TKey>(this IOrderedQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IComparer<TKey> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return (IOrderedQueryable<TSource>) source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.ThenByDescending, source, keySelector, comparer), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IComparer<TKey>)) } )); } public static IQueryable<TSource> Take<TSource>(this IQueryable<TSource> source, int count) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Take, source, count), new Expression[] { source.Expression, Expression.Constant(count) } )); } public static IQueryable<TSource> TakeWhile<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.TakeWhile, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static IQueryable<TSource> TakeWhile<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.TakeWhile, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static IQueryable<TSource> Skip<TSource>(this IQueryable<TSource> source, int count) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Skip, source, count), new Expression[] { source.Expression, Expression.Constant(count) } )); } public static IQueryable<TSource> SkipWhile<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.SkipWhile, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static IQueryable<TSource> SkipWhile<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, int, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.SkipWhile, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static IQueryable<IGrouping<TKey,TSource>> GroupBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return source.Provider.CreateQuery<IGrouping<TKey,TSource>>( Expression.Call( null, GetMethodInfo(Queryable.GroupBy, source, keySelector), new Expression[] { source.Expression, Expression.Quote(keySelector) } )); } public static IQueryable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); if (elementSelector == null) throw Error.ArgumentNull("elementSelector"); return source.Provider.CreateQuery<IGrouping<TKey,TElement>>( Expression.Call( null, GetMethodInfo(Queryable.GroupBy, source, keySelector, elementSelector), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector) } )); } public static IQueryable<IGrouping<TKey, TSource>> GroupBy<TSource, TKey>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, IEqualityComparer<TKey> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); return source.Provider.CreateQuery<IGrouping<TKey,TSource>>( Expression.Call( null, GetMethodInfo(Queryable.GroupBy, source, keySelector, comparer), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) } )); } public static IQueryable<IGrouping<TKey, TElement>> GroupBy<TSource, TKey, TElement>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource,TElement>> elementSelector, IEqualityComparer<TKey> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); if (elementSelector == null) throw Error.ArgumentNull("elementSelector"); return source.Provider.CreateQuery<IGrouping<TKey,TElement>>( Expression.Call( null, GetMethodInfo(Queryable.GroupBy, source, keySelector, elementSelector, comparer), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) } )); } public static IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector, Expression<Func<TKey, IEnumerable<TElement>, TResult>> resultSelector) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); if (elementSelector == null) throw Error.ArgumentNull("elementSelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.GroupBy, source, keySelector, elementSelector, resultSelector), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Quote(resultSelector) } )); } public static IQueryable<TResult> GroupBy<TSource, TKey, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector,Expression<Func<TKey, IEnumerable<TSource>, TResult>> resultSelector) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.GroupBy, source, keySelector, resultSelector), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(resultSelector) } )); } public static IQueryable<TResult> GroupBy<TSource, TKey, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TKey, IEnumerable<TSource>, TResult>> resultSelector, IEqualityComparer<TKey> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.GroupBy, source, keySelector, resultSelector, comparer), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) } )); } public static IQueryable<TResult> GroupBy<TSource, TKey, TElement, TResult>(this IQueryable<TSource> source, Expression<Func<TSource, TKey>> keySelector, Expression<Func<TSource, TElement>> elementSelector, Expression<Func<TKey, IEnumerable<TElement>, TResult>> resultSelector, IEqualityComparer<TKey> comparer) { if (source == null) throw Error.ArgumentNull("source"); if (keySelector == null) throw Error.ArgumentNull("keySelector"); if (elementSelector == null) throw Error.ArgumentNull("elementSelector"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return source.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.GroupBy, source, keySelector, elementSelector, resultSelector, comparer), new Expression[] { source.Expression, Expression.Quote(keySelector), Expression.Quote(elementSelector), Expression.Quote(resultSelector), Expression.Constant(comparer, typeof(IEqualityComparer<TKey>)) } )); } public static IQueryable<TSource> Distinct<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Distinct, source), new Expression[] { source.Expression } )); } public static IQueryable<TSource> Distinct<TSource>(this IQueryable<TSource> source, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Distinct, source, comparer), new Expression[] { source.Expression, Expression.Constant(comparer, typeof(IEqualityComparer<TSource>)) } )); } public static IQueryable<TSource> Concat<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Concat, source1, source2), new Expression[] { source1.Expression, GetSourceExpression(source2) } )); } public static IQueryable<TResult> Zip<TFirst, TSecond, TResult>(this IQueryable<TFirst> source1, IEnumerable<TSecond> source2, Expression<Func<TFirst, TSecond, TResult>> resultSelector) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); if (resultSelector == null) throw Error.ArgumentNull("resultSelector"); return source1.Provider.CreateQuery<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Zip, source1, source2, resultSelector), new Expression[] { source1.Expression, GetSourceExpression(source2), Expression.Quote(resultSelector) } )); } public static IQueryable<TSource> Union<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Union, source1, source2), new Expression[] { source1.Expression, GetSourceExpression(source2) } )); } public static IQueryable<TSource> Union<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Union, source1, source2, comparer), new Expression[] { source1.Expression, GetSourceExpression(source2), Expression.Constant(comparer, typeof(IEqualityComparer<TSource>)) } )); } public static IQueryable<TSource> Intersect<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Intersect, source1, source2), new Expression[] { source1.Expression, GetSourceExpression(source2) } )); } public static IQueryable<TSource> Intersect<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Intersect, source1, source2, comparer), new Expression[] { source1.Expression, GetSourceExpression(source2), Expression.Constant(comparer, typeof(IEqualityComparer<TSource>)) } )); } public static IQueryable<TSource> Except<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Except, source1, source2), new Expression[] { source1.Expression, GetSourceExpression(source2) } )); } public static IQueryable<TSource> Except<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Except, source1, source2, comparer), new Expression[] { source1.Expression, GetSourceExpression(source2), Expression.Constant(comparer, typeof(IEqualityComparer<TSource>)) } )); } public static TSource First<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.First, source), new Expression[] { source.Expression } )); } public static TSource First<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.First, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static TSource FirstOrDefault<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.FirstOrDefault, source), new Expression[] { source.Expression } )); } public static TSource FirstOrDefault<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.FirstOrDefault, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static TSource Last<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Last, source), new Expression[] { source.Expression } )); } public static TSource Last<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Last, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static TSource LastOrDefault<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.LastOrDefault, source), new Expression[] { source.Expression } )); } public static TSource LastOrDefault<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.LastOrDefault, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static TSource Single<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Single, source), new Expression[] { source.Expression } )); } public static TSource Single<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Single, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static TSource SingleOrDefault<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.SingleOrDefault, source), new Expression[] { source.Expression } )); } public static TSource SingleOrDefault<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.SingleOrDefault, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static TSource ElementAt<TSource>(this IQueryable<TSource> source, int index) { if (source == null) throw Error.ArgumentNull("source"); if (index < 0) throw Error.ArgumentOutOfRange("index"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.ElementAt, source, index), new Expression[] { source.Expression, Expression.Constant(index) } )); } public static TSource ElementAtOrDefault<TSource>(this IQueryable<TSource> source, int index) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.ElementAtOrDefault, source, index), new Expression[] { source.Expression, Expression.Constant(index) } )); } public static IQueryable<TSource> DefaultIfEmpty<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.DefaultIfEmpty, source), new Expression[] { source.Expression } )); } public static IQueryable<TSource> DefaultIfEmpty<TSource>(this IQueryable<TSource> source, TSource defaultValue) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.DefaultIfEmpty, source, defaultValue), new Expression[] { source.Expression, Expression.Constant(defaultValue, typeof(TSource)) } )); } public static bool Contains<TSource>(this IQueryable<TSource> source, TSource item) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<bool>( Expression.Call( null, GetMethodInfo(Queryable.Contains, source, item), new Expression[] { source.Expression, Expression.Constant(item, typeof(TSource)) } )); } public static bool Contains<TSource>(this IQueryable<TSource> source, TSource item, IEqualityComparer<TSource> comparer) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<bool>( Expression.Call( null, GetMethodInfo(Queryable.Contains, source, item, comparer), new Expression[] { source.Expression, Expression.Constant(item, typeof(TSource)), Expression.Constant(comparer, typeof(IEqualityComparer<TSource>)) } )); } public static IQueryable<TSource> Reverse<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.CreateQuery<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Reverse, source), new Expression[] { source.Expression } )); } public static bool SequenceEqual<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.Execute<bool>( Expression.Call( null, GetMethodInfo(Queryable.SequenceEqual, source1, source2), new Expression[] { source1.Expression, GetSourceExpression(source2) } )); } public static bool SequenceEqual<TSource>(this IQueryable<TSource> source1, IEnumerable<TSource> source2, IEqualityComparer<TSource> comparer) { if (source1 == null) throw Error.ArgumentNull("source1"); if (source2 == null) throw Error.ArgumentNull("source2"); return source1.Provider.Execute<bool>( Expression.Call( null, GetMethodInfo(Queryable.SequenceEqual, source1, source2, comparer), new Expression[] { source1.Expression, GetSourceExpression(source2), Expression.Constant(comparer, typeof(IEqualityComparer<TSource>)) } )); } public static bool Any<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<bool>( Expression.Call( null, GetMethodInfo(Queryable.Any, source), new Expression[] { source.Expression } )); } public static bool Any<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<bool>( Expression.Call( null, GetMethodInfo(Queryable.Any, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static bool All<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<bool>( Expression.Call( null, GetMethodInfo(Queryable.All, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static int Count<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<int>( Expression.Call( null, GetMethodInfo(Queryable.Count, source), new Expression[] { source.Expression } )); } public static int Count<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<int>( Expression.Call( null, GetMethodInfo(Queryable.Count, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static long LongCount<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<long>( Expression.Call( null, GetMethodInfo(Queryable.LongCount, source), new Expression[] { source.Expression } )); } public static long LongCount<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) { if (source == null) throw Error.ArgumentNull("source"); if (predicate == null) throw Error.ArgumentNull("predicate"); return source.Provider.Execute<long>( Expression.Call( null, GetMethodInfo(Queryable.LongCount, source, predicate), new Expression[] { source.Expression, Expression.Quote(predicate) } )); } public static TSource Min<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Min, source), new Expression[] { source.Expression } )); } public static TResult Min<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource,TResult>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Min, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static TSource Max<TSource>(this IQueryable<TSource> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Max, source), new Expression[] { source.Expression } )); } public static TResult Max<TSource,TResult>(this IQueryable<TSource> source, Expression<Func<TSource,TResult>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Max, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static int Sum(this IQueryable<int> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<int>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static int? Sum(this IQueryable<int?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<int?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static long Sum(this IQueryable<long> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<long>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static long? Sum(this IQueryable<long?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<long?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static float Sum(this IQueryable<float> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<float>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static float? Sum(this IQueryable<float?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<float?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static double Sum(this IQueryable<double> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<double>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static double? Sum(this IQueryable<double?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<double?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static decimal Sum(this IQueryable<decimal> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<decimal>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static decimal? Sum(this IQueryable<decimal?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<decimal?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source), new Expression[] { source.Expression } )); } public static int Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,int>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<int>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static int? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,int?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<int?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static long Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,long>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<long>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static long? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,long?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<long?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static float Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,float>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<float>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static float? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,float?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<float?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static double Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,double>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<double>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static double? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,double?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<double?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static decimal Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,decimal>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<decimal>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static decimal? Sum<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,decimal?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<decimal?>( Expression.Call( null, GetMethodInfo(Queryable.Sum, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static double Average(this IQueryable<int> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<double>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static double? Average(this IQueryable<int?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<double?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static double Average(this IQueryable<long> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<double>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static double? Average(this IQueryable<long?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<double?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static float Average(this IQueryable<float> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<float>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static float? Average(this IQueryable<float?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<float?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static double Average(this IQueryable<double> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<double>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static double? Average(this IQueryable<double?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<double?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static decimal Average(this IQueryable<decimal> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<decimal>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static decimal? Average(this IQueryable<decimal?> source) { if (source == null) throw Error.ArgumentNull("source"); return source.Provider.Execute<decimal?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source), new Expression[] { source.Expression } )); } public static double Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,int>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<double>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static double? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,int?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<double?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static float Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<float>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static float? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, float?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<float?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static double Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,long>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<double>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static double? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,long?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<double?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static double Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,double>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<double>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static double? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,double?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<double?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static decimal Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,decimal>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<decimal>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static decimal? Average<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,decimal?>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<decimal?>( Expression.Call( null, GetMethodInfo(Queryable.Average, source, selector), new Expression[] { source.Expression, Expression.Quote(selector) } )); } public static TSource Aggregate<TSource>(this IQueryable<TSource> source, Expression<Func<TSource,TSource,TSource>> func) { if (source == null) throw Error.ArgumentNull("source"); if (func == null) throw Error.ArgumentNull("func"); return source.Provider.Execute<TSource>( Expression.Call( null, GetMethodInfo(Queryable.Aggregate, source, func), new Expression[] { source.Expression, Expression.Quote(func) } )); } public static TAccumulate Aggregate<TSource,TAccumulate>(this IQueryable<TSource> source, TAccumulate seed, Expression<Func<TAccumulate,TSource,TAccumulate>> func) { if (source == null) throw Error.ArgumentNull("source"); if (func == null) throw Error.ArgumentNull("func"); return source.Provider.Execute<TAccumulate>( Expression.Call( null, GetMethodInfo(Queryable.Aggregate, source, seed, func), new Expression[] { source.Expression, Expression.Constant(seed), Expression.Quote(func) } )); } public static TResult Aggregate<TSource,TAccumulate,TResult>(this IQueryable<TSource> source, TAccumulate seed, Expression<Func<TAccumulate,TSource,TAccumulate>> func, Expression<Func<TAccumulate,TResult>> selector) { if (source == null) throw Error.ArgumentNull("source"); if (func == null) throw Error.ArgumentNull("func"); if (selector == null) throw Error.ArgumentNull("selector"); return source.Provider.Execute<TResult>( Expression.Call( null, GetMethodInfo(Queryable.Aggregate, source, seed, func, selector), new Expression[] { source.Expression, Expression.Constant(seed), Expression.Quote(func), Expression.Quote(selector) } )); } } }
/* * CKEditor Html Editor Provider for DotNetNuke * ======== * http://dnnckeditor.codeplex.com/ * Copyright (C) Ingo Herbote * * The software, this file and its contents are subject to the CKEditor Provider * License. Please read the license.txt file before using, installing, copying, * modifying or distribute this file or part of its contents. The contents of * this file is part of the Source Code of the CKEditor Provider. */ namespace WatchersNET.CKEditor.Browser { using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using System.Web; using System.Web.Script.Serialization; using DotNetNuke.Common.Utilities; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.FileSystem; using WatchersNET.CKEditor.Objects; using WatchersNET.CKEditor.Utilities; /// <summary> /// The File Upload Handler /// </summary> public class FileUploader : IHttpHandler { /// <summary> /// The JavaScript Serializer /// </summary> private readonly JavaScriptSerializer js = new JavaScriptSerializer(); /// <summary> /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler" /> instance. /// </summary> public bool IsReusable { get { return false; } } /// <summary> /// Gets a value indicating whether [override files]. /// </summary> /// <value> /// <c>true</c> if [override files]; otherwise, <c>false</c>. /// </value> private bool OverrideFiles { get { return HttpContext.Current.Request["overrideFiles"].Equals("1") || HttpContext.Current.Request["overrideFiles"].Equals( "true", StringComparison.InvariantCultureIgnoreCase); } } /// <summary> /// Gets the storage folder. /// </summary> /// <value> /// The storage folder. /// </value> private FolderInfo StorageFolder { get { return new FolderController().GetFolderInfo( PortalSettings.PortalId, Convert.ToInt32(HttpContext.Current.Request["storageFolderID"])); } } /// <summary> /// Gets the storage folder. /// </summary> /// <value> /// The storage folder. /// </value> private PortalSettings PortalSettings { get { return new PortalSettings(Convert.ToInt32(HttpContext.Current.Request["portalID"])); } } /// <summary> /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler" /> interface. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpContext" /> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param> public void ProcessRequest(HttpContext context) { context.Response.AddHeader("Pragma", "no-cache"); context.Response.AddHeader("Cache-Control", "private, no-cache"); this.HandleMethod(context); } /// <summary> /// Returns the options. /// </summary> /// <param name="context">The context.</param> private static void ReturnOptions(HttpContext context) { context.Response.AddHeader("Allow", "DELETE,GET,HEAD,POST,PUT,OPTIONS"); context.Response.StatusCode = 200; } /// <summary> /// Handle request based on method /// </summary> /// <param name="context">The context.</param> private void HandleMethod(HttpContext context) { switch (context.Request.HttpMethod) { case "HEAD": case "GET": /*if (GivenFilename(context)) { this.DeliverFile(context); } else { ListCurrentFiles(context); }*/ break; case "POST": case "PUT": this.UploadFile(context); break; case "OPTIONS": ReturnOptions(context); break; default: context.Response.ClearHeaders(); context.Response.StatusCode = 405; break; } } /// <summary> /// Uploads the file. /// </summary> /// <param name="context">The context.</param> private void UploadFile(HttpContext context) { var statuses = new List<FilesUploadStatus>(); this.UploadWholeFile(context, statuses); this.WriteJsonIframeSafe(context, statuses); } /// <summary> /// Uploads the whole file. /// </summary> /// <param name="context">The context.</param> /// <param name="statuses">The statuses.</param> private void UploadWholeFile(HttpContext context, List<FilesUploadStatus> statuses) { for (int i = 0; i < context.Request.Files.Count; i++) { var file = context.Request.Files[i]; var fileName = Path.GetFileName(file.FileName); if (!string.IsNullOrEmpty(fileName)) { // Replace dots in the name with underscores (only one dot can be there... security issue). fileName = Regex.Replace(fileName, @"\.(?![^.]*$)", "_", RegexOptions.None); // Check for Illegal Chars if (Utility.ValidateFileName(fileName)) { fileName = Utility.CleanFileName(fileName); } // Convert Unicode Chars fileName = Utility.ConvertUnicodeChars(fileName); } else { throw new HttpRequestValidationException("File does not have a name"); } if (fileName.Length > 220) { fileName = fileName.Substring(fileName.Length - 220); } var fileNameNoExtenstion = Path.GetFileNameWithoutExtension(fileName); // Rename File if Exists if (!this.OverrideFiles) { var counter = 0; while (File.Exists(Path.Combine(this.StorageFolder.PhysicalPath, fileName))) { counter++; fileName = string.Format( "{0}_{1}{2}", fileNameNoExtenstion, counter, Path.GetExtension(file.FileName)); } } FileSystemUtils.UploadFile(this.StorageFolder.FolderPath, file, fileName); var fullName = Path.GetFileName(fileName); statuses.Add(new FilesUploadStatus(fullName, file.ContentLength)); } } /// <summary> /// Writes the JSON iFrame safe. /// </summary> /// <param name="context">The context.</param> /// <param name="statuses">The statuses.</param> private void WriteJsonIframeSafe(HttpContext context, List<FilesUploadStatus> statuses) { context.Response.AddHeader("Vary", "Accept"); try { context.Response.ContentType = context.Request["HTTP_ACCEPT"].Contains("application/json") ? "application/json" : "text/plain"; } catch { context.Response.ContentType = "text/plain"; } var jsonObj = this.js.Serialize(statuses.ToArray()); context.Response.Write(jsonObj); } } }
// 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.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO.Compression { public partial class DeflateStream : Stream { private const int DefaultBufferSize = 8192; private Stream _stream; private CompressionMode _mode; private bool _leaveOpen; private Inflater _inflater; private Deflater _deflater; private byte[] _buffer; private int _activeAsyncOperation; // 1 == true, 0 == false private bool _wroteBytes; public DeflateStream(Stream stream, CompressionMode mode) : this(stream, mode, leaveOpen: false) { } public DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen) : this(stream, mode, leaveOpen, ZLibNative.Deflate_DefaultWindowBits) { } // Implies mode = Compress public DeflateStream(Stream stream, CompressionLevel compressionLevel) : this(stream, compressionLevel, leaveOpen: false) { } // Implies mode = Compress public DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen) : this(stream, compressionLevel, leaveOpen, ZLibNative.Deflate_DefaultWindowBits) { } /// <summary> /// Internal constructor to check stream validity and call the correct initialization function depending on /// the value of the CompressionMode given. /// </summary> internal DeflateStream(Stream stream, CompressionMode mode, bool leaveOpen, int windowBits) { if (stream == null) throw new ArgumentNullException(nameof(stream)); switch (mode) { case CompressionMode.Decompress: InitializeInflater(stream, leaveOpen, windowBits); break; case CompressionMode.Compress: InitializeDeflater(stream, leaveOpen, windowBits, CompressionLevel.Optimal); break; default: throw new ArgumentException(SR.ArgumentOutOfRange_Enum, nameof(mode)); } } /// <summary> /// Internal constructor to specify the compressionlevel as well as the windowbits /// </summary> internal DeflateStream(Stream stream, CompressionLevel compressionLevel, bool leaveOpen, int windowBits) { if (stream == null) throw new ArgumentNullException(nameof(stream)); InitializeDeflater(stream, leaveOpen, windowBits, compressionLevel); } /// <summary> /// Sets up this DeflateStream to be used for Zlib Inflation/Decompression /// </summary> internal void InitializeInflater(Stream stream, bool leaveOpen, int windowBits) { Debug.Assert(stream != null); if (!stream.CanRead) throw new ArgumentException(SR.NotSupported_UnreadableStream, nameof(stream)); _inflater = new Inflater(windowBits); _stream = stream; _mode = CompressionMode.Decompress; _leaveOpen = leaveOpen; } /// <summary> /// Sets up this DeflateStream to be used for Zlib Deflation/Compression /// </summary> internal void InitializeDeflater(Stream stream, bool leaveOpen, int windowBits, CompressionLevel compressionLevel) { Debug.Assert(stream != null); if (!stream.CanWrite) throw new ArgumentException(SR.NotSupported_UnwritableStream, nameof(stream)); _deflater = new Deflater(compressionLevel, windowBits); _stream = stream; _mode = CompressionMode.Compress; _leaveOpen = leaveOpen; InitializeBuffer(); } private void InitializeBuffer() { Debug.Assert(_buffer == null); _buffer = ArrayPool<byte>.Shared.Rent(DefaultBufferSize); } private void EnsureBufferInitialized() { if (_buffer == null) { InitializeBuffer(); } } public Stream BaseStream => _stream; public override bool CanRead { get { if (_stream == null) { return false; } return (_mode == CompressionMode.Decompress && _stream.CanRead); } } public override bool CanWrite { get { if (_stream == null) { return false; } return (_mode == CompressionMode.Compress && _stream.CanWrite); } } public override bool CanSeek => false; public override long Length { get { throw new NotSupportedException(SR.NotSupported); } } public override long Position { get { throw new NotSupportedException(SR.NotSupported); } set { throw new NotSupportedException(SR.NotSupported); } } public override void Flush() { EnsureNotDisposed(); if (_mode == CompressionMode.Compress) FlushBuffers(); } public override Task FlushAsync(CancellationToken cancellationToken) { EnsureNoActiveAsyncOperation(); EnsureNotDisposed(); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); return _mode != CompressionMode.Compress || !_wroteBytes ? Task.CompletedTask : FlushAsyncCore(cancellationToken); } private async Task FlushAsyncCore(CancellationToken cancellationToken) { AsyncOperationStarting(); try { // Compress any bytes left: await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); // Pull out any bytes left inside deflater: bool flushSuccessful; do { int compressedBytes; flushSuccessful = _deflater.Flush(_buffer, out compressedBytes); if (flushSuccessful) { await _stream.WriteAsync(_buffer, 0, compressedBytes, cancellationToken).ConfigureAwait(false); } Debug.Assert(flushSuccessful == (compressedBytes > 0)); } while (flushSuccessful); } finally { AsyncOperationCompleting(); } } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(SR.NotSupported); } public override void SetLength(long value) { throw new NotSupportedException(SR.NotSupported); } public override int ReadByte() { EnsureDecompressionMode(); EnsureNotDisposed(); // Try to read a single byte from zlib without allocating an array, pinning an array, etc. // If zlib doesn't have any data, fall back to the base stream implementation, which will do that. byte b; return _inflater.Inflate(out b) ? b : base.ReadByte(); } public override int Read(byte[] array, int offset, int count) { ValidateParameters(array, offset, count); return ReadCore(new Span<byte>(array, offset, count)); } public override int Read(Span<byte> destination) { if (GetType() != typeof(DeflateStream)) { // DeflateStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior // to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload // should use the behavior of Read(byte[],int,int) overload. return base.Read(destination); } else { return ReadCore(destination); } } internal int ReadCore(Span<byte> destination) { EnsureDecompressionMode(); EnsureNotDisposed(); EnsureBufferInitialized(); int totalRead = 0; while (true) { int bytesRead = _inflater.Inflate(destination.Slice(totalRead)); totalRead += bytesRead; if (totalRead == destination.Length) { break; } if (_inflater.Finished()) { break; } int bytes = _stream.Read(_buffer, 0, _buffer.Length); if (bytes <= 0) { break; } else if (bytes > _buffer.Length) { // The stream is either malicious or poorly implemented and returned a number of // bytes larger than the buffer supplied to it. throw new InvalidDataException(SR.GenericInvalidData); } _inflater.SetInput(_buffer, 0, bytes); } return totalRead; } private void ValidateParameters(byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count)); if (array.Length - offset < count) throw new ArgumentException(SR.InvalidArgumentOffsetCount); } private void EnsureNotDisposed() { if (_stream == null) ThrowStreamClosedException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowStreamClosedException() { throw new ObjectDisposedException(null, SR.ObjectDisposed_StreamClosed); } private void EnsureDecompressionMode() { if (_mode != CompressionMode.Decompress) ThrowCannotReadFromDeflateStreamException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowCannotReadFromDeflateStreamException() { throw new InvalidOperationException(SR.CannotReadFromDeflateStream); } private void EnsureCompressionMode() { if (_mode != CompressionMode.Compress) ThrowCannotWriteToDeflateStreamException(); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowCannotWriteToDeflateStreamException() { throw new InvalidOperationException(SR.CannotWriteToDeflateStream); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) => TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override Task<int> ReadAsync(byte[] array, int offset, int count, CancellationToken cancellationToken) { ValidateParameters(array, offset, count); return ReadAsyncMemory(new Memory<byte>(array, offset, count), cancellationToken).AsTask(); } public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken)) { if (GetType() != typeof(DeflateStream)) { // Ensure that existing streams derived from DeflateStream and that override ReadAsync(byte[],...) // get their existing behaviors when the newer Memory-based overload is used. return base.ReadAsync(destination, cancellationToken); } else { return ReadAsyncMemory(destination, cancellationToken); } } internal ValueTask<int> ReadAsyncMemory(Memory<byte> destination, CancellationToken cancellationToken) { EnsureDecompressionMode(); EnsureNoActiveAsyncOperation(); EnsureNotDisposed(); if (cancellationToken.IsCancellationRequested) { return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)); } EnsureBufferInitialized(); bool cleanup = true; AsyncOperationStarting(); try { // Try to read decompressed data in output buffer int bytesRead = _inflater.Inflate(destination.Span); if (bytesRead != 0) { // If decompression output buffer is not empty, return immediately. return new ValueTask<int>(bytesRead); } if (_inflater.Finished()) { // end of compression stream return new ValueTask<int>(0); } // If there is no data on the output buffer and we are not at // the end of the stream, we need to get more data from the base stream ValueTask<int> readTask = _stream.ReadAsync(_buffer, cancellationToken); cleanup = false; return FinishReadAsyncMemory(readTask, destination, cancellationToken); } finally { // if we haven't started any async work, decrement the counter to end the transaction if (cleanup) { AsyncOperationCompleting(); } } } private async ValueTask<int> FinishReadAsyncMemory( ValueTask<int> readTask, Memory<byte> destination, CancellationToken cancellationToken) { try { while (true) { int bytesRead = await readTask.ConfigureAwait(false); EnsureNotDisposed(); if (bytesRead <= 0) { // This indicates the base stream has received EOF return 0; } else if (bytesRead > _buffer.Length) { // The stream is either malicious or poorly implemented and returned a number of // bytes larger than the buffer supplied to it. throw new InvalidDataException(SR.GenericInvalidData); } cancellationToken.ThrowIfCancellationRequested(); // Feed the data from base stream into decompression engine _inflater.SetInput(_buffer, 0, bytesRead); bytesRead = _inflater.Inflate(destination.Span); if (bytesRead == 0 && !_inflater.Finished()) { // We could have read in head information and didn't get any data. // Read from the base stream again. readTask = _stream.ReadAsync(_buffer, cancellationToken); } else { return bytesRead; } } } finally { AsyncOperationCompleting(); } } public override void Write(byte[] array, int offset, int count) { ValidateParameters(array, offset, count); WriteCore(new ReadOnlySpan<byte>(array, offset, count)); } public override void Write(ReadOnlySpan<byte> source) { if (GetType() != typeof(DeflateStream)) { // DeflateStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior // to this Write(ReadOnlySpan<byte>) overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload // should use the behavior of Write(byte[],int,int) overload. base.Write(source); } else { WriteCore(source); } } internal void WriteCore(ReadOnlySpan<byte> source) { EnsureCompressionMode(); EnsureNotDisposed(); // Write compressed the bytes we already passed to the deflater: WriteDeflaterOutput(); unsafe { // Pass new bytes through deflater and write them too: fixed (byte* bufferPtr = &MemoryMarshal.GetReference(source)) { _deflater.SetInput(bufferPtr, source.Length); WriteDeflaterOutput(); _wroteBytes = true; } } } private void WriteDeflaterOutput() { while (!_deflater.NeedsInput()) { int compressedBytes = _deflater.GetDeflateOutput(_buffer); if (compressedBytes > 0) { _stream.Write(_buffer, 0, compressedBytes); } } } // This is called by Flush: private void FlushBuffers() { // Make sure to only "flush" when we actually had some input: if (_wroteBytes) { // Compress any bytes left: WriteDeflaterOutput(); // Pull out any bytes left inside deflater: bool flushSuccessful; do { int compressedBytes; flushSuccessful = _deflater.Flush(_buffer, out compressedBytes); if (flushSuccessful) { _stream.Write(_buffer, 0, compressedBytes); } Debug.Assert(flushSuccessful == (compressedBytes > 0)); } while (flushSuccessful); } } // This is called by Dispose: private void PurgeBuffers(bool disposing) { if (!disposing) return; if (_stream == null) return; if (_mode != CompressionMode.Compress) return; // Some deflaters (e.g. ZLib) write more than zero bytes for zero byte inputs. // This round-trips and we should be ok with this, but our legacy managed deflater // always wrote zero output for zero input and upstack code (e.g. ZipArchiveEntry) // took dependencies on it. Thus, make sure to only "flush" when we actually had // some input: if (_wroteBytes) { // Compress any bytes left WriteDeflaterOutput(); // Pull out any bytes left inside deflater: bool finished; do { int compressedBytes; finished = _deflater.Finish(_buffer, out compressedBytes); if (compressedBytes > 0) _stream.Write(_buffer, 0, compressedBytes); } while (!finished); } else { // In case of zero length buffer, we still need to clean up the native created stream before // the object get disposed because eventually ZLibNative.ReleaseHandle will get called during // the dispose operation and although it frees the stream but it return error code because the // stream state was still marked as in use. The symptoms of this problem will not be seen except // if running any diagnostic tools which check for disposing safe handle objects bool finished; do { int compressedBytes; finished = _deflater.Finish(_buffer, out compressedBytes); } while (!finished); } } protected override void Dispose(bool disposing) { try { PurgeBuffers(disposing); } finally { // Close the underlying stream even if PurgeBuffers threw. // Stream.Close() may throw here (may or may not be due to the same error). // In this case, we still need to clean up internal resources, hence the inner finally blocks. try { if (disposing && !_leaveOpen) _stream?.Dispose(); } finally { _stream = null; try { _deflater?.Dispose(); _inflater?.Dispose(); } finally { _deflater = null; _inflater = null; byte[] buffer = _buffer; if (buffer != null) { _buffer = null; if (!AsyncOperationIsActive) { ArrayPool<byte>.Shared.Return(buffer); } } base.Dispose(disposing); } } } } public override IAsyncResult BeginWrite(byte[] array, int offset, int count, AsyncCallback asyncCallback, object asyncState) => TaskToApm.Begin(WriteAsync(array, offset, count, CancellationToken.None), asyncCallback, asyncState); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override Task WriteAsync(byte[] array, int offset, int count, CancellationToken cancellationToken) { ValidateParameters(array, offset, count); return WriteAsyncMemory(new ReadOnlyMemory<byte>(array, offset, count), cancellationToken); } public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { if (GetType() != typeof(DeflateStream)) { // Ensure that existing streams derived from DeflateStream and that override WriteAsync(byte[],...) // get their existing behaviors when the newer Memory-based overload is used. return base.WriteAsync(source, cancellationToken); } else { return WriteAsyncMemory(source, cancellationToken); } } internal Task WriteAsyncMemory(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { EnsureCompressionMode(); EnsureNoActiveAsyncOperation(); EnsureNotDisposed(); return cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : WriteAsyncMemoryCore(source, cancellationToken); } private async Task WriteAsyncMemoryCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { AsyncOperationStarting(); try { await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); // Pass new bytes through deflater _deflater.SetInput(source); await WriteDeflaterOutputAsync(cancellationToken).ConfigureAwait(false); _wroteBytes = true; } finally { AsyncOperationCompleting(); } } /// <summary> /// Writes the bytes that have already been deflated /// </summary> private async Task WriteDeflaterOutputAsync(CancellationToken cancellationToken) { while (!_deflater.NeedsInput()) { int compressedBytes = _deflater.GetDeflateOutput(_buffer); if (compressedBytes > 0) { await _stream.WriteAsync(_buffer, 0, compressedBytes, cancellationToken).ConfigureAwait(false); } } } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // Validation as base CopyToAsync would do StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // Validation as ReadAsync would do EnsureDecompressionMode(); EnsureNoActiveAsyncOperation(); EnsureNotDisposed(); // Early check for cancellation if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } // Do the copy return new CopyToAsyncStream(this, destination, bufferSize, cancellationToken).CopyFromSourceToDestination(); } private sealed class CopyToAsyncStream : Stream { private readonly DeflateStream _deflateStream; private readonly Stream _destination; private readonly CancellationToken _cancellationToken; private byte[] _arrayPoolBuffer; private int _arrayPoolBufferHighWaterMark; public CopyToAsyncStream(DeflateStream deflateStream, Stream destination, int bufferSize, CancellationToken cancellationToken) { Debug.Assert(deflateStream != null); Debug.Assert(destination != null); Debug.Assert(bufferSize > 0); _deflateStream = deflateStream; _destination = destination; _cancellationToken = cancellationToken; _arrayPoolBuffer = ArrayPool<byte>.Shared.Rent(bufferSize); } public async Task CopyFromSourceToDestination() { _deflateStream.AsyncOperationStarting(); try { // Flush any existing data in the inflater to the destination stream. while (true) { int bytesRead = _deflateStream._inflater.Inflate(_arrayPoolBuffer, 0, _arrayPoolBuffer.Length); if (bytesRead > 0) { if (bytesRead > _arrayPoolBufferHighWaterMark) _arrayPoolBufferHighWaterMark = bytesRead; await _destination.WriteAsync(_arrayPoolBuffer, 0, bytesRead, _cancellationToken).ConfigureAwait(false); } else break; } // Now, use the source stream's CopyToAsync to push directly to our inflater via this helper stream await _deflateStream._stream.CopyToAsync(this, _arrayPoolBuffer.Length, _cancellationToken).ConfigureAwait(false); } finally { _deflateStream.AsyncOperationCompleting(); Array.Clear(_arrayPoolBuffer, 0, _arrayPoolBufferHighWaterMark); // clear only the most we used ArrayPool<byte>.Shared.Return(_arrayPoolBuffer, clearArray: false); _arrayPoolBuffer = null; } } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // Validate inputs Debug.Assert(buffer != _arrayPoolBuffer); _deflateStream.EnsureNotDisposed(); if (count <= 0) { return; } else if (count > buffer.Length - offset) { // The source stream is either malicious or poorly implemented and returned a number of // bytes larger than the buffer supplied to it. throw new InvalidDataException(SR.GenericInvalidData); } // Feed the data from base stream into the decompression engine. _deflateStream._inflater.SetInput(buffer, offset, count); // While there's more decompressed data available, forward it to the destination stream. while (true) { int bytesRead = _deflateStream._inflater.Inflate(_arrayPoolBuffer, 0, _arrayPoolBuffer.Length); if (bytesRead > 0) { if (bytesRead > _arrayPoolBufferHighWaterMark) _arrayPoolBufferHighWaterMark = bytesRead; await _destination.WriteAsync(_arrayPoolBuffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } else break; } } public override void Write(byte[] buffer, int offset, int count) => WriteAsync(buffer, offset, count, default(CancellationToken)).GetAwaiter().GetResult(); public override bool CanWrite => true; public override void Flush() { } public override bool CanRead => false; public override bool CanSeek => false; public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } private bool AsyncOperationIsActive => _activeAsyncOperation != 0; private void EnsureNoActiveAsyncOperation() { if (AsyncOperationIsActive) ThrowInvalidBeginCall(); } private void AsyncOperationStarting() { if (Interlocked.CompareExchange(ref _activeAsyncOperation, 1, 0) != 0) { ThrowInvalidBeginCall(); } } private void AsyncOperationCompleting() { int oldValue = Interlocked.CompareExchange(ref _activeAsyncOperation, 0, 1); Debug.Assert(oldValue == 1, $"Expected {nameof(_activeAsyncOperation)} to be 1, got {oldValue}"); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ThrowInvalidBeginCall() { throw new InvalidOperationException(SR.InvalidBeginCall); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // /*============================================================================= ** ** ** ** Purpose: Synchronizes access to a shared resource or region of code in a multi-threaded ** program. ** ** =============================================================================*/ using System; using System.Runtime; using System.Threading; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics; namespace System.Threading { public static class Monitor { /*========================================================================= ** Obtain the monitor lock of obj. Will block if another thread holds the lock ** Will not block if the current thread holds the lock, ** however the caller must ensure that the same number of Exit ** calls are made as there were Enter calls. ** ** Exceptions: ArgumentNullException if object is null. =========================================================================*/ [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void Enter(Object obj); // Use a ref bool instead of out to ensure that unverifiable code must // initialize this value to something. If we used out, the value // could be uninitialized if we threw an exception in our prolog. // The JIT should inline this method to allow check of lockTaken argument to be optimized out // in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM. public static void Enter(Object obj, ref bool lockTaken) { if (lockTaken) ThrowLockTakenException(); ReliableEnter(obj, ref lockTaken); Debug.Assert(lockTaken); } private static void ThrowLockTakenException() { throw new ArgumentException(SR.Argument_MustBeFalse, "lockTaken"); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void ReliableEnter(Object obj, ref bool lockTaken); /*========================================================================= ** Release the monitor lock. If one or more threads are waiting to acquire the ** lock, and the current thread has executed as many Exits as ** Enters, one of the threads will be unblocked and allowed to proceed. ** ** Exceptions: ArgumentNullException if object is null. ** SynchronizationLockException if the current thread does not ** own the lock. =========================================================================*/ [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void Exit(Object obj); /*========================================================================= ** Similar to Enter, but will never block. That is, if the current thread can ** acquire the monitor lock without blocking, it will do so and TRUE will ** be returned. Otherwise FALSE will be returned. ** ** Exceptions: ArgumentNullException if object is null. =========================================================================*/ public static bool TryEnter(Object obj) { bool lockTaken = false; TryEnter(obj, 0, ref lockTaken); return lockTaken; } // The JIT should inline this method to allow check of lockTaken argument to be optimized out // in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM. public static void TryEnter(Object obj, ref bool lockTaken) { if (lockTaken) ThrowLockTakenException(); ReliableEnterTimeout(obj, 0, ref lockTaken); } /*========================================================================= ** Version of TryEnter that will block, but only up to a timeout period ** expressed in milliseconds. If timeout == Timeout.Infinite the method ** becomes equivalent to Enter. ** ** Exceptions: ArgumentNullException if object is null. ** ArgumentException if timeout < 0. =========================================================================*/ // The JIT should inline this method to allow check of lockTaken argument to be optimized out // in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM. public static bool TryEnter(Object obj, int millisecondsTimeout) { bool lockTaken = false; TryEnter(obj, millisecondsTimeout, ref lockTaken); return lockTaken; } private static int MillisecondsTimeoutFromTimeSpan(TimeSpan timeout) { long tm = (long)timeout.TotalMilliseconds; if (tm < -1 || tm > (long)Int32.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); return (int)tm; } public static bool TryEnter(Object obj, TimeSpan timeout) { return TryEnter(obj, MillisecondsTimeoutFromTimeSpan(timeout)); } // The JIT should inline this method to allow check of lockTaken argument to be optimized out // in the typical case. Note that the method has to be transparent for inlining to be allowed by the VM. public static void TryEnter(Object obj, int millisecondsTimeout, ref bool lockTaken) { if (lockTaken) ThrowLockTakenException(); ReliableEnterTimeout(obj, millisecondsTimeout, ref lockTaken); } public static void TryEnter(Object obj, TimeSpan timeout, ref bool lockTaken) { if (lockTaken) ThrowLockTakenException(); ReliableEnterTimeout(obj, MillisecondsTimeoutFromTimeSpan(timeout), ref lockTaken); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void ReliableEnterTimeout(Object obj, int timeout, ref bool lockTaken); public static bool IsEntered(object obj) { if (obj == null) throw new ArgumentNullException(nameof(obj)); return IsEnteredNative(obj); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsEnteredNative(Object obj); /*======================================================================== ** Waits for notification from the object (via a Pulse/PulseAll). ** timeout indicates how long to wait before the method returns. ** This method acquires the monitor waithandle for the object ** If this thread holds the monitor lock for the object, it releases it. ** On exit from the method, it obtains the monitor lock back. ** If exitContext is true then the synchronization domain for the context ** (if in a synchronized context) is exited before the wait and reacquired ** ** Exceptions: ArgumentNullException if object is null. ========================================================================*/ [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool ObjWait(bool exitContext, int millisecondsTimeout, Object obj); public static bool Wait(Object obj, int millisecondsTimeout, bool exitContext) { if (obj == null) throw (new ArgumentNullException(nameof(obj))); return ObjWait(exitContext, millisecondsTimeout, obj); } public static bool Wait(Object obj, TimeSpan timeout, bool exitContext) { return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), exitContext); } public static bool Wait(Object obj, int millisecondsTimeout) { return Wait(obj, millisecondsTimeout, false); } public static bool Wait(Object obj, TimeSpan timeout) { return Wait(obj, MillisecondsTimeoutFromTimeSpan(timeout), false); } public static bool Wait(Object obj) { return Wait(obj, Timeout.Infinite, false); } /*======================================================================== ** Sends a notification to a single waiting object. * Exceptions: SynchronizationLockException if this method is not called inside * a synchronized block of code. ========================================================================*/ [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void ObjPulse(Object obj); public static void Pulse(Object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } ObjPulse(obj); } /*======================================================================== ** Sends a notification to all waiting objects. ========================================================================*/ [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void ObjPulseAll(Object obj); public static void PulseAll(Object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } ObjPulseAll(obj); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 OpenSimulator Project 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 DEVELOPERS ``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 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 log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using System; using System.Data; using System.Reflection; namespace OpenSim.Data.MySQL { public class UserProfilesData: IProfilesData { static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region Properites string ConnectionString { get; set; } protected virtual Assembly Assembly { get { return GetType().Assembly; } } #endregion Properties #region class Member Functions public UserProfilesData(string connectionString) { ConnectionString = connectionString; Init(); } void Init() { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); Migration m = new Migration(dbcon, Assembly, "UserProfiles"); m.Update(); } } #endregion Member Functions #region Classifieds Queries /// <summary> /// Gets the classified records. /// </summary> /// <returns> /// Array of classified records /// </returns> /// <param name='creatorId'> /// Creator identifier. /// </param> public OSDArray GetClassifiedRecords(UUID creatorId) { OSDArray data = new OSDArray(); using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { string query = "SELECT classifieduuid, name FROM classifieds WHERE creatoruuid = ?Id"; dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", creatorId); using( MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.Default)) { if(reader.HasRows) { while (reader.Read()) { OSDMap n = new OSDMap(); UUID Id = UUID.Zero; string Name = null; try { UUID.TryParse(Convert.ToString( reader["classifieduuid"]), out Id); Name = Convert.ToString(reader["name"]); } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UserAccount exception {0}", e.Message); } n.Add("classifieduuid", OSD.FromUUID(Id)); n.Add("name", OSD.FromString(Name)); data.Add(n); } } } } } return data; } public bool UpdateClassifiedRecord(UserClassifiedAdd ad, ref string result) { string query = string.Empty; query += "INSERT INTO classifieds ("; query += "`classifieduuid`,"; query += "`creatoruuid`,"; query += "`creationdate`,"; query += "`expirationdate`,"; query += "`category`,"; query += "`name`,"; query += "`description`,"; query += "`parceluuid`,"; query += "`parentestate`,"; query += "`snapshotuuid`,"; query += "`simname`,"; query += "`posglobal`,"; query += "`parcelname`,"; query += "`classifiedflags`,"; query += "`priceforlisting`) "; query += "VALUES ("; query += "?ClassifiedId,"; query += "?CreatorId,"; query += "?CreatedDate,"; query += "?ExpirationDate,"; query += "?Category,"; query += "?Name,"; query += "?Description,"; query += "?ParcelId,"; query += "?ParentEstate,"; query += "?SnapshotId,"; query += "?SimName,"; query += "?GlobalPos,"; query += "?ParcelName,"; query += "?Flags,"; query += "?ListingPrice ) "; query += "ON DUPLICATE KEY UPDATE "; query += "category=?Category, "; query += "expirationdate=?ExpirationDate, "; query += "name=?Name, "; query += "description=?Description, "; query += "parentestate=?ParentEstate, "; query += "posglobal=?GlobalPos, "; query += "parcelname=?ParcelName, "; query += "classifiedflags=?Flags, "; query += "priceforlisting=?ListingPrice, "; query += "snapshotuuid=?SnapshotId"; if(string.IsNullOrEmpty(ad.ParcelName)) ad.ParcelName = "Unknown"; if(ad.ParcelId == null) ad.ParcelId = UUID.Zero; if(string.IsNullOrEmpty(ad.Description)) ad.Description = "No Description"; DateTime epoch = new DateTime(1970, 1, 1); DateTime now = DateTime.Now; TimeSpan epochnow = now - epoch; TimeSpan duration; DateTime expiration; TimeSpan epochexp; if(ad.Flags == 2) { duration = new TimeSpan(7,0,0,0); expiration = now.Add(duration); epochexp = expiration - epoch; } else { duration = new TimeSpan(365,0,0,0); expiration = now.Add(duration); epochexp = expiration - epoch; } ad.CreationDate = (int)epochnow.TotalSeconds; ad.ExpirationDate = (int)epochexp.TotalSeconds; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?ClassifiedId", ad.ClassifiedId.ToString()); cmd.Parameters.AddWithValue("?CreatorId", ad.CreatorId.ToString()); cmd.Parameters.AddWithValue("?CreatedDate", ad.CreationDate.ToString()); cmd.Parameters.AddWithValue("?ExpirationDate", ad.ExpirationDate.ToString()); cmd.Parameters.AddWithValue("?Category", ad.Category.ToString()); cmd.Parameters.AddWithValue("?Name", ad.Name.ToString()); cmd.Parameters.AddWithValue("?Description", ad.Description.ToString()); cmd.Parameters.AddWithValue("?ParcelId", ad.ParcelId.ToString()); cmd.Parameters.AddWithValue("?ParentEstate", ad.ParentEstate.ToString()); cmd.Parameters.AddWithValue("?SnapshotId", ad.SnapshotId.ToString ()); cmd.Parameters.AddWithValue("?SimName", ad.SimName.ToString()); cmd.Parameters.AddWithValue("?GlobalPos", ad.GlobalPos.ToString()); cmd.Parameters.AddWithValue("?ParcelName", ad.ParcelName.ToString()); cmd.Parameters.AddWithValue("?Flags", ad.Flags.ToString()); cmd.Parameters.AddWithValue("?ListingPrice", ad.Price.ToString ()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": ClassifiedesUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } public bool DeleteClassifiedRecord(UUID recordId) { string query = string.Empty; query += "DELETE FROM classifieds WHERE "; query += "classifieduuid = ?ClasifiedId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?ClassifiedId", recordId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": DeleteClassifiedRecord exception {0}", e.Message); return false; } return true; } public bool GetClassifiedInfo(ref UserClassifiedAdd ad, ref string result) { string query = string.Empty; query += "SELECT * FROM classifieds WHERE "; query += "classifieduuid = ?AdId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?AdId", ad.ClassifiedId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.Read ()) { ad.CreatorId = new UUID(reader.GetGuid("creatoruuid")); ad.ParcelId = new UUID(reader.GetGuid("parceluuid")); ad.SnapshotId = new UUID(reader.GetGuid("snapshotuuid")); ad.CreationDate = Convert.ToInt32(reader["creationdate"]); ad.ExpirationDate = Convert.ToInt32(reader["expirationdate"]); ad.ParentEstate = Convert.ToInt32(reader["parentestate"]); ad.Flags = (byte)reader.GetUInt32("classifiedflags"); ad.Category = reader.GetInt32("category"); ad.Price = reader.GetInt16("priceforlisting"); ad.Name = reader.GetString("name"); ad.Description = reader.GetString("description"); ad.SimName = reader.GetString("simname"); ad.GlobalPos = reader.GetString("posglobal"); ad.ParcelName = reader.GetString("parcelname"); } } } dbcon.Close(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetPickInfo exception {0}", e.Message); } return true; } #endregion Classifieds Queries #region Picks Queries public OSDArray GetAvatarPicks(UUID avatarId) { string query = string.Empty; query += "SELECT `pickuuid`,`name` FROM userpicks WHERE "; query += "creatoruuid = ?Id"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { while (reader.Read()) { OSDMap record = new OSDMap(); record.Add("pickuuid",OSD.FromString((string)reader["pickuuid"])); record.Add("name",OSD.FromString((string)reader["name"])); data.Add(record); } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarPicks exception {0}", e.Message); } return data; } public UserProfilePick GetPickInfo(UUID avatarId, UUID pickId) { string query = string.Empty; UserProfilePick pick = new UserProfilePick(); query += "SELECT * FROM userpicks WHERE "; query += "creatoruuid = ?CreatorId AND "; query += "pickuuid = ?PickId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?CreatorId", avatarId.ToString()); cmd.Parameters.AddWithValue("?PickId", pickId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { reader.Read(); string description = (string)reader["description"]; if (string.IsNullOrEmpty(description)) description = "No description given."; UUID.TryParse((string)reader["pickuuid"], out pick.PickId); UUID.TryParse((string)reader["creatoruuid"], out pick.CreatorId); UUID.TryParse((string)reader["parceluuid"], out pick.ParcelId); UUID.TryParse((string)reader["snapshotuuid"], out pick.SnapshotId); pick.GlobalPos = (string)reader["posglobal"]; bool.TryParse((string)reader["toppick"], out pick.TopPick); bool.TryParse((string)reader["enabled"], out pick.Enabled); pick.Name = (string)reader["name"]; pick.Desc = description; pick.User = (string)reader["user"]; pick.OriginalName = (string)reader["originalname"]; pick.SimName = (string)reader["simname"]; pick.SortOrder = (int)reader["sortorder"]; } } } dbcon.Close(); } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetPickInfo exception {0}", e.Message); } return pick; } public bool UpdatePicksRecord(UserProfilePick pick) { string query = string.Empty; query += "INSERT INTO userpicks VALUES ("; query += "?PickId,"; query += "?CreatorId,"; query += "?TopPick,"; query += "?ParcelId,"; query += "?Name,"; query += "?Desc,"; query += "?SnapshotId,"; query += "?User,"; query += "?Original,"; query += "?SimName,"; query += "?GlobalPos,"; query += "?SortOrder,"; query += "?Enabled) "; query += "ON DUPLICATE KEY UPDATE "; query += "parceluuid=?ParcelId,"; query += "name=?Name,"; query += "description=?Desc,"; query += "snapshotuuid=?SnapshotId,"; query += "pickuuid=?PickId,"; query += "posglobal=?GlobalPos"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?PickId", pick.PickId.ToString()); cmd.Parameters.AddWithValue("?CreatorId", pick.CreatorId.ToString()); cmd.Parameters.AddWithValue("?TopPick", pick.TopPick.ToString()); cmd.Parameters.AddWithValue("?ParcelId", pick.ParcelId.ToString()); cmd.Parameters.AddWithValue("?Name", pick.Name.ToString()); cmd.Parameters.AddWithValue("?Desc", pick.Desc.ToString()); cmd.Parameters.AddWithValue("?SnapshotId", pick.SnapshotId.ToString()); cmd.Parameters.AddWithValue("?User", pick.User.ToString()); cmd.Parameters.AddWithValue("?Original", pick.OriginalName.ToString()); cmd.Parameters.AddWithValue("?SimName",pick.SimName.ToString()); cmd.Parameters.AddWithValue("?GlobalPos", pick.GlobalPos); cmd.Parameters.AddWithValue("?SortOrder", pick.SortOrder.ToString ()); cmd.Parameters.AddWithValue("?Enabled", pick.Enabled.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UpdateAvatarNotes exception {0}", e.Message); return false; } return true; } public bool DeletePicksRecord(UUID pickId) { string query = string.Empty; query += "DELETE FROM userpicks WHERE "; query += "pickuuid = ?PickId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?PickId", pickId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": DeleteUserPickRecord exception {0}", e.Message); return false; } return true; } #endregion Picks Queries #region Avatar Notes Queries public bool GetAvatarNotes(ref UserProfileNotes notes) { // WIP string query = string.Empty; query += "SELECT `notes` FROM usernotes WHERE "; query += "useruuid = ?Id AND "; query += "targetuuid = ?TargetId"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", notes.UserId.ToString()); cmd.Parameters.AddWithValue("?TargetId", notes.TargetId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { reader.Read(); notes.Notes = OSD.FromString((string)reader["notes"]); } else { notes.Notes = OSD.FromString(""); } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return true; } public bool UpdateAvatarNotes(ref UserProfileNotes note, ref string result) { string query = string.Empty; bool remove; if(string.IsNullOrEmpty(note.Notes)) { remove = true; query += "DELETE FROM usernotes WHERE "; query += "useruuid=?UserId AND "; query += "targetuuid=?TargetId"; } else { remove = false; query += "INSERT INTO usernotes VALUES ( "; query += "?UserId,"; query += "?TargetId,"; query += "?Notes )"; query += "ON DUPLICATE KEY "; query += "UPDATE "; query += "notes=?Notes"; } try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { if(!remove) cmd.Parameters.AddWithValue("?Notes", note.Notes); cmd.Parameters.AddWithValue("?TargetId", note.TargetId.ToString ()); cmd.Parameters.AddWithValue("?UserId", note.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": UpdateAvatarNotes exception {0}", e.Message); return false; } return true; } #endregion Avatar Notes Queries #region Avatar Properties public bool GetAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "SELECT * FROM userprofile WHERE "; query += "useruuid = ?Id"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", props.UserId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { reader.Read(); props.WebUrl = (string)reader["profileURL"]; UUID.TryParse((string)reader["profileImage"], out props.ImageId); props.AboutText = (string)reader["profileAboutText"]; UUID.TryParse((string)reader["profileFirstImage"], out props.FirstLifeImageId); props.FirstLifeText = (string)reader["profileFirstText"]; UUID.TryParse((string)reader["profilePartner"], out props.PartnerId); props.WantToMask = (int)reader["profileWantToMask"]; props.WantToText = (string)reader["profileWantToText"]; props.SkillsMask = (int)reader["profileSkillsMask"]; props.SkillsText = (string)reader["profileSkillsText"]; props.Language = (string)reader["profileLanguages"]; } else { props.WebUrl = string.Empty; props.ImageId = UUID.Zero; props.AboutText = string.Empty; props.FirstLifeImageId = UUID.Zero; props.FirstLifeText = string.Empty; props.PartnerId = UUID.Zero; props.WantToMask = 0; props.WantToText = string.Empty; props.SkillsMask = 0; props.SkillsText = string.Empty; props.Language = string.Empty; props.PublishProfile = false; props.PublishMature = false; query = "INSERT INTO userprofile ("; query += "useruuid, "; query += "profilePartner, "; query += "profileAllowPublish, "; query += "profileMaturePublish, "; query += "profileURL, "; query += "profileWantToMask, "; query += "profileWantToText, "; query += "profileSkillsMask, "; query += "profileSkillsText, "; query += "profileLanguages, "; query += "profileImage, "; query += "profileAboutText, "; query += "profileFirstImage, "; query += "profileFirstText) VALUES ("; query += "?userId, "; query += "?profilePartner, "; query += "?profileAllowPublish, "; query += "?profileMaturePublish, "; query += "?profileURL, "; query += "?profileWantToMask, "; query += "?profileWantToText, "; query += "?profileSkillsMask, "; query += "?profileSkillsText, "; query += "?profileLanguages, "; query += "?profileImage, "; query += "?profileAboutText, "; query += "?profileFirstImage, "; query += "?profileFirstText)"; dbcon.Close(); dbcon.Open(); using (MySqlCommand put = new MySqlCommand(query, dbcon)) { put.Parameters.AddWithValue("?userId", props.UserId.ToString()); put.Parameters.AddWithValue("?profilePartner", props.PartnerId.ToString()); put.Parameters.AddWithValue("?profileAllowPublish", props.PublishProfile); put.Parameters.AddWithValue("?profileMaturePublish", props.PublishMature); put.Parameters.AddWithValue("?profileURL", props.WebUrl); put.Parameters.AddWithValue("?profileWantToMask", props.WantToMask); put.Parameters.AddWithValue("?profileWantToText", props.WantToText); put.Parameters.AddWithValue("?profileSkillsMask", props.SkillsMask); put.Parameters.AddWithValue("?profileSkillsText", props.SkillsText); put.Parameters.AddWithValue("?profileLanguages", props.Language); put.Parameters.AddWithValue("?profileImage", props.ImageId.ToString()); put.Parameters.AddWithValue("?profileAboutText", props.AboutText); put.Parameters.AddWithValue("?profileFirstImage", props.FirstLifeImageId.ToString()); put.Parameters.AddWithValue("?profileFirstText", props.FirstLifeText); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": Requst properties exception {0}", e.Message); result = e.Message; return false; } return true; } public bool UpdateAvatarProperties(ref UserProfileProperties props, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "profileURL=?profileURL, "; query += "profileImage=?image, "; query += "profileAboutText=?abouttext,"; query += "profileFirstImage=?firstlifeimage,"; query += "profileFirstText=?firstlifetext "; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?profileURL", props.WebUrl); cmd.Parameters.AddWithValue("?image", props.ImageId.ToString()); cmd.Parameters.AddWithValue("?abouttext", props.AboutText); cmd.Parameters.AddWithValue("?firstlifeimage", props.FirstLifeImageId.ToString()); cmd.Parameters.AddWithValue("?firstlifetext", props.FirstLifeText); cmd.Parameters.AddWithValue("?uuid", props.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentPropertiesUpdate exception {0}", e.Message); return false; } return true; } #endregion Avatar Properties #region Avatar Interests public bool UpdateAvatarInterests(UserProfileProperties up, ref string result) { string query = string.Empty; query += "UPDATE userprofile SET "; query += "profileWantToMask=?WantMask, "; query += "profileWantToText=?WantText,"; query += "profileSkillsMask=?SkillsMask,"; query += "profileSkillsText=?SkillsText, "; query += "profileLanguages=?Languages "; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?WantMask", up.WantToMask); cmd.Parameters.AddWithValue("?WantText", up.WantToText); cmd.Parameters.AddWithValue("?SkillsMask", up.SkillsMask); cmd.Parameters.AddWithValue("?SkillsText", up.SkillsText); cmd.Parameters.AddWithValue("?Languages", up.Language); cmd.Parameters.AddWithValue("?uuid", up.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentInterestsUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } #endregion Avatar Interests public OSDArray GetUserImageAssets(UUID avatarId) { OSDArray data = new OSDArray(); string query = "SELECT `snapshotuuid` FROM {0} WHERE `creatoruuid` = ?Id"; // Get classified image assets try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`classifieds`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); } } } } dbcon.Close(); dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`userpicks`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["snapshotuuid"].ToString ())); } } } } dbcon.Close(); dbcon.Open(); query = "SELECT `profileImage`, `profileFirstImage` FROM `userprofile` WHERE `useruuid` = ?Id"; using (MySqlCommand cmd = new MySqlCommand(string.Format (query,"`userpicks`"), dbcon)) { cmd.Parameters.AddWithValue("?Id", avatarId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { while (reader.Read()) { data.Add(new OSDString((string)reader["profileImage"].ToString ())); data.Add(new OSDString((string)reader["profileFirstImage"].ToString ())); } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": GetAvatarNotes exception {0}", e.Message); } return data; } #region User Preferences public bool GetUserPreferences(ref UserPreferences pref, ref string result) { string query = string.Empty; query += "SELECT imviaemail,visible,email FROM "; query += "usersettings WHERE "; query += "useruuid = ?Id"; OSDArray data = new OSDArray(); try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", pref.UserId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader()) { if(reader.HasRows) { reader.Read(); bool.TryParse((string)reader["imviaemail"], out pref.IMViaEmail); bool.TryParse((string)reader["visible"], out pref.Visible); pref.EMail = (string)reader["email"]; } else { dbcon.Close(); dbcon.Open(); query = "INSERT INTO usersettings VALUES "; query += "(?uuid,'false','false', ?Email)"; using (MySqlCommand put = new MySqlCommand(query, dbcon)) { put.Parameters.AddWithValue("?Email", pref.EMail); put.Parameters.AddWithValue("?uuid", pref.UserId.ToString()); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": Get preferences exception {0}", e.Message); result = e.Message; return false; } return true; } public bool UpdateUserPreferences(ref UserPreferences pref, ref string result) { string query = string.Empty; query += "UPDATE usersettings SET "; query += "imviaemail=?ImViaEmail, "; query += "visible=?Visible "; query += "WHERE useruuid=?uuid"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?ImViaEmail", pref.IMViaEmail.ToString().ToLower()); cmd.Parameters.AddWithValue("?Visible", pref.Visible.ToString().ToLower()); cmd.Parameters.AddWithValue("?uuid", pref.UserId.ToString()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": AgentInterestsUpdate exception {0}", e.Message); result = e.Message; return false; } return true; } #endregion User Preferences #region Integration public bool GetUserAppData(ref UserAppData props, ref string result) { string query = string.Empty; query += "SELECT * FROM `userdata` WHERE "; query += "UserId = ?Id AND "; query += "TagId = ?TagId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?Id", props.UserId.ToString()); cmd.Parameters.AddWithValue ("?TagId", props.TagId.ToString()); using (MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow)) { if(reader.HasRows) { reader.Read(); props.DataKey = (string)reader["DataKey"]; props.DataVal = (string)reader["DataVal"]; } else { query += "INSERT INTO userdata VALUES ( "; query += "?UserId,"; query += "?TagId,"; query += "?DataKey,"; query += "?DataVal) "; using (MySqlCommand put = new MySqlCommand(query, dbcon)) { put.Parameters.AddWithValue("?Id", props.UserId.ToString()); put.Parameters.AddWithValue("?TagId", props.TagId.ToString()); put.Parameters.AddWithValue("?DataKey", props.DataKey.ToString()); put.Parameters.AddWithValue("?DataVal", props.DataVal.ToString()); put.ExecuteNonQuery(); } } } } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": Requst application data exception {0}", e.Message); result = e.Message; return false; } return true; } public bool SetUserAppData(UserAppData props, ref string result) { string query = string.Empty; query += "UPDATE userdata SET "; query += "TagId = ?TagId, "; query += "DataKey = ?DataKey, "; query += "DataVal = ?DataVal WHERE "; query += "UserId = ?UserId AND "; query += "TagId = ?TagId"; try { using (MySqlConnection dbcon = new MySqlConnection(ConnectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand(query, dbcon)) { cmd.Parameters.AddWithValue("?UserId", props.UserId.ToString()); cmd.Parameters.AddWithValue("?TagId", props.TagId.ToString ()); cmd.Parameters.AddWithValue("?DataKey", props.DataKey.ToString ()); cmd.Parameters.AddWithValue("?DataVal", props.DataKey.ToString ()); cmd.ExecuteNonQuery(); } } } catch (Exception e) { m_log.DebugFormat("[PROFILES_DATA]" + ": SetUserData exception {0}", e.Message); return false; } return true; } #endregion Integration } }
namespace Factotum { partial class DucerModelEdit { /// <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(DucerModelEdit)); this.btnOK = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.errorProvider1 = new System.Windows.Forms.ErrorProvider(this.components); this.btnCancel = new System.Windows.Forms.Button(); this.ckActive = new System.Windows.Forms.CheckBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.txtSize = new Factotum.TextBoxWithUndo(); this.txtFrequency = new Factotum.TextBoxWithUndo(); this.txtName = new Factotum.TextBoxWithUndo(); ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).BeginInit(); this.SuspendLayout(); // // btnOK // this.btnOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOK.Location = new System.Drawing.Point(144, 117); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(64, 22); this.btnOK.TabIndex = 6; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(45, 15); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(67, 13); this.label1.TabIndex = 0; this.label1.Text = "Model Name"; // // errorProvider1 // this.errorProvider1.ContainerControl = this; // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.Location = new System.Drawing.Point(214, 117); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(64, 22); this.btnCancel.TabIndex = 7; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click); // // ckActive // this.ckActive.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.ckActive.AutoSize = true; this.ckActive.Location = new System.Drawing.Point(27, 117); this.ckActive.Name = "ckActive"; this.ckActive.Size = new System.Drawing.Size(56, 17); this.ckActive.TabIndex = 8; this.ckActive.TabStop = false; this.ckActive.Text = "Active"; this.ckActive.UseVisualStyleBackColor = true; this.ckActive.Click += new System.EventHandler(this.ckActive_Click); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(55, 41); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(57, 13); this.label2.TabIndex = 2; this.label2.Text = "Frequency"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(85, 67); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(27, 13); this.label3.TabIndex = 4; this.label3.Text = "Size"; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(189, 67); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(18, 13); this.label4.TabIndex = 13; this.label4.Text = "in."; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(189, 41); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(27, 13); this.label5.TabIndex = 12; this.label5.Text = "Mhz"; // // txtSize // this.txtSize.Location = new System.Drawing.Point(118, 64); this.txtSize.Name = "txtSize"; this.txtSize.Size = new System.Drawing.Size(56, 20); this.txtSize.TabIndex = 5; this.txtSize.TextChanged += new System.EventHandler(this.txtSize_TextChanged); this.txtSize.Validating += new System.ComponentModel.CancelEventHandler(this.txtSize_Validating); // // txtFrequency // this.txtFrequency.Location = new System.Drawing.Point(118, 38); this.txtFrequency.Name = "txtFrequency"; this.txtFrequency.Size = new System.Drawing.Size(56, 20); this.txtFrequency.TabIndex = 3; this.txtFrequency.TextChanged += new System.EventHandler(this.txtFrequency_TextChanged); this.txtFrequency.Validating += new System.ComponentModel.CancelEventHandler(this.txtFrequency_Validating); // // txtName // this.txtName.Location = new System.Drawing.Point(118, 12); this.txtName.Name = "txtName"; this.txtName.Size = new System.Drawing.Size(113, 20); this.txtName.TabIndex = 1; this.txtName.TextChanged += new System.EventHandler(this.txtName_TextChanged); this.txtName.Validating += new System.ComponentModel.CancelEventHandler(this.txtName_Validating); // // DucerModelEdit // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(290, 151); this.Controls.Add(this.label4); this.Controls.Add(this.label5); this.Controls.Add(this.txtSize); this.Controls.Add(this.label3); this.Controls.Add(this.txtFrequency); this.Controls.Add(this.label2); this.Controls.Add(this.txtName); this.Controls.Add(this.ckActive); this.Controls.Add(this.btnCancel); this.Controls.Add(this.label1); this.Controls.Add(this.btnOK); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(298, 185); this.Name = "DucerModelEdit"; this.Text = "Edit Transducer Model"; ((System.ComponentModel.ISupportInitialize)(this.errorProvider1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Label label1; private System.Windows.Forms.ErrorProvider errorProvider1; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.CheckBox ckActive; private TextBoxWithUndo txtName; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private TextBoxWithUndo txtSize; private System.Windows.Forms.Label label3; private TextBoxWithUndo txtFrequency; private System.Windows.Forms.Label label2; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Windows.Data; using BudgetAnalyser.Engine; using BudgetAnalyser.Annotations; using BudgetAnalyser.Engine.Budget; using BudgetAnalyser.Engine.Matching; using BudgetAnalyser.Engine.Services; using BudgetAnalyser.ShellDialog; using Rees.UserInteraction.Contracts; using Rees.Wpf; namespace BudgetAnalyser.Matching { [AutoRegisterWithIoC(SingleInstance = true)] public class NewRuleController : ControllerBase, IInitializableController, IShellDialogInteractivity, IShellDialogToolTips { private readonly IBudgetBucketRepository bucketRepo; private readonly ILogger logger; private readonly IUserMessageBox messageBoxService; private readonly ITransactionRuleService rulesService; private bool doNotUseAndChecked; private bool doNotUseOrChecked; private Guid shellDialogCorrelationId; public NewRuleController( [NotNull] UiContext uiContext, [NotNull] ITransactionRuleService rulesService, [NotNull] IBudgetBucketRepository bucketRepo) { if (uiContext == null) { throw new ArgumentNullException(nameof(uiContext)); } if (rulesService == null) { throw new ArgumentNullException(nameof(rulesService)); } if (bucketRepo == null) { throw new ArgumentNullException(nameof(bucketRepo)); } this.rulesService = rulesService; this.bucketRepo = bucketRepo; this.messageBoxService = uiContext.UserPrompts.MessageBox; this.logger = uiContext.Logger; MessengerInstance = uiContext.Messenger; MessengerInstance.Register<ShellDialogResponseMessage>(this, OnShellDialogResponseReceived); } public event EventHandler RuleCreated; public string ActionButtonToolTip => "Save the new rule."; public DecimalCriteria Amount { get; set; } public bool AndChecked { get { return this.doNotUseAndChecked; } set { this.doNotUseAndChecked = value; RaisePropertyChanged(); this.doNotUseOrChecked = !AndChecked; RaisePropertyChanged(() => OrChecked); } } public BudgetBucket Bucket { get; set; } public bool CanExecuteCancelButton => true; public bool CanExecuteOkButton => false; public bool CanExecuteSaveButton => Amount.Applicable || Description.Applicable || Reference1.Applicable || Reference2.Applicable || Reference3.Applicable || TransactionType.Applicable; public string CloseButtonToolTip => "Cancel"; public StringCriteria Description { get; set; } public MatchingRule NewRule { get; set; } public bool OrChecked { get { return this.doNotUseOrChecked; } [UsedImplicitly] set { this.doNotUseOrChecked = value; RaisePropertyChanged(); this.doNotUseAndChecked = !OrChecked; RaisePropertyChanged(() => AndChecked); } } public StringCriteria Reference1 { get; set; } public StringCriteria Reference2 { get; set; } public StringCriteria Reference3 { get; set; } public IEnumerable<SimilarMatchedRule> SimilarRules { get; private set; } public bool SimilarRulesExist { get; private set; } public string Title => "New Matching Rule for: " + Bucket; public StringCriteria TransactionType { get; set; } public void Initialize() { SimilarRules = null; AndChecked = true; NewRule = null; if (Description != null) { Description.PropertyChanged -= OnCriteriaValuePropertyChanged; } if (Reference1 != null) { Reference1.PropertyChanged -= OnCriteriaValuePropertyChanged; } if (Reference2 != null) { Reference2.PropertyChanged -= OnCriteriaValuePropertyChanged; } if (Reference3 != null) { Reference3.PropertyChanged -= OnCriteriaValuePropertyChanged; } if (Amount != null) { Amount.PropertyChanged -= OnCriteriaValuePropertyChanged; } if (TransactionType != null) { TransactionType.PropertyChanged -= OnCriteriaValuePropertyChanged; } Description = new StringCriteria { Applicable = true }; Description.PropertyChanged += OnCriteriaValuePropertyChanged; Reference1 = new StringCriteria(); Reference1.PropertyChanged += OnCriteriaValuePropertyChanged; Reference2 = new StringCriteria(); Reference2.PropertyChanged += OnCriteriaValuePropertyChanged; Reference3 = new StringCriteria(); Reference3.PropertyChanged += OnCriteriaValuePropertyChanged; Amount = new DecimalCriteria(); Amount.PropertyChanged += OnCriteriaValuePropertyChanged; TransactionType = new StringCriteria(); TransactionType.PropertyChanged += OnCriteriaValuePropertyChanged; } public void ShowDialog(IEnumerable<MatchingRule> allRules) { SimilarRules = allRules.Select(r => new SimilarMatchedRule(this.bucketRepo, r)).ToList(); UpdateSimilarRules(); this.shellDialogCorrelationId = Guid.NewGuid(); var dialogRequest = new ShellDialogRequestMessage(BudgetAnalyserFeature.Transactions, this, ShellDialogType.SaveCancel) { CorrelationId = this.shellDialogCorrelationId, Title = Title }; MessengerInstance.Send(dialogRequest); } private void OnCriteriaValuePropertyChanged(object sender, PropertyChangedEventArgs e) { RefreshSimilarRules(); } private void OnShellDialogResponseReceived(ShellDialogResponseMessage message) { if (!message.IsItForMe(this.shellDialogCorrelationId)) { return; } if (message.Response == ShellDialogButton.Cancel) { return; } if (Bucket == null) { this.messageBoxService.Show("Bucket cannot be null."); return; } NewRule = this.rulesService.CreateNewRule( Bucket.Code, Description.Applicable ? Description.Value : null, new[] { Reference1.Applicable ? Reference1.Value : null, Reference2.Applicable ? Reference2.Value : null, Reference3.Applicable ? Reference3.Value : null }, TransactionType.Applicable ? TransactionType.Value : null, Amount.Applicable ? Amount.Value : null, AndChecked); EventHandler handler = RuleCreated; handler?.Invoke(this, EventArgs.Empty); } private void RefreshSimilarRules() { ICollectionView view = CollectionViewSource.GetDefaultView(SimilarRules); view?.Refresh(); } [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Reviewed, acceptable here.")] private void UpdateSimilarRules() { if (SimilarRules == null) { return; } this.logger.LogInfo(l => l.Format("UpdateSimilarRules1: Rules.Count() = {0}", SimilarRules.Count())); ICollectionView view = CollectionViewSource.GetDefaultView(SimilarRules); view.Filter = item => this.rulesService.IsRuleSimilar((SimilarMatchedRule)item, Amount, Description, new[] { Reference1, Reference2, Reference3 }, TransactionType); view.SortDescriptions.Add(new SortDescription(nameof(SimilarMatchedRule.SortOrder), ListSortDirection.Descending)); SimilarRulesExist = !view.IsEmpty; RaisePropertyChanged(() => SimilarRulesExist); RaisePropertyChanged(() => SimilarRules); this.logger.LogInfo(l => l.Format("UpdateSimilarRules2: Rules.Count() = {0}", SimilarRules.Count())); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Utils; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class JuiceStreamPathTest { [TestCase(1e3, true, false)] // When the coordinates are large, the slope invariant fails within the specified absolute allowance due to the floating-number precision. [TestCase(1e9, false, false)] // Using discrete values sometimes discover more edge cases. [TestCase(10, true, true)] public void TestRandomInsertSetPosition(double scale, bool checkSlope, bool integralValues) { var rng = new Random(1); var path = new JuiceStreamPath(); for (int iteration = 0; iteration < 100000; iteration++) { if (rng.Next(10) == 0) path.Clear(); int vertexCount = path.Vertices.Count; switch (rng.Next(2)) { case 0: { double distance = rng.NextDouble() * scale * 2 - scale; if (integralValues) distance = Math.Round(distance); float oldX = path.PositionAtDistance(distance); int index = path.InsertVertex(distance); Assert.That(path.Vertices.Count, Is.EqualTo(vertexCount + 1)); Assert.That(path.Vertices[index].Distance, Is.EqualTo(distance)); Assert.That(path.Vertices[index].X, Is.EqualTo(oldX)); break; } case 1: { int index = rng.Next(path.Vertices.Count); double distance = path.Vertices[index].Distance; float newX = (float)(rng.NextDouble() * scale * 2 - scale); if (integralValues) newX = MathF.Round(newX); path.SetVertexPosition(index, newX); Assert.That(path.Vertices.Count, Is.EqualTo(vertexCount)); Assert.That(path.Vertices[index].Distance, Is.EqualTo(distance)); Assert.That(path.Vertices[index].X, Is.EqualTo(newX)); break; } } assertInvariants(path.Vertices, checkSlope); } } [Test] public void TestRemoveVertices() { var path = new JuiceStreamPath(); path.Add(10, 5); path.Add(20, -5); int removeCount = path.RemoveVertices((v, i) => v.Distance == 10 && i == 1); Assert.That(removeCount, Is.EqualTo(1)); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex(0, 0), new JuiceStreamPathVertex(20, -5) })); removeCount = path.RemoveVertices((_, i) => i == 0); Assert.That(removeCount, Is.EqualTo(1)); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex(20, -5) })); removeCount = path.RemoveVertices((_, i) => true); Assert.That(removeCount, Is.EqualTo(1)); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex() })); } [Test] public void TestResampleVertices() { var path = new JuiceStreamPath(); path.Add(-100, -10); path.Add(100, 50); path.ResampleVertices(new double[] { -50, 0, 70, 120 }); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex(-100, -10), new JuiceStreamPathVertex(-50, -5), new JuiceStreamPathVertex(0, 0), new JuiceStreamPathVertex(70, 35), new JuiceStreamPathVertex(100, 50), new JuiceStreamPathVertex(100, 50), })); path.Clear(); path.SetVertexPosition(0, 10); path.ResampleVertices(Array.Empty<double>()); Assert.That(path.Vertices, Is.EqualTo(new[] { new JuiceStreamPathVertex(0, 10) })); } [Test] public void TestRandomConvertFromSliderPath() { var rng = new Random(1); var path = new JuiceStreamPath(); var sliderPath = new SliderPath(); for (int iteration = 0; iteration < 10000; iteration++) { sliderPath.ControlPoints.Clear(); do { int start = sliderPath.ControlPoints.Count; do { float x = (float)(rng.NextDouble() * 1e3); float y = (float)(rng.NextDouble() * 1e3); sliderPath.ControlPoints.Add(new PathControlPoint(new Vector2(x, y))); } while (rng.Next(2) != 0); int length = sliderPath.ControlPoints.Count - start + 1; sliderPath.ControlPoints[start].Type.Value = length <= 2 ? PathType.Linear : length == 3 ? PathType.PerfectCurve : PathType.Bezier; } while (rng.Next(3) != 0); if (rng.Next(5) == 0) sliderPath.ExpectedDistance.Value = rng.NextDouble() * 3e3; else sliderPath.ExpectedDistance.Value = null; path.ConvertFromSliderPath(sliderPath); Assert.That(path.Vertices[0].Distance, Is.EqualTo(0)); Assert.That(path.Distance, Is.EqualTo(sliderPath.Distance).Within(1e-3)); assertInvariants(path.Vertices, true); double[] sampleDistances = Enumerable.Range(0, 10) .Select(_ => rng.NextDouble() * sliderPath.Distance) .ToArray(); foreach (double distance in sampleDistances) { float expected = sliderPath.PositionAt(distance / sliderPath.Distance).X; Assert.That(path.PositionAtDistance(distance), Is.EqualTo(expected).Within(1e-3)); } path.ResampleVertices(sampleDistances); assertInvariants(path.Vertices, true); foreach (double distance in sampleDistances) { float expected = sliderPath.PositionAt(distance / sliderPath.Distance).X; Assert.That(path.PositionAtDistance(distance), Is.EqualTo(expected).Within(1e-3)); } } } [Test] public void TestRandomConvertToSliderPath() { var rng = new Random(1); var path = new JuiceStreamPath(); var sliderPath = new SliderPath(); for (int iteration = 0; iteration < 10000; iteration++) { path.Clear(); do { double distance = rng.NextDouble() * 1e3; float x = (float)(rng.NextDouble() * 1e3); path.Add(distance, x); } while (rng.Next(5) != 0); float sliderStartY = (float)(rng.NextDouble() * JuiceStreamPath.OSU_PLAYFIELD_HEIGHT); path.ConvertToSliderPath(sliderPath, sliderStartY); Assert.That(sliderPath.Distance, Is.EqualTo(path.Distance).Within(1e-3)); Assert.That(sliderPath.ControlPoints[0].Position.Value.X, Is.EqualTo(path.Vertices[0].X)); assertInvariants(path.Vertices, true); foreach (var point in sliderPath.ControlPoints) { Assert.That(point.Type.Value, Is.EqualTo(PathType.Linear).Or.Null); Assert.That(sliderStartY + point.Position.Value.Y, Is.InRange(0, JuiceStreamPath.OSU_PLAYFIELD_HEIGHT)); } for (int i = 0; i < 10; i++) { double distance = rng.NextDouble() * path.Distance; float expected = path.PositionAtDistance(distance); Assert.That(sliderPath.PositionAt(distance / sliderPath.Distance).X, Is.EqualTo(expected).Within(1e-3)); } } } [Test] public void TestInvalidation() { var path = new JuiceStreamPath(); Assert.That(path.InvalidationID, Is.EqualTo(1)); int previousId = path.InvalidationID; path.InsertVertex(10); checkNewId(); path.SetVertexPosition(1, 5); checkNewId(); path.Add(20, 0); checkNewId(); path.RemoveVertices((v, _) => v.Distance == 20); checkNewId(); path.ResampleVertices(new double[] { 5, 10, 15 }); checkNewId(); path.Clear(); checkNewId(); path.ConvertFromSliderPath(new SliderPath()); checkNewId(); void checkNewId() { Assert.That(path.InvalidationID, Is.Not.EqualTo(previousId)); previousId = path.InvalidationID; } } private void assertInvariants(IReadOnlyList<JuiceStreamPathVertex> vertices, bool checkSlope) { Assert.That(vertices, Is.Not.Empty); for (int i = 0; i < vertices.Count; i++) { Assert.That(double.IsFinite(vertices[i].Distance)); Assert.That(float.IsFinite(vertices[i].X)); } for (int i = 1; i < vertices.Count; i++) { Assert.That(vertices[i].Distance, Is.GreaterThanOrEqualTo(vertices[i - 1].Distance)); if (!checkSlope) continue; float xDiff = Math.Abs(vertices[i].X - vertices[i - 1].X); double distanceDiff = vertices[i].Distance - vertices[i - 1].Distance; Assert.That(xDiff, Is.LessThanOrEqualTo(distanceDiff).Within(Precision.FLOAT_EPSILON)); } } } }
using UnityEngine; //Just modified from unity's build-in Image Effect Glow. [ExecuteInEditMode] [RequireComponent (typeof(Camera))] public class XftGlow : MonoBehaviour { /// The brightness of the glow. Values larger than one give extra "boost". public float glowIntensity = 1.5f; /// Blur iterations - larger number means more blur. public int blurIterations = 3; /// Blur spread for each iteration. Lower values /// give better looking blur, but require more iterations to /// get large blurs. Value is usually between 0.5 and 1.0. public float blurSpread = 0.7f; /// Tint glow with this color. Alpha adds additional glow everywhere. public Color glowTint = new Color(1,1,1,1); protected XftEventComponent m_client = null; // -------------------------------------------------------- // The final composition shader: // adds (glow color * glow alpha * amount) to the original image. // In the combiner glow amount can be only in 0..1 range; we apply extra // amount during the blurring phase. public Shader compositeShader; Material m_CompositeMaterial = null; protected Material compositeMaterial { get { if (m_CompositeMaterial == null) { m_CompositeMaterial = new Material(compositeShader); m_CompositeMaterial.hideFlags = HideFlags.HideAndDontSave; } return m_CompositeMaterial; } } // -------------------------------------------------------- // The blur iteration shader. // Basically it just takes 4 texture samples and averages them. // By applying it repeatedly and spreading out sample locations // we get a Gaussian blur approximation. // The alpha value in _Color would normally be 0.25 (to average 4 samples), // however if we have glow amount larger than 1 then we increase this. public Shader blurShader; Material m_BlurMaterial = null; protected Material blurMaterial { get { if (m_BlurMaterial == null) { m_BlurMaterial = new Material(blurShader); m_BlurMaterial.hideFlags = HideFlags.HideAndDontSave; } return m_BlurMaterial; } } // -------------------------------------------------------- // The image downsample shaders for each brightness mode. // It is in external assets as it's quite complex and uses Cg. public Shader downsampleShader; Material m_DownsampleMaterial = null; protected Material downsampleMaterial { get { if (m_DownsampleMaterial == null) { m_DownsampleMaterial = new Material( downsampleShader ); m_DownsampleMaterial.hideFlags = HideFlags.HideAndDontSave; } return m_DownsampleMaterial; } } // -------------------------------------------------------- // finally, the actual code /*protected void OnDisable() { if( m_CompositeMaterial ) { DestroyImmediate( m_CompositeMaterial ); } if( m_BlurMaterial ) { DestroyImmediate( m_BlurMaterial ); } if( m_DownsampleMaterial ) DestroyImmediate( m_DownsampleMaterial ); }*/ void Awake() { this.enabled = false; } public void Init(XftEventComponent client) { m_client = client; if (m_DownsampleMaterial == null) { downsampleShader = client.GlowDownSampleShader; m_DownsampleMaterial = new Material( downsampleShader ); m_DownsampleMaterial.hideFlags = HideFlags.HideAndDontSave; } if (m_CompositeMaterial == null) { compositeShader = client.GlowCompositeShader; m_CompositeMaterial = new Material(compositeShader); m_CompositeMaterial.hideFlags = HideFlags.HideAndDontSave; } if (m_BlurMaterial == null) { blurShader = client.GlowBlurShader; m_BlurMaterial = new Material(blurShader); m_BlurMaterial.hideFlags = HideFlags.HideAndDontSave; } SetClientParam(); } void SetClientParam() { glowIntensity = m_client.GlowIntensity; blurIterations = m_client.GlowBlurIterations; blurSpread = m_client.GlowBlurSpread; glowTint = m_client.GlowColorStart; } public bool CheckSupport() { bool ret = true; if (!SystemInfo.supportsImageEffects) { ret = false; } // Disable the effect if no downsample shader is setup if( downsampleShader == null ) { Debug.Log ("No downsample shader assigned! Disabling glow."); ret = false; } // Disable if any of the shaders can't run on the users graphics card else { if( !blurMaterial.shader.isSupported ) ret = false; if( !compositeMaterial.shader.isSupported ) ret = false; if( !downsampleMaterial.shader.isSupported ) ret = false; } return ret; } // Performs one blur iteration. public void FourTapCone (RenderTexture source, RenderTexture dest, int iteration) { float off = 0.5f + iteration*blurSpread; Graphics.BlitMultiTap (source, dest, blurMaterial, new Vector2( off, off), new Vector2(-off, off), new Vector2( off,-off), new Vector2(-off,-off) ); } // Downsamples the texture to a quarter resolution. private void DownSample4x (RenderTexture source, RenderTexture dest) { downsampleMaterial.color = new Color( glowTint.r, glowTint.g, glowTint.b, glowTint.a/4.0f ); Graphics.Blit (source, dest, downsampleMaterial); } // Called by the camera to apply the image effect void OnRenderImage (RenderTexture source, RenderTexture destination) { // Clamp parameters to sane values glowIntensity = Mathf.Clamp( glowIntensity, 0.0f, 10.0f ); blurIterations = Mathf.Clamp( blurIterations, 0, 30 ); blurSpread = Mathf.Clamp( blurSpread, 0.5f, 1.0f ); RenderTexture buffer = RenderTexture.GetTemporary(source.width/4, source.height/4, 0); RenderTexture buffer2 = RenderTexture.GetTemporary(source.width/4, source.height/4, 0); // Copy source to the 4x4 smaller texture. DownSample4x (source, buffer); // Blur the small texture float extraBlurBoost = Mathf.Clamp01( (glowIntensity - 1.0f) / 4.0f ); blurMaterial.color = new Color( 1F, 1F, 1F, 0.25f + extraBlurBoost ); bool oddEven = true; for(int i = 0; i < blurIterations; i++) { if( oddEven ) FourTapCone (buffer, buffer2, i); else FourTapCone (buffer2, buffer, i); oddEven = !oddEven; } Graphics.Blit(source,destination); if( oddEven ) BlitGlow(buffer, destination); else BlitGlow(buffer2, destination); RenderTexture.ReleaseTemporary(buffer); RenderTexture.ReleaseTemporary(buffer2); } public void BlitGlow( RenderTexture source, RenderTexture dest ) { compositeMaterial.color = new Color(1F, 1F, 1F, Mathf.Clamp01(glowIntensity)); Graphics.Blit (source, dest, compositeMaterial); } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Patterns.Logging; namespace SocketHttpListener.Net { // FIXME: Does this buffer the response until Close? // Update: we send a single packet for the first non-chunked Write // What happens when we set content-length to X and write X-1 bytes then close? // what if we don't set content-length at all? class ResponseStream : Stream { HttpListenerResponse response; bool ignore_errors; bool disposed; bool trailer_sent; Stream stream; private readonly ILogger _logger; private readonly string _connectionId; internal ResponseStream(Stream stream, HttpListenerResponse response, bool ignore_errors, ILogger logger, string connectionId) { this.response = response; this.ignore_errors = ignore_errors; _logger = logger; _connectionId = connectionId; this.stream = stream; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return true; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override void Close() { if (disposed == false) { disposed = true; byte[] bytes = null; MemoryStream ms = GetHeaders(true); bool chunked = response.SendChunked; if (ms != null) { long start = ms.Position; if (chunked && !trailer_sent) { bytes = GetChunkSizeBytes(0, true); ms.Position = ms.Length; ms.Write(bytes, 0, bytes.Length); } InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start)); trailer_sent = true; } else if (chunked && !trailer_sent) { bytes = GetChunkSizeBytes(0, true); InternalWrite(bytes, 0, bytes.Length); trailer_sent = true; } response.Close(); } } MemoryStream GetHeaders(bool closing) { if (response.HeadersSent) return null; // SendHeaders works on shared headers lock (response.headers_lock) { if (response.HeadersSent) return null; MemoryStream ms = new MemoryStream(); response.SendHeaders(closing, ms); return ms; } } public override void Flush() { } static byte[] crlf = new byte[] { 13, 10 }; static byte[] GetChunkSizeBytes(int size, bool final) { string str = String.Format("{0:x}\r\n{1}", size, final ? "\r\n" : ""); return Encoding.ASCII.GetBytes(str); } internal void InternalWrite(byte[] buffer, int offset, int count) { if (ignore_errors) { try { stream.Write(buffer, offset, count); } catch { } } else { stream.Write(buffer, offset, count); } } public override void Write(byte[] buffer, int offset, int count) { if (disposed) throw new ObjectDisposedException(GetType().ToString()); byte[] bytes = null; MemoryStream ms = GetHeaders(false); bool chunked = response.SendChunked; if (ms != null) { long start = ms.Position; // After the possible preamble for the encoding ms.Position = ms.Length; if (chunked) { bytes = GetChunkSizeBytes(count, false); ms.Write(bytes, 0, bytes.Length); } int new_count = Math.Min(count, 16384 - (int)ms.Position + (int)start); ms.Write(buffer, offset, new_count); count -= new_count; offset += new_count; InternalWrite(ms.GetBuffer(), (int)start, (int)(ms.Length - start)); ms.SetLength(0); ms.Capacity = 0; // 'dispose' the buffer in ms. } else if (chunked) { bytes = GetChunkSizeBytes(count, false); InternalWrite(bytes, 0, bytes.Length); } if (count > 0) InternalWrite(buffer, offset, count); if (chunked) InternalWrite(crlf, 0, 2); } internal async Task InternalWriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (ignore_errors) { try { await stream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); } catch { } } else { await stream.WriteAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false); } } //public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) //{ // if (disposed) // throw new ObjectDisposedException(GetType().ToString()); // byte[] bytes = null; // MemoryStream ms = GetHeaders(false); // bool chunked = response.SendChunked; // if (ms != null) // { // long start = ms.Position; // After the possible preamble for the encoding // ms.Position = ms.Length; // if (chunked) // { // bytes = GetChunkSizeBytes(count, false); // await ms.WriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false); // } // int new_count = Math.Min(count, 16384 - (int)ms.Position + (int)start); // await ms.WriteAsync(buffer, offset, new_count, cancellationToken).ConfigureAwait(false); // count -= new_count; // offset += new_count; // await InternalWriteAsync(ms.GetBuffer(), (int)start, (int)(ms.Length - start), cancellationToken).ConfigureAwait(false); // ms.SetLength(0); // ms.Capacity = 0; // 'dispose' the buffer in ms. // } // else if (chunked) // { // bytes = GetChunkSizeBytes(count, false); // await InternalWriteAsync(bytes, 0, bytes.Length, cancellationToken).ConfigureAwait(false); // } // if (count > 0) // await InternalWriteAsync(buffer, offset, count, cancellationToken); // if (chunked) // await InternalWriteAsync(crlf, 0, 2, cancellationToken).ConfigureAwait(false); //} public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback cback, object state) { if (disposed) throw new ObjectDisposedException(GetType().ToString()); byte[] bytes = null; MemoryStream ms = GetHeaders(false); bool chunked = response.SendChunked; if (ms != null) { long start = ms.Position; ms.Position = ms.Length; if (chunked) { bytes = GetChunkSizeBytes(count, false); ms.Write(bytes, 0, bytes.Length); } ms.Write(buffer, offset, count); buffer = ms.GetBuffer(); offset = (int)start; count = (int)(ms.Position - start); } else if (chunked) { bytes = GetChunkSizeBytes(count, false); InternalWrite(bytes, 0, bytes.Length); } return stream.BeginWrite(buffer, offset, count, cback, state); } public override void EndWrite(IAsyncResult ares) { if (disposed) throw new ObjectDisposedException(GetType().ToString()); if (ignore_errors) { try { stream.EndWrite(ares); if (response.SendChunked) stream.Write(crlf, 0, 2); } catch { } } else { stream.EndWrite(ares); if (response.SendChunked) stream.Write(crlf, 0, 2); } } public override int Read([In, Out] byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback cback, object state) { throw new NotSupportedException(); } public override int EndRead(IAsyncResult ares) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Engine\Classes\Engine\EngineTypes.h:1175 namespace UnrealEngine { public partial class FRigidBodyErrorCorrection : NativeStructWrapper { public FRigidBodyErrorCorrection(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef) { } public FRigidBodyErrorCorrection() : base(E_CreateStruct_FRigidBodyErrorCorrection(), false) { } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_AngleLerp_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_AngleLerp_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_AngularVelocityCoefficient_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_AngularVelocityCoefficient_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationDistanceSq_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationDistanceSq_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationSeconds_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationSeconds_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationSimilarity_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationSimilarity_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_ErrorPerAngularDifference_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_ErrorPerAngularDifference_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_ErrorPerLinearDifference_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_ErrorPerLinearDifference_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_LinearVelocityCoefficient_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_LinearVelocityCoefficient_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_MaxLinearHardSnapDistance_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_MaxLinearHardSnapDistance_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_MaxRestoredStateError_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_MaxRestoredStateError_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_PingExtrapolation_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_PingExtrapolation_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_PingLimit_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_PingLimit_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FRigidBodyErrorCorrection_PositionLerp_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FRigidBodyErrorCorrection_PositionLerp_SET(IntPtr Ptr, float Value); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FRigidBodyErrorCorrection(); #endregion #region Property /// <summary> /// How much to directly lerp to the correct angle. /// </summary> public float AngleLerp { get => E_PROP_FRigidBodyErrorCorrection_AngleLerp_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_AngleLerp_SET(NativePointer, value); } /// <summary> /// This is the angular analog to LinearVelocityCoefficient. /// </summary> public float AngularVelocityCoefficient { get => E_PROP_FRigidBodyErrorCorrection_AngularVelocityCoefficient_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_AngularVelocityCoefficient_SET(NativePointer, value); } /// <summary> /// If the body has moved less than the square root of /// <para>this amount towards a resolved state in the previous </para> /// frame, then error may accumulate towards a hard snap. /// </summary> public float ErrorAccumulationDistanceSq { get => E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationDistanceSq_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationDistanceSq_SET(NativePointer, value); } /// <summary> /// Number of seconds to remain in a heuristically /// <para>unresolveable state before hard snapping. </para> /// </summary> public float ErrorAccumulationSeconds { get => E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationSeconds_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationSeconds_SET(NativePointer, value); } /// <summary> /// If the previous error projected onto the current error /// <para>is greater than this value (indicating "similarity" </para> /// between states), then error may accumulate towards a /// <para>hard snap. </para> /// </summary> public float ErrorAccumulationSimilarity { get => E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationSimilarity_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_ErrorAccumulationSimilarity_SET(NativePointer, value); } /// <summary> /// Error per degree /// </summary> public float ErrorPerAngularDifference { get => E_PROP_FRigidBodyErrorCorrection_ErrorPerAngularDifference_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_ErrorPerAngularDifference_SET(NativePointer, value); } /// <summary> /// Error per centimeter /// </summary> public float ErrorPerLinearDifference { get => E_PROP_FRigidBodyErrorCorrection_ErrorPerLinearDifference_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_ErrorPerLinearDifference_SET(NativePointer, value); } /// <summary> /// This is the coefficient `k` in the differential equation: /// <para>dx/dt = k ( x_target(t) - x(t) ), which is used to update </para> /// the velocity in a replication step. /// </summary> public float LinearVelocityCoefficient { get => E_PROP_FRigidBodyErrorCorrection_LinearVelocityCoefficient_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_LinearVelocityCoefficient_SET(NativePointer, value); } public float MaxLinearHardSnapDistance { get => E_PROP_FRigidBodyErrorCorrection_MaxLinearHardSnapDistance_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_MaxLinearHardSnapDistance_SET(NativePointer, value); } /// <summary> /// Maximum allowable error for a state to be considered "resolved" /// </summary> public float MaxRestoredStateError { get => E_PROP_FRigidBodyErrorCorrection_MaxRestoredStateError_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_MaxRestoredStateError_SET(NativePointer, value); } /// <summary> /// Value between 0 and 1 which indicates how much velocity /// <para>and ping based correction to use </para> /// </summary> public float PingExtrapolation { get => E_PROP_FRigidBodyErrorCorrection_PingExtrapolation_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_PingExtrapolation_SET(NativePointer, value); } /// <summary> /// For the purpose of extrapolation, ping will be clamped to this value /// </summary> public float PingLimit { get => E_PROP_FRigidBodyErrorCorrection_PingLimit_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_PingLimit_SET(NativePointer, value); } /// <summary> /// How much to directly lerp to the correct position. Generally /// <para>this should be very low, if not zero. A higher value will </para> /// increase precision along with jerkiness. /// </summary> public float PositionLerp { get => E_PROP_FRigidBodyErrorCorrection_PositionLerp_GET(NativePointer); set => E_PROP_FRigidBodyErrorCorrection_PositionLerp_SET(NativePointer, value); } #endregion public static implicit operator IntPtr(FRigidBodyErrorCorrection self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator FRigidBodyErrorCorrection(IntPtr adress) { return adress == IntPtr.Zero ? null : new FRigidBodyErrorCorrection(adress, false); } } }
// 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// An Azure Batch job. /// </summary> public partial class CloudJob : ITransportObjectProvider<Models.JobAddParameter>, IInheritedBehaviors, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<IList<EnvironmentSetting>> CommonEnvironmentSettingsProperty; public readonly PropertyAccessor<JobConstraints> ConstraintsProperty; public readonly PropertyAccessor<DateTime?> CreationTimeProperty; public readonly PropertyAccessor<string> DisplayNameProperty; public readonly PropertyAccessor<string> ETagProperty; public readonly PropertyAccessor<JobExecutionInformation> ExecutionInformationProperty; public readonly PropertyAccessor<string> IdProperty; public readonly PropertyAccessor<JobManagerTask> JobManagerTaskProperty; public readonly PropertyAccessor<JobPreparationTask> JobPreparationTaskProperty; public readonly PropertyAccessor<JobReleaseTask> JobReleaseTaskProperty; public readonly PropertyAccessor<DateTime?> LastModifiedProperty; public readonly PropertyAccessor<IList<MetadataItem>> MetadataProperty; public readonly PropertyAccessor<Common.OnAllTasksComplete?> OnAllTasksCompleteProperty; public readonly PropertyAccessor<Common.OnTaskFailure?> OnTaskFailureProperty; public readonly PropertyAccessor<PoolInformation> PoolInformationProperty; public readonly PropertyAccessor<Common.JobState?> PreviousStateProperty; public readonly PropertyAccessor<DateTime?> PreviousStateTransitionTimeProperty; public readonly PropertyAccessor<int?> PriorityProperty; public readonly PropertyAccessor<Common.JobState?> StateProperty; public readonly PropertyAccessor<DateTime?> StateTransitionTimeProperty; public readonly PropertyAccessor<JobStatistics> StatisticsProperty; public readonly PropertyAccessor<string> UrlProperty; public readonly PropertyAccessor<bool?> UsesTaskDependenciesProperty; public PropertyContainer() : base(BindingState.Unbound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>("CommonEnvironmentSettings", BindingAccess.Read | BindingAccess.Write); this.ConstraintsProperty = this.CreatePropertyAccessor<JobConstraints>("Constraints", BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor<DateTime?>("CreationTime", BindingAccess.None); this.DisplayNameProperty = this.CreatePropertyAccessor<string>("DisplayName", BindingAccess.Read | BindingAccess.Write); this.ETagProperty = this.CreatePropertyAccessor<string>("ETag", BindingAccess.None); this.ExecutionInformationProperty = this.CreatePropertyAccessor<JobExecutionInformation>("ExecutionInformation", BindingAccess.None); this.IdProperty = this.CreatePropertyAccessor<string>("Id", BindingAccess.Read | BindingAccess.Write); this.JobManagerTaskProperty = this.CreatePropertyAccessor<JobManagerTask>("JobManagerTask", BindingAccess.Read | BindingAccess.Write); this.JobPreparationTaskProperty = this.CreatePropertyAccessor<JobPreparationTask>("JobPreparationTask", BindingAccess.Read | BindingAccess.Write); this.JobReleaseTaskProperty = this.CreatePropertyAccessor<JobReleaseTask>("JobReleaseTask", BindingAccess.Read | BindingAccess.Write); this.LastModifiedProperty = this.CreatePropertyAccessor<DateTime?>("LastModified", BindingAccess.None); this.MetadataProperty = this.CreatePropertyAccessor<IList<MetadataItem>>("Metadata", BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor<Common.OnAllTasksComplete?>("OnAllTasksComplete", BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor<Common.OnTaskFailure?>("OnTaskFailure", BindingAccess.Read | BindingAccess.Write); this.PoolInformationProperty = this.CreatePropertyAccessor<PoolInformation>("PoolInformation", BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor<Common.JobState?>("PreviousState", BindingAccess.None); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("PreviousStateTransitionTime", BindingAccess.None); this.PriorityProperty = this.CreatePropertyAccessor<int?>("Priority", BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor<Common.JobState?>("State", BindingAccess.None); this.StateTransitionTimeProperty = this.CreatePropertyAccessor<DateTime?>("StateTransitionTime", BindingAccess.None); this.StatisticsProperty = this.CreatePropertyAccessor<JobStatistics>("Statistics", BindingAccess.None); this.UrlProperty = this.CreatePropertyAccessor<string>("Url", BindingAccess.None); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor<bool?>("UsesTaskDependencies", BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.CloudJob protocolObject) : base(BindingState.Bound) { this.CommonEnvironmentSettingsProperty = this.CreatePropertyAccessor( EnvironmentSetting.ConvertFromProtocolCollectionAndFreeze(protocolObject.CommonEnvironmentSettings), "CommonEnvironmentSettings", BindingAccess.Read); this.ConstraintsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Constraints, o => new JobConstraints(o)), "Constraints", BindingAccess.Read | BindingAccess.Write); this.CreationTimeProperty = this.CreatePropertyAccessor( protocolObject.CreationTime, "CreationTime", BindingAccess.Read); this.DisplayNameProperty = this.CreatePropertyAccessor( protocolObject.DisplayName, "DisplayName", BindingAccess.Read); this.ETagProperty = this.CreatePropertyAccessor( protocolObject.ETag, "ETag", BindingAccess.Read); this.ExecutionInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ExecutionInfo, o => new JobExecutionInformation(o).Freeze()), "ExecutionInformation", BindingAccess.Read); this.IdProperty = this.CreatePropertyAccessor( protocolObject.Id, "Id", BindingAccess.Read); this.JobManagerTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobManagerTask, o => new JobManagerTask(o).Freeze()), "JobManagerTask", BindingAccess.Read); this.JobPreparationTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobPreparationTask, o => new JobPreparationTask(o).Freeze()), "JobPreparationTask", BindingAccess.Read); this.JobReleaseTaskProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.JobReleaseTask, o => new JobReleaseTask(o).Freeze()), "JobReleaseTask", BindingAccess.Read); this.LastModifiedProperty = this.CreatePropertyAccessor( protocolObject.LastModified, "LastModified", BindingAccess.Read); this.MetadataProperty = this.CreatePropertyAccessor( MetadataItem.ConvertFromProtocolCollection(protocolObject.Metadata), "Metadata", BindingAccess.Read | BindingAccess.Write); this.OnAllTasksCompleteProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnAllTasksComplete, Common.OnAllTasksComplete>(protocolObject.OnAllTasksComplete), "OnAllTasksComplete", BindingAccess.Read | BindingAccess.Write); this.OnTaskFailureProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.OnTaskFailure, Common.OnTaskFailure>(protocolObject.OnTaskFailure), "OnTaskFailure", BindingAccess.Read); this.PoolInformationProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.PoolInfo, o => new PoolInformation(o)), "PoolInformation", BindingAccess.Read | BindingAccess.Write); this.PreviousStateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.PreviousState), "PreviousState", BindingAccess.Read); this.PreviousStateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.PreviousStateTransitionTime, "PreviousStateTransitionTime", BindingAccess.Read); this.PriorityProperty = this.CreatePropertyAccessor( protocolObject.Priority, "Priority", BindingAccess.Read | BindingAccess.Write); this.StateProperty = this.CreatePropertyAccessor( UtilitiesInternal.MapNullableEnum<Models.JobState, Common.JobState>(protocolObject.State), "State", BindingAccess.Read); this.StateTransitionTimeProperty = this.CreatePropertyAccessor( protocolObject.StateTransitionTime, "StateTransitionTime", BindingAccess.Read); this.StatisticsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.Stats, o => new JobStatistics(o).Freeze()), "Statistics", BindingAccess.Read); this.UrlProperty = this.CreatePropertyAccessor( protocolObject.Url, "Url", BindingAccess.Read); this.UsesTaskDependenciesProperty = this.CreatePropertyAccessor( protocolObject.UsesTaskDependencies, "UsesTaskDependencies", BindingAccess.Read); } } private PropertyContainer propertyContainer; private readonly BatchClient parentBatchClient; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CloudJob"/> class. /// </summary> /// <param name='parentBatchClient'>The parent <see cref="BatchClient"/> to use.</param> /// <param name='baseBehaviors'>The base behaviors to use.</param> internal CloudJob( BatchClient parentBatchClient, IEnumerable<BatchClientBehavior> baseBehaviors) { this.propertyContainer = new PropertyContainer(); this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); } internal CloudJob( BatchClient parentBatchClient, Models.CloudJob protocolObject, IEnumerable<BatchClientBehavior> baseBehaviors) { this.parentBatchClient = parentBatchClient; InheritUtil.InheritClientBehaviorsAndSetPublicProperty(this, baseBehaviors); this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region IInheritedBehaviors /// <summary> /// Gets or sets a list of behaviors that modify or customize requests to the Batch service /// made via this <see cref="CloudJob"/>. /// </summary> /// <remarks> /// <para>These behaviors are inherited by child objects.</para> /// <para>Modifications are applied in the order of the collection. The last write wins.</para> /// </remarks> public IList<BatchClientBehavior> CustomBehaviors { get; set; } #endregion IInheritedBehaviors #region CloudJob /// <summary> /// Gets or sets a list of common environment variable settings. These environment variables are set for all tasks /// in this <see cref="CloudJob"/> (including the Job Manager, Job Preparation and Job Release tasks). /// </summary> public IList<EnvironmentSetting> CommonEnvironmentSettings { get { return this.propertyContainer.CommonEnvironmentSettingsProperty.Value; } set { this.propertyContainer.CommonEnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the execution constraints for the job. /// </summary> public JobConstraints Constraints { get { return this.propertyContainer.ConstraintsProperty.Value; } set { this.propertyContainer.ConstraintsProperty.Value = value; } } /// <summary> /// Gets the creation time of the job. /// </summary> public DateTime? CreationTime { get { return this.propertyContainer.CreationTimeProperty.Value; } } /// <summary> /// Gets or sets the display name of the job. /// </summary> public string DisplayName { get { return this.propertyContainer.DisplayNameProperty.Value; } set { this.propertyContainer.DisplayNameProperty.Value = value; } } /// <summary> /// Gets the ETag for the job. /// </summary> public string ETag { get { return this.propertyContainer.ETagProperty.Value; } } /// <summary> /// Gets the execution information for the job. /// </summary> public JobExecutionInformation ExecutionInformation { get { return this.propertyContainer.ExecutionInformationProperty.Value; } } /// <summary> /// Gets or sets the id of the job. /// </summary> public string Id { get { return this.propertyContainer.IdProperty.Value; } set { this.propertyContainer.IdProperty.Value = value; } } /// <summary> /// Gets or sets the Job Manager task. The Job Manager task is launched when the <see cref="CloudJob"/> is started. /// </summary> public JobManagerTask JobManagerTask { get { return this.propertyContainer.JobManagerTaskProperty.Value; } set { this.propertyContainer.JobManagerTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Preparation task. The Batch service will run the Job Preparation task on a compute node /// before starting any tasks of that job on that compute node. /// </summary> public JobPreparationTask JobPreparationTask { get { return this.propertyContainer.JobPreparationTaskProperty.Value; } set { this.propertyContainer.JobPreparationTaskProperty.Value = value; } } /// <summary> /// Gets or sets the Job Release task. The Batch service runs the Job Release task when the job ends, on each compute /// node where any task of the job has run. /// </summary> public JobReleaseTask JobReleaseTask { get { return this.propertyContainer.JobReleaseTaskProperty.Value; } set { this.propertyContainer.JobReleaseTaskProperty.Value = value; } } /// <summary> /// Gets the last modified time of the job. /// </summary> public DateTime? LastModified { get { return this.propertyContainer.LastModifiedProperty.Value; } } /// <summary> /// Gets or sets a list of name-value pairs associated with the job as metadata. /// </summary> public IList<MetadataItem> Metadata { get { return this.propertyContainer.MetadataProperty.Value; } set { this.propertyContainer.MetadataProperty.Value = ConcurrentChangeTrackedModifiableList<MetadataItem>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the action the Batch service should take when all tasks in the job are in the <see cref="Common.JobState.Completed"/> /// state. /// </summary> public Common.OnAllTasksComplete? OnAllTasksComplete { get { return this.propertyContainer.OnAllTasksCompleteProperty.Value; } set { this.propertyContainer.OnAllTasksCompleteProperty.Value = value; } } /// <summary> /// Gets or sets the action the Batch service should take when any task in the job fails. /// </summary> public Common.OnTaskFailure? OnTaskFailure { get { return this.propertyContainer.OnTaskFailureProperty.Value; } set { this.propertyContainer.OnTaskFailureProperty.Value = value; } } /// <summary> /// Gets or sets the pool on which the Batch service runs the job's tasks. /// </summary> public PoolInformation PoolInformation { get { return this.propertyContainer.PoolInformationProperty.Value; } set { this.propertyContainer.PoolInformationProperty.Value = value; } } /// <summary> /// Gets the previous state of the job. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousState property is not defined. /// </remarks> public Common.JobState? PreviousState { get { return this.propertyContainer.PreviousStateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its previous state. /// </summary> /// <remarks> /// If the job is in its initial <see cref="Common.JobState.Active"/> state, the PreviousStateTransitionTime property /// is not defined. /// </remarks> public DateTime? PreviousStateTransitionTime { get { return this.propertyContainer.PreviousStateTransitionTimeProperty.Value; } } /// <summary> /// Gets or sets the priority of the job. Priority values can range from -1000 to 1000, with -1000 being the lowest /// priority and 1000 being the highest priority. /// </summary> /// <remarks> /// The default value is 0. /// </remarks> public int? Priority { get { return this.propertyContainer.PriorityProperty.Value; } set { this.propertyContainer.PriorityProperty.Value = value; } } /// <summary> /// Gets the current state of the job. /// </summary> public Common.JobState? State { get { return this.propertyContainer.StateProperty.Value; } } /// <summary> /// Gets the time at which the job entered its current state. /// </summary> public DateTime? StateTransitionTime { get { return this.propertyContainer.StateTransitionTimeProperty.Value; } } /// <summary> /// Gets resource usage statistics for the entire lifetime of the job. /// </summary> /// <remarks> /// This property is populated only if the <see cref="CloudJob"/> was retrieved with an <see cref="ODATADetailLevel.ExpandClause"/> /// including the 'stats' attribute; otherwise it is null. /// </remarks> public JobStatistics Statistics { get { return this.propertyContainer.StatisticsProperty.Value; } } /// <summary> /// Gets the URL of the job. /// </summary> public string Url { get { return this.propertyContainer.UrlProperty.Value; } } /// <summary> /// Gets or sets whether tasks in the job can define dependencies on each other. /// </summary> /// <remarks> /// The default value is false. /// </remarks> public bool? UsesTaskDependencies { get { return this.propertyContainer.UsesTaskDependenciesProperty.Value; } set { this.propertyContainer.UsesTaskDependenciesProperty.Value = value; } } #endregion // CloudJob #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.JobAddParameter ITransportObjectProvider<Models.JobAddParameter>.GetTransportObject() { Models.JobAddParameter result = new Models.JobAddParameter() { CommonEnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.CommonEnvironmentSettings), Constraints = UtilitiesInternal.CreateObjectWithNullCheck(this.Constraints, (o) => o.GetTransportObject()), DisplayName = this.DisplayName, Id = this.Id, JobManagerTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobManagerTask, (o) => o.GetTransportObject()), JobPreparationTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobPreparationTask, (o) => o.GetTransportObject()), JobReleaseTask = UtilitiesInternal.CreateObjectWithNullCheck(this.JobReleaseTask, (o) => o.GetTransportObject()), Metadata = UtilitiesInternal.ConvertToProtocolCollection(this.Metadata), OnAllTasksComplete = UtilitiesInternal.MapNullableEnum<Common.OnAllTasksComplete, Models.OnAllTasksComplete>(this.OnAllTasksComplete), OnTaskFailure = UtilitiesInternal.MapNullableEnum<Common.OnTaskFailure, Models.OnTaskFailure>(this.OnTaskFailure), PoolInfo = UtilitiesInternal.CreateObjectWithNullCheck(this.PoolInformation, (o) => o.GetTransportObject()), Priority = this.Priority, UsesTaskDependencies = this.UsesTaskDependencies, }; return result; } #endregion // Internal/private methods } }
// 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.Runtime.CompilerServices; using System.IO; using System.Collections; using System.Globalization; using System.Text; using System.Threading; using Xunit; public class File_Open_fm_fa { public static String s_strActiveBugNums = ""; public static String s_strDtTmVer = "2000/05/08 12:18"; public static String s_strClassMethod = "File.OpenText(String)"; public static String s_strTFName = "Open_fm_fa.cs"; public static String s_strTFPath = Directory.GetCurrentDirectory(); private static String s_strLoc = "Loc_000oo"; private static int s_iCountErrors = 0; private static int s_iCountTestcases = 0; [Fact] public static void runTest() { try { // CreateNew // Create // Open // OpenOrCreate // Truncate // Append // [] FileMode.CreateNew and FileAccess.Read // [][] File does not exist // [][] File already exists // [] FileMode.CreateNew and FileAccess.Write // [][] File does not exist // [][] File already exists // [] FileMode.CreateNew and FileAccess.ReadWrite // [][] File does not exist // [][] File already exists // [] FileMode.Create and FileAccess.Read // [][] File does not exist // [][] File already exists // [] FileMode.Create and FileAccess.Write // [][] File does not exist // [][] File already exists // [] FileMode.Create and FileAccess.ReadWrite // [][] File does not exist // [][] File already exists // [] FileMode.Open and FileAccess.Read // [][] File does not exist // [][] File already exists // [] FileMode.Open and FileAccess.Write // [][] File does not exist // [][] File already exists // [] FileMode.Open and FileAccess.ReadWrite // [][] File does not exist // [][] File already exists // [] FileMode.OpenOrCreate and FileAccess.Read // [][] File does not exist // [][] File already exists // [] FileMode.OpenOrCreate and FileAccess.Write // [][] File does not exist // [][] File already exists // [] FileMode.OpenOrCreate and FileAccess.ReadWrite // [][] File does not exist // [][] File already exists // [] FileMode.Truncate and FileAccess.Read // [][] File does not exist // [][] File already exists // [] FileMode.Truncate and FileAccess.Write // [][] File does not exist // [][] File already exists // [] FileMode.Truncate and FileAccess.ReadWrite // [][] File does not exist // [][] File already exists // [] FileMode.Append and FileAccess.Read // [][] File does not exist // [][] File already exists // [] FileMode.Append and FileAccess.Write // [][] File does not exist // [][] File already exists // [] FileMode.Append and FileAccess.ReadWrite // [][] File does not exist // [][] File already exists // Simple call throughs to FileStream, just test functionality TestMethod(FileMode.CreateNew, FileAccess.Read); TestMethod(FileMode.CreateNew, FileAccess.Write); TestMethod(FileMode.CreateNew, FileAccess.ReadWrite); TestMethod(FileMode.Create, FileAccess.Read); TestMethod(FileMode.Create, FileAccess.Write); TestMethod(FileMode.Create, FileAccess.ReadWrite); TestMethod(FileMode.Open, FileAccess.Read); TestMethod(FileMode.Open, FileAccess.Write); TestMethod(FileMode.Open, FileAccess.ReadWrite); TestMethod(FileMode.OpenOrCreate, FileAccess.Read); TestMethod(FileMode.OpenOrCreate, FileAccess.Write); TestMethod(FileMode.OpenOrCreate, FileAccess.ReadWrite); TestMethod(FileMode.Truncate, FileAccess.Read); TestMethod(FileMode.Truncate, FileAccess.Write); TestMethod(FileMode.Truncate, FileAccess.ReadWrite); TestMethod(FileMode.Append, FileAccess.Read); TestMethod(FileMode.Append, FileAccess.Write); TestMethod(FileMode.Append, FileAccess.ReadWrite); } catch (Exception exc_general) { ++s_iCountErrors; Console.WriteLine("Error Err_8888yyy! strLoc==" + s_strLoc + ", exc_general==" + exc_general.ToString()); } //// Finish Diagnostics if (s_iCountErrors != 0) { Console.WriteLine("FAiL! " + s_strTFName + " ,iCountErrors==" + s_iCountErrors.ToString()); } Assert.Equal(0, s_iCountErrors); } public static void TestMethod(FileMode fm, FileAccess fa) { String fileName = Path.Combine(TestInfo.CurrentDirectory, Path.GetRandomFileName()); StreamWriter sw2; FileStream fs2; String str2; if (File.Exists(fileName)) File.Delete(fileName); // File does not exist //------------------------------------------------------------------ s_strLoc = "Loc_234yg"; switch (fm) { case FileMode.CreateNew: case FileMode.Create: case FileMode.OpenOrCreate: try { fs2 = File.Open(null, fm, fa); s_iCountTestcases++; if (!File.Exists(fileName)) { s_iCountErrors++; printerr("Error_0001! File not created, FileMode==" + fm.ToString("G")); } fs2.Dispose(); } catch (ArgumentException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_0004! Incorrect exception thrown, exc==" + exc); } try { fs2 = File.Open("", fm, fa); s_iCountTestcases++; if (!File.Exists(fileName)) { s_iCountErrors++; printerr("Error_0005! File not created, FileMode==" + fm.ToString("G")); } fs2.Dispose(); } catch (ArgumentException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_0008! Incorrect exception thrown, exc==" + exc); } try { fs2 = File.Open(fileName, fm, fa); s_iCountTestcases++; if (!File.Exists(fileName)) { s_iCountErrors++; printerr("Error_48gb7! File not created, FileMode==" + fm.ToString("G")); } fs2.Dispose(); } catch (ArgumentException aexc) { if (!((fm == FileMode.Create && fa == FileAccess.Read) || (fm == FileMode.CreateNew && fa == FileAccess.Read))) { s_iCountErrors++; printerr("Error_478v8! Unexpected exception, aexc==" + aexc); } } catch (Exception exc) { s_iCountErrors++; printerr("Error_4879v! Incorrect exception thrown, exc==" + exc); } break; case FileMode.Open: case FileMode.Truncate: s_iCountTestcases++; try { fs2 = File.Open(null, fm, fa); s_iCountErrors++; printerr("Error_1001! Expected exception not thrown"); fs2.Dispose(); } catch (IOException) { } catch (ArgumentException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_1005! Incorrect exception thrown, exc==" + exc.ToString()); } s_iCountTestcases++; try { fs2 = File.Open("", fm, fa); s_iCountErrors++; printerr("Error_1006! Expected exception not thrown"); fs2.Dispose(); } catch (IOException) { } catch (ArgumentException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_1010! Incorrect exception thrown, exc==" + exc.ToString()); } s_iCountTestcases++; try { fs2 = File.Open(fileName, fm, fa); s_iCountErrors++; printerr("Error_2yg8b! Expected exception not thrown"); fs2.Dispose(); } catch (IOException) { } catch (ArgumentException aexc) { if (fa != FileAccess.Read) { s_iCountErrors++; printerr("Error_v48y8! Unexpected exception thrown, aexc==" + aexc); } } catch (Exception exc) { s_iCountErrors++; printerr("Error_2y7gf! Incorrect exception thrown, exc==" + exc.ToString()); } break; case FileMode.Append: if (fa == FileAccess.Write) { fs2 = File.Open(fileName, fm, fa); s_iCountTestcases++; if (!File.Exists(fileName)) { s_iCountErrors++; printerr("Error_2498y! File not created"); } fs2.Dispose(); } else { s_iCountTestcases++; try { fs2 = File.Open(fileName, fm, fa); s_iCountErrors++; printerr("Error_2g78b! Expected exception not thrown"); fs2.Dispose(); } catch (ArgumentException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_g77b7! Incorrect exception thrown, exc==" + exc.ToString()); } } break; default: s_iCountErrors++; printerr("Error_27tbv! This should not be...."); break; } if (File.Exists(fileName)) File.Delete(fileName); //------------------------------------------------------------------ // File already exists //------------------------------------------------------------------ s_strLoc = "Loc_4yg7b"; FileStream stream = new FileStream(fileName, FileMode.Create); sw2 = new StreamWriter(stream); str2 = "Du er en ape"; sw2.Write(str2); sw2.Dispose(); stream.Dispose(); switch (fm) { case FileMode.CreateNew: s_iCountTestcases++; try { fs2 = File.Open(null, fm, fa); s_iCountErrors++; printerr("Error_2001! Expected exception not thrown"); fs2.Dispose(); } catch (ArgumentException) { } catch (IOException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_2005! Incorrect exception thrown, exc==" + exc.ToString()); } s_iCountTestcases++; try { fs2 = File.Open("", fm, fa); s_iCountErrors++; printerr("Error_2006! Expected exception not thrown"); fs2.Dispose(); } catch (ArgumentException) { } catch (IOException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_2010! Incorrect exception thrown, exc==" + exc.ToString()); } s_iCountTestcases++; try { fs2 = File.Open(fileName, fm, fa); s_iCountErrors++; printerr("Error_27b98! Expected exception not thrown"); fs2.Dispose(); } catch (ArgumentException aexc) { if (fa != FileAccess.Read) { s_iCountErrors++; printerr("Error_4387v! Unexpected exception, aexc==" + aexc); } } catch (IOException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_g8782! Incorrect exception thrown, exc==" + exc.ToString()); } break; case FileMode.Create: try { fs2 = File.Open(fileName, fm, fa); if (fs2.Length != 0) { s_iCountErrors++; printerr("Error_287vb! Incorrect length of file==" + fs2.Length); } fs2.Dispose(); } catch (ArgumentException aexc) { if (fa != FileAccess.Read) { s_iCountErrors++; printerr("Error_48vy7! Unexpected exception, aexc==" + aexc); } } catch (Exception exc) { s_iCountErrors++; printerr("Error_47yv3! Incorrect exception thrown, exc==" + exc.ToString()); } break; case FileMode.OpenOrCreate: case FileMode.Open: fs2 = File.Open(fileName, fm, fa); if (fs2.Length != str2.Length) { s_iCountErrors++; printerr("Error_2gy78! Incorrect length on file==" + fs2.Length); } fs2.Dispose(); break; case FileMode.Truncate: if (fa == FileAccess.Read) { s_iCountTestcases++; try { fs2 = File.Open(fileName, fm, fa); s_iCountErrors++; printerr("Error_g95y8! Expected exception not thrown"); } catch (ArgumentException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_98y4v! Incorrect exception thrown, exc==" + exc.ToString()); } } else { fs2 = File.Open(fileName, fm, fa); if (fs2.Length != 0) { s_iCountErrors++; printerr("Error_29gv9! Incorrect length on file==" + fs2.Length); } fs2.Dispose(); } break; case FileMode.Append: if (fa == FileAccess.Write) { fs2 = File.Open(fileName, fm, fa); s_iCountTestcases++; if (!File.Exists(fileName)) { s_iCountErrors++; printerr("Error_4089v! File not created"); } fs2.Dispose(); } else { s_iCountTestcases++; try { fs2 = File.Open(fileName, fm, fa); s_iCountErrors++; printerr("Error_287yb! Expected exception not thrown"); fs2.Dispose(); } catch (ArgumentException) { } catch (Exception exc) { s_iCountErrors++; printerr("Error_27878! Incorrect exception thrown, exc==" + exc.ToString()); } } break; default: s_iCountErrors++; printerr("Error_587yb! This should not be..."); break; } //------------------------------------------------------------------ if (File.Exists(fileName)) File.Delete(fileName); } public static void printerr(String err, [CallerMemberName] string memberName = "", [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0) { Console.WriteLine("ERROR: ({0}, {1}, {2}) {3}", memberName, filePath, lineNumber, err); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== //========================================================================== // File: TcpSocketManager.cs // // Summary: Provides a base for the client and server tcp socket // managers. // //========================================================================== using System; using System.Collections; using System.Globalization; using System.IO; using System.Net; using System.Net.Sockets; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading; namespace System.Runtime.Remoting.Channels.Tcp { // A client socket manager instance should encapsulate the socket // for the purpose of reading a response internal abstract class TcpSocketHandler : SocketHandler { private static byte[] s_protocolPreamble = Encoding.ASCII.GetBytes(".NET"); private static byte[] s_protocolVersion1_0 = new byte[]{1,0}; public TcpSocketHandler(Socket socket, Stream stream) : this(socket, null, stream) { } // TcpSocketHandler public TcpSocketHandler(Socket socket, RequestQueue requestQueue, Stream stream) : base(socket, requestQueue, stream) { } // TcpSocketHandler private void ReadAndMatchPreamble() { // make sure that the incoming data starts with the preamble InternalRemotingServices.RemotingAssert( s_protocolPreamble.Length == 4, "The preamble is supposed to be 4 bytes ('.NET'). Somebody changed it..."); if (ReadAndMatchFourBytes(s_protocolPreamble) == false) { throw new RemotingException( CoreChannel.GetResourceString("Remoting_Tcp_ExpectingPreamble")); } } // ReadAndMatchPreamble protected void WritePreambleAndVersion(Stream outputStream) { outputStream.Write(s_protocolPreamble, 0, s_protocolPreamble.Length); outputStream.Write(s_protocolVersion1_0, 0, s_protocolVersion1_0.Length); } // WritePreamble protected void ReadVersionAndOperation(out UInt16 operation) { // check for the preamble ReadAndMatchPreamble(); // Check the version number. byte majorVersion = (byte)ReadByte(); byte minorVersion = (byte)ReadByte(); if ((majorVersion != 1) || (minorVersion != 0)) { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_UnknownProtocolVersion"), majorVersion.ToString(CultureInfo.CurrentCulture) + "." + minorVersion.ToString(CultureInfo.CurrentCulture))); } // Read the operation operation = ReadUInt16(); } // ReadVersionAndOperation protected void ReadContentLength(out bool chunked, out int contentLength) { contentLength = -1; UInt16 header = ReadUInt16(); if (header == TcpContentDelimiter.Chunked) { chunked = true; } else if (header == TcpContentDelimiter.ContentLength) { chunked = false; contentLength = ReadInt32(); } else { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ExpectingContentLengthHeader"), header.ToString(CultureInfo.CurrentCulture))); } } // ReadContentLength protected void ReadToEndOfHeaders(BaseTransportHeaders headers) { bool bError = false; String statusPhrase = null; UInt16 headerType = ReadUInt16(); while (headerType != TcpHeaders.EndOfHeaders) { if (headerType == TcpHeaders.Custom) { String headerName = ReadCountedString(); String headerValue = ReadCountedString(); headers[headerName] = headerValue; } else if (headerType == TcpHeaders.RequestUri) { ReadAndVerifyHeaderFormat("RequestUri", TcpHeaderFormat.CountedString); // read uri (and make sure that no channel specific data is present) String uri = ReadCountedString(); String channelURI; String objectURI; channelURI = TcpChannelHelper.ParseURL(uri, out objectURI); if (channelURI == null) objectURI = uri; headers.RequestUri = objectURI; } else if (headerType == TcpHeaders.StatusCode) { ReadAndVerifyHeaderFormat("StatusCode", TcpHeaderFormat.UInt16); UInt16 statusCode = ReadUInt16(); // We'll throw an exception here if there was an error. If an error // occurs above the transport level, the status code will still be // success here. if (statusCode != TcpStatusCode.Success) bError = true; } else if (headerType == TcpHeaders.StatusPhrase) { ReadAndVerifyHeaderFormat("StatusPhrase", TcpHeaderFormat.CountedString); statusPhrase = ReadCountedString(); } else if (headerType == TcpHeaders.ContentType) { ReadAndVerifyHeaderFormat("Content-Type", TcpHeaderFormat.CountedString); String contentType = ReadCountedString(); headers.ContentType = contentType; } else { // unknown header: Read header format and ignore rest of data byte headerFormat = (byte)ReadByte(); switch (headerFormat) { case TcpHeaderFormat.Void: break; case TcpHeaderFormat.CountedString: ReadCountedString(); break; case TcpHeaderFormat.Byte: ReadByte(); break; case TcpHeaderFormat.UInt16: ReadUInt16(); break; case TcpHeaderFormat.Int32: ReadInt32(); break; default: { // unknown format throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_UnknownHeaderType"), headerType, headerFormat)); } } // switch (format) } // read next header token headerType = ReadUInt16(); } // loop until end of headers // if an error occurred, throw an exception if (bError) { if (statusPhrase == null) statusPhrase = ""; throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_GenericServerError"), statusPhrase)); } } // ReadToEndOfHeaders protected void WriteHeaders(ITransportHeaders headers, Stream outputStream) { IEnumerator it = null; BaseTransportHeaders wkHeaders = headers as BaseTransportHeaders; if (wkHeaders != null) { // write out well known headers // NOTE: RequestUri is written out elsewhere. if (wkHeaders.ContentType != null) { WriteContentTypeHeader(wkHeaders.ContentType, outputStream); } it = wkHeaders.GetOtherHeadersEnumerator(); } else { it = headers.GetEnumerator(); } // write custom headers if (it != null) { while (it.MoveNext()) { DictionaryEntry header = (DictionaryEntry)it.Current; String headerName = (String)header.Key; if (!StringHelper.StartsWithDoubleUnderscore(headerName)) // exclude special headers { String headerValue = header.Value.ToString(); if (wkHeaders == null) { if (String.Compare(headerName, "Content-Type", StringComparison.OrdinalIgnoreCase) == 0) { WriteContentTypeHeader(headerValue, outputStream); continue; } } WriteCustomHeader(headerName, headerValue, outputStream); } } // while (it.MoveNext()) } // write EndOfHeaders token WriteUInt16(TcpHeaders.EndOfHeaders, outputStream); } // WriteHeaders private void WriteContentTypeHeader(String value, Stream outputStream) { WriteUInt16(TcpHeaders.ContentType, outputStream); WriteByte(TcpHeaderFormat.CountedString, outputStream); WriteCountedString(value, outputStream); } // WriteContentTypeHeader private void WriteCustomHeader(String name, String value, Stream outputStream) { WriteUInt16(TcpHeaders.Custom, outputStream); WriteCountedString(name, outputStream); WriteCountedString(value, outputStream); } // WriteCustomHeader protected String ReadCountedString() { // strings are formatted as follows // [string format (1-byte)][encoded-size (int32)][string value (encoded-size length in bytes)] byte strFormat = (byte)ReadByte(); int strDataSize = ReadInt32(); if (strDataSize > 0) { byte[] data = new byte[strDataSize]; // SocketHander::Read waits until it reads all requested data Read(data, 0, strDataSize); switch (strFormat) { case TcpStringFormat.Unicode: return Encoding.Unicode.GetString(data); case TcpStringFormat.UTF8: return Encoding.UTF8.GetString(data); default: throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_UnrecognizedStringFormat"), strFormat.ToString(CultureInfo.CurrentCulture))); } } else { return null; } } // ReadCountedString protected void WriteCountedString(String str, Stream outputStream) { // strings are formatted as follows [string length (int32)][string value (unicode)] int strLength = 0; if (str != null) strLength = str.Length; if (strLength > 0) { byte[] strBytes = Encoding.UTF8.GetBytes(str); // write string format WriteByte(TcpStringFormat.UTF8, outputStream); // write string data size WriteInt32(strBytes.Length, outputStream); // write string data outputStream.Write(strBytes, 0, strBytes.Length); } else { // write string format // (just call it Unicode (doesn't matter since there is no data)) WriteByte(TcpStringFormat.Unicode, outputStream); // stream data size is 0. WriteInt32(0, outputStream); } } // WriteCountedString private void ReadAndVerifyHeaderFormat(String headerName, byte expectedFormat) { byte headerFormat = (byte)ReadByte(); if (headerFormat != expectedFormat) { throw new RemotingException( String.Format( CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_IncorrectHeaderFormat"), expectedFormat, headerName)); } } // ReadAndVerifyHeaderFormat } // TcpSocketHandler } // namespace System.Runtime.Remoting.Channels
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** ** Purpose: Class for creating and managing a threadpool ** ** =============================================================================*/ using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading.Tasks; using Internal.Runtime.CompilerServices; namespace System.Threading { internal static class ThreadPoolGlobals { public static volatile bool threadPoolInitialized; public static bool enableWorkerTracking; public static readonly ThreadPoolWorkQueue workQueue = new ThreadPoolWorkQueue(); /// <summary>Shim used to invoke <see cref="IAsyncStateMachineBox.MoveNext"/> of the supplied <see cref="IAsyncStateMachineBox"/>.</summary> internal static readonly Action<object?> s_invokeAsyncStateMachineBox = state => { if (!(state is IAsyncStateMachineBox box)) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state); return; } box.MoveNext(); }; } [StructLayout(LayoutKind.Sequential)] // enforce layout so that padding reduces false sharing internal sealed class ThreadPoolWorkQueue { internal static class WorkStealingQueueList { #pragma warning disable CA1825 // avoid the extra generic instantation for Array.Empty<T>(); this is the only place we'll ever create this array private static volatile WorkStealingQueue[] _queues = new WorkStealingQueue[0]; #pragma warning restore CA1825 public static WorkStealingQueue[] Queues => _queues; public static void Add(WorkStealingQueue queue) { Debug.Assert(queue != null); while (true) { WorkStealingQueue[] oldQueues = _queues; Debug.Assert(Array.IndexOf(oldQueues, queue) == -1); var newQueues = new WorkStealingQueue[oldQueues.Length + 1]; Array.Copy(oldQueues, newQueues, oldQueues.Length); newQueues[^1] = queue; if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues) { break; } } } public static void Remove(WorkStealingQueue queue) { Debug.Assert(queue != null); while (true) { WorkStealingQueue[] oldQueues = _queues; if (oldQueues.Length == 0) { return; } int pos = Array.IndexOf(oldQueues, queue); if (pos == -1) { Debug.Fail("Should have found the queue"); return; } var newQueues = new WorkStealingQueue[oldQueues.Length - 1]; if (pos == 0) { Array.Copy(oldQueues, 1, newQueues, 0, newQueues.Length); } else if (pos == oldQueues.Length - 1) { Array.Copy(oldQueues, newQueues, newQueues.Length); } else { Array.Copy(oldQueues, newQueues, pos); Array.Copy(oldQueues, pos + 1, newQueues, pos, newQueues.Length - pos); } if (Interlocked.CompareExchange(ref _queues, newQueues, oldQueues) == oldQueues) { break; } } } } internal sealed class WorkStealingQueue { private const int INITIAL_SIZE = 32; internal volatile object?[] m_array = new object[INITIAL_SIZE]; // SOS's ThreadPool command depends on this name private volatile int m_mask = INITIAL_SIZE - 1; #if DEBUG // in debug builds, start at the end so we exercise the index reset logic. private const int START_INDEX = int.MaxValue; #else private const int START_INDEX = 0; #endif private volatile int m_headIndex = START_INDEX; private volatile int m_tailIndex = START_INDEX; private SpinLock m_foreignLock = new SpinLock(enableThreadOwnerTracking: false); public void LocalPush(object obj) { int tail = m_tailIndex; // We're going to increment the tail; if we'll overflow, then we need to reset our counts if (tail == int.MaxValue) { bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); if (m_tailIndex == int.MaxValue) { // // Rather than resetting to zero, we'll just mask off the bits we don't care about. // This way we don't need to rearrange the items already in the queue; they'll be found // correctly exactly where they are. One subtlety here is that we need to make sure that // if head is currently < tail, it remains that way. This happens to just fall out from // the bit-masking, because we only do this if tail == int.MaxValue, meaning that all // bits are set, so all of the bits we're keeping will also be set. Thus it's impossible // for the head to end up > than the tail, since you can't set any more bits than all of // them. // m_headIndex &= m_mask; m_tailIndex = tail = m_tailIndex & m_mask; Debug.Assert(m_headIndex <= m_tailIndex); } } finally { if (lockTaken) m_foreignLock.Exit(useMemoryBarrier: true); } } // When there are at least 2 elements' worth of space, we can take the fast path. if (tail < m_headIndex + m_mask) { Volatile.Write(ref m_array[tail & m_mask], obj); m_tailIndex = tail + 1; } else { // We need to contend with foreign pops, so we lock. bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); int head = m_headIndex; int count = m_tailIndex - m_headIndex; // If there is still space (one left), just add the element. if (count >= m_mask) { // We're full; expand the queue by doubling its size. var newArray = new object?[m_array.Length << 1]; for (int i = 0; i < m_array.Length; i++) newArray[i] = m_array[(i + head) & m_mask]; // Reset the field values, incl. the mask. m_array = newArray; m_headIndex = 0; m_tailIndex = tail = count; m_mask = (m_mask << 1) | 1; } Volatile.Write(ref m_array[tail & m_mask], obj); m_tailIndex = tail + 1; } finally { if (lockTaken) m_foreignLock.Exit(useMemoryBarrier: false); } } } public bool LocalFindAndPop(object obj) { // Fast path: check the tail. If equal, we can skip the lock. if (m_array[(m_tailIndex - 1) & m_mask] == obj) { object? unused = LocalPop(); Debug.Assert(unused == null || unused == obj); return unused != null; } // Else, do an O(N) search for the work item. The theory of work stealing and our // inlining logic is that most waits will happen on recently queued work. And // since recently queued work will be close to the tail end (which is where we // begin our search), we will likely find it quickly. In the worst case, we // will traverse the whole local queue; this is typically not going to be a // problem (although degenerate cases are clearly an issue) because local work // queues tend to be somewhat shallow in length, and because if we fail to find // the work item, we are about to block anyway (which is very expensive). for (int i = m_tailIndex - 2; i >= m_headIndex; i--) { if (m_array[i & m_mask] == obj) { // If we found the element, block out steals to avoid interference. bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); // If we encountered a race condition, bail. if (m_array[i & m_mask] == null) return false; // Otherwise, null out the element. Volatile.Write(ref m_array[i & m_mask], null); // And then check to see if we can fix up the indexes (if we're at // the edge). If we can't, we just leave nulls in the array and they'll // get filtered out eventually (but may lead to superfluous resizing). if (i == m_tailIndex) m_tailIndex--; else if (i == m_headIndex) m_headIndex++; return true; } finally { if (lockTaken) m_foreignLock.Exit(useMemoryBarrier: false); } } } return false; } public object? LocalPop() => m_headIndex < m_tailIndex ? LocalPopCore() : null; private object? LocalPopCore() { while (true) { int tail = m_tailIndex; if (m_headIndex >= tail) { return null; } // Decrement the tail using a fence to ensure subsequent read doesn't come before. tail--; Interlocked.Exchange(ref m_tailIndex, tail); // If there is no interaction with a take, we can head down the fast path. if (m_headIndex <= tail) { int idx = tail & m_mask; object? obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. if (obj == null) continue; m_array[idx] = null; return obj; } else { // Interaction with takes: 0 or 1 elements left. bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); if (m_headIndex <= tail) { // Element still available. Take it. int idx = tail & m_mask; object? obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. if (obj == null) continue; m_array[idx] = null; return obj; } else { // If we encountered a race condition and element was stolen, restore the tail. m_tailIndex = tail + 1; return null; } } finally { if (lockTaken) m_foreignLock.Exit(useMemoryBarrier: false); } } } } public bool CanSteal => m_headIndex < m_tailIndex; public object? TrySteal(ref bool missedSteal) { while (true) { if (CanSteal) { bool taken = false; try { m_foreignLock.TryEnter(ref taken); if (taken) { // Increment head, and ensure read of tail doesn't move before it (fence). int head = m_headIndex; Interlocked.Exchange(ref m_headIndex, head + 1); if (head < m_tailIndex) { int idx = head & m_mask; object? obj = Volatile.Read(ref m_array[idx]); // Check for nulls in the array. if (obj == null) continue; m_array[idx] = null; return obj; } else { // Failed, restore head. m_headIndex = head; } } } finally { if (taken) m_foreignLock.Exit(useMemoryBarrier: false); } missedSteal = true; } return null; } } public int Count { get { bool lockTaken = false; try { m_foreignLock.Enter(ref lockTaken); return Math.Max(0, m_tailIndex - m_headIndex); } finally { if (lockTaken) { m_foreignLock.Exit(useMemoryBarrier: false); } } } } } internal bool loggingEnabled; internal readonly ConcurrentQueue<object> workItems = new ConcurrentQueue<object>(); // SOS's ThreadPool command depends on this name private readonly Internal.PaddingFor32 pad1; private volatile int numOutstandingThreadRequests = 0; private readonly Internal.PaddingFor32 pad2; public ThreadPoolWorkQueue() { loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer); } public ThreadPoolWorkQueueThreadLocals GetOrCreateThreadLocals() => ThreadPoolWorkQueueThreadLocals.threadLocals ?? CreateThreadLocals(); [MethodImpl(MethodImplOptions.NoInlining)] private ThreadPoolWorkQueueThreadLocals CreateThreadLocals() { Debug.Assert(ThreadPoolWorkQueueThreadLocals.threadLocals == null); return ThreadPoolWorkQueueThreadLocals.threadLocals = new ThreadPoolWorkQueueThreadLocals(this); } internal void EnsureThreadRequested() { // // If we have not yet requested #procs threads, then request a new thread. // // CoreCLR: Note that there is a separate count in the VM which has already been incremented // by the VM by the time we reach this point. // int count = numOutstandingThreadRequests; while (count < Environment.ProcessorCount) { int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count + 1, count); if (prev == count) { ThreadPool.RequestWorkerThread(); break; } count = prev; } } internal void MarkThreadRequestSatisfied() { // // One of our outstanding thread requests has been satisfied. // Decrement the count so that future calls to EnsureThreadRequested will succeed. // // CoreCLR: Note that there is a separate count in the VM which has already been decremented // by the VM by the time we reach this point. // int count = numOutstandingThreadRequests; while (count > 0) { int prev = Interlocked.CompareExchange(ref numOutstandingThreadRequests, count - 1, count); if (prev == count) { break; } count = prev; } } public void Enqueue(object callback, bool forceGlobal) { Debug.Assert((callback is IThreadPoolWorkItem) ^ (callback is Task)); if (loggingEnabled) System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolEnqueueWorkObject(callback); ThreadPoolWorkQueueThreadLocals? tl = null; if (!forceGlobal) tl = ThreadPoolWorkQueueThreadLocals.threadLocals; if (null != tl) { tl.workStealingQueue.LocalPush(callback); } else { workItems.Enqueue(callback); } EnsureThreadRequested(); } internal bool LocalFindAndPop(object callback) { ThreadPoolWorkQueueThreadLocals? tl = ThreadPoolWorkQueueThreadLocals.threadLocals; return tl != null && tl.workStealingQueue.LocalFindAndPop(callback); } public object? Dequeue(ThreadPoolWorkQueueThreadLocals tl, ref bool missedSteal) { WorkStealingQueue localWsq = tl.workStealingQueue; object? callback; if ((callback = localWsq.LocalPop()) == null && // first try the local queue !workItems.TryDequeue(out callback)) // then try the global queue { // finally try to steal from another thread's local queue WorkStealingQueue[] queues = WorkStealingQueueList.Queues; int c = queues.Length; Debug.Assert(c > 0, "There must at least be a queue for this thread."); int maxIndex = c - 1; int i = tl.random.Next(c); while (c > 0) { i = (i < maxIndex) ? i + 1 : 0; WorkStealingQueue otherQueue = queues[i]; if (otherQueue != localWsq && otherQueue.CanSteal) { callback = otherQueue.TrySteal(ref missedSteal); if (callback != null) { break; } } c--; } } return callback; } public long LocalCount { get { long count = 0; foreach (WorkStealingQueue workStealingQueue in WorkStealingQueueList.Queues) { count += workStealingQueue.Count; } return count; } } public long GlobalCount => workItems.Count; /// <summary> /// Dispatches work items to this thread. /// </summary> /// <returns> /// <c>true</c> if this thread did as much work as was available or its quantum expired. /// <c>false</c> if this thread stopped working early. /// </returns> internal static bool Dispatch() { ThreadPoolWorkQueue outerWorkQueue = ThreadPoolGlobals.workQueue; // // Save the start time // int startTickCount = Environment.TickCount; // // Update our records to indicate that an outstanding request for a thread has now been fulfilled. // From this point on, we are responsible for requesting another thread if we stop working for any // reason, and we believe there might still be work in the queue. // // CoreCLR: Note that if this thread is aborted before we get a chance to request another one, the VM will // record a thread request on our behalf. So we don't need to worry about getting aborted right here. // outerWorkQueue.MarkThreadRequestSatisfied(); // Has the desire for logging changed since the last time we entered? outerWorkQueue.loggingEnabled = FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.ThreadPool | FrameworkEventSource.Keywords.ThreadTransfer); // // Assume that we're going to need another thread if this one returns to the VM. We'll set this to // false later, but only if we're absolutely certain that the queue is empty. // bool needAnotherThread = true; try { // // Set up our thread-local data // // Use operate on workQueue local to try block so it can be enregistered ThreadPoolWorkQueue workQueue = outerWorkQueue; ThreadPoolWorkQueueThreadLocals tl = workQueue.GetOrCreateThreadLocals(); Thread currentThread = tl.currentThread; // Start on clean ExecutionContext and SynchronizationContext currentThread._executionContext = null; currentThread._synchronizationContext = null; // // Loop until our quantum expires or there is no work. // while (ThreadPool.KeepDispatching(startTickCount)) { bool missedSteal = false; // Use operate on workItem local to try block so it can be enregistered object? workItem = workQueue.Dequeue(tl, ref missedSteal); if (workItem == null) { // // No work. // If we missed a steal, though, there may be more work in the queue. // Instead of looping around and trying again, we'll just request another thread. Hopefully the thread // that owns the contended work-stealing queue will pick up its own workitems in the meantime, // which will be more efficient than this thread doing it anyway. // needAnotherThread = missedSteal; // Tell the VM we're returning normally, not because Hill Climbing asked us to return. return true; } if (workQueue.loggingEnabled) System.Diagnostics.Tracing.FrameworkEventSource.Log.ThreadPoolDequeueWorkObject(workItem); // // If we found work, there may be more work. Ask for another thread so that the other work can be processed // in parallel. Note that this will only ask for a max of #procs threads, so it's safe to call it for every dequeue. // workQueue.EnsureThreadRequested(); // // Execute the workitem outside of any finally blocks, so that it can be aborted if needed. // if (ThreadPoolGlobals.enableWorkerTracking) { bool reportedStatus = false; try { ThreadPool.ReportThreadStatus(isWorking: true); reportedStatus = true; if (workItem is Task task) { task.ExecuteFromThreadPool(currentThread); } else { Debug.Assert(workItem is IThreadPoolWorkItem); Unsafe.As<IThreadPoolWorkItem>(workItem).Execute(); } } finally { if (reportedStatus) ThreadPool.ReportThreadStatus(isWorking: false); } } else if (workItem is Task task) { // Check for Task first as it's currently faster to type check // for Task and then Unsafe.As for the interface, rather than // vice versa, in particular when the object implements a bunch // of interfaces. task.ExecuteFromThreadPool(currentThread); } else { Debug.Assert(workItem is IThreadPoolWorkItem); Unsafe.As<IThreadPoolWorkItem>(workItem).Execute(); } currentThread.ResetThreadPoolThread(); // Release refs workItem = null; // Return to clean ExecutionContext and SynchronizationContext ExecutionContext.ResetThreadPoolThread(currentThread); // // Notify the VM that we executed this workitem. This is also our opportunity to ask whether Hill Climbing wants // us to return the thread to the pool or not. // if (!ThreadPool.NotifyWorkItemComplete()) return false; } // If we get here, it's because our quantum expired. Tell the VM we're returning normally. return true; } finally { // // If we are exiting for any reason other than that the queue is definitely empty, ask for another // thread to pick up where we left off. // if (needAnotherThread) outerWorkQueue.EnsureThreadRequested(); } } } // Simple random number generator. We don't need great randomness, we just need a little and for it to be fast. internal struct FastRandom // xorshift prng { private uint _w, _x, _y, _z; public FastRandom(int seed) { _x = (uint)seed; _w = 88675123; _y = 362436069; _z = 521288629; } public int Next(int maxValue) { Debug.Assert(maxValue > 0); uint t = _x ^ (_x << 11); _x = _y; _y = _z; _z = _w; _w = _w ^ (_w >> 19) ^ (t ^ (t >> 8)); return (int)(_w % (uint)maxValue); } } // Holds a WorkStealingQueue, and removes it from the list when this object is no longer referenced. internal sealed class ThreadPoolWorkQueueThreadLocals { [ThreadStatic] public static ThreadPoolWorkQueueThreadLocals? threadLocals; public readonly ThreadPoolWorkQueue workQueue; public readonly ThreadPoolWorkQueue.WorkStealingQueue workStealingQueue; public readonly Thread currentThread; public FastRandom random = new FastRandom(Thread.CurrentThread.ManagedThreadId); // mutable struct, do not copy or make readonly public ThreadPoolWorkQueueThreadLocals(ThreadPoolWorkQueue tpq) { workQueue = tpq; workStealingQueue = new ThreadPoolWorkQueue.WorkStealingQueue(); ThreadPoolWorkQueue.WorkStealingQueueList.Add(workStealingQueue); currentThread = Thread.CurrentThread; } ~ThreadPoolWorkQueueThreadLocals() { // Transfer any pending workitems into the global queue so that they will be executed by another thread if (null != workStealingQueue) { if (null != workQueue) { object? cb; while ((cb = workStealingQueue.LocalPop()) != null) { Debug.Assert(null != cb); workQueue.Enqueue(cb, forceGlobal: true); } } ThreadPoolWorkQueue.WorkStealingQueueList.Remove(workStealingQueue); } } } public delegate void WaitCallback(object? state); public delegate void WaitOrTimerCallback(object? state, bool timedOut); // signaled or timed out internal abstract class QueueUserWorkItemCallbackBase : IThreadPoolWorkItem { #if DEBUG private int executed; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1821:RemoveEmptyFinalizers")] ~QueueUserWorkItemCallbackBase() { Interlocked.MemoryBarrier(); // ensure that an old cached value is not read below Debug.Assert( executed != 0, "A QueueUserWorkItemCallback was never called!"); } #endif public virtual void Execute() { #if DEBUG GC.SuppressFinalize(this); Debug.Assert( 0 == Interlocked.Exchange(ref executed, 1), "A QueueUserWorkItemCallback was called twice!"); #endif } } internal sealed class QueueUserWorkItemCallback : QueueUserWorkItemCallbackBase { private WaitCallback? _callback; // SOS's ThreadPool command depends on this name private readonly object? _state; private readonly ExecutionContext _context; private static readonly Action<QueueUserWorkItemCallback> s_executionContextShim = quwi => { Debug.Assert(quwi._callback != null); WaitCallback callback = quwi._callback; quwi._callback = null; callback(quwi._state); }; internal QueueUserWorkItemCallback(WaitCallback callback, object? state, ExecutionContext context) { Debug.Assert(context != null); _callback = callback; _state = state; _context = context; } public override void Execute() { base.Execute(); ExecutionContext.RunForThreadPoolUnsafe(_context, s_executionContextShim, this); } } internal sealed class QueueUserWorkItemCallback<TState> : QueueUserWorkItemCallbackBase { private Action<TState>? _callback; // SOS's ThreadPool command depends on this name private readonly TState _state; private readonly ExecutionContext _context; internal QueueUserWorkItemCallback(Action<TState> callback, TState state, ExecutionContext context) { Debug.Assert(callback != null); _callback = callback; _state = state; _context = context; } public override void Execute() { base.Execute(); Debug.Assert(_callback != null); Action<TState> callback = _callback; _callback = null; ExecutionContext.RunForThreadPoolUnsafe(_context, callback, in _state); } } internal sealed class QueueUserWorkItemCallbackDefaultContext : QueueUserWorkItemCallbackBase { private WaitCallback? _callback; // SOS's ThreadPool command depends on this name private readonly object? _state; internal QueueUserWorkItemCallbackDefaultContext(WaitCallback callback, object? state) { Debug.Assert(callback != null); _callback = callback; _state = state; } public override void Execute() { ExecutionContext.CheckThreadPoolAndContextsAreDefault(); base.Execute(); Debug.Assert(_callback != null); WaitCallback callback = _callback; _callback = null; callback(_state); // ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default } } internal sealed class QueueUserWorkItemCallbackDefaultContext<TState> : QueueUserWorkItemCallbackBase { private Action<TState>? _callback; // SOS's ThreadPool command depends on this name private readonly TState _state; internal QueueUserWorkItemCallbackDefaultContext(Action<TState> callback, TState state) { Debug.Assert(callback != null); _callback = callback; _state = state; } public override void Execute() { ExecutionContext.CheckThreadPoolAndContextsAreDefault(); base.Execute(); Debug.Assert(_callback != null); Action<TState> callback = _callback; _callback = null; callback(_state); // ThreadPoolWorkQueue.Dispatch will handle notifications and reset EC and SyncCtx back to default } } internal sealed class _ThreadPoolWaitOrTimerCallback { private readonly WaitOrTimerCallback _waitOrTimerCallback; private readonly ExecutionContext? _executionContext; private readonly object? _state; private static readonly ContextCallback _ccbt = new ContextCallback(WaitOrTimerCallback_Context_t); private static readonly ContextCallback _ccbf = new ContextCallback(WaitOrTimerCallback_Context_f); internal _ThreadPoolWaitOrTimerCallback(WaitOrTimerCallback waitOrTimerCallback, object? state, bool flowExecutionContext) { _waitOrTimerCallback = waitOrTimerCallback; _state = state; if (flowExecutionContext) { // capture the exection context _executionContext = ExecutionContext.Capture(); } } private static void WaitOrTimerCallback_Context_t(object? state) => WaitOrTimerCallback_Context(state, timedOut: true); private static void WaitOrTimerCallback_Context_f(object? state) => WaitOrTimerCallback_Context(state, timedOut: false); private static void WaitOrTimerCallback_Context(object? state, bool timedOut) { _ThreadPoolWaitOrTimerCallback helper = (_ThreadPoolWaitOrTimerCallback)state!; helper._waitOrTimerCallback(helper._state, timedOut); } // call back helper internal static void PerformWaitOrTimerCallback(_ThreadPoolWaitOrTimerCallback helper, bool timedOut) { Debug.Assert(helper != null, "Null state passed to PerformWaitOrTimerCallback!"); // call directly if it is an unsafe call OR EC flow is suppressed ExecutionContext? context = helper._executionContext; if (context == null) { WaitOrTimerCallback callback = helper._waitOrTimerCallback; callback(helper._state, timedOut); } else { ExecutionContext.Run(context, timedOut ? _ccbt : _ccbf, helper); } } } public static partial class ThreadPool { [CLSCompliant(false)] public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, uint millisecondsTimeOutInterval, bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, true); } [CLSCompliant(false)] public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, uint millisecondsTimeOutInterval, bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval > (uint)int.MaxValue && millisecondsTimeOutInterval != uint.MaxValue) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); return RegisterWaitForSingleObject(waitObject, callBack, state, millisecondsTimeOutInterval, executeOnlyOnce, false); } public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, int millisecondsTimeOutInterval, bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, int millisecondsTimeOutInterval, bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false); } public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, long millisecondsTimeOutInterval, bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (millisecondsTimeOutInterval > (uint)int.MaxValue) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, long millisecondsTimeOutInterval, bool executeOnlyOnce // NOTE: we do not allow other options that allow the callback to be queued as an APC ) { if (millisecondsTimeOutInterval < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (millisecondsTimeOutInterval > (uint)int.MaxValue) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeOutInterval), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)millisecondsTimeOutInterval, executeOnlyOnce, false); } public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, TimeSpan timeout, bool executeOnlyOnce ) { long tm = (long)timeout.TotalMilliseconds; if (tm < -1) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (tm > (long)int.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, true); } public static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, TimeSpan timeout, bool executeOnlyOnce ) { long tm = (long)timeout.TotalMilliseconds; if (tm < -1) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_NeedNonNegOrNegative1); if (tm > (long)int.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout), SR.ArgumentOutOfRange_LessEqualToIntegerMaxVal); return RegisterWaitForSingleObject(waitObject, callBack, state, (uint)tm, executeOnlyOnce, false); } public static bool QueueUserWorkItem(WaitCallback callBack) => QueueUserWorkItem(callBack, null); public static bool QueueUserWorkItem(WaitCallback callBack, object? state) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } EnsureInitialized(); ExecutionContext? context = ExecutionContext.Capture(); object tpcallBack = (context == null || context.IsDefault) ? new QueueUserWorkItemCallbackDefaultContext(callBack!, state) : (object)new QueueUserWorkItemCallback(callBack!, state, context); ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true); return true; } public static bool QueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } EnsureInitialized(); ExecutionContext? context = ExecutionContext.Capture(); object tpcallBack = (context == null || context.IsDefault) ? new QueueUserWorkItemCallbackDefaultContext<TState>(callBack!, state) : (object)new QueueUserWorkItemCallback<TState>(callBack!, state, context); ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: !preferLocal); return true; } public static bool UnsafeQueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } // If the callback is the runtime-provided invocation of an IAsyncStateMachineBox, // then we can queue the Task state directly to the ThreadPool instead of // wrapping it in a QueueUserWorkItemCallback. // // This occurs when user code queues its provided continuation to the ThreadPool; // internally we call UnsafeQueueUserWorkItemInternal directly for Tasks. if (ReferenceEquals(callBack, ThreadPoolGlobals.s_invokeAsyncStateMachineBox)) { if (!(state is IAsyncStateMachineBox)) { // The provided state must be the internal IAsyncStateMachineBox (Task) type ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.state); } UnsafeQueueUserWorkItemInternal((object)state!, preferLocal); return true; } EnsureInitialized(); ThreadPoolGlobals.workQueue.Enqueue( new QueueUserWorkItemCallbackDefaultContext<TState>(callBack!, state), forceGlobal: !preferLocal); return true; } public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object? state) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } EnsureInitialized(); object tpcallBack = new QueueUserWorkItemCallbackDefaultContext(callBack!, state); ThreadPoolGlobals.workQueue.Enqueue(tpcallBack, forceGlobal: true); return true; } public static bool UnsafeQueueUserWorkItem(IThreadPoolWorkItem callBack, bool preferLocal) { if (callBack == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.callBack); } if (callBack is Task) { // Prevent code from queueing a derived Task that also implements the interface, // as that would bypass Task.Start and its safety checks. ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.callBack); } UnsafeQueueUserWorkItemInternal(callBack!, preferLocal); return true; } internal static void UnsafeQueueUserWorkItemInternal(object callBack, bool preferLocal) { Debug.Assert((callBack is IThreadPoolWorkItem) ^ (callBack is Task)); EnsureInitialized(); ThreadPoolGlobals.workQueue.Enqueue(callBack, forceGlobal: !preferLocal); } // This method tries to take the target callback out of the current thread's queue. internal static bool TryPopCustomWorkItem(object workItem) { Debug.Assert(null != workItem); return ThreadPoolGlobals.threadPoolInitialized && // if not initialized, so there's no way this workitem was ever queued. ThreadPoolGlobals.workQueue.LocalFindAndPop(workItem); } // Get all workitems. Called by TaskScheduler in its debugger hooks. internal static IEnumerable<object> GetQueuedWorkItems() { // Enumerate global queue foreach (object workItem in ThreadPoolGlobals.workQueue.workItems) { yield return workItem; } // Enumerate each local queue foreach (ThreadPoolWorkQueue.WorkStealingQueue wsq in ThreadPoolWorkQueue.WorkStealingQueueList.Queues) { if (wsq != null && wsq.m_array != null) { object?[] items = wsq.m_array; for (int i = 0; i < items.Length; i++) { object? item = items[i]; if (item != null) { yield return item; } } } } } internal static IEnumerable<object> GetLocallyQueuedWorkItems() { ThreadPoolWorkQueue.WorkStealingQueue? wsq = ThreadPoolWorkQueueThreadLocals.threadLocals?.workStealingQueue; if (wsq != null && wsq.m_array != null) { object?[] items = wsq.m_array; for (int i = 0; i < items.Length; i++) { object? item = items[i]; if (item != null) yield return item; } } } internal static IEnumerable<object> GetGloballyQueuedWorkItems() => ThreadPoolGlobals.workQueue.workItems; private static object[] ToObjectArray(IEnumerable<object> workitems) { int i = 0; foreach (object item in workitems) { i++; } object[] result = new object[i]; i = 0; foreach (object item in workitems) { if (i < result.Length) // just in case someone calls us while the queues are in motion result[i] = item; i++; } return result; } // This is the method the debugger will actually call, if it ends up calling // into ThreadPool directly. Tests can use this to simulate a debugger, as well. internal static object[] GetQueuedWorkItemsForDebugger() => ToObjectArray(GetQueuedWorkItems()); internal static object[] GetGloballyQueuedWorkItemsForDebugger() => ToObjectArray(GetGloballyQueuedWorkItems()); internal static object[] GetLocallyQueuedWorkItemsForDebugger() => ToObjectArray(GetLocallyQueuedWorkItems()); /// <summary> /// Gets the number of work items that are currently queued to be processed. /// </summary> /// <remarks> /// For a thread pool implementation that may have different types of work items, the count includes all types that can /// be tracked, which may only be the user work items including tasks. Some implementations may also include queued /// timer and wait callbacks in the count. On Windows, the count is unlikely to include the number of pending IO /// completions, as they get posted directly to an IO completion port. /// </remarks> public static long PendingWorkItemCount { get { ThreadPoolWorkQueue workQueue = ThreadPoolGlobals.workQueue; return workQueue.LocalCount + workQueue.GlobalCount + PendingUnmanagedWorkItemCount; } } } }
using System; using System.IO; using System.Text; using Autofac.Extras.FakeItEasy; using Elasticsearch.Net.Connection; using Elasticsearch.Net.Tests.Unit.Stubs; using FakeItEasy; using FakeItEasy.Configuration; using FluentAssertions; using NUnit.Framework; namespace Elasticsearch.Net.Tests.Unit.Connection { [TestFixture] public class BuildInResponseTests { private class Requester<T> : IDisposable where T : class { public Requester( object responseValue, Func<ConnectionConfiguration, ConnectionConfiguration> configSetup, Func<ConnectionConfiguration, Stream, ElasticsearchResponse<Stream>> responseSetup, Func<IElasticsearchClient, ElasticsearchResponse<T>> call = null ) { var responseStream = CreateServerExceptionResponse(responseValue); this.Fake = new AutoFake(callsDoNothing: true); var connectionConfiguration = configSetup(new ConnectionConfiguration()); var response = responseSetup(connectionConfiguration, responseStream); this.Fake.Provide<IConnectionConfigurationValues>(connectionConfiguration); FakeCalls.ProvideDefaultTransport(this.Fake); this.GetCall = FakeCalls.GetSyncCall(this.Fake); this.GetCall.Returns(response); var client = this.Fake.Resolve<ElasticsearchClient>(); this.Result = call != null ? call(client) : client.Info<T>(); this.GetCall.MustHaveHappened(Repeated.Exactly.Once); } public ElasticsearchResponse<T> Result { get; set; } public IReturnValueConfiguration<ElasticsearchResponse<Stream>> GetCall { get; set; } public AutoFake Fake { get; set; } private MemoryStream CreateServerExceptionResponse(object responseValue) { if (responseValue is string) responseValue = string.Format(@"""{0}""", responseValue); var format = @"{{ ""value"": {0} }}"; this.ResponseBytes = Encoding.UTF8.GetBytes(string.Format(format, responseValue)); var stream = new MemoryStream(this.ResponseBytes); return stream; } public byte[] ResponseBytes { get; set; } public void Dispose() { if (this.Fake != null) this.Fake.Dispose(); } } private class Document { public object value { get; set; } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void Typed_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<Document>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); object v = r.Response.value; v.ShouldBeEquivalentTo(responseValue); r.ResponseRaw.Should().BeNull(); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void Typed_Ok_KeepResponse(object responseValue) { using (var request = new Requester<Document>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); object v = r.Response.value; v.ShouldBeEquivalentTo(responseValue); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void Typed_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<Document>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); Assert.IsNull(r.Response); r.ResponseRaw.Should().BeNull(); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void Typed_Bad_KeepResponse(object responseValue) { using (var request = new Requester<Document>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); Assert.IsNull(r.Response); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void DynamicDictionary_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<DynamicDictionary>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream), client => client.Info() )) { var r = request.Result; r.Success.Should().BeTrue(); object v = r.Response["value"]; v.ShouldBeEquivalentTo(responseValue); r.ResponseRaw.Should().BeNull(); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void DynamicDictionary_Ok_KeepResponse(object responseValue) { using (var request = new Requester<DynamicDictionary>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream), client => client.Info() )) { var r = request.Result; r.Success.Should().BeTrue(); object v = r.Response["value"]; v.ShouldBeEquivalentTo(responseValue); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void DynamicDictionary_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<DynamicDictionary>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream), client => client.Info() )) { var r = request.Result; r.Success.Should().BeFalse(); Assert.IsNull(r.Response); r.ResponseRaw.Should().BeNull(); } } [Test] [TestCase(505)] [TestCase(10.2)] [TestCase("hello world")] public void DynamicDictionary_Bad_KeepResponse(object responseValue) { using (var request = new Requester<DynamicDictionary>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream), client => client.Info() )) { var r = request.Result; r.Success.Should().BeFalse(); Assert.IsNull(r.Response); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void ByteArray_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<byte[]>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void ByteArray_Ok_KeepResponse(object responseValue) { using (var request = new Requester<byte[]>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void ByteArray_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<byte[]>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void ByteArray_Bad_KeepResponse(object responseValue) { using (var request = new Requester<byte[]>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); r.Response.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void String_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<string>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void String_Ok_KeepResponse(object responseValue) { using (var request = new Requester<string>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void String_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<string>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void String_Bad_KeepResponse(object responseValue) { using (var request = new Requester<string>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); Encoding.UTF8.GetBytes(r.Response).Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); r.ResponseRaw.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } } [Test, TestCase(505123)] public void Stream_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<Stream>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); using (r.Response) using (var ms = new MemoryStream()) { r.Response.CopyTo(ms); var bytes = ms.ToArray(); bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void Stream_Ok_KeepResponse(object responseValue) { using (var request = new Requester<Stream>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); using (r.Response) using (var ms = new MemoryStream()) { r.Response.CopyTo(ms); var bytes = ms.ToArray(); bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } //raw response is ALWAYS null when requesting the stream directly //the client should not interfere with it r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void Stream_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<Stream>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); using (r.Response) using (var ms = new MemoryStream()) { r.Response.CopyTo(ms); var bytes = ms.ToArray(); bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void Stream_Bad_KeepResponse(object responseValue) { using (var request = new Requester<Stream>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); using (r.Response) using (var ms = new MemoryStream()) { r.Response.CopyTo(ms); var bytes = ms.ToArray(); bytes.Should().NotBeNull().And.BeEquivalentTo(request.ResponseBytes); } //raw response is ALWAYS null when requesting the stream directly //the client should not interfere with it r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void VoidResponse_Ok_DiscardResponse(object responseValue) { using (var request = new Requester<VoidResponse>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); //Response and rawresponse should ALWAYS be null for VoidResponse responses r.Response.Should().BeNull(); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void VoidResponse_Ok_KeepResponse(object responseValue) { using (var request = new Requester<VoidResponse>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Ok(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeTrue(); //Response and rawresponse should ALWAYS be null for VoidResponse responses r.Response.Should().BeNull(); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void VoidResponse_Bad_DiscardResponse(object responseValue) { using (var request = new Requester<VoidResponse>( responseValue, settings => settings.ExposeRawResponse(false), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); //Response and rawresponse should ALWAYS be null for VoidResponse responses r.Response.Should().BeNull(); r.ResponseRaw.Should().BeNull(); } } [Test, TestCase(505123)] public void VoidResponse_Bad_KeepResponse(object responseValue) { using (var request = new Requester<VoidResponse>( responseValue, settings => settings.ExposeRawResponse(true), (settings, stream) => FakeResponse.Bad(settings, response: stream) )) { var r = request.Result; r.Success.Should().BeFalse(); //Response and rawresponse should ALWAYS be null for VoidResponse responses r.Response.Should().BeNull(); r.ResponseRaw.Should().BeNull(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml; using Examine; using NUnit.Framework; using umbraco.BusinessLogic; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Tests.PublishedContent; using Umbraco.Tests.TestHelpers; using Umbraco.Web; using Umbraco.Web.PublishedCache; using Umbraco.Web.PublishedCache.XmlPublishedCache; namespace Umbraco.Tests.Cache.PublishedCache { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture] public class PublishMediaCacheTests : BaseWebTest { protected override void FreezeResolution() { PublishedContentModelFactoryResolver.Current = new PublishedContentModelFactoryResolver(); base.FreezeResolution(); } [Test] public void Get_Root_Docs() { var user = new User(0); var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); var mRoot1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot1", mType, user, -1); var mRoot2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot2", mType, user, -1); var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot1.Id); var mChild2 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child2", mType, user, mRoot2.Id); var ctx = GetUmbracoContext("/test", 1234); var cache = new ContextualPublishedMediaCache(new PublishedMediaCache(ctx.Application), ctx); var roots = cache.GetAtRoot(); Assert.AreEqual(2, roots.Count()); Assert.IsTrue(roots.Select(x => x.Id).ContainsAll(new[] {mRoot1.Id, mRoot2.Id})); } [Test] public void Get_Item_Without_Examine() { var user = new User(0); var mType = global::umbraco.cms.businesslogic.media.MediaType.MakeNew(user, "TestMediaType"); var mRoot = global::umbraco.cms.businesslogic.media.Media.MakeNew("MediaRoot", mType, user, -1); var mChild1 = global::umbraco.cms.businesslogic.media.Media.MakeNew("Child1", mType, user, mRoot.Id); var publishedMedia = PublishedMediaTests.GetNode(mRoot.Id, GetUmbracoContext("/test", 1234)); Assert.AreEqual(mRoot.Id, publishedMedia.Id); Assert.AreEqual(mRoot.CreateDateTime.ToString("dd/MM/yyyy HH:mm:ss"), publishedMedia.CreateDate.ToString("dd/MM/yyyy HH:mm:ss")); Assert.AreEqual(mRoot.User.Id, publishedMedia.CreatorId); Assert.AreEqual(mRoot.User.Name, publishedMedia.CreatorName); Assert.AreEqual(mRoot.ContentType.Alias, publishedMedia.DocumentTypeAlias); Assert.AreEqual(mRoot.ContentType.Id, publishedMedia.DocumentTypeId); Assert.AreEqual(mRoot.Level, publishedMedia.Level); Assert.AreEqual(mRoot.Text, publishedMedia.Name); Assert.AreEqual(mRoot.Path, publishedMedia.Path); Assert.AreEqual(mRoot.sortOrder, publishedMedia.SortOrder); Assert.IsNull(publishedMedia.Parent); } [TestCase("id")] [TestCase("nodeId")] [TestCase("__NodeId")] public void DictionaryDocument_Id_Keys(string key) { var dicDoc = GetDictionaryDocument(idKey: key); DoAssert(dicDoc); } [TestCase("template")] [TestCase("templateId")] public void DictionaryDocument_Template_Keys(string key) { var dicDoc = GetDictionaryDocument(templateKey: key); DoAssert(dicDoc); } [TestCase("nodeName")] [TestCase("__nodeName")] public void DictionaryDocument_NodeName_Keys(string key) { var dicDoc = GetDictionaryDocument(nodeNameKey: key); DoAssert(dicDoc); } [TestCase("nodeTypeAlias")] [TestCase("__NodeTypeAlias")] public void DictionaryDocument_NodeTypeAlias_Keys(string key) { var dicDoc = GetDictionaryDocument(nodeTypeAliasKey: key); DoAssert(dicDoc); } [TestCase("path")] [TestCase("__Path")] public void DictionaryDocument_Path_Keys(string key) { var dicDoc = GetDictionaryDocument(pathKey: key); DoAssert(dicDoc); } [Test] public void DictionaryDocument_Key() { var key = Guid.NewGuid(); var dicDoc = GetDictionaryDocument(keyVal: key); DoAssert(dicDoc, keyVal: key); } [Test] public void DictionaryDocument_Get_Children() { var child1 = GetDictionaryDocument(idVal: 222333); var child2 = GetDictionaryDocument(idVal: 444555); var dicDoc = GetDictionaryDocument(children: new List<IPublishedContent>() { child1, child2 }); Assert.AreEqual(2, dicDoc.Children.Count()); Assert.AreEqual(222333, dicDoc.Children.ElementAt(0).Id); Assert.AreEqual(444555, dicDoc.Children.ElementAt(1).Id); } [TestCase(true)] [TestCase(false)] public void Convert_From_Search_Result(bool withKey) { var ctx = GetUmbracoContext("/test", 1234); var key = Guid.NewGuid(); var result = new SearchResult() { Id = 1234, Score = 1 }; result.Fields.Add("__IndexType", "media"); result.Fields.Add("__NodeId", "1234"); result.Fields.Add("__NodeTypeAlias", Constants.Conventions.MediaTypes.Image); result.Fields.Add("__Path", "-1,1234"); result.Fields.Add("__nodeName", "Test"); result.Fields.Add("id", "1234"); if (withKey) result.Fields.Add("key", key.ToString()); result.Fields.Add("nodeName", "Test"); result.Fields.Add("nodeTypeAlias", Constants.Conventions.MediaTypes.Image); result.Fields.Add("parentID", "-1"); result.Fields.Add("path", "-1,1234"); result.Fields.Add("updateDate", "2012-07-16T10:34:09"); result.Fields.Add("writerName", "Shannon"); var store = new PublishedMediaCache(ctx.Application); var doc = store.CreateFromCacheValues(store.ConvertFromSearchResult(result)); DoAssert(doc, 1234, withKey ? key : default(Guid), 0, 0, "", "Image", 0, "Shannon", "", 0, 0, "-1,1234", default(DateTime), DateTime.Parse("2012-07-16T10:34:09"), 2); Assert.AreEqual(null, doc.Parent); } [TestCase(true)] [TestCase(false)] public void Convert_From_XPath_Navigator(bool withKey) { var ctx = GetUmbracoContext("/test", 1234); var key = Guid.NewGuid(); var xmlDoc = GetMediaXml(); if (withKey) ((XmlElement)xmlDoc.DocumentElement.FirstChild).SetAttribute("key", key.ToString()); var navigator = xmlDoc.SelectSingleNode("/root/Image").CreateNavigator(); var cache = new PublishedMediaCache(ctx.Application); var doc = cache.CreateFromCacheValues(cache.ConvertFromXPathNavigator(navigator, true)); DoAssert(doc, 2000, withKey ? key : default(Guid), 0, 2, "image1", "Image", 2044, "Shannon", "Shannon2", 22, 33, "-1,2000", DateTime.Parse("2012-06-12T14:13:17"), DateTime.Parse("2012-07-20T18:50:43"), 1); Assert.AreEqual(null, doc.Parent); Assert.AreEqual(2, doc.Children.Count()); Assert.AreEqual(2001, doc.Children.ElementAt(0).Id); Assert.AreEqual(2002, doc.Children.ElementAt(1).Id); } private XmlDocument GetMediaXml() { var xml = @"<?xml version=""1.0"" encoding=""utf-8""?> <!DOCTYPE root[ <!ELEMENT Home ANY> <!ATTLIST Home id ID #REQUIRED> <!ELEMENT CustomDocument ANY> <!ATTLIST CustomDocument id ID #REQUIRED> ]> <root id=""-1""> <Image id=""2000"" parentID=""-1"" level=""1"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000"" isDoc=""""> <file><![CDATA[/media/1234/image1.png]]></file> <Image id=""2001"" parentID=""2000"" level=""2"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000,2001"" isDoc=""""> <file><![CDATA[/media/1234/image1.png]]></file> </Image> <Image id=""2002"" parentID=""2000"" level=""2"" writerID=""22"" creatorID=""33"" nodeType=""2044"" template=""0"" sortOrder=""2"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Image1"" urlName=""image1"" writerName=""Shannon"" creatorName=""Shannon2"" path=""-1,2000,2002"" isDoc=""""> <file><![CDATA[/media/1234/image1.png]]></file> </Image> </Image> </root>"; var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); return xmlDoc; } private Dictionary<string, string> GetDictionary( int id, Guid key, int parentId, string idKey, string templateKey, string nodeNameKey, string nodeTypeAliasKey, string pathKey) { return new Dictionary<string, string>() { {idKey, id.ToString()}, {"key", key.ToString()}, {templateKey, "333"}, {"sortOrder", "44"}, {nodeNameKey, "Testing"}, {"urlName", "testing"}, {nodeTypeAliasKey, "myType"}, {"nodeType", "22"}, {"writerName", "Shannon"}, {"creatorName", "Shannon2"}, {"writerID", "33"}, {"creatorID", "44"}, {pathKey, "1,2,3,4,5"}, {"createDate", "2012-01-02"}, {"updateDate", "2012-01-03"}, {"level", "3"}, {"parentID", parentId.ToString()} }; } private PublishedMediaCache.DictionaryPublishedContent GetDictionaryDocument( string idKey = "id", string templateKey = "template", string nodeNameKey = "nodeName", string nodeTypeAliasKey = "nodeTypeAlias", string pathKey = "path", int idVal = 1234, Guid keyVal = default(Guid), int parentIdVal = 321, IEnumerable<IPublishedContent> children = null) { if (children == null) children = new List<IPublishedContent>(); var dicDoc = new PublishedMediaCache.DictionaryPublishedContent( //the dictionary GetDictionary(idVal, keyVal, parentIdVal, idKey, templateKey, nodeNameKey, nodeTypeAliasKey, pathKey), //callback to get the parent d => new PublishedMediaCache.DictionaryPublishedContent( GetDictionary(parentIdVal, default(Guid), -1, idKey, templateKey, nodeNameKey, nodeTypeAliasKey, pathKey), //there is no parent a => null, //we're not going to test this so ignore (dd, n) => new List<IPublishedContent>(), (dd, a) => dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(a)), null, false), //callback to get the children (dd, n) => children, (dd, a) => dd.Properties.FirstOrDefault(x => x.PropertyTypeAlias.InvariantEquals(a)), null, false); return dicDoc; } private void DoAssert( PublishedMediaCache.DictionaryPublishedContent dicDoc, int idVal = 1234, Guid keyVal = default(Guid), int templateIdVal = 333, int sortOrderVal = 44, string urlNameVal = "testing", string nodeTypeAliasVal = "myType", int nodeTypeIdVal = 22, string writerNameVal = "Shannon", string creatorNameVal = "Shannon2", int writerIdVal = 33, int creatorIdVal = 44, string pathVal = "1,2,3,4,5", DateTime? createDateVal = null, DateTime? updateDateVal = null, int levelVal = 3, int parentIdVal = 321) { if (!createDateVal.HasValue) createDateVal = DateTime.Parse("2012-01-02"); if (!updateDateVal.HasValue) updateDateVal = DateTime.Parse("2012-01-03"); DoAssert((IPublishedContent)dicDoc, idVal, keyVal, templateIdVal, sortOrderVal, urlNameVal, nodeTypeAliasVal, nodeTypeIdVal, writerNameVal, creatorNameVal, writerIdVal, creatorIdVal, pathVal, createDateVal, updateDateVal, levelVal); //now validate the parentId that has been parsed, this doesn't exist on the IPublishedContent Assert.AreEqual(parentIdVal, dicDoc.ParentId); } private void DoAssert( IPublishedContent doc, int idVal = 1234, Guid keyVal = default(Guid), int templateIdVal = 333, int sortOrderVal = 44, string urlNameVal = "testing", string nodeTypeAliasVal = "myType", int nodeTypeIdVal = 22, string writerNameVal = "Shannon", string creatorNameVal = "Shannon2", int writerIdVal = 33, int creatorIdVal = 44, string pathVal = "1,2,3,4,5", DateTime? createDateVal = null, DateTime? updateDateVal = null, int levelVal = 3) { if (!createDateVal.HasValue) createDateVal = DateTime.Parse("2012-01-02"); if (!updateDateVal.HasValue) updateDateVal = DateTime.Parse("2012-01-03"); Assert.AreEqual(idVal, doc.Id); Assert.AreEqual(keyVal, doc.GetKey()); Assert.AreEqual(templateIdVal, doc.TemplateId); Assert.AreEqual(sortOrderVal, doc.SortOrder); Assert.AreEqual(urlNameVal, doc.UrlName); Assert.AreEqual(nodeTypeAliasVal, doc.DocumentTypeAlias); Assert.AreEqual(nodeTypeIdVal, doc.DocumentTypeId); Assert.AreEqual(writerNameVal, doc.WriterName); Assert.AreEqual(creatorNameVal, doc.CreatorName); Assert.AreEqual(writerIdVal, doc.WriterId); Assert.AreEqual(creatorIdVal, doc.CreatorId); Assert.AreEqual(pathVal, doc.Path); Assert.AreEqual(createDateVal.Value, doc.CreateDate); Assert.AreEqual(updateDateVal.Value, doc.UpdateDate); Assert.AreEqual(levelVal, doc.Level); } } }
// // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // /** * Namespace: System.Web.UI * Class: StateBag * * Author: Gaurav Vaish * Maintainer: gvaish@iitk.ac.in * Implementation: yes * Contact: <gvaish@iitk.ac.in> * Status: 100% * * (C) Gaurav Vaish (2001) */ using System; using System.Web; using System.Collections; using System.Collections.Specialized; namespace System.Web.UI { public sealed class StateBag : IStateManager, IDictionary, ICollection, IEnumerable { private bool marked; private HybridDictionary bag; public StateBag (bool ignoreCase) { Initialize (ignoreCase); } public StateBag () { Initialize (false); } private void Initialize (bool ignoreCase) { marked = false; bag = new HybridDictionary (ignoreCase); } public int Count { get { return bag.Count; } } public object this [string key] { get { if (key == null || key.Length == 0) throw new ArgumentException (HttpRuntime.FormatResourceString ("Key_Cannot_Be_Null")); object val = bag [key]; if (val is StateItem) return ((StateItem) val).Value; return null; // } set { Add (key, value); } } object IDictionary.this [object key] { get { return this [(string) key] as object; } set { Add ((string) key, value); } } public ICollection Keys { get { return bag.Keys; } } public ICollection Values { get { return bag.Values; } } public StateItem Add (string key, object value) { if (key == null || key.Length == 0) throw new ArgumentException (HttpRuntime.FormatResourceString ("Key_Cannot_Be_Null")); StateItem val = bag [key] as StateItem; //don't throw exception when null if(val == null) { if(value != null || marked) { val = new StateItem (value); bag.Add (key, val); } } else if (value == null && !marked) bag.Remove (key); else val.Value = value; if (val != null && marked) { val.IsDirty = true; } return val; } public void Clear () { bag.Clear (); } public IDictionaryEnumerator GetEnumerator () { return bag.GetEnumerator (); } public bool IsItemDirty (string key) { object o = bag [key]; if (o is StateItem) return ((StateItem) o).IsDirty; return false; } public void Remove (string key) { bag.Remove (key); } /// <summary> /// Undocumented /// </summary> public void SetItemDirty (string key, bool dirty) { if (bag [key] is StateItem) ((StateItem) bag [key]).IsDirty = dirty; } internal bool IsTrackingViewState { get { return marked; } } internal void LoadViewState (object state) { if(state!=null) { Pair pair = (Pair) state; ArrayList keyList = (ArrayList) (pair.First); ArrayList valList = (ArrayList) (pair.Second); int valCount = valList.Count; for(int i = 0; i < keyList.Count; i++) { if (i < valCount) Add ((string) keyList [i], valList [i]); else Add ((string) keyList [i], null); } } } internal object SaveViewState () { if(bag.Count > 0) { ArrayList keyList = null, valList = null; foreach (string key in bag.Keys) { StateItem item = (StateItem) bag [key]; if (item.IsDirty) { if (keyList == null) { keyList = new ArrayList (); valList = new ArrayList (); } keyList.Add (key); valList.Add (item.Value); } } if (keyList!=null) return new Pair (keyList, valList); } return null; } internal void TrackViewState() { marked = true; } IEnumerator IEnumerable.GetEnumerator () { return GetEnumerator (); } void IStateManager.LoadViewState (object savedState) { LoadViewState (savedState); } object IStateManager.SaveViewState () { return SaveViewState (); } void IStateManager.TrackViewState () { TrackViewState (); } bool IStateManager.IsTrackingViewState { get { return IsTrackingViewState; } } void ICollection.CopyTo (Array array, int index) { Values.CopyTo (array, index); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return this; } } void IDictionary.Add (object key, object value) { Add ((string) key, value); } void IDictionary.Remove (object key) { Remove ((string) key); } bool IDictionary.Contains (object key) { return bag.Contains ((string) key); } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } #if NET_2_0 public void SetDirty () { foreach (string key in bag.Keys) SetItemDirty (key, true); } #endif } }
using System; using System.IO; using System.Text; using System.Collections; using Zeus.ErrorHandling; using Zeus.Legacy; namespace Zeus { /// <summary> /// Summary description for ZeusTemplateParser. /// </summary> public class ZeusTemplateParser { public ZeusTemplateParser() {} public static ZeusTemplateHeader LoadTemplateHeader(string filePath) { ZeusTemplateParser parser = new ZeusTemplateParser(); return parser.LoadTemplateHeaderStruct(filePath); } public ZeusTemplateHeader LoadTemplateHeaderStruct(string filePath) { ZeusTemplateHeader header = new ZeusTemplateHeader(); try { StreamReader reader = new StreamReader(filePath, true); LoadIntoTemplateHeader(reader, filePath, ref header); reader.Close(); } catch (ZeusParseException ex) { header = new ZeusTemplateHeader(); throw ex; } return header; } public ZeusTemplate LoadTemplate(string filePath) { ZeusTemplate template = new ZeusTemplate(); LoadIntoTemplate(filePath, template); return template; } public void LoadIntoTemplate(string filePath, ZeusTemplate template) { try { StreamReader reader = new StreamReader(filePath, true); LoadIntoTemplate(reader, filePath, template); reader.Close(); } catch (ZeusParseException parseEx) { if (parseEx.ParseError == ZeusParseError.OutdatedTemplateStructure) { LegacyTemplateParser parser = new LegacyTemplateParser(); parser.LoadIntoTemplate(filePath, template); } else { throw parseEx; } } } public ZeusTemplate LoadIntoTemplate(Stream stream, string filepath, ZeusTemplate template) { StreamReader reader = new StreamReader(stream, true); LoadIntoTemplate(reader, filepath, template); reader.Close(); return template; } public void LoadIntoTemplateHeader(StreamReader reader, string filepath, ref ZeusTemplateHeader header) { char[] whitespace = new char[4] {'\n', '\r', '\t', ' '}; string key, val, line; int tagLength = ZeusConstants.START_DIRECTIVE.Length; int x, y; bool inGroupMode = false; string startGroupTag = string.Empty; StringBuilder builder = null; if (filepath != null) { int lastIndex = filepath.LastIndexOf('\\'); header.FileName = filepath.Substring(lastIndex + 1); header.FilePath = filepath.Substring(0, lastIndex + 1); } line = reader.ReadLine(); while (line != null) { if (line.StartsWith(ZeusConstants.START_DIRECTIVE)) { x = line.IndexOfAny(whitespace); if (x < 0) x = line.Length; y = x - tagLength; key = line.Substring(tagLength, y); if (!inGroupMode) { if (IsGroupStartTag(key)) { inGroupMode = true; startGroupTag = key; builder = new StringBuilder(); } else { val = line.Substring(x).Trim(); AssignProperty(ref header, key, val); } } else { if (IsGroupEndTag(key)) { AssignGroup(ref header, key, builder); inGroupMode = false; startGroupTag = string.Empty; } else { //TODO: *** Could put a warning here. Possibly have a warnings collection. Maybe a CompileInfo class? builder.Append(line + "\r\n"); } } } else if (inGroupMode) { builder.Append(line + "\r\n"); } line = reader.ReadLine(); } } public void LoadIntoTemplate(StreamReader reader, string filepath, ZeusTemplate template) { char[] whitespace = new char[4] {'\n', '\r', '\t', ' '}; string key, val, line; int tagLength = ZeusConstants.START_DIRECTIVE.Length; int x, y; bool inGroupMode = false; string startGroupTag = string.Empty; StringBuilder builder = null; if (filepath != null) { int lastIndex = filepath.LastIndexOf('\\'); template.FileName = filepath.Substring(lastIndex + 1); template.FilePath = filepath.Substring(0, lastIndex + 1); } line = reader.ReadLine(); if (!line.StartsWith(ZeusConstants.START_DIRECTIVE + ZeusConstants.Directives.TYPE)) { throw new ZeusParseException(template, ZeusParseError.OutdatedTemplateStructure, "OutdatedTemplateStructure"); } while (line != null) { if (line.StartsWith(ZeusConstants.START_DIRECTIVE)) { x = line.IndexOfAny(whitespace); if (x < 0) x = line.Length; y = x - tagLength; key = line.Substring(tagLength, y); if (!inGroupMode) { if (IsGroupStartTag(key)) { inGroupMode = true; startGroupTag = key; builder = new StringBuilder(); } else { val = line.Substring(x).Trim(); AssignProperty(template, key, val); } } else { if (IsGroupEndTag(key)) { AssignGroup(template, key, builder); inGroupMode = false; startGroupTag = string.Empty; } else { //TODO: *** Could put a warning here. Possibly have a warnings collection. Maybe a CompileInfo class? builder.Append(line + "\r\n"); } } } else if (inGroupMode) { builder.Append(line + "\r\n"); } line = reader.ReadLine(); } } protected void AssignGroup(ZeusTemplate template, string key, StringBuilder builder) { switch (key) { case ZeusConstants.Directives.BODY_END: template.BodySegment.CodeUnparsed = builder.ToString().TrimEnd(); break; case ZeusConstants.Directives.GUI_END: template.GuiSegment.CodeUnparsed = builder.ToString().TrimEnd(); break; case ZeusConstants.Directives.COMMENTS_END: template.Comments = builder.ToString().TrimEnd(); break; } } protected void AssignProperty(ZeusTemplate template, string key, string val) { template.AddDirective(key, val); switch (key) { case ZeusConstants.Directives.TYPE: template.Type = val; break; case ZeusConstants.Directives.SOURCE_TYPE: template.SourceType = val; break; case ZeusConstants.Directives.BODY_ENGINE: template.BodySegment.Engine = val; break; case ZeusConstants.Directives.BODY_LANGUAGE: template.BodySegment.Language = val; break; case ZeusConstants.Directives.BODY_MODE: template.BodySegment.Mode = val; break; case ZeusConstants.Directives.GUI_ENGINE: template.GuiSegment.Engine = val; break; case ZeusConstants.Directives.GUI_LANGUAGE: template.GuiSegment.Language = val; break; case ZeusConstants.Directives.OUTPUT_LANGUAGE: template.OutputLanguage = val; break; case ZeusConstants.Directives.UNIQUEID: template.UniqueID = val; break; case ZeusConstants.Directives.TITLE: template.Title = val; break; case ZeusConstants.Directives.NAMESPACE: template.NamespacePathString = val; break; case ZeusConstants.Directives.BODY_TAG_START: template.TagStart = val; break; case ZeusConstants.Directives.BODY_TAG_END: template.TagEnd = val; break; case ZeusConstants.Directives.INCLUDE_TEMPLATE: template.AddIncludedTemplatePath(val); break; } } protected void AssignGroup(ref ZeusTemplateHeader header, string key, StringBuilder builder) { switch (key) { case ZeusConstants.Directives.COMMENTS_END: header.Comments = builder.ToString().TrimEnd(); break; } } protected void AssignProperty(ref ZeusTemplateHeader header, string key, string val) { switch (key) { case ZeusConstants.Directives.UNIQUEID: header.UniqueID = val; break; case ZeusConstants.Directives.TITLE: header.Title = val; break; case ZeusConstants.Directives.NAMESPACE: header.Namespace = val; break; case ZeusConstants.Directives.SOURCE_TYPE: header.SourceType = val; break; } } protected bool IsGroupStartTag(string key) { bool isValid = false; switch (key) { case ZeusConstants.Directives.BODY_BEGIN: case ZeusConstants.Directives.COMMENTS_BEGIN: case ZeusConstants.Directives.GUI_BEGIN: isValid = true; break; } return isValid; } protected bool IsGroupEndTag(string key) { bool isValid = false; switch (key) { case ZeusConstants.Directives.BODY_END: case ZeusConstants.Directives.COMMENTS_END: case ZeusConstants.Directives.GUI_END: isValid = true; break; } return isValid; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using Glimpse.Core.Extensibility; namespace Glimpse.Core.Framework { /// <summary> /// Contains all configuration required by <see cref="IGlimpseRuntime"/> instances to execute. /// </summary> public class GlimpseConfiguration : IGlimpseConfiguration { private static IMessageBroker messageBroker; private static Func<IExecutionTimer> timerStrategy; private static ILogger logger; private ICollection<IClientScript> clientScripts; private IResource defaultResource; private string endpointBaseUri; private IFrameworkProvider frameworkProvider; private IHtmlEncoder htmlEncoder; private IPersistenceStore persistenceStore; private ICollection<IInspector> inspectors; private IProxyFactory proxyFactory; private ResourceEndpointConfiguration resourceEndpoint; private ICollection<IResource> resources; private ICollection<IRuntimePolicy> runtimePolicies; private ISerializer serializer; private ICollection<ITab> tabs; private ICollection<IDisplay> displays; private static RuntimePolicy defaultRuntimePolicy; private static Func<RuntimePolicy> runtimePolicyStrategy; private string hash; /// <summary> /// Initializes a new instance of the <see cref="GlimpseConfiguration" /> class. /// </summary> /// <param name="frameworkProvider">The framework provider.</param> /// <param name="endpointConfiguration">The resource endpoint configuration.</param> /// <param name="clientScripts">The client scripts collection.</param> /// <param name="logger">The logger.</param> /// <param name="defaultRuntimePolicy">The default runtime policy.</param> /// <param name="htmlEncoder">The Html encoder.</param> /// <param name="persistenceStore">The persistence store.</param> /// <param name="inspectors">The inspectors collection.</param> /// <param name="resources">The resources collection.</param> /// <param name="serializer">The serializer.</param> /// <param name="tabs">The tabs collection.</param> /// <param name="displays">The displays collection.</param> /// <param name="runtimePolicies">The runtime policies collection.</param> /// <param name="defaultResource">The default resource.</param> /// <param name="proxyFactory">The proxy factory.</param> /// <param name="messageBroker">The message broker.</param> /// <param name="endpointBaseUri">The endpoint base Uri.</param> /// <param name="timerStrategy">The timer strategy.</param> /// <param name="runtimePolicyStrategy">The runtime policy strategy.</param> /// <exception cref="System.ArgumentNullException">An exception is thrown if any parameter is <c>null</c>.</exception> public GlimpseConfiguration( IFrameworkProvider frameworkProvider, ResourceEndpointConfiguration endpointConfiguration, ICollection<IClientScript> clientScripts, ILogger logger, RuntimePolicy defaultRuntimePolicy, IHtmlEncoder htmlEncoder, IPersistenceStore persistenceStore, ICollection<IInspector> inspectors, ICollection<IResource> resources, ISerializer serializer, ICollection<ITab> tabs, ICollection<IDisplay> displays, ICollection<IRuntimePolicy> runtimePolicies, IResource defaultResource, IProxyFactory proxyFactory, IMessageBroker messageBroker, string endpointBaseUri, Func<IExecutionTimer> timerStrategy, Func<RuntimePolicy> runtimePolicyStrategy) { if (frameworkProvider == null) { throw new ArgumentNullException("frameworkProvider"); } if (endpointConfiguration == null) { throw new ArgumentNullException("endpointConfiguration"); } if (logger == null) { throw new ArgumentNullException("logger"); } if (htmlEncoder == null) { throw new ArgumentNullException("htmlEncoder"); } if (persistenceStore == null) { throw new ArgumentNullException("persistenceStore"); } if (clientScripts == null) { throw new ArgumentNullException("clientScripts"); } if (resources == null) { throw new ArgumentNullException("inspectors"); } if (serializer == null) { throw new ArgumentNullException("serializer"); } if (tabs == null) { throw new ArgumentNullException("tabs"); } if (displays == null) { throw new ArgumentNullException("displays"); } if (runtimePolicies == null) { throw new ArgumentNullException("runtimePolicies"); } if (defaultResource == null) { throw new ArgumentNullException("defaultResource"); } if (proxyFactory == null) { throw new ArgumentNullException("proxyFactory"); } if (messageBroker == null) { throw new ArgumentNullException("messageBroker"); } if (endpointBaseUri == null) { throw new ArgumentNullException("endpointBaseUri"); } if (timerStrategy == null) { throw new ArgumentNullException("timerStrategy"); } if (runtimePolicyStrategy == null) { throw new ArgumentNullException("runtimePolicyStrategy"); } Logger = logger; ClientScripts = clientScripts; FrameworkProvider = frameworkProvider; HtmlEncoder = htmlEncoder; PersistenceStore = persistenceStore; Inspectors = inspectors; ResourceEndpoint = endpointConfiguration; Resources = resources; Serializer = serializer; Tabs = tabs; Displays = displays; RuntimePolicies = runtimePolicies; DefaultRuntimePolicy = defaultRuntimePolicy; DefaultResource = defaultResource; ProxyFactory = proxyFactory; MessageBroker = messageBroker; EndpointBaseUri = endpointBaseUri; TimerStrategy = timerStrategy; RuntimePolicyStrategy = runtimePolicyStrategy; } /// <summary> /// Gets or sets the client scripts collection. /// </summary> /// <value> /// The client scripts. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public ICollection<IClientScript> ClientScripts { get { return clientScripts; } set { if (value == null) { throw new ArgumentNullException("value"); } clientScripts = value; } } /// <summary> /// Gets or sets the default <see cref="IResource"/> to execute. /// </summary> /// <value> /// The default resource. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public IResource DefaultResource { get { return defaultResource; } set { if (value == null) { throw new ArgumentNullException("value"); } defaultResource = value; } } /// <summary> /// Gets or sets the default runtime policy. /// </summary> /// <value> /// The default runtime policy. /// </value> public RuntimePolicy DefaultRuntimePolicy { get { return defaultRuntimePolicy; } set { defaultRuntimePolicy = value; } } /// <summary> /// Gets or sets the endpoint base URI. /// </summary> /// <value> /// The endpoint base URI. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public string EndpointBaseUri { get { return endpointBaseUri; } set { if (value == null) { throw new ArgumentNullException("value"); } endpointBaseUri = value; } } /// <summary> /// Gets or sets the <see cref="IFrameworkProvider"/>. /// </summary> /// <value> /// The configured <see cref="IFrameworkProvider"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public IFrameworkProvider FrameworkProvider { get { return frameworkProvider; } set { if (value == null) { throw new ArgumentNullException("value"); } frameworkProvider = value; } } /// <summary> /// Gets or sets the <see cref="IHtmlEncoder"/>. /// </summary> /// <value> /// The configured <see cref="IHtmlEncoder"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public IHtmlEncoder HtmlEncoder { get { return htmlEncoder; } set { if (value == null) { throw new ArgumentNullException("value"); } htmlEncoder = value; } } /// <summary> /// Gets or sets the <see cref="ILogger"/>. /// </summary> /// <value> /// The configured <see cref="ILogger"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public ILogger Logger { get { return logger; } set { if (value == null) { throw new ArgumentNullException("value"); } logger = value; } } /// <summary> /// Gets or sets the <see cref="IMessageBroker"/>. /// </summary> /// <value> /// The configured <see cref="IMessageBroker"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public IMessageBroker MessageBroker { get { return messageBroker; } set { if (value == null) { throw new ArgumentNullException("value"); } messageBroker = value; } } /// <summary> /// Gets or sets the <see cref="IPersistenceStore"/>. /// </summary> /// <value> /// The configured <see cref="IPersistenceStore"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public IPersistenceStore PersistenceStore { get { return persistenceStore; } set { if (value == null) { throw new ArgumentNullException("value"); } persistenceStore = value; } } /// <summary> /// Gets or sets the collection of <see cref="IInspector"/>. /// </summary> /// <value> /// The configured collection of <see cref="IInspector"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public ICollection<IInspector> Inspectors { get { return inspectors; } set { if (value == null) { throw new ArgumentNullException("value"); } inspectors = value; } } /// <summary> /// Gets or sets the <see cref="IProxyFactory"/>. /// </summary> /// <value> /// The configured <see cref="IProxyFactory"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public IProxyFactory ProxyFactory { get { return proxyFactory; } set { if (value == null) { throw new ArgumentNullException("value"); } proxyFactory = value; } } /// <summary> /// Gets or sets the <see cref="ResourceEndpointConfiguration"/>. /// </summary> /// <value> /// The configured <see cref="ResourceEndpointConfiguration"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public ResourceEndpointConfiguration ResourceEndpoint { get { return resourceEndpoint; } set { if (value == null) { throw new ArgumentNullException("value"); } resourceEndpoint = value; } } /// <summary> /// Gets or sets the collection of <see cref="IResource"/>. /// </summary> /// <value> /// The configured collection of <see cref="IResource"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public ICollection<IResource> Resources { get { return resources; } set { if (value == null) { throw new ArgumentNullException("value"); } resources = value; } } /// <summary> /// Gets or sets the collection of <see cref="IRuntimePolicy"/>. /// </summary> /// <value> /// The configured collection of <see cref="IRuntimePolicy"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public ICollection<IRuntimePolicy> RuntimePolicies { get { return runtimePolicies; } set { if (value == null) { throw new ArgumentNullException("value"); } runtimePolicies = value; } } /// <summary> /// Gets or sets the <see cref="RuntimePolicy"/> strategy. /// </summary> /// <value> /// The configured <see cref="RuntimePolicy"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public Func<RuntimePolicy> RuntimePolicyStrategy { get { return runtimePolicyStrategy; } set { if (value == null) { throw new ArgumentNullException("value"); } runtimePolicyStrategy = value; } } /// <summary> /// Gets or sets the <see cref="ISerializer"/>. /// </summary> /// <value> /// The configured <see cref="ISerializer"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public ISerializer Serializer { get { return serializer; } set { if (value == null) { throw new ArgumentNullException("value"); } serializer = value; } } /// <summary> /// Gets or sets the collection of <see cref="ITab"/>. /// </summary> /// <value> /// The configured <see cref="ITab"/>. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public ICollection<ITab> Tabs { get { return tabs; } set { if (value == null) { throw new ArgumentNullException("value"); } tabs = value; } } public ICollection<IDisplay> Displays { get { return displays; } set { if (value == null) { throw new ArgumentNullException("value"); } displays = value; } } /// <summary> /// Gets or sets the <see cref="IExecutionTimer"/> strategy. /// </summary> /// <value> /// The configured <see cref="IExecutionTimer"/> strategy. /// </value> /// <exception cref="System.ArgumentNullException">An exception is thrown if the value is set to <c>null</c>.</exception> public Func<IExecutionTimer> TimerStrategy { get { return timerStrategy; } set { if (value == null) { throw new ArgumentNullException("value"); } timerStrategy = value; } } public string Hash { get { if (!string.IsNullOrEmpty(hash)) { return hash; } var configuredTypes = new List<Type> { GetType() }; configuredTypes.AddRange(Tabs.Select(tab => tab.GetType()).OrderBy(type => type.Name)); configuredTypes.AddRange(Inspectors.Select(inspector => inspector.GetType()).OrderBy(type => type.Name)); configuredTypes.AddRange(Resources.Select(resource => resource.GetType()).OrderBy(type => type.Name)); configuredTypes.AddRange(ClientScripts.Select(clientScript => clientScript.GetType()).OrderBy(type => type.Name)); configuredTypes.AddRange(RuntimePolicies.Select(policy => policy.GetType()).OrderBy(type => type.Name)); var crc32 = new Crc32(); var sb = new StringBuilder(); using (var memoryStream = new MemoryStream()) { var binaryFormatter = new BinaryFormatter(); binaryFormatter.Serialize(memoryStream, configuredTypes); memoryStream.Position = 0; var computeHash = crc32.ComputeHash(memoryStream); foreach (var b in computeHash) { sb.Append(b.ToString("x2")); } } hash = sb.ToString(); return hash; } set { hash = value; } } [Obsolete("HACK: To support TraceListener with TraceSource via web.config")] public static ILogger GetLogger() { return logger; } [Obsolete("HACK: To support TraceListener with TraceSource via web.config")] public static Func<IExecutionTimer> GetConfiguredTimerStrategy() { return () => { try { return timerStrategy(); } catch { // Avoid exception being thrown from threads without access to request store return null; } }; } [Obsolete("HACK: To support TraceListener with TraceSource via web.config")] public static IMessageBroker GetConfiguredMessageBroker() { return messageBroker; } [Obsolete("HACK: To prevent unnecessary wrapping of SQL connections, commands etc")] public static RuntimePolicy GetDefaultRuntimePolicy() { return defaultRuntimePolicy; } [Obsolete("HACK: To prevent unnecessary wrapping of SQL connections, commands etc")] public static Func<RuntimePolicy> GetRuntimePolicyStategy() { return runtimePolicyStrategy; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading.Tests; using Xunit; namespace System.Threading.Threads.Tests { public static class ThreadTests { private const int UnexpectedTimeoutMilliseconds = ThreadTestHelpers.UnexpectedTimeoutMilliseconds; private const int ExpectedTimeoutMilliseconds = ThreadTestHelpers.ExpectedTimeoutMilliseconds; [Fact] public static void ConstructorTest() { Action<Thread> startThreadAndJoin = t => { t.IsBackground = true; t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); }; Action<int> verifyStackSize = stackSizeBytes => { // Try to stack-allocate an array to verify that close to the expected amount of stack space is actually // available int bufferSizeBytes = Math.Max(16 << 10, stackSizeBytes - (64 << 10)); unsafe { byte* buffer = stackalloc byte[bufferSizeBytes]; Volatile.Write(ref buffer[0], 0xff); Volatile.Write(ref buffer[bufferSizeBytes - 1], 0xff); } }; startThreadAndJoin(new Thread(() => verifyStackSize(0))); startThreadAndJoin(new Thread(() => verifyStackSize(0), 0)); startThreadAndJoin(new Thread(() => verifyStackSize(64 << 10), 64 << 10)); // 64 KB startThreadAndJoin(new Thread(() => verifyStackSize(16 << 20), 16 << 20)); // 16 MB startThreadAndJoin(new Thread(state => verifyStackSize(0))); startThreadAndJoin(new Thread(state => verifyStackSize(0), 0)); startThreadAndJoin(new Thread(state => verifyStackSize(64 << 10), 64 << 10)); // 64 KB startThreadAndJoin(new Thread(state => verifyStackSize(16 << 20), 16 << 20)); // 16 MB Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null)); Assert.Throws<ArgumentNullException>(() => new Thread((ThreadStart)null, 0)); Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null)); Assert.Throws<ArgumentNullException>(() => new Thread((ParameterizedThreadStart)null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(() => { }, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => new Thread(state => { }, -1)); } private static IEnumerable<object[]> ApartmentStateTest_MemberData() { yield return new object[] { #pragma warning disable 618 // Obsolete members new Func<Thread, ApartmentState>(t => t.ApartmentState), #pragma warning restore 618 // Obsolete members new Func<Thread, ApartmentState, int>( (t, value) => { try { #pragma warning disable 618 // Obsolete members t.ApartmentState = value; #pragma warning restore 618 // Obsolete members return 0; } catch (ArgumentOutOfRangeException) { return 1; } catch (PlatformNotSupportedException) { return 3; } }), 0 }; yield return new object[] { new Func<Thread, ApartmentState>(t => t.GetApartmentState()), new Func<Thread, ApartmentState, int>( (t, value) => { try { t.SetApartmentState(value); return 0; } catch (ArgumentOutOfRangeException) { return 1; } catch (InvalidOperationException) { return 2; } catch (PlatformNotSupportedException) { return 3; } }), 1 }; yield return new object[] { new Func<Thread, ApartmentState>(t => t.GetApartmentState()), new Func<Thread, ApartmentState, int>( (t, value) => { try { return t.TrySetApartmentState(value) ? 0 : 2; } catch (ArgumentOutOfRangeException) { return 1; } catch (PlatformNotSupportedException) { return 3; } }), 2 }; } [Theory] [MemberData(nameof(ApartmentStateTest_MemberData))] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows public static void GetSetApartmentStateTest_ChangeAfterThreadStarted_Windows( Func<Thread, ApartmentState> getApartmentState, Func<Thread, ApartmentState, int> setApartmentState, int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */) { ThreadTestHelpers.RunTestInBackgroundThread(() => { var t = Thread.CurrentThread; Assert.Equal(1, setApartmentState(t, ApartmentState.STA - 1)); Assert.Equal(1, setApartmentState(t, ApartmentState.Unknown + 1)); Assert.Equal(ApartmentState.MTA, getApartmentState(t)); Assert.Equal(0, setApartmentState(t, ApartmentState.MTA)); Assert.Equal(ApartmentState.MTA, getApartmentState(t)); Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.STA)); // cannot be changed after thread is started Assert.Equal(ApartmentState.MTA, getApartmentState(t)); }); } [Theory] [MemberData(nameof(ApartmentStateTest_MemberData))] [PlatformSpecific(TestPlatforms.Windows)] // Expected behavior differs on Unix and Windows public static void ApartmentStateTest_ChangeBeforeThreadStarted_Windows( Func<Thread, ApartmentState> getApartmentState, Func<Thread, ApartmentState, int> setApartmentState, int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */) { ApartmentState apartmentStateInThread = ApartmentState.Unknown; Thread t = null; t = new Thread(() => apartmentStateInThread = getApartmentState(t)); t.IsBackground = true; Assert.Equal(0, setApartmentState(t, ApartmentState.STA)); Assert.Equal(ApartmentState.STA, getApartmentState(t)); Assert.Equal(setType == 0 ? 0 : 2, setApartmentState(t, ApartmentState.MTA)); // cannot be changed more than once Assert.Equal(ApartmentState.STA, getApartmentState(t)); t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); Assert.Equal(ApartmentState.STA, apartmentStateInThread); } [Theory] [MemberData(nameof(ApartmentStateTest_MemberData))] [PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior differs on Unix and Windows public static void ApartmentStateTest_Unix( Func<Thread, ApartmentState> getApartmentState, Func<Thread, ApartmentState, int> setApartmentState, int setType /* 0 = ApartmentState setter, 1 = SetApartmentState, 2 = TrySetApartmentState */) { var t = new Thread(() => { }); Assert.Equal(ApartmentState.Unknown, getApartmentState(t)); Assert.Equal(0, setApartmentState(t, ApartmentState.Unknown)); int expectedFailure; switch (setType) { case 0: expectedFailure = 0; // ApartmentState setter - no exception, but value does not change break; case 1: expectedFailure = 3; // SetApartmentState - InvalidOperationException break; default: expectedFailure = 2; // TrySetApartmentState - returns false break; } Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.STA)); Assert.Equal(expectedFailure, setApartmentState(t, ApartmentState.MTA)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void CurrentCultureTest_SkipOnDesktopFramework() { // Cannot access culture properties on a thread object from a different thread var t = new Thread(() => { }); Assert.Throws<InvalidOperationException>(() => t.CurrentCulture); Assert.Throws<InvalidOperationException>(() => t.CurrentUICulture); } [Fact] public static void CurrentCultureTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var t = Thread.CurrentThread; var originalCulture = CultureInfo.CurrentCulture; var originalUICulture = CultureInfo.CurrentUICulture; var otherCulture = CultureInfo.InvariantCulture; // Culture properties return the same value as those on CultureInfo Assert.Equal(originalCulture, t.CurrentCulture); Assert.Equal(originalUICulture, t.CurrentUICulture); try { // Changing culture properties on CultureInfo causes the values of properties on the current thread to change CultureInfo.CurrentCulture = otherCulture; CultureInfo.CurrentUICulture = otherCulture; Assert.Equal(otherCulture, t.CurrentCulture); Assert.Equal(otherCulture, t.CurrentUICulture); // Changing culture properties on the current thread causes new values to be returned, and causes the values of // properties on CultureInfo to change t.CurrentCulture = originalCulture; t.CurrentUICulture = originalUICulture; Assert.Equal(originalCulture, t.CurrentCulture); Assert.Equal(originalUICulture, t.CurrentUICulture); Assert.Equal(originalCulture, CultureInfo.CurrentCulture); Assert.Equal(originalUICulture, CultureInfo.CurrentUICulture); } finally { CultureInfo.CurrentCulture = originalCulture; CultureInfo.CurrentUICulture = originalUICulture; } Assert.Throws<ArgumentNullException>(() => t.CurrentCulture = null); Assert.Throws<ArgumentNullException>(() => t.CurrentUICulture = null); }); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void CurrentPrincipalTest_SkipOnDesktopFramework() { ThreadTestHelpers.RunTestInBackgroundThread(() => Assert.Null(Thread.CurrentPrincipal)); } [Fact] public static void CurrentPrincipalTest() { ThreadTestHelpers.RunTestInBackgroundThread(() => { var originalPrincipal = Thread.CurrentPrincipal; var otherPrincipal = new GenericPrincipal(new GenericIdentity(string.Empty, string.Empty), new string[] { string.Empty }); Thread.CurrentPrincipal = otherPrincipal; Assert.Equal(otherPrincipal, Thread.CurrentPrincipal); Thread.CurrentPrincipal = originalPrincipal; Assert.Equal(originalPrincipal, Thread.CurrentPrincipal); }); } [Fact] public static void CurrentThreadTest() { Thread otherThread = null; var t = new Thread(() => otherThread = Thread.CurrentThread); t.IsBackground = true; t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); Assert.Equal(t, otherThread); var mainThread = Thread.CurrentThread; Assert.NotNull(mainThread); Assert.NotEqual(mainThread, otherThread); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void ExecutionContextTest() { ThreadTestHelpers.RunTestInBackgroundThread( () => Assert.Equal(ExecutionContext.Capture(), Thread.CurrentThread.ExecutionContext)); } [Fact] public static void IsAliveTest() { var isAliveWhenRunning = false; Thread t = null; t = new Thread(() => isAliveWhenRunning = t.IsAlive); t.IsBackground = true; Assert.False(t.IsAlive); t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); Assert.True(isAliveWhenRunning); Assert.False(t.IsAlive); } [Fact] public static void IsBackgroundTest() { var t = new Thread(() => { }); Assert.False(t.IsBackground); t.IsBackground = true; Assert.True(t.IsBackground); t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); // Cannot use this property after the thread is dead Assert.Throws<ThreadStateException>(() => t.IsBackground); Assert.Throws<ThreadStateException>(() => t.IsBackground = false); Assert.Throws<ThreadStateException>(() => t.IsBackground = true); // Verify that the test process can shut down gracefully with a hung background thread t = new Thread(() => Thread.Sleep(Timeout.Infinite)); t.IsBackground = true; t.Start(); } [Fact] public static void IsThreadPoolThreadTest() { var isThreadPoolThread = false; Thread t = null; t = new Thread(() => { isThreadPoolThread = t.IsThreadPoolThread; }); t.IsBackground = true; Assert.False(t.IsThreadPoolThread); t.Start(); Assert.True(t.Join(UnexpectedTimeoutMilliseconds)); Assert.False(isThreadPoolThread); var e = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem( state => { isThreadPoolThread = Thread.CurrentThread.IsThreadPoolThread; e.Set(); }); e.CheckedWait(); Assert.True(isThreadPoolThread); } [Fact] public static void ManagedThreadIdTest() { var e = new ManualResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait); t.IsBackground = true; t.Start(); Assert.NotEqual(Thread.CurrentThread.ManagedThreadId, t.ManagedThreadId); e.Set(); waitForThread(); } [Fact] public static void NameTest() { var t = new Thread(() => { }); Assert.Null(t.Name); t.Name = "a"; Assert.Equal("a", t.Name); Assert.Throws<InvalidOperationException>(() => t.Name = "b"); Assert.Equal("a", t.Name); } [Fact] public static void PriorityTest() { var e = new ManualResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait); t.IsBackground = true; Assert.Equal(ThreadPriority.Normal, t.Priority); t.Priority = ThreadPriority.AboveNormal; Assert.Equal(ThreadPriority.AboveNormal, t.Priority); t.Start(); Assert.Equal(ThreadPriority.AboveNormal, t.Priority); t.Priority = ThreadPriority.Normal; Assert.Equal(ThreadPriority.Normal, t.Priority); e.Set(); waitForThread(); } [Fact] public static void ThreadStateTest() { var e0 = new ManualResetEvent(false); var e1 = new AutoResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { e0.CheckedWait(); ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0)); }); Assert.Equal(ThreadState.Unstarted, t.ThreadState); t.IsBackground = true; Assert.Equal(ThreadState.Unstarted | ThreadState.Background, t.ThreadState); t.Start(); ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.WaitSleepJoin | ThreadState.Background)); e0.Set(); ThreadTestHelpers.WaitForCondition(() => t.ThreadState == (ThreadState.Running | ThreadState.Background)); e1.Set(); waitForThread(); Assert.Equal(ThreadState.Stopped, t.ThreadState); t = ThreadTestHelpers.CreateGuardedThread( out waitForThread, () => ThreadTestHelpers.WaitForConditionWithoutBlocking(() => e1.WaitOne(0))); t.Start(); ThreadTestHelpers.WaitForCondition(() => t.ThreadState == ThreadState.Running); e1.Set(); waitForThread(); Assert.Equal(ThreadState.Stopped, t.ThreadState); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void AbortSuspendTest() { var e = new ManualResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait); t.IsBackground = true; Action verify = () => { Assert.Throws<PlatformNotSupportedException>(() => t.Abort()); Assert.Throws<PlatformNotSupportedException>(() => t.Abort(t)); #pragma warning disable 618 // Obsolete members Assert.Throws<PlatformNotSupportedException>(() => t.Suspend()); Assert.Throws<PlatformNotSupportedException>(() => t.Resume()); #pragma warning restore 618 // Obsolete members }; verify(); t.Start(); verify(); e.Set(); waitForThread(); Assert.Throws<PlatformNotSupportedException>(() => Thread.ResetAbort()); } private static void VerifyLocalDataSlot(LocalDataStoreSlot slot) { Assert.NotNull(slot); var waitForThreadArray = new Action[2]; var threadArray = new Thread[2]; var barrier = new Barrier(threadArray.Length); var cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = cancellationTokenSource.Token; Func<bool> barrierSignalAndWait = () => { try { Assert.True(barrier.SignalAndWait(UnexpectedTimeoutMilliseconds, cancellationToken)); } catch (OperationCanceledException) { return false; } return true; }; Action<int> threadMain = threadIndex => { try { Assert.Null(Thread.GetData(slot)); if (!barrierSignalAndWait()) { return; } if (threadIndex == 0) { Thread.SetData(slot, threadIndex); } if (!barrierSignalAndWait()) { return; } if (threadIndex == 0) { Assert.Equal(threadIndex, Thread.GetData(slot)); } else { Assert.Null(Thread.GetData(slot)); } if (!barrierSignalAndWait()) { return; } if (threadIndex != 0) { Thread.SetData(slot, threadIndex); } if (!barrierSignalAndWait()) { return; } Assert.Equal(threadIndex, Thread.GetData(slot)); if (!barrierSignalAndWait()) { return; } } catch (Exception ex) { cancellationTokenSource.Cancel(); throw new TargetInvocationException(ex); } }; for (int i = 0; i < threadArray.Length; ++i) { threadArray[i] = ThreadTestHelpers.CreateGuardedThread(out waitForThreadArray[i], () => threadMain(i)); threadArray[i].IsBackground = true; threadArray[i].Start(); } foreach (var waitForThread in waitForThreadArray) { waitForThread(); } } [Fact] public static void LocalDataSlotTest() { var slot = Thread.AllocateDataSlot(); var slot2 = Thread.AllocateDataSlot(); Assert.NotEqual(slot, slot2); VerifyLocalDataSlot(slot); VerifyLocalDataSlot(slot2); var slotName = "System.Threading.Threads.Tests.LocalDataSlotTest"; var slotName2 = slotName + ".2"; var invalidSlotName = slotName + ".Invalid"; try { // AllocateNamedDataSlot allocates slot = Thread.AllocateNamedDataSlot(slotName); Assert.Throws<ArgumentException>(() => Thread.AllocateNamedDataSlot(slotName)); slot2 = Thread.AllocateNamedDataSlot(slotName2); Assert.NotEqual(slot, slot2); VerifyLocalDataSlot(slot); VerifyLocalDataSlot(slot2); // Free the same slot twice, should be fine Thread.FreeNamedDataSlot(slotName2); Thread.FreeNamedDataSlot(slotName2); } catch (Exception ex) { Thread.FreeNamedDataSlot(slotName); Thread.FreeNamedDataSlot(slotName2); throw new TargetInvocationException(ex); } try { // GetNamedDataSlot gets or allocates var tempSlot = Thread.GetNamedDataSlot(slotName); Assert.Equal(slot, tempSlot); tempSlot = Thread.GetNamedDataSlot(slotName2); Assert.NotEqual(slot2, tempSlot); slot2 = tempSlot; Assert.NotEqual(slot, slot2); VerifyLocalDataSlot(slot); VerifyLocalDataSlot(slot2); } finally { Thread.FreeNamedDataSlot(slotName); Thread.FreeNamedDataSlot(slotName2); } try { // A named slot can be used after the name is freed, since only the name is freed, not the slot slot = Thread.AllocateNamedDataSlot(slotName); Thread.FreeNamedDataSlot(slotName); slot2 = Thread.AllocateNamedDataSlot(slotName); // same name Thread.FreeNamedDataSlot(slotName); Assert.NotEqual(slot, slot2); VerifyLocalDataSlot(slot); VerifyLocalDataSlot(slot2); } finally { Thread.FreeNamedDataSlot(slotName); Thread.FreeNamedDataSlot(slotName2); } } [Fact] public static void InterruptTest() { // Interrupting a thread that is not blocked does not do anything, but once the thread starts blocking, it gets // interrupted and does not auto-reset the signaled event var threadReady = new AutoResetEvent(false); var continueThread = new AutoResetEvent(false); bool continueThreadBool = false; Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { threadReady.Set(); ThreadTestHelpers.WaitForConditionWithoutBlocking(() => Volatile.Read(ref continueThreadBool)); threadReady.Set(); Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()); }); t.IsBackground = true; t.Start(); threadReady.CheckedWait(); continueThread.Set(); t.Interrupt(); Assert.False(threadReady.WaitOne(ExpectedTimeoutMilliseconds)); Volatile.Write(ref continueThreadBool, true); waitForThread(); Assert.True(continueThread.WaitOne(0)); // Interrupting a dead thread does nothing t.Interrupt(); // Interrupting an unstarted thread causes the thread to be interrupted after it is started and starts blocking t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait())); t.IsBackground = true; t.Interrupt(); t.Start(); waitForThread(); // A thread that is already blocked on a synchronization primitive unblocks immediately continueThread.Reset(); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait())); t.IsBackground = true; t.Start(); ThreadTestHelpers.WaitForCondition(() => (t.ThreadState & ThreadState.WaitSleepJoin) != 0); t.Interrupt(); waitForThread(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void InterruptInFinallyBlockTest_SkipOnDesktopFramework() { // A wait in a finally block can be interrupted. The desktop framework applies the same rules as thread abort, and // does not allow thread interrupt in a finally block. There is nothing special about thread interrupt that requires // not allowing it in finally blocks, so this behavior has changed in .NET Core. var continueThread = new AutoResetEvent(false); Action waitForThread; Thread t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { try { } finally { Assert.Throws<ThreadInterruptedException>(() => continueThread.CheckedWait()); } }); t.IsBackground = true; t.Start(); t.Interrupt(); waitForThread(); } [Fact] public static void JoinTest() { var threadReady = new ManualResetEvent(false); var continueThread = new ManualResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, () => { threadReady.Set(); continueThread.CheckedWait(); Thread.Sleep(ExpectedTimeoutMilliseconds); }); t.IsBackground = true; Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(-2)); Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(TimeSpan.FromMilliseconds(-2))); Assert.Throws<ArgumentOutOfRangeException>(() => t.Join(TimeSpan.FromMilliseconds((double)int.MaxValue + 1))); Assert.Throws<ThreadStateException>(() => t.Join()); Assert.Throws<ThreadStateException>(() => t.Join(UnexpectedTimeoutMilliseconds)); Assert.Throws<ThreadStateException>(() => t.Join(TimeSpan.FromMilliseconds(UnexpectedTimeoutMilliseconds))); t.Start(); threadReady.CheckedWait(); Assert.False(t.Join(ExpectedTimeoutMilliseconds)); Assert.False(t.Join(TimeSpan.FromMilliseconds(ExpectedTimeoutMilliseconds))); continueThread.Set(); waitForThread(); Assert.True(t.Join(0)); Assert.True(t.Join(TimeSpan.Zero)); } [Fact] public static void SleepTest() { Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(-2)); Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(TimeSpan.FromMilliseconds(-2))); Assert.Throws<ArgumentOutOfRangeException>(() => Thread.Sleep(TimeSpan.FromMilliseconds((double)int.MaxValue + 1))); Thread.Sleep(0); var startTime = DateTime.Now; Thread.Sleep(500); Assert.True((DateTime.Now - startTime).TotalMilliseconds >= 100); } [Fact] public static void StartTest() { var e = new AutoResetEvent(false); Action waitForThread; var t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, e.CheckedWait); t.IsBackground = true; Assert.Throws<InvalidOperationException>(() => t.Start(null)); Assert.Throws<InvalidOperationException>(() => t.Start(t)); t.Start(); Assert.Throws<ThreadStateException>(() => t.Start()); e.Set(); waitForThread(); Assert.Throws<ThreadStateException>(() => t.Start()); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => e.CheckedWait()); t.IsBackground = true; t.Start(); Assert.Throws<ThreadStateException>(() => t.Start()); Assert.Throws<ThreadStateException>(() => t.Start(null)); Assert.Throws<ThreadStateException>(() => t.Start(t)); e.Set(); waitForThread(); Assert.Throws<ThreadStateException>(() => t.Start()); Assert.Throws<ThreadStateException>(() => t.Start(null)); Assert.Throws<ThreadStateException>(() => t.Start(t)); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Null(parameter)); t.IsBackground = true; t.Start(); waitForThread(); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Null(parameter)); t.IsBackground = true; t.Start(null); waitForThread(); t = ThreadTestHelpers.CreateGuardedThread(out waitForThread, parameter => Assert.Equal(t, parameter)); t.IsBackground = true; t.Start(t); waitForThread(); } [Fact] public static void MiscellaneousTest() { Thread.BeginCriticalRegion(); Thread.EndCriticalRegion(); Thread.BeginThreadAffinity(); Thread.EndThreadAffinity(); ThreadTestHelpers.RunTestInBackgroundThread(() => { // TODO: Port tests for these once all of the necessary interop APIs are available Thread.CurrentThread.DisableComObjectEagerCleanup(); Marshal.CleanupUnusedObjectsInCurrentContext(); }); #pragma warning disable 618 // obsolete members Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.GetCompressedStack()); Assert.Throws<InvalidOperationException>(() => Thread.CurrentThread.SetCompressedStack(CompressedStack.Capture())); #pragma warning restore 618 // obsolete members Thread.MemoryBarrier(); var ad = Thread.GetDomain(); Assert.NotNull(ad); Assert.Equal(AppDomain.CurrentDomain, ad); Assert.Equal(ad.Id, Thread.GetDomainID()); Thread.SpinWait(int.MinValue); Thread.SpinWait(-1); Thread.SpinWait(0); Thread.SpinWait(1); Thread.Yield(); } } }
//Created by Peoharen using System; namespace Server.Items { public class NorthWestDoor : BaseDoor { [Constructable] public NorthWestDoor() : base( 0x679, 0x67A, 0xEC, 0xF3, new Point3D( -1, 0, 0 ) ) { } public NorthWestDoor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class NorthEastDoor : BaseDoor { [Constructable] public NorthEastDoor() : base( 0x67B, 0x67C, 0xEC, 0xF3, new Point3D( 1, -1, 0 ) ) { } public NorthEastDoor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class SouthWestDoor : BaseDoor { [Constructable] public SouthWestDoor() : base( 0x675, 0x676, 0xEC, 0xF3, new Point3D( -1, 1, 0 ) ) { } public SouthWestDoor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class SouthEastDoor : BaseDoor { [Constructable] public SouthEastDoor() : base( 0x677, 0x678, 0xEC, 0xF3, new Point3D( 1, 1, 0 ) ) { } public SouthEastDoor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class WestNorthDoor : BaseDoor { [Constructable] public WestNorthDoor() : base( 0x683, 1, 0xEC, 0xF3, new Point3D( -1, -1, 0 ) ) { } public WestNorthDoor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class WestSouthDoor : BaseDoor { [Constructable] public WestSouthDoor() : base( 0x681, 1, 0xEC, 0xF3, new Point3D( -1, 1, 0 ) ) { } public WestSouthDoor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class EastNorthDoor : BaseDoor { [Constructable] public EastNorthDoor() : base( 0x67F, 1, 0xEC, 0xF3, new Point3D( 1, -1, 0 ) ) { } public EastNorthDoor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class EastSouthDoor : BaseDoor { [Constructable] public EastSouthDoor() : base( 0x67D, 0x67E, 0xEC, 0xF3, new Point3D( 0, 1, 0 ) ) { } public EastSouthDoor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } } /* public class Door : BaseDoor { [Constructable] public Door() : base( , , 0xEC, 0xF3, new Point3D( 0, 0, 0 ) ) { } public Door( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } */
// Copyright 2018 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 // // 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 Google.Ads.GoogleAds.Config; using Google.Ads.GoogleAds.Lib; using Newtonsoft.Json; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Net; namespace Google.Ads.GoogleAds.Tests.Config { /// <summary> /// Tests for <see cref="GoogleAdsConfig"/> class. /// </summary> [TestFixture] [Category("Smoke")] [Parallelizable(ParallelScope.Self)] internal class GoogleAdsConfigTests : GoogleAdsConfig { /// <summary> /// Test value for <see cref="GoogleAdsConfig.ServerUrl"/> property. /// </summary> private const string SERVER_URL_VALUE = "TEST_SERVER_URL"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.Timeout"/> property. /// </summary> private const int TIMEOUT_VALUE = 5000; /// <summary> /// Test value for <see cref="GoogleAdsConfig.MaxReceiveMessageSizeInBytes"/> property. /// </summary> private const int MAX_RECEIVE_MESSAGE_SIZE_IN_BYTES_VALUE = 8000; /// <summary> /// Test value for <see cref="GoogleAdsConfig.MaxMetadataSizeInBytes"/> property. /// </summary> private const int MAX_METADATA_SIZE_IN_BYTES_VALUE = 9000; /// <summary> /// Test value for <see cref="GoogleAdsConfig.DeveloperToken"/> property. /// </summary> private const string DEVELOPER_TOKEN_VALUE = "abcdefghijkl1234567890"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.LoginCustomerId"/> property. /// </summary> private const string LOGIN_CUSTOMER_ID_VALUE = "1234567890"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.LinkedCustomerId"/> property. /// </summary> private const string LINKED_CUSTOMER_ID_VALUE = "4567891234"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.ClientCustomerId"/> property. /// </summary> private const string CLIENT_CUSTOMER_ID_VALUE = "987654543"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.OAuth2Mode"/> property. /// </summary> private const string OAUTH2_MODE_VALUE = "APPLICATION"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.OAuth2ClientId"/> property. /// </summary> private const string OAUTH2_CLIENT_ID_VALUE = "TEST_OAUTH2_CLIENT_ID"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.OAuth2ClientSecret"/> property. /// </summary> private const string OAUTH2_CLIENT_SECRET_VALUE = "TEST_OAUTH2_CLIENT_SECRET"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.OAuth2RefreshToken"/> property. /// </summary> private const string OAUTH2_REFRESH_TOKEN_VALUE = "TEST_OAUTH2_REFRESH_TOKEN"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.OAuth2Scope"/> property. /// </summary> private const string OAUTH2_SCOPE_VALUE = "TEST_OAUTH2_SCOPE"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.OAuth2PrnEmail"/> property. /// </summary> private const string OAUTH2_PRN_EMAIL_VALUE = "TEST_OAUTH2_PRN_EMAIL"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.Proxy"/> property. /// </summary> private const string PROXY_SERVER_VALUE = "http://test.url"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.Proxy"/> property. /// </summary> private const string PROXY_USER_VALUE = "TEST_PROXY_USER"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.Proxy"/> property. /// </summary> private const string PROXY_PASSWORD_VALUE = "TEST_PROXY_PASSWORD"; /// <summary> /// Test value for <see cref="GoogleAdsConfig.Proxy"/> property. /// </summary> private const string PROXY_DOMAIN_VALUE = "TEST_PROXY_DOMAIN"; /// <summary> /// The temporary setting json file for running tests. /// </summary> private string TEMP_SETTING_JSON_FILE; /// <summary> /// The temporary secret json file for running tests. /// </summary> private string TEMP_SECRET_JSON_FILE; /// <summary> /// The test configuration settings. /// </summary> private readonly Dictionary<string, string> CONFIG_SETTINGS = new Dictionary<string, string>() { { "Timeout", TIMEOUT_VALUE.ToString() }, { "MaxReceiveMessageLengthInBytes", MAX_RECEIVE_MESSAGE_SIZE_IN_BYTES_VALUE.ToString() }, { "MaxMetadataSizeInBytes", MAX_METADATA_SIZE_IN_BYTES_VALUE.ToString() }, { "GoogleAds.Server", SERVER_URL_VALUE }, { "DeveloperToken", DEVELOPER_TOKEN_VALUE }, { "LoginCustomerId", LOGIN_CUSTOMER_ID_VALUE }, { "LinkedCustomerId", LINKED_CUSTOMER_ID_VALUE }, { "ClientCustomerId", CLIENT_CUSTOMER_ID_VALUE }, { "OAuth2Mode", OAUTH2_MODE_VALUE }, { "OAuth2ClientId", OAUTH2_CLIENT_ID_VALUE }, { "OAuth2ClientSecret", OAUTH2_CLIENT_SECRET_VALUE }, { "OAuth2RefreshToken", OAUTH2_REFRESH_TOKEN_VALUE }, { "OAuth2PrnEmail", OAUTH2_PRN_EMAIL_VALUE }, { "OAuth2Scope", OAUTH2_SCOPE_VALUE }, { "ProxyServer", PROXY_SERVER_VALUE }, { "ProxyUser", PROXY_USER_VALUE }, { "ProxyPassword", PROXY_PASSWORD_VALUE }, { "ProxyDomain", PROXY_DOMAIN_VALUE }, }; [SetUp] public void Init() { TEMP_SETTING_JSON_FILE = CreateSettingsJson(); TEMP_SECRET_JSON_FILE = CreateSecretsJson(); CONFIG_SETTINGS["OAuth2SecretsJsonPath"] = TEMP_SECRET_JSON_FILE; foreach (string envKey in ENV_VAR_TO_CONFIG_KEY_MAP.Keys) { string configKey = ENV_VAR_TO_CONFIG_KEY_MAP[envKey]; if (CONFIG_SETTINGS.ContainsKey(configKey)) { string value = CONFIG_SETTINGS[configKey]; Environment.SetEnvironmentVariable(envKey, value); } } } [TearDown] public void Cleanup() { Environment.SetEnvironmentVariable(EnvironmentVariableNames.CONFIG_FILE_PATH, null); foreach (string envKey in ENV_VAR_TO_CONFIG_KEY_MAP.Keys) { Environment.SetEnvironmentVariable(envKey, null); } } /// <summary> /// Tests the <see cref="GoogleAdsConfig.ReadSettings(Dictionary{string, string})"/> method. /// </summary> [Test] public void TestReadSettings() { ReadSettings(CONFIG_SETTINGS); VerifySettings(); } private void VerifySettings() { Assert.AreEqual(SERVER_URL_VALUE, this.ServerUrl); Assert.AreEqual(TIMEOUT_VALUE, this.Timeout); Assert.AreEqual(MAX_RECEIVE_MESSAGE_SIZE_IN_BYTES_VALUE, this.MaxReceiveMessageSizeInBytes); Assert.AreEqual(MAX_METADATA_SIZE_IN_BYTES_VALUE, this.MaxMetadataSizeInBytes); Assert.AreEqual(DEVELOPER_TOKEN_VALUE, this.DeveloperToken); Assert.AreEqual(LOGIN_CUSTOMER_ID_VALUE, this.LoginCustomerId); Assert.AreEqual(LINKED_CUSTOMER_ID_VALUE, this.LinkedCustomerId); Assert.AreEqual(CLIENT_CUSTOMER_ID_VALUE, this.ClientCustomerId.ToString()); Assert.AreEqual(OAUTH2_CLIENT_ID_VALUE, this.OAuth2ClientId); Assert.AreEqual(OAUTH2_CLIENT_SECRET_VALUE, this.OAuth2ClientSecret); Assert.AreEqual(OAUTH2_REFRESH_TOKEN_VALUE, this.OAuth2RefreshToken); Assert.AreEqual(OAUTH2_SCOPE_VALUE, this.OAuth2Scope); // Tests for Proxy field. NetworkCredential credential = (NetworkCredential) this.Proxy.Credentials; Assert.AreEqual(new Uri(PROXY_SERVER_VALUE).AbsoluteUri, this.Proxy.Address.AbsoluteUri); Assert.AreEqual(PROXY_USER_VALUE, credential.UserName); Assert.AreEqual(PROXY_PASSWORD_VALUE, credential.Password); Assert.AreEqual(PROXY_DOMAIN_VALUE, credential.Domain); } /// <summary> /// Tests for <see cref="ConfigBase.TryLoadFromEnvironmentFilePath(string, string)"/> /// </summary> [Test] public void TestLoadFromEnvironmentFilePath() { Environment.SetEnvironmentVariable(EnvironmentVariableNames.CONFIG_FILE_PATH, TEMP_SETTING_JSON_FILE); TryLoadFromEnvironmentFilePath(EnvironmentVariableNames.CONFIG_FILE_PATH, CONFIG_SECTION_NAME); VerifySettings(); Environment.SetEnvironmentVariable(EnvironmentVariableNames.CONFIG_FILE_PATH, null); } /// <summary> /// Tests for <see cref="ConfigBase.LoadFromSettingsJson(string, string)"/> /// </summary> [Test] public void TestLoadFromSettingsJson() { LoadFromSettingsJson(TEMP_SETTING_JSON_FILE, CONFIG_SECTION_NAME); VerifySettings(); } /// <summary> /// Tests for <see cref="ConfigBase.LoadFromEnvironmentVariables()"/> /// </summary> [Test] public void TestLoadFromEnvironmentVariables() { LoadFromEnvironmentVariables(); Assert.AreEqual(DEVELOPER_TOKEN_VALUE, this.DeveloperToken); Assert.AreEqual(LOGIN_CUSTOMER_ID_VALUE, this.LoginCustomerId); Assert.AreEqual(LINKED_CUSTOMER_ID_VALUE, this.LinkedCustomerId); Assert.AreEqual(OAUTH2_MODE_VALUE, this.OAuth2Mode.ToString()); Assert.AreEqual(OAUTH2_CLIENT_ID_VALUE, this.OAuth2ClientId); Assert.AreEqual(OAUTH2_CLIENT_SECRET_VALUE, this.OAuth2ClientSecret); Assert.AreEqual(OAUTH2_REFRESH_TOKEN_VALUE, this.OAuth2RefreshToken); Assert.AreEqual(SERVER_URL_VALUE, this.ServerUrl); Assert.AreEqual(OAUTH2_PRN_EMAIL_VALUE, this.OAuth2PrnEmail); Assert.AreEqual(TEMP_SECRET_JSON_FILE, this.OAuth2SecretsJsonPath); } /// <summary> /// Creates a settings.json file for testing purposes. /// </summary> /// <returns>The path to the temporary settings json file.</returns> private string CreateSettingsJson() { Dictionary<string, Dictionary<string, string>> jsonMap = new Dictionary<string, Dictionary<string, string>>() { { CONFIG_SECTION_NAME, CONFIG_SETTINGS } }; string json = JsonConvert.SerializeObject(jsonMap); string jsonPath = Path.GetTempFileName(); using (StreamWriter writer = new StreamWriter(jsonPath)) { writer.Write(json); writer.Flush(); } return jsonPath; } /// <summary> /// Creates a secrets json for testing purposes. /// </summary> /// <returns>The path to the temporary secrets json file.</returns> private string CreateSecretsJson() { string jsonPath = Path.GetTempFileName(); using (StreamWriter writer = new StreamWriter(jsonPath)) { writer.Write(TestResources.SecretJson); writer.Flush(); } return jsonPath; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class SelectTest { private readonly ITestOutputHelper _log; public SelectTest(ITestOutputHelper output) { _log = output; } private const int SmallTimeoutMicroseconds = 10 * 1000; private const int FailTimeoutMicroseconds = 30 * 1000 * 1000; [PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value [Theory] [InlineData(90, 0)] [InlineData(0, 90)] [InlineData(45, 45)] public void Select_ReadWrite_AllReady_ManySockets(int reads, int writes) { Select_ReadWrite_AllReady(reads, writes); } [Theory] [InlineData(1, 0)] [InlineData(0, 1)] [InlineData(2, 2)] public void Select_ReadWrite_AllReady(int reads, int writes) { var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray(); var writePairs = Enumerable.Range(0, writes).Select(_ => CreateConnectedSockets()).ToArray(); try { foreach (var pair in readPairs) { pair.Value.Send(new byte[1] { 42 }); } var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray()); var writeList = new List<Socket>(writePairs.Select(p => p.Key).ToArray()); Socket.Select(readList, writeList, null, FailTimeoutMicroseconds); // Since no buffers are full, all writes should be available. Assert.Equal(writePairs.Length, writeList.Count); // We could wake up from Select for writes even if reads are about to become available, // so there's very little we can assert if writes is non-zero. if (writes == 0 && reads > 0) { Assert.InRange(readList.Count, 1, readPairs.Length); } // When we do the select again, the lists shouldn't change at all, as they've already // been filtered to ones that were ready. int readListCountBefore = readList.Count; int writeListCountBefore = writeList.Count; Socket.Select(readList, writeList, null, FailTimeoutMicroseconds); Assert.Equal(readListCountBefore, readList.Count); Assert.Equal(writeListCountBefore, writeList.Count); } finally { DisposeSockets(readPairs); DisposeSockets(writePairs); } } [PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value [Fact] public void Select_ReadError_NoneReady_ManySockets() { Select_ReadError_NoneReady(45, 45); } [Theory] [InlineData(1, 0)] [InlineData(0, 1)] [InlineData(2, 2)] public void Select_ReadError_NoneReady(int reads, int errors) { var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray(); var errorPairs = Enumerable.Range(0, errors).Select(_ => CreateConnectedSockets()).ToArray(); try { var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray()); var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray()); Socket.Select(readList, null, errorList, SmallTimeoutMicroseconds); Assert.Empty(readList); Assert.Empty(errorList); } finally { DisposeSockets(readPairs); DisposeSockets(errorPairs); } } [PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value public void Select_Read_OneReadyAtATime_ManySockets(int reads) { Select_Read_OneReadyAtATime(90); // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation } [Theory] [InlineData(2)] public void Select_Read_OneReadyAtATime(int reads) { var rand = new Random(42); var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToList(); try { while (readPairs.Count > 0) { int next = rand.Next(0, readPairs.Count); readPairs[next].Value.Send(new byte[1] { 42 }); var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray()); Socket.Select(readList, null, null, FailTimeoutMicroseconds); Assert.Equal(1, readList.Count); Assert.Same(readPairs[next].Key, readList[0]); readPairs.RemoveAt(next); } } finally { DisposeSockets(readPairs); } } [PlatformSpecific(~PlatformID.OSX)] // typical OSX install has very low max open file descriptors value [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/989 public void Select_Error_OneReadyAtATime() { const int Errors = 90; // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation var rand = new Random(42); var errorPairs = Enumerable.Range(0, Errors).Select(_ => CreateConnectedSockets()).ToList(); try { while (errorPairs.Count > 0) { int next = rand.Next(0, errorPairs.Count); errorPairs[next].Value.Send(new byte[1] { 42 }, SocketFlags.OutOfBand); var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray()); Socket.Select(null, null, errorList, FailTimeoutMicroseconds); Assert.Equal(1, errorList.Count); Assert.Same(errorPairs[next].Key, errorList[0]); errorPairs.RemoveAt(next); } } finally { DisposeSockets(errorPairs); } } [Theory] [InlineData(SelectMode.SelectRead)] [InlineData(SelectMode.SelectError)] public void Poll_NotReady(SelectMode mode) { KeyValuePair<Socket, Socket> pair = CreateConnectedSockets(); try { Assert.False(pair.Key.Poll(SmallTimeoutMicroseconds, mode)); } finally { pair.Key.Dispose(); pair.Value.Dispose(); } } [Theory] [InlineData(-1)] [InlineData(FailTimeoutMicroseconds)] public void Poll_ReadReady_LongTimeouts(int microsecondsTimeout) { KeyValuePair<Socket, Socket> pair = CreateConnectedSockets(); try { Task.Delay(1).ContinueWith(_ => pair.Value.Send(new byte[1] { 42 }), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Assert.True(pair.Key.Poll(microsecondsTimeout, SelectMode.SelectRead)); } finally { pair.Key.Dispose(); pair.Value.Dispose(); } } private static KeyValuePair<Socket, Socket> CreateConnectedSockets() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.LingerState = new LingerOption(true, 0); listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.LingerState = new LingerOption(true, 0); Task<Socket> acceptTask = listener.AcceptAsync(); client.Connect(listener.LocalEndPoint); Socket server = acceptTask.GetAwaiter().GetResult(); return new KeyValuePair<Socket, Socket>(client, server); } } private static void DisposeSockets(IEnumerable<KeyValuePair<Socket, Socket>> sockets) { foreach (var pair in sockets) { pair.Key.Dispose(); pair.Value.Dispose(); } } } }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * 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.Collections.Generic; using System.IO; namespace Aerospike.Client { /// <summary> /// Serialize collection objects using MessagePack format specification: /// /// https://github.com/msgpack/msgpack/blob/master/spec.md /// </summary> public sealed class Packer { public static byte[] Pack(Value[] val) { Packer packer = new Packer(); packer.PackValueArray(val); return packer.ToByteArray(); } public static byte[] Pack(IList val) { Packer packer = new Packer(); packer.PackList(val); return packer.ToByteArray(); } public static byte[] Pack(IDictionary val) { Packer packer = new Packer(); packer.PackMap(val); return packer.ToByteArray(); } private byte[] buffer; private int offset; private List<BufferItem> bufferList; public Packer() { this.buffer = ThreadLocalData.GetBuffer(); } public void PackValueArray(Value[] values) { PackArrayBegin(values.Length); foreach (Value value in values) { value.Pack(this); } } public void PackList(IList list) { PackArrayBegin(list.Count); foreach (object obj in list) { PackObject(obj); } } private void PackArrayBegin(int size) { if (size < 16) { PackByte((byte)(0x90 | size)); } else if (size < 65536) { PackShort(0xdc, (ushort)size); } else { PackInt(0xdd, (uint)size); } } public void PackMap(IDictionary map) { PackMapBegin(map.Count); foreach (DictionaryEntry entry in map) { PackObject(entry.Key); PackObject(entry.Value); } } private void PackMapBegin(int size) { if (size < 16) { PackByte((byte) (0x80 | size)); } else if (size < 65536) { PackShort(0xde, (ushort)size); } else { PackInt(0xdf, (uint)size); } } public void PackBytes(byte[] b) { PackByteArrayBegin(b.Length + 1); PackByte(ParticleType.BLOB); PackByteArray(b, 0, b.Length); } public void PackBytes(byte[] b, int offset, int length) { PackByteArrayBegin(length + 1); PackByte(ParticleType.BLOB); PackByteArray(b, offset, length); } public void PackBlob(object val) { using (MemoryStream ms = new MemoryStream()) { Formatter.Default.Serialize(ms, val); byte[] bytes = ms.ToArray(); PackByteArrayBegin(bytes.Length + 1); PackByte(ParticleType.CSHARP_BLOB); PackByteArray(bytes, 0, bytes.Length); } } private void PackByteArrayBegin(int len) { if (len < 32) { PackByte((byte)(0xa0 | len)); } else if (len < 65536) { PackShort(0xda, (ushort)len); } else { PackInt(0xdb, (uint)len); } } private void PackObject(object obj) { if (obj == null) { PackNil(); return; } if (obj is Value) { Value value = (Value) obj; value.Pack(this); return; } if (obj is byte[]) { PackBytes((byte[]) obj); return; } if (obj is string) { PackString((string) obj); return; } if (obj is int) { PackNumber((int) obj); return; } if (obj is long) { PackNumber((long) obj); return; } if (obj is double) { PackDouble((double)obj); return; } if (obj is float) { PackFloat((float)obj); return; } if (obj is IList) { PackList((IList) obj); return; } if (obj is IDictionary) { PackMap((IDictionary) obj); return; } PackBlob(obj); } public void PackNumber(long val) { if (val >= 0L) { if (val < 128L) { PackByte((byte)val); return; } if (val < 256L) { PackByte(0xcc, (byte)val); return; } if (val < 65536L) { PackShort(0xcd, (ushort)val); return; } if (val < 4294967296L) { PackInt(0xce, (uint)val); return; } PackLong(0xcf, (ulong)val); } else { if (val >= -32) { PackByte((byte)(0xe0 | ((int)val + 32))); return; } if (val >= byte.MinValue) { PackByte(0xd0, (byte)val); return; } if (val >= short.MinValue) { PackShort(0xd1, (ushort)val); return; } if (val >= int.MinValue) { PackInt(0xd2, (uint)val); return; } PackLong(0xd3, (ulong)val); } } public void PackNumber(ulong val) { if (val < 128L) { PackByte((byte)val); return; } if (val < 256L) { PackByte(0xcc, (byte)val); return; } if (val < 65536L) { PackShort(0xcd, (ushort)val); return; } if (val < 4294967296L) { PackInt(0xce, (uint)val); return; } PackLong(0xcf, val); } public void PackBoolean(bool val) { if (val) { PackByte(0xc3); } else { PackByte(0xc2); } } public void PackString(string val) { int size = ByteUtil.EstimateSizeUtf8(val) + 1; PackByteArrayBegin(size); if (offset + size > buffer.Length) { Resize(size); } buffer[offset++] = (byte)ParticleType.STRING; offset += ByteUtil.StringToUtf8(val, buffer, offset); } private void PackByteArray(byte[] src, int srcOffset, int srcLength) { if (offset + srcLength > buffer.Length) { Resize(srcLength); } Array.Copy(src, srcOffset, buffer, offset, srcLength); offset += srcLength; } public void PackDouble(double val) { if (offset + 9 > buffer.Length) { Resize(9); } buffer[offset++] = (byte)0xcb; offset += ByteUtil.DoubleToBytes(val, buffer, offset); } public void PackFloat(float val) { if (offset + 5 > buffer.Length) { Resize(5); } buffer[offset++] = (byte)0xca; offset += ByteUtil.FloatToBytes(val, buffer, offset); } private void PackLong(int type, ulong val) { if (offset + 9 > buffer.Length) { Resize(9); } buffer[offset++] = (byte)type; ByteUtil.LongToBytes(val, buffer, offset); offset += 8; } private void PackInt(int type, uint val) { if (offset + 5 > buffer.Length) { Resize(5); } buffer[offset++] = (byte)type; ByteUtil.IntToBytes(val, buffer, offset); offset += 4; } private void PackShort(int type, ushort val) { if (offset + 3 > buffer.Length) { Resize(3); } buffer[offset++] = (byte)type; ByteUtil.ShortToBytes(val, buffer, offset); offset += 2; } private void PackByte(int type, byte val) { if (offset + 2 > buffer.Length) { Resize(2); } buffer[offset++] = (byte)type; buffer[offset++] = val; } public void PackNil() { if (offset >= buffer.Length) { Resize(1); } buffer[offset++] = unchecked((byte)0xc0); } private void PackByte(byte val) { if (offset >= buffer.Length) { Resize(1); } buffer[offset++] = val; } private void Resize(int size) { if (bufferList == null) { bufferList = new List<BufferItem>(); } bufferList.Add(new BufferItem(buffer, offset)); if (size < buffer.Length) { size = buffer.Length; } buffer = new byte[size]; offset = 0; } public byte[] ToByteArray() { if (bufferList != null) { int size = offset; foreach (BufferItem item in bufferList) { size += item.length; } byte[] target = new byte[size]; size = 0; foreach (BufferItem item in bufferList) { Array.Copy(item.buffer, 0, target, size, item.length); size += item.length; } Array.Copy(buffer, 0, target, size, offset); return target; } else { byte[] target = new byte[offset]; Array.Copy(buffer, 0, target, 0, offset); return target; } } private sealed class BufferItem { internal byte[] buffer; internal int length; internal BufferItem(byte[] buffer, int length) { this.buffer = buffer; this.length = length; } } } }
namespace android.graphics { [global::MonoJavaBridge.JavaClass()] public partial class BitmapFactory : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected BitmapFactory(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass()] public partial class Options : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected Options(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public virtual void requestCancelDecode() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.graphics.BitmapFactory.Options.staticClass, "requestCancelDecode", "()V", ref global::android.graphics.BitmapFactory.Options._m0); } private static global::MonoJavaBridge.MethodId _m1; public Options() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory.Options._m1.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory.Options._m1 = @__env.GetMethodIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.BitmapFactory.Options.staticClass, global::android.graphics.BitmapFactory.Options._m1); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _inJustDecodeBounds2245; public bool inJustDecodeBounds { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetBooleanField(this.JvmHandle, _inJustDecodeBounds2245); } set { } } internal static global::MonoJavaBridge.FieldId _inSampleSize2246; public int inSampleSize { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _inSampleSize2246); } set { } } internal static global::MonoJavaBridge.FieldId _inPreferredConfig2247; public global::android.graphics.Bitmap.Config inPreferredConfig { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap.Config>(@__env.GetObjectField(this.JvmHandle, _inPreferredConfig2247)) as android.graphics.Bitmap.Config; } set { } } internal static global::MonoJavaBridge.FieldId _inDither2248; public bool inDither { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetBooleanField(this.JvmHandle, _inDither2248); } set { } } internal static global::MonoJavaBridge.FieldId _inDensity2249; public int inDensity { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _inDensity2249); } set { } } internal static global::MonoJavaBridge.FieldId _inTargetDensity2250; public int inTargetDensity { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _inTargetDensity2250); } set { } } internal static global::MonoJavaBridge.FieldId _inScreenDensity2251; public int inScreenDensity { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _inScreenDensity2251); } set { } } internal static global::MonoJavaBridge.FieldId _inScaled2252; public bool inScaled { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetBooleanField(this.JvmHandle, _inScaled2252); } set { } } internal static global::MonoJavaBridge.FieldId _inPurgeable2253; public bool inPurgeable { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetBooleanField(this.JvmHandle, _inPurgeable2253); } set { } } internal static global::MonoJavaBridge.FieldId _inInputShareable2254; public bool inInputShareable { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetBooleanField(this.JvmHandle, _inInputShareable2254); } set { } } internal static global::MonoJavaBridge.FieldId _outWidth2255; public int outWidth { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _outWidth2255); } set { } } internal static global::MonoJavaBridge.FieldId _outHeight2256; public int outHeight { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetIntField(this.JvmHandle, _outHeight2256); } set { } } internal static global::MonoJavaBridge.FieldId _outMimeType2257; public global::java.lang.String outMimeType { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<java.lang.String>(@__env.GetObjectField(this.JvmHandle, _outMimeType2257)) as java.lang.String; } set { } } internal static global::MonoJavaBridge.FieldId _inTempStorage2258; public byte[] inTempStorage { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.GetObjectField(this.JvmHandle, _inTempStorage2258)) as byte[]; } set { } } internal static global::MonoJavaBridge.FieldId _mCancel2259; public bool mCancel { get { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return @__env.GetBooleanField(this.JvmHandle, _mCancel2259); } set { } } static Options() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.BitmapFactory.Options.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/BitmapFactory$Options")); global::android.graphics.BitmapFactory.Options._inJustDecodeBounds2245 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inJustDecodeBounds", "Z"); global::android.graphics.BitmapFactory.Options._inSampleSize2246 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inSampleSize", "I"); global::android.graphics.BitmapFactory.Options._inPreferredConfig2247 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inPreferredConfig", "Landroid/graphics/Bitmap$Config;"); global::android.graphics.BitmapFactory.Options._inDither2248 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inDither", "Z"); global::android.graphics.BitmapFactory.Options._inDensity2249 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inDensity", "I"); global::android.graphics.BitmapFactory.Options._inTargetDensity2250 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inTargetDensity", "I"); global::android.graphics.BitmapFactory.Options._inScreenDensity2251 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inScreenDensity", "I"); global::android.graphics.BitmapFactory.Options._inScaled2252 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inScaled", "Z"); global::android.graphics.BitmapFactory.Options._inPurgeable2253 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inPurgeable", "Z"); global::android.graphics.BitmapFactory.Options._inInputShareable2254 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inInputShareable", "Z"); global::android.graphics.BitmapFactory.Options._outWidth2255 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "outWidth", "I"); global::android.graphics.BitmapFactory.Options._outHeight2256 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "outHeight", "I"); global::android.graphics.BitmapFactory.Options._outMimeType2257 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "outMimeType", "Ljava/lang/String;"); global::android.graphics.BitmapFactory.Options._inTempStorage2258 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "inTempStorage", "[B"); global::android.graphics.BitmapFactory.Options._mCancel2259 = @__env.GetFieldIDNoThrow(global::android.graphics.BitmapFactory.Options.staticClass, "mCancel", "Z"); } } private static global::MonoJavaBridge.MethodId _m0; public static global::android.graphics.Bitmap decodeStream(java.io.InputStream arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m0.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m0 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeStream", "(Ljava/io/InputStream;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m1; public static global::android.graphics.Bitmap decodeStream(java.io.InputStream arg0, android.graphics.Rect arg1, android.graphics.BitmapFactory.Options arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m1.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m1 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeStream", "(Ljava/io/InputStream;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m2; public static global::android.graphics.Bitmap decodeByteArray(byte[] arg0, int arg1, int arg2, android.graphics.BitmapFactory.Options arg3) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m2.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m2 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeByteArray", "([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m3; public static global::android.graphics.Bitmap decodeByteArray(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m3.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m3 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeByteArray", "([BII)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m4; public static global::android.graphics.Bitmap decodeFile(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m4.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m4 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeFile", "(Ljava/lang/String;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m5; public static global::android.graphics.Bitmap decodeFile(java.lang.String arg0, android.graphics.BitmapFactory.Options arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m5.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m5 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeFile", "(Ljava/lang/String;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m6; public static global::android.graphics.Bitmap decodeResourceStream(android.content.res.Resources arg0, android.util.TypedValue arg1, java.io.InputStream arg2, android.graphics.Rect arg3, android.graphics.BitmapFactory.Options arg4) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m6.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m6 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeResourceStream", "(Landroid/content/res/Resources;Landroid/util/TypedValue;Ljava/io/InputStream;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m7; public static global::android.graphics.Bitmap decodeResource(android.content.res.Resources arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m7.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m7 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeResource", "(Landroid/content/res/Resources;I)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m8; public static global::android.graphics.Bitmap decodeResource(android.content.res.Resources arg0, int arg1, android.graphics.BitmapFactory.Options arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m8.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m8 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeResource", "(Landroid/content/res/Resources;ILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m9; public static global::android.graphics.Bitmap decodeFileDescriptor(java.io.FileDescriptor arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m9.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m9 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeFileDescriptor", "(Ljava/io/FileDescriptor;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m10; public static global::android.graphics.Bitmap decodeFileDescriptor(java.io.FileDescriptor arg0, android.graphics.Rect arg1, android.graphics.BitmapFactory.Options arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m10.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m10 = @__env.GetStaticMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "decodeFileDescriptor", "(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap;"); return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.graphics.Bitmap>(@__env.CallStaticObjectMethod(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2))) as android.graphics.Bitmap; } private static global::MonoJavaBridge.MethodId _m11; public BitmapFactory() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::android.graphics.BitmapFactory._m11.native == global::System.IntPtr.Zero) global::android.graphics.BitmapFactory._m11 = @__env.GetMethodIDNoThrow(global::android.graphics.BitmapFactory.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.BitmapFactory.staticClass, global::android.graphics.BitmapFactory._m11); Init(@__env, handle); } static BitmapFactory() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.graphics.BitmapFactory.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/BitmapFactory")); } } }
// <copyright file="Constants.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-2010 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> namespace MathNet.Numerics { /// <summary> /// A collection of frequently used mathematical constants. /// </summary> public static class Constants { #region Mathematical Constants /// <summary>The number e</summary> public const double E = 2.7182818284590452353602874713526624977572470937000d; /// <summary>The number log[2](e)</summary> public const double Log2E = 1.4426950408889634073599246810018921374266459541530d; /// <summary>The number log[10](e)</summary> public const double Log10E = 0.43429448190325182765112891891660508229439700580366d; /// <summary>The number log[e](2)</summary> public const double Ln2 = 0.69314718055994530941723212145817656807550013436026d; /// <summary>The number log[e](10)</summary> public const double Ln10 = 2.3025850929940456840179914546843642076011014886288d; /// <summary>The number log[e](pi)</summary> public const double LnPi = 1.1447298858494001741434273513530587116472948129153d; /// <summary>The number log[e](2*pi)/2</summary> public const double Ln2PiOver2 = 0.91893853320467274178032973640561763986139747363780d; /// <summary>The number 1/e</summary> public const double InvE = 0.36787944117144232159552377016146086744581113103176d; /// <summary>The number sqrt(e)</summary> public const double SqrtE = 1.6487212707001281468486507878141635716537761007101d; /// <summary>The number sqrt(2)</summary> public const double Sqrt2 = 1.4142135623730950488016887242096980785696718753769d; /// <summary>The number sqrt(3)</summary> public const double Sqrt3 = 1.7320508075688772935274463415058723669428052538104d; /// <summary>The number sqrt(1/2) = 1/sqrt(2) = sqrt(2)/2</summary> public const double Sqrt1Over2 = 0.70710678118654752440084436210484903928483593768845d; /// <summary>The number sqrt(3)/2</summary> public const double HalfSqrt3 = 0.86602540378443864676372317075293618347140262690520d; /// <summary>The number pi</summary> public const double Pi = 3.1415926535897932384626433832795028841971693993751d; /// <summary>The number pi*2</summary> public const double Pi2 = 6.2831853071795864769252867665590057683943387987502d; /// <summary>The number pi/2</summary> public const double PiOver2 = 1.5707963267948966192313216916397514420985846996876d; /// <summary>The number pi*3/2</summary> public const double Pi3Over2 = 4.71238898038468985769396507491925432629575409906266d; /// <summary>The number pi/4</summary> public const double PiOver4 = 0.78539816339744830961566084581987572104929234984378d; /// <summary>The number sqrt(pi)</summary> public const double SqrtPi = 1.7724538509055160272981674833411451827975494561224d; /// <summary>The number sqrt(2pi)</summary> public const double Sqrt2Pi = 2.5066282746310005024157652848110452530069867406099d; /// <summary>The number sqrt(2*pi*e)</summary> public const double Sqrt2PiE = 4.1327313541224929384693918842998526494455219169913d; /// <summary>The number log(sqrt(2*pi))</summary> public const double LogSqrt2Pi = 0.91893853320467274178032973640561763986139747363778; /// <summary>The number log(sqrt(2*pi*e))</summary> public const double LogSqrt2PiE = 1.4189385332046727417803297364056176398613974736378d; /// <summary>The number log(2 * sqrt(e / pi))</summary> public const double LogTwoSqrtEOverPi = 0.6207822376352452223455184457816472122518527279025978; /// <summary>The number 1/pi</summary> public const double InvPi = 0.31830988618379067153776752674502872406891929148091d; /// <summary>The number 2/pi</summary> public const double TwoInvPi = 0.63661977236758134307553505349005744813783858296182d; /// <summary>The number 1/sqrt(pi)</summary> public const double InvSqrtPi = 0.56418958354775628694807945156077258584405062932899d; /// <summary>The number 1/sqrt(2pi)</summary> public const double InvSqrt2Pi = 0.39894228040143267793994605993438186847585863116492d; /// <summary>The number 2/sqrt(pi)</summary> public const double TwoInvSqrtPi = 1.1283791670955125738961589031215451716881012586580d; /// <summary>The number 2 * sqrt(e / pi)</summary> public const double TwoSqrtEOverPi = 1.8603827342052657173362492472666631120594218414085755; /// <summary>The number (pi)/180 - factor to convert from Degree (deg) to Radians (rad).</summary> /// <seealso cref="Trig.DegreeToRadian"/> /// <seealso cref="Trig.RadianToDegree"/> public const double Degree = 0.017453292519943295769236907684886127134428718885417d; /// <summary>The number (pi)/200 - factor to convert from NewGrad (grad) to Radians (rad).</summary> /// <seealso cref="Trig.GradToRadian"/> /// <seealso cref="Trig.RadianToGrad"/> public const double Grad = 0.015707963267948966192313216916397514420985846996876d; /// <summary>The number ln(10)/20 - factor to convert from Power Decibel (dB) to Neper (Np). Use this version when the Decibel represent a power gain but the compared values are not powers (e.g. amplitude, current, voltage).</summary> public const double PowerDecibel = 0.11512925464970228420089957273421821038005507443144d; /// <summary>The number ln(10)/10 - factor to convert from Neutral Decibel (dB) to Neper (Np). Use this version when either both or neither of the Decibel and the compared values represent powers.</summary> public const double NeutralDecibel = 0.23025850929940456840179914546843642076011014886288d; /// <summary>The Catalan constant</summary> /// <remarks>Sum(k=0 -> inf){ (-1)^k/(2*k + 1)2 }</remarks> public const double Catalan = 0.9159655941772190150546035149323841107741493742816721342664981196217630197762547694794d; /// <summary>The Euler-Mascheroni constant</summary> /// <remarks>lim(n -> inf){ Sum(k=1 -> n) { 1/k - log(n) } }</remarks> public const double EulerMascheroni = 0.5772156649015328606065120900824024310421593359399235988057672348849d; /// <summary>The number (1+sqrt(5))/2, also known as the golden ratio</summary> public const double GoldenRatio = 1.6180339887498948482045868343656381177203091798057628621354486227052604628189024497072d; /// <summary>The Glaisher constant</summary> /// <remarks>e^(1/12 - Zeta(-1))</remarks> public const double Glaisher = 1.2824271291006226368753425688697917277676889273250011920637400217404063088588264611297d; /// <summary>The Khinchin constant</summary> /// <remarks>prod(k=1 -> inf){1+1/(k*(k+2))^log(k,2)}</remarks> public const double Khinchin = 2.6854520010653064453097148354817956938203822939944629530511523455572188595371520028011d; /// <summary> /// The size of a double in bytes. /// </summary> public const int SizeOfDouble = sizeof(double); /// <summary> /// The size of an int in bytes. /// </summary> public const int SizeOfInt = sizeof(int); /// <summary> /// The size of a float in bytes. /// </summary> public const int SizeOfFloat = sizeof(float); /// <summary> /// The size of a Complex in bytes. /// </summary> public const int SizeOfComplex = 2 * SizeOfDouble; /// <summary> /// The size of a Complex in bytes. /// </summary> public const int SizeOfComplex32 = 2 * SizeOfFloat; #endregion #region UNIVERSAL CONSTANTS /// <summary>Speed of Light in Vacuum: c_0 = 2.99792458e8 [m s^-1] (defined, exact; 2007 CODATA)</summary> public const double SpeedOfLight = 2.99792458e8; /// <summary>Magnetic Permeability in Vacuum: mu_0 = 4*Pi * 10^-7 [N A^-2 = kg m A^-2 s^-2] (defined, exact; 2007 CODATA)</summary> public const double MagneticPermeability = 1.2566370614359172953850573533118011536788677597500e-6; /// <summary>Electric Permittivity in Vacuum: epsilon_0 = 1/(mu_0*c_0^2) [F m^-1 = A^2 s^4 kg^-1 m^-3] (defined, exact; 2007 CODATA)</summary> public const double ElectricPermittivity = 8.8541878171937079244693661186959426889222899381429e-12; /// <summary>Characteristic Impedance of Vacuum: Z_0 = mu_0*c_0 [Ohm = m^2 kg s^-3 A^-2] (defined, exact; 2007 CODATA)</summary> public const double CharacteristicImpedanceVacuum = 376.73031346177065546819840042031930826862350835242; /// <summary>Newtonian Constant of Gravitation: G = 6.67429e-11 [m^3 kg^-1 s^-2] (2007 CODATA)</summary> public const double GravitationalConstant = 6.67429e-11; /// <summary>Planck's constant: h = 6.62606896e-34 [J s = m^2 kg s^-1] (2007 CODATA)</summary> public const double PlancksConstant = 6.62606896e-34; /// <summary>Reduced Planck's constant: h_bar = h / (2*Pi) [J s = m^2 kg s^-1] (2007 CODATA)</summary> public const double DiracsConstant = 1.054571629e-34; /// <summary>Planck mass: m_p = (h_bar*c_0/G)^(1/2) [kg] (2007 CODATA)</summary> public const double PlancksMass = 2.17644e-8; /// <summary>Planck temperature: T_p = (h_bar*c_0^5/G)^(1/2)/k [K] (2007 CODATA)</summary> public const double PlancksTemperature = 1.416786e32; /// <summary>Planck length: l_p = h_bar/(m_p*c_0) [m] (2007 CODATA)</summary> public const double PlancksLength = 1.616253e-35; /// <summary>Planck time: t_p = l_p/c_0 [s] (2007 CODATA)</summary> public const double PlancksTime = 5.39124e-44; #endregion #region ELECTROMAGNETIC CONSTANTS /// <summary>Elementary Electron Charge: e = 1.602176487e-19 [C = A s] (2007 CODATA)</summary> public const double ElementaryCharge = 1.602176487e-19; /// <summary>Magnetic Flux Quantum: theta_0 = h/(2*e) [Wb = m^2 kg s^-2 A^-1] (2007 CODATA)</summary> public const double MagneticFluxQuantum = 2.067833668e-15; /// <summary>Conductance Quantum: G_0 = 2*e^2/h [S = m^-2 kg^-1 s^3 A^2] (2007 CODATA)</summary> public const double ConductanceQuantum = 7.7480917005e-5; /// <summary>Josephson Constant: K_J = 2*e/h [Hz V^-1] (2007 CODATA)</summary> public const double JosephsonConstant = 483597.891e9; /// <summary>Von Klitzing Constant: R_K = h/e^2 [Ohm = m^2 kg s^-3 A^-2] (2007 CODATA)</summary> public const double VonKlitzingConstant = 25812.807557; /// <summary>Bohr Magneton: mu_B = e*h_bar/2*m_e [J T^-1] (2007 CODATA)</summary> public const double BohrMagneton = 927.400915e-26; /// <summary>Nuclear Magneton: mu_N = e*h_bar/2*m_p [J T^-1] (2007 CODATA)</summary> public const double NuclearMagneton = 5.05078324e-27; #endregion #region ATOMIC AND NUCLEAR CONSTANTS /// <summary>Fine Structure Constant: alpha = e^2/4*Pi*e_0*h_bar*c_0 [1] (2007 CODATA)</summary> public const double FineStructureConstant = 7.2973525376e-3; /// <summary>Rydberg Constant: R_infty = alpha^2*m_e*c_0/2*h [m^-1] (2007 CODATA)</summary> public const double RydbergConstant = 10973731.568528; /// <summary>Bor Radius: a_0 = alpha/4*Pi*R_infty [m] (2007 CODATA)</summary> public const double BohrRadius = 0.52917720859e-10; /// <summary>Hartree Energy: E_h = 2*R_infty*h*c_0 [J] (2007 CODATA)</summary> public const double HartreeEnergy = 4.35974394e-18; /// <summary>Quantum of Circulation: h/2*m_e [m^2 s^-1] (2007 CODATA)</summary> public const double QuantumOfCirculation = 3.6369475199e-4; /// <summary>Fermi Coupling Constant: G_F/(h_bar*c_0)^3 [GeV^-2] (2007 CODATA)</summary> public const double FermiCouplingConstant = 1.16637e-5; /// <summary>Weak Mixin Angle: sin^2(theta_W) [1] (2007 CODATA)</summary> public const double WeakMixingAngle = 0.22256; /// <summary>Electron Mass: [kg] (2007 CODATA)</summary> public const double ElectronMass = 9.10938215e-31; /// <summary>Electron Mass Energy Equivalent: [J] (2007 CODATA)</summary> public const double ElectronMassEnergyEquivalent = 8.18710438e-14; /// <summary>Electron Molar Mass: [kg mol^-1] (2007 CODATA)</summary> public const double ElectronMolarMass = 5.4857990943e-7; /// <summary>Electron Compton Wavelength: [m] (2007 CODATA)</summary> public const double ComptonWavelength = 2.4263102175e-12; /// <summary>Classical Electron Radius: [m] (2007 CODATA)</summary> public const double ClassicalElectronRadius = 2.8179402894e-15; /// <summary>Tomson Cross Section: [m^2] (2002 CODATA)</summary> public const double ThomsonCrossSection = 0.6652458558e-28; /// <summary>Electron Magnetic Moment: [J T^-1] (2007 CODATA)</summary> public const double ElectronMagneticMoment = -928.476377e-26; /// <summary>Electon G-Factor: [1] (2007 CODATA)</summary> public const double ElectronGFactor = -2.0023193043622; /// <summary>Muon Mass: [kg] (2007 CODATA)</summary> public const double MuonMass = 1.88353130e-28; /// <summary>Muon Mass Energy Equivalent: [J] (2007 CODATA)</summary> public const double MuonMassEnegryEquivalent = 1.692833511e-11; /// <summary>Muon Molar Mass: [kg mol^-1] (2007 CODATA)</summary> public const double MuonMolarMass = 0.1134289256e-3; /// <summary>Muon Compton Wavelength: [m] (2007 CODATA)</summary> public const double MuonComptonWavelength = 11.73444104e-15; /// <summary>Muon Magnetic Moment: [J T^-1] (2007 CODATA)</summary> public const double MuonMagneticMoment = -4.49044786e-26; /// <summary>Muon G-Factor: [1] (2007 CODATA)</summary> public const double MuonGFactor = -2.0023318414; /// <summary>Tau Mass: [kg] (2007 CODATA)</summary> public const double TauMass = 3.16777e-27; /// <summary>Tau Mass Energy Equivalent: [J] (2007 CODATA)</summary> public const double TauMassEnergyEquivalent = 2.84705e-10; /// <summary>Tau Molar Mass: [kg mol^-1] (2007 CODATA)</summary> public const double TauMolarMass = 1.90768e-3; /// <summary>Tau Compton Wavelength: [m] (2007 CODATA)</summary> public const double TauComptonWavelength = 0.69772e-15; /// <summary>Proton Mass: [kg] (2007 CODATA)</summary> public const double ProtonMass = 1.672621637e-27; /// <summary>Proton Mass Energy Equivalent: [J] (2007 CODATA)</summary> public const double ProtonMassEnergyEquivalent = 1.503277359e-10; /// <summary>Proton Molar Mass: [kg mol^-1] (2007 CODATA)</summary> public const double ProtonMolarMass = 1.00727646677e-3; /// <summary>Proton Compton Wavelength: [m] (2007 CODATA)</summary> public const double ProtonComptonWavelength = 1.3214098446e-15; /// <summary>Proton Magnetic Moment: [J T^-1] (2007 CODATA)</summary> public const double ProtonMagneticMoment = 1.410606662e-26; /// <summary>Proton G-Factor: [1] (2007 CODATA)</summary> public const double ProtonGFactor = 5.585694713; /// <summary>Proton Shielded Magnetic Moment: [J T^-1] (2007 CODATA)</summary> public const double ShieldedProtonMagneticMoment = 1.410570419e-26; /// <summary>Proton Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary> public const double ProtonGyromagneticRatio = 2.675222099e8; /// <summary>Proton Shielded Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary> public const double ShieldedProtonGyromagneticRatio = 2.675153362e8; /// <summary>Neutron Mass: [kg] (2007 CODATA)</summary> public const double NeutronMass = 1.674927212e-27; /// <summary>Neutron Mass Energy Equivalent: [J] (2007 CODATA)</summary> public const double NeutronMassEnegryEquivalent = 1.505349506e-10; /// <summary>Neutron Molar Mass: [kg mol^-1] (2007 CODATA)</summary> public const double NeutronMolarMass = 1.00866491597e-3; /// <summary>Neuron Compton Wavelength: [m] (2007 CODATA)</summary> public const double NeutronComptonWavelength = 1.3195908951e-1; /// <summary>Neutron Magnetic Moment: [J T^-1] (2007 CODATA)</summary> public const double NeutronMagneticMoment = -0.96623641e-26; /// <summary>Neutron G-Factor: [1] (2007 CODATA)</summary> public const double NeutronGFactor = -3.82608545; /// <summary>Neutron Gyro-Magnetic Ratio: [s^-1 T^-1] (2007 CODATA)</summary> public const double NeutronGyromagneticRatio = 1.83247185e8; /// <summary>Deuteron Mass: [kg] (2007 CODATA)</summary> public const double DeuteronMass = 3.34358320e-27; /// <summary>Deuteron Mass Energy Equivalent: [J] (2007 CODATA)</summary> public const double DeuteronMassEnegryEquivalent = 3.00506272e-10; /// <summary>Deuteron Molar Mass: [kg mol^-1] (2007 CODATA)</summary> public const double DeuteronMolarMass = 2.013553212725e-3; /// <summary>Deuteron Magnetic Moment: [J T^-1] (2007 CODATA)</summary> public const double DeuteronMagneticMoment = 0.433073465e-26; /// <summary>Helion Mass: [kg] (2007 CODATA)</summary> public const double HelionMass = 5.00641192e-27; /// <summary>Helion Mass Energy Equivalent: [J] (2007 CODATA)</summary> public const double HelionMassEnegryEquivalent = 4.49953864e-10; /// <summary>Helion Molar Mass: [kg mol^-1] (2007 CODATA)</summary> public const double HelionMolarMass = 3.0149322473e-3; /// <summary>Avogadro constant: [mol^-1] (2010 CODATA)</summary> public const double Avogadro = 6.0221412927e23; #endregion #region Scientific Prefixes /// <summary>The SI prefix factor corresponding to 1 000 000 000 000 000 000 000 000</summary> public const double Yotta = 1e24; /// <summary>The SI prefix factor corresponding to 1 000 000 000 000 000 000 000</summary> public const double Zetta = 1e21; /// <summary>The SI prefix factor corresponding to 1 000 000 000 000 000 000</summary> public const double Exa = 1e18; /// <summary>The SI prefix factor corresponding to 1 000 000 000 000 000</summary> public const double Peta = 1e15; /// <summary>The SI prefix factor corresponding to 1 000 000 000 000</summary> public const double Tera = 1e12; /// <summary>The SI prefix factor corresponding to 1 000 000 000</summary> public const double Giga = 1e9; /// <summary>The SI prefix factor corresponding to 1 000 000</summary> public const double Mega = 1e6; /// <summary>The SI prefix factor corresponding to 1 000</summary> public const double Kilo = 1e3; /// <summary>The SI prefix factor corresponding to 100</summary> public const double Hecto = 1e2; /// <summary>The SI prefix factor corresponding to 10</summary> public const double Deca = 1e1; /// <summary>The SI prefix factor corresponding to 0.1</summary> public const double Deci = 1e-1; /// <summary>The SI prefix factor corresponding to 0.01</summary> public const double Centi = 1e-2; /// <summary>The SI prefix factor corresponding to 0.001</summary> public const double Milli = 1e-3; /// <summary>The SI prefix factor corresponding to 0.000 001</summary> public const double Micro = 1e-6; /// <summary>The SI prefix factor corresponding to 0.000 000 001</summary> public const double Nano = 1e-9; /// <summary>The SI prefix factor corresponding to 0.000 000 000 001</summary> public const double Pico = 1e-12; /// <summary>The SI prefix factor corresponding to 0.000 000 000 000 001</summary> public const double Femto = 1e-15; /// <summary>The SI prefix factor corresponding to 0.000 000 000 000 000 001</summary> public const double Atto = 1e-18; /// <summary>The SI prefix factor corresponding to 0.000 000 000 000 000 000 001</summary> public const double Zepto = 1e-21; /// <summary>The SI prefix factor corresponding to 0.000 000 000 000 000 000 000 001</summary> public const double Yocto = 1e-24; #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; /// <summary> /// Convert.ToUInt64(String) /// </summary> public class ConvertToUInt6416 { public static int Main() { ConvertToUInt6416 convertToUInt6416 = new ConvertToUInt6416(); TestLibrary.TestFramework.BeginTestCase("ConvertToUInt6416"); if (convertToUInt6416.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; retVal = NegTest4() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt64 from string 1"); try { string strVal = UInt64.MaxValue.ToString(); ulong ulongVal = Convert.ToUInt64(strVal); if (ulongVal != UInt64.MaxValue) { TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt64 from string 2"); try { string strVal = UInt64.MinValue.ToString(); ulong ulongVal = Convert.ToUInt64(strVal); if (ulongVal != UInt64.MinValue) { TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt64 from string 3"); try { string strVal = "-" + UInt64.MinValue.ToString(); ulong ulongVal = Convert.ToUInt64(strVal); if (ulongVal != UInt64.MinValue) { TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt64 from string 4"); try { ulong sourceVal = (ulong)TestLibrary.Generator.GetInt64(-55); string strVal = "+" + sourceVal.ToString(); ulong ulongVal = Convert.ToUInt64(strVal); if (ulongVal != sourceVal) { TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Convert to UInt64 from string 5"); try { string strVal = null; ulong ulongVal = Convert.ToUInt64(strVal); if (ulongVal != 0) { TestLibrary.TestFramework.LogError("009", "The ExpectResult is not the ActualResult"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region NegativeTest public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: the string represents a number less than MinValue"); try { int intVal = this.GetInt32(1, Int32.MaxValue); string strVal = "-" + intVal.ToString(); ulong ulongVal = Convert.ToUInt64(strVal); TestLibrary.TestFramework.LogError("N001", "the string represents a number less than MinValue but not throw exception"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a number greater than MaxValue"); try { string strVal = "18446744073709551616"; ulong ulongVal = Convert.ToUInt64(strVal); TestLibrary.TestFramework.LogError("N003", "the string represents a number greater than MaxValue but not throw exception"); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: the string does not consist of an optional sign followed by a sequence of digits "); try { string strVal = "helloworld"; ulong ulongVal = Convert.ToUInt64(strVal); TestLibrary.TestFramework.LogError("N005", "the string does not consist of an optional sign followed by a sequence of digits but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e); retVal = false; } return retVal; } public bool NegTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest4: the string is empty string"); try { string strVal = string.Empty; ulong ulongVal = Convert.ToUInt64(strVal); TestLibrary.TestFramework.LogError("N007", "the string is empty string but not throw exception"); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e); retVal = false; } return retVal; } #endregion #region HelpMethod private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } #endregion }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using MSBuild = Microsoft.Build.Evaluation; using MSBuildExecution = Microsoft.Build.Execution; namespace Microsoft.VisualStudio.Project { /// <summary> /// Allows projects to group outputs according to usage. /// </summary> [CLSCompliant(false), ComVisible(true)] public class OutputGroup : IVsOutputGroup2 { #region fields private ProjectConfig projectCfg; private ProjectNode project; private List<Output> outputs = new List<Output>(); private Output keyOutput; private string name; private string targetName; #endregion #region properties /// <summary> /// Get the project configuration object associated with this output group /// </summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cfg")] protected ProjectConfig ProjectCfg { get { return projectCfg; } } /// <summary> /// Get the project object that produces this output group. /// </summary> protected ProjectNode Project { get { return project; } } /// <summary> /// Gets the msbuild target name which is assciated to the outputgroup. /// ProjectNode defines a static collection of output group names and their associated MsBuild target /// </summary> protected string TargetName { get { return targetName; } } #endregion #region ctors /// <summary> /// Constructor for IVSOutputGroup2 implementation /// </summary> /// <param name="outputName">Name of the output group. See VS_OUTPUTGROUP_CNAME_Build in vsshell.idl for the list of standard values</param> /// <param name="msBuildTargetName">MSBuild target name</param> /// <param name="projectManager">Project that produce this output</param> /// <param name="configuration">Configuration that produce this output</param> public OutputGroup(string outputName, string msBuildTargetName, ProjectNode projectManager, ProjectConfig configuration) { if(outputName == null) throw new ArgumentNullException("outputName"); if(msBuildTargetName == null) throw new ArgumentNullException("outputName"); if(projectManager == null) throw new ArgumentNullException("projectManager"); if(configuration == null) throw new ArgumentNullException("configuration"); name = outputName; targetName = msBuildTargetName; project = projectManager; projectCfg = configuration; } #endregion #region virtual methods protected virtual void Refresh() { // Let MSBuild know which configuration we are working with project.SetConfiguration(projectCfg.ConfigName); // Generate dependencies if such a task exist const string generateDependencyList = "AllProjectOutputGroups"; if(project.BuildProject.Targets.ContainsKey(generateDependencyList)) { bool succeeded = false; project.BuildTarget(generateDependencyList, out succeeded); Debug.Assert(succeeded, "Failed to build target: " + generateDependencyList); } // Rebuild the content of our list of output string outputType = this.targetName + "Output"; this.outputs.Clear(); foreach (MSBuildExecution.ProjectItemInstance assembly in project.CurrentConfig.GetItems(outputType)) { Output output = new Output(project, assembly); this.outputs.Add(output); // See if it is our key output if(String.Compare(assembly.GetMetadataValue("IsKeyOutput"), true.ToString(), StringComparison.OrdinalIgnoreCase) == 0) keyOutput = output; } project.SetCurrentConfiguration(); // Now that the group is built we have to check if it is invalidated by a property // change on the project. project.OnProjectPropertyChanged += new EventHandler<ProjectPropertyChangedArgs>(OnProjectPropertyChanged); } public virtual void InvalidateGroup() { // Set keyOutput to null so that a refresh will be performed the next time // a property getter is called. if(null != keyOutput) { // Once the group is invalidated there is no more reason to listen for events. project.OnProjectPropertyChanged -= new EventHandler<ProjectPropertyChangedArgs>(OnProjectPropertyChanged); } keyOutput = null; } #endregion #region event handlers private void OnProjectPropertyChanged(object sender, ProjectPropertyChangedArgs args) { // In theory here we should decide if we have to invalidate the group according with the kind of property // that is changed. InvalidateGroup(); } #endregion #region IVsOutputGroup2 Members public virtual int get_CanonicalName(out string pbstrCanonicalName) { pbstrCanonicalName = this.name; return VSConstants.S_OK; } public virtual int get_DeployDependencies(uint celt, IVsDeployDependency[] rgpdpd, uint[] pcActual) { return VSConstants.E_NOTIMPL; } public virtual int get_Description(out string pbstrDescription) { pbstrDescription = null; string description; int hr = this.get_CanonicalName(out description); if(ErrorHandler.Succeeded(hr)) pbstrDescription = this.Project.GetOutputGroupDescription(description); return hr; } public virtual int get_DisplayName(out string pbstrDisplayName) { pbstrDisplayName = null; string displayName; int hr = this.get_CanonicalName(out displayName); if(ErrorHandler.Succeeded(hr)) pbstrDisplayName = this.Project.GetOutputGroupDisplayName(displayName); return hr; } public virtual int get_KeyOutput(out string pbstrCanonicalName) { pbstrCanonicalName = null; if(keyOutput == null) Refresh(); if(keyOutput == null) { pbstrCanonicalName = String.Empty; return VSConstants.S_FALSE; } return keyOutput.get_CanonicalName(out pbstrCanonicalName); } public virtual int get_KeyOutputObject(out IVsOutput2 ppKeyOutput) { if(keyOutput == null) Refresh(); ppKeyOutput = keyOutput; if(ppKeyOutput == null) return VSConstants.S_FALSE; return VSConstants.S_OK; } public virtual int get_Outputs(uint celt, IVsOutput2[] rgpcfg, uint[] pcActual) { // Ensure that we are refreshed. This is somewhat of a hack that enables project to // project reference scenarios to work. Normally, output groups are populated as part // of build. However, in the project to project reference case, what ends up happening // is that the referencing projects requests the referenced project's output group // before a build is done on the referenced project. // // Furthermore, the project auto toolbox manager requires output groups to be populated // on project reopen as well... // // In the end, this is probably the right thing to do, though -- as it keeps the output // groups always up to date. Refresh(); // See if only the caller only wants to know the count if(celt == 0 || rgpcfg == null) { if(pcActual != null && pcActual.Length > 0) pcActual[0] = (uint)outputs.Count; return VSConstants.S_OK; } // Fill the array with our outputs uint count = 0; foreach(Output output in outputs) { if(rgpcfg.Length > count && celt > count && output != null) { rgpcfg[count] = output; ++count; } } if(pcActual != null && pcActual.Length > 0) pcActual[0] = count; // If the number asked for does not match the number returned, return S_FALSE return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE; } public virtual int get_ProjectCfg(out IVsProjectCfg2 ppIVsProjectCfg2) { ppIVsProjectCfg2 = (IVsProjectCfg2)this.projectCfg; return VSConstants.S_OK; } public virtual int get_Property(string pszProperty, out object pvar) { pvar = project.GetProjectProperty(pszProperty); return VSConstants.S_OK; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Internal.Interop; using Internal.Threading.Tasks; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.CompilerServices; using System.Runtime.InteropServices.WindowsRuntime; using System.Runtime.InteropServices; using System.Runtime.WindowsRuntime.Internal; using System.Threading; using Windows.Foundation; namespace System.Threading.Tasks { /// <summary>Provides a bridge between IAsyncOperation* and Task.</summary> /// <typeparam name="TResult">Specifies the type of the result of the asynchronous operation.</typeparam> /// <typeparam name="TProgress">Specifies the type of progress notification data.</typeparam> internal sealed class AsyncInfoToTaskBridge<TResult> : TaskCompletionSource<TResult> { /// <summary>The CancellationToken associated with this operation.</summary> private readonly CancellationToken _ct; /// <summary>A registration for cancellation that needs to be disposed of when the operation completes.</summary> private CancellationTokenRegistration _ctr; /// <summary>A flag set to true as soon as the completion callback begins to execute.</summary> private bool _completing; internal AsyncInfoToTaskBridge(CancellationToken cancellationToken) { if (AsyncCausalitySupport.LoggingOn) AsyncCausalitySupport.TraceOperationCreation(this.Task, "WinRT Operation as Task"); AsyncCausalitySupport.AddToActiveTasks(this.Task); _ct = cancellationToken; } /// <summary>The synchronization object to use for protecting the state of this bridge.</summary> private object StateLock { get { return this; } // "this" isn't available publicly, so we can safely use it as a syncobj } /// <summary>Registers the async operation for cancellation.</summary> /// <param name="asyncInfo">The asynchronous operation.</param> /// <param name="cancellationToken">The token used to request cancellation of the asynchronous operation.</param> internal void RegisterForCancellation(IAsyncInfo asyncInfo) { Contract.Requires(asyncInfo != null); try { if (_ct.CanBeCanceled && !_completing) { // benign race on m_completing... it's ok if it's not up-to-date. var ctr = _ct.Register(ai => ((IAsyncInfo)ai).Cancel(), asyncInfo); // delegate cached by compiler // The operation may already be completing by this time, in which case // we might need to dispose of our new cancellation registration here. bool disposeOfCtr = false; lock (StateLock) { if (_completing) disposeOfCtr = true; else _ctr = ctr; // under lock to avoid torn writes } if (disposeOfCtr) ctr.TryDeregister(); } } catch (Exception ex) { // We do not want exceptions propagating out of the AsTask / GetAwaiter calls, as the // Completed handler will instead store the exception into the returned Task. // Such exceptions should cause the Completed handler to be invoked synchronously and thus the Task should already be completed. if (!base.Task.IsFaulted) { Debug.Assert(false, String.Format("Expected base task to already be faulted but found it in state {0}", base.Task.Status)); base.TrySetException(ex); } } } /// <summary>Bridge to Completed handler on IAsyncAction.</summary> internal void CompleteFromAsyncAction(IAsyncAction asyncInfo, AsyncStatus asyncStatus) { Complete(asyncInfo, null, asyncStatus); } /// <summary>Bridge to Completed handler on IAsyncActionWithProgress{TProgress}.</summary> internal void CompleteFromAsyncActionWithProgress<TProgress>(IAsyncActionWithProgress<TProgress> asyncInfo, AsyncStatus asyncStatus) { Complete(asyncInfo, null, asyncStatus); } /// <summary>Bridge to Completed handler on IAsyncOperation{TResult}.</summary> internal void CompleteFromAsyncOperation(IAsyncOperation<TResult> asyncInfo, AsyncStatus asyncStatus) { Complete(asyncInfo, ai => ((IAsyncOperation<TResult>)ai).GetResults(), asyncStatus); // delegate cached by compiler } /// <summary>Bridge to Completed handler on IAsyncOperationWithProgress{TResult,TProgress}.</summary> internal void CompleteFromAsyncOperationWithProgress<TProgress>(IAsyncOperationWithProgress<TResult, TProgress> asyncInfo, AsyncStatus asyncStatus) { // delegate cached by compiler: Complete(asyncInfo, ai => ((IAsyncOperationWithProgress<TResult, TProgress>)ai).GetResults(), asyncStatus); } /// <summary>Completes the task from the completed asynchronous operation.</summary> /// <param name="asyncInfo">The asynchronous operation.</param> /// <param name="getResultsFunction">A function used to retrieve the TResult from the async operation; may be null.</param> /// <param name="asyncStatus">The status of the asynchronous operation.</param> private void Complete(IAsyncInfo asyncInfo, Func<IAsyncInfo, TResult> getResultsFunction, AsyncStatus asyncStatus) { if (asyncInfo == null) throw new ArgumentNullException("asyncInfo"); Contract.EndContractBlock(); AsyncCausalitySupport.RemoveFromActiveTasks(this.Task); try { Debug.Assert(asyncInfo.Status == asyncStatus, "asyncInfo.Status does not match asyncStatus; are we dealing with a faulty IAsyncInfo implementation?"); // Assuming a correct underlying implementation, the task should not have been // completed yet. If it is completed, we shouldn't try to do any further work // with the operation or the task, as something is horked. bool taskAlreadyCompleted = Task.IsCompleted; Debug.Assert(!taskAlreadyCompleted, "Expected the task to not yet be completed."); if (taskAlreadyCompleted) throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion); // Clean up our registration with the cancellation token, noting that we're now in the process of cleaning up. CancellationTokenRegistration ctr; lock (StateLock) { _completing = true; ctr = _ctr; // under lock to avoid torn reads _ctr = default(CancellationTokenRegistration); } ctr.TryDeregister(); // It's ok if we end up unregistering a not-initialized registration; it'll just be a nop. try { // Find out how the async operation completed. It must be in a terminal state. bool terminalState = asyncStatus == AsyncStatus.Completed || asyncStatus == AsyncStatus.Canceled || asyncStatus == AsyncStatus.Error; Debug.Assert(terminalState, "The async operation should be in a terminal state."); if (!terminalState) throw new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion); // Retrieve the completion data from the IAsyncInfo. TResult result = default(TResult); Exception error = null; if (asyncStatus == AsyncStatus.Error) { error = asyncInfo.ErrorCode; // Defend against a faulty IAsyncInfo implementation: if (error == null) { Debug.Assert(false, "IAsyncInfo.Status == Error, but ErrorCode returns a null Exception (implying S_OK)."); error = new InvalidOperationException(SR.InvalidOperation_InvalidAsyncCompletion); } else { error = asyncInfo.ErrorCode.AttachRestrictedErrorInfo(); } } else if (asyncStatus == AsyncStatus.Completed && getResultsFunction != null) { try { result = getResultsFunction(asyncInfo); } catch (Exception resultsEx) { // According to the WinRT team, this can happen in some egde cases, such as marshalling errors in GetResults. error = resultsEx; asyncStatus = AsyncStatus.Error; } } // Nothing to retrieve for a canceled operation or for a completed operation with no result. // Complete the task based on the previously retrieved results: bool success = false; switch (asyncStatus) { case AsyncStatus.Completed: if (AsyncCausalitySupport.LoggingOn) AsyncCausalitySupport.TraceOperationCompletedSuccess(this.Task); success = base.TrySetResult(result); break; case AsyncStatus.Error: Debug.Assert(error != null, "The error should have been retrieved previously."); success = base.TrySetException(error); break; case AsyncStatus.Canceled: success = base.TrySetCanceled(_ct.IsCancellationRequested ? _ct : new CancellationToken(true)); break; } Debug.Assert(success, "Expected the outcome to be successfully transfered to the task."); } catch (Exception exc) { // This really shouldn't happen, but could in a variety of misuse cases // such as a faulty underlying IAsyncInfo implementation. Debug.Assert(false, string.Format("Unexpected exception in Complete: {0}", exc.ToString())); if (AsyncCausalitySupport.LoggingOn) AsyncCausalitySupport.TraceOperationCompletedError(this.Task); // For these cases, store the exception into the task so that it makes its way // back to the caller. Only if something went horribly wrong and we can't store the exception // do we allow it to be propagated out to the invoker of the Completed handler. if (!base.TrySetException(exc)) { Debug.Assert(false, "The task was already completed and thus the exception couldn't be stored."); throw; } } } finally { // We may be called on an STA thread which we don't own, so make sure that the RCW is released right // away. Otherwise, if we leave it up to the finalizer, the apartment may already be gone. if (Marshal.IsComObject(asyncInfo)) Marshal.ReleaseComObject(asyncInfo); } } // private void Complete(..) } // class AsyncInfoToTaskBridge<TResult, TProgress> } // namespace
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Web.UI; using System.Web.UI.WebControls; using ICSharpCode.SharpZipLib.Zip; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Configuration; using Subtext.Framework.Web; using Subtext.Web.Admin.Commands; using Subtext.Web.Properties; using Image=Subtext.Framework.Components.Image; namespace Subtext.Web.Admin.Pages { public partial class EditGalleries : AdminPage { protected bool IsListHidden; // jsbright added to support prompting for new file name protected EditGalleries() { TabSectionId = "Galleries"; } private int CategoryId { get { if(null != ViewState["CategoryId"]) { return (int)ViewState["CategoryId"]; } return NullValue.NullInt32; } set { ViewState["CategoryId"] = value; } } protected void Page_Load(object sender, EventArgs e) { if(!Config.Settings.AllowImages) { Response.Redirect(AdminUrl.Home()); } if(!IsPostBack) { HideImages(); ShowResults(); BindList(); ckbIsActiveImage.Checked = Preferences.AlwaysCreateIsActive; ckbNewIsActive.Checked = Preferences.AlwaysCreateIsActive; if(null != Request.QueryString[Keys.QRYSTR_CATEGORYID]) { CategoryId = Convert.ToInt32(Request.QueryString[Keys.QRYSTR_CATEGORYID]); BindGallery(CategoryId); } } } private void BindList() { // TODO: possibly, later on, add paging support a la other cat editors ICollection<LinkCategory> selectionList = Links.GetCategories(CategoryType.ImageCollection, ActiveFilter.None); dgrSelectionList.DataSource = selectionList; dgrSelectionList.DataKeyField = "Id"; dgrSelectionList.DataBind(); dgrSelectionList.Visible = selectionList.Count > 0; //need not be shown when there are no galleries... } private void BindGallery() { // HACK: reverse the call order with the overloaded version BindGallery(CategoryId); } private void BindGallery(int galleryId) { CategoryId = galleryId; LinkCategory selectedGallery = SubtextContext.Repository.GetLinkCategory(galleryId, false); ICollection<Image> imageList = Images.GetImagesByCategoryId(galleryId, false); plhImageHeader.Controls.Clear(); if (selectedGallery != null) { string galleryTitle = string.Format(CultureInfo.InvariantCulture, "{0} - {1} " + Resources.Label_Images, selectedGallery.Title, imageList.Count); plhImageHeader.Controls.Add(new LiteralControl(galleryTitle)); } else //invalid gallery { Messages.ShowError("The gallery does not exist anymore. Please update your bookmarks."); return; } rprImages.DataSource = imageList; rprImages.DataBind(); ShowImages(); if(AdminMasterPage != null) { string title = string.Format(CultureInfo.InvariantCulture, Resources.EditGalleries_ViewingGallery, selectedGallery.Title); AdminMasterPage.Title = title; } AddImages.Collapsed = !Preferences.AlwaysExpandAdvanced; } private void ShowResults() { Results.Visible = true; } private void HideResults() { Results.Visible = false; } private void ShowImages() { HideResults(); ImagesDiv.Visible = true; } private void HideImages() { ShowResults(); ImagesDiv.Visible = false; } protected string EvalImageUrl(object potentialImage) { var image = potentialImage as Image; if(image != null) { image.Blog = Blog; return Url.GalleryImageUrl(image, image.ThumbNailFile); } return String.Empty; } protected string EvalImageNavigateUrl(object potentialImage) { var image = potentialImage as Image; if(image != null) { return Url.GalleryImagePageUrl(image); } return String.Empty; } protected string EvalImageTitle(object potentialImage) { const int targetHeight = 138; const int maxImageHeight = 120; const int charPerLine = 19; const int lineHeightPixels = 16; var image = potentialImage as Image; if(image != null) { // do a rough calculation of how many chars we can shoehorn into the title space // we have to back into an estimated thumbnail height right now with aspect * max double aspectRatio = (double)image.Height / image.Width; if(aspectRatio > 1 || aspectRatio <= 0) { aspectRatio = 1; } var allowedChars = (int)((targetHeight - maxImageHeight * aspectRatio) / lineHeightPixels * charPerLine); return Utilities.Truncate(image.Title, allowedChars); } return String.Empty; } // REFACTOR: duplicate from category editor; generalize a la EntryEditor private void PersistCategory(LinkCategory category) { try { if(category.Id > 0) { Repository.UpdateLinkCategory(category); Messages.ShowMessage(string.Format(CultureInfo.InvariantCulture, Resources.Message_CategoryUpdated, category.Title)); } else { category.Id = Links.CreateLinkCategory(category); Messages.ShowMessage(string.Format(CultureInfo.InvariantCulture, Resources.Message_CategoryAdded, category.Title)); } } catch(Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, "TODO...", ex.Message)); } } /// <summary> /// We're being asked to upload and store an image on the server (re-sizing and /// all of that). Ideally this will work. It may not. We may have to ask /// the user for an alternative file name. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void OnAddImage(object sender, EventArgs e) { string fileName = ImageFile.PostedFile.FileName; string extension = Path.GetExtension(fileName); if(extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { // Handle as an archive PersistImageArchive(); return; } // If there was no dot, or extension wasn't ZIP, then treat as a single image PersistImage(fileName); } private void PersistImageArchive() { List<string> goodFiles = new List<string>(), badFiles = new List<string>(), updatedFiles = new List<string>(); byte[] archiveData = ImageFile.PostedFile.GetFileStream(); using(var memoryStream = new MemoryStream(archiveData)) { using(var zip = new ZipInputStream(memoryStream)) { ZipEntry theEntry; while((theEntry = zip.GetNextEntry()) != null) { string fileName = Path.GetFileName(theEntry.Name); // TODO: Filter for image types? if(!String.IsNullOrEmpty(fileName)) { byte[] fileData; var image = new Image { Blog = Blog, CategoryID = CategoryId, Title = fileName, IsActive = ckbIsActiveImage.Checked, FileName = Path.GetFileName(fileName), Url = Url.ImageGalleryDirectoryUrl(Blog, CategoryId), LocalDirectoryPath = Url.GalleryDirectoryPath(Blog, CategoryId) }; // Read the next file from the Zip stream using(var currentFileData = new MemoryStream((int)theEntry.Size)) { int size = 2048; var data = new byte[size]; while(true) { size = zip.Read(data, 0, data.Length); if(size > 0) { currentFileData.Write(data, 0, size); } else { break; } } fileData = currentFileData.ToArray(); } try { // If it exists, update it if(File.Exists(image.OriginalFilePath)) { Images.Update(image, fileData); updatedFiles.Add(theEntry.Name); } else { // Attempt insertion as a new image int imageId = Images.InsertImage(image, fileData); if(imageId > 0) { goodFiles.Add(theEntry.Name); } else { // Wrong format, perhaps? badFiles.Add(theEntry.Name); } } } catch(Exception ex) { badFiles.Add(theEntry.Name + " (" + ex.Message + ")"); } } } } } // Construct and display the status message of added/updated/deleted images string status = string.Format(CultureInfo.InvariantCulture, Resources.EditGalleries_ArchiveProcessed + @"<br /> <b><a onclick=""javascript:ToggleVisibility(document.getElementById('ImportAddDetails'))"">" + Resources.Label_Adds + @" ({0})</a></b><span id=""ImportAddDetails"" style=""display:none""> : <br />&nbsp;&nbsp;{1}</span><br /> <b><a onclick=""javascript:ToggleVisibility(document.getElementById('ImportUpdateDetails'))"">" + Resources.Label_Updates + @" ({2})</a></b><span id=""ImportUpdateDetails"" style=""display:none""> : <br />&nbsp;&nbsp;{3}</span><br /> <b><a onclick=""javascript:ToggleVisibility(document.getElementById('ImportErrorDetails'))"">" + Resources.Label_Errors + @" ({4})</a></b><span id=""ImportErrorDetails"" style=""display:none""> : <br />&nbsp;&nbsp;{5}</span>", goodFiles.Count, (goodFiles.Count > 0 ? string.Join("<br />&nbsp;&nbsp;", goodFiles.ToArray()) : "none"), updatedFiles.Count, (updatedFiles.Count > 0 ? string.Join("<br />&nbsp;&nbsp;", updatedFiles.ToArray()) : "none"), badFiles.Count, (badFiles.Count > 0 ? string.Join("<br />&nbsp;&nbsp;", badFiles.ToArray()) : "none")); Messages.ShowMessage(status); txbImageTitle.Text = String.Empty; // if we're successful we need to revert back to our standard view PanelSuggestNewName.Visible = false; PanelDefaultName.Visible = true; // re-bind the gallery; note we'll skip this step if a correctable error occurs. BindGallery(); } /// <summary> /// The user is providing the file name here. /// </summary> protected void OnAddImageUserProvidedName(object sender, EventArgs e) { if(TextBoxImageFileName.Text.Length == 0) { Messages.ShowError(Resources.EditGalleries_ValidFilenameRequired); return; } PersistImage(TextBoxImageFileName.Text); } /// <summary> /// A fancy term for saving the image to disk :-). We'll take the image and try to save /// it. This currently puts all images in the same directory which can cause a conflict /// if the file already exists. So we'll add in a way to take a new file name. /// </summary> private void PersistImage(string fileName) { if(Page.IsValid) { var image = new Image { Blog = Blog, CategoryID = CategoryId, Title = txbImageTitle.Text, IsActive = ckbIsActiveImage.Checked, FileName = Path.GetFileName(fileName), Url = Url.ImageGalleryDirectoryUrl(Blog, CategoryId), LocalDirectoryPath = Url.GalleryDirectoryPath(Blog, CategoryId) }; try { if(File.Exists(image.OriginalFilePath)) { // tell the user we can't accept this file. Messages.ShowError(Resources.EditGalleries_FileAlreadyExists); // switch around our GUI. PanelSuggestNewName.Visible = true; PanelDefaultName.Visible = false; AddImages.Collapsed = false; // Unfortunately you can't set ImageFile.PostedFile.FileName. At least suggest // a name for the new file. TextBoxImageFileName.Text = image.FileName; return; } int imageId = Images.InsertImage(image, ImageFile.PostedFile.GetFileStream()); if(imageId > 0) { Messages.ShowMessage(Resources.EditGalleries_ImageAdded); txbImageTitle.Text = String.Empty; } else { Messages.ShowError(Constants.RES_FAILUREEDIT + " " + Resources.EditGalleries_ProblemPosting); } } catch(Exception ex) { Messages.ShowError(String.Format(Constants.RES_EXCEPTION, "TODO...", ex.Message)); } } // if we're successful we need to revert back to our standard view PanelSuggestNewName.Visible = false; PanelDefaultName.Visible = true; // re-bind the gallery; note we'll skip this step if a correctable error occurs. BindGallery(); } private void DeleteGallery(int categoryId, string categoryTitle) { var command = new DeleteGalleryCommand(Url.ImageGalleryDirectoryUrl(Blog, categoryId), categoryId, categoryTitle) { ExecuteSuccessMessage = String.Format(CultureInfo.CurrentCulture, "Gallery '{0}' deleted", categoryTitle) }; Messages.ShowMessage(command.Execute()); BindList(); } private void DeleteImage(int imageId) { Image image = Repository.GetImage(imageId, false /* activeOnly */); var command = new DeleteImageCommand(image, Url.ImageGalleryDirectoryUrl(Blog, image.CategoryID)) { ExecuteSuccessMessage = string.Format(CultureInfo.CurrentCulture, "Image '{0}' deleted", image.OriginalFile) }; Messages.ShowMessage(command.Execute()); BindGallery(); } override protected void OnInit(EventArgs e) { dgrSelectionList.ItemCommand += dgrSelectionList_ItemCommand; dgrSelectionList.CancelCommand += dgrSelectionList_CancelCommand; dgrSelectionList.EditCommand += dgrSelectionList_EditCommand; dgrSelectionList.UpdateCommand += dgrSelectionList_UpdateCommand; dgrSelectionList.DeleteCommand += dgrSelectionList_DeleteCommand; rprImages.ItemCommand += rprImages_ItemCommand; base.OnInit(e); } private void dgrSelectionList_ItemCommand(object source, DataGridCommandEventArgs e) { switch(e.CommandName.ToLower(CultureInfo.InvariantCulture)) { case "view": int galleryId = Convert.ToInt32(e.CommandArgument); BindGallery(galleryId); break; default: break; } } private void dgrSelectionList_EditCommand(object source, DataGridCommandEventArgs e) { HideImages(); dgrSelectionList.EditItemIndex = e.Item.ItemIndex; BindList(); Messages.Clear(); } private void dgrSelectionList_UpdateCommand(object source, DataGridCommandEventArgs e) { var title = e.Item.FindControl("txbTitle") as TextBox; var desc = e.Item.FindControl("txbDescription") as TextBox; var isActive = e.Item.FindControl("ckbIsActive") as CheckBox; if(Page.IsValid && null != title && null != isActive) { int id = Convert.ToInt32(dgrSelectionList.DataKeys[e.Item.ItemIndex]); LinkCategory existingCategory = SubtextContext.Repository.GetLinkCategory(id, false); existingCategory.Title = title.Text; existingCategory.IsActive = isActive.Checked; if(desc != null) { existingCategory.Description = desc.Text; } if(id != 0) { PersistCategory(existingCategory); } dgrSelectionList.EditItemIndex = -1; BindList(); } } private void dgrSelectionList_DeleteCommand(object source, DataGridCommandEventArgs e) { int id = Convert.ToInt32(dgrSelectionList.DataKeys[e.Item.ItemIndex]); LinkCategory lc = SubtextContext.Repository.GetLinkCategory(id, false); if (lc != null) { DeleteGallery(id, lc.Title); } else { Messages.ShowError("The gallery does not exist. Possibly you refreshed the page after deleting the gallery?"); } BindList(); } private void dgrSelectionList_CancelCommand(object source, DataGridCommandEventArgs e) { dgrSelectionList.EditItemIndex = -1; BindList(); Messages.Clear(); } protected void lkbPost_Click(object sender, EventArgs e) { var newCategory = new LinkCategory { CategoryType = CategoryType.ImageCollection, Title = txbNewTitle.Text, IsActive = ckbNewIsActive.Checked, Description = txbNewDescription.Text }; PersistCategory(newCategory); BindList(); txbNewTitle.Text = String.Empty; ckbNewIsActive.Checked = Preferences.AlwaysCreateIsActive; } private void rprImages_ItemCommand(object source, RepeaterCommandEventArgs e) { switch(e.CommandName.ToLower(CultureInfo.InvariantCulture)) { case "deleteimage": DeleteImage(Convert.ToInt32(e.CommandArgument)); break; default: break; } } } }
using UnityEngine; using System; using System.Collections; using System.Runtime.InteropServices; namespace Noesis.Samples { public class UnityObject : NotifyPropertyChangedBase { // Type property public string Type { get { return _type; } set { if (_type != value) { _type = value; OnPropertyChanged("Type"); } } } // Color property public Noesis.SolidColorBrush Color { get { return _color; } set { if (_color != value) { _color = value; OnPropertyChanged("Color"); } } } public string Scale { get { return _scale; } set { if (_scale != value) { _scale = value; OnPropertyChanged("Scale"); } } } public string Pos { get { return _pos; } set { if (_pos != value) { _pos = value; OnPropertyChanged("Pos"); } } } public GameObject MyObject { set { _object = value; } get { return _object; } } public static void Register() { } // X scale //@{ public void SetScaleX(float val) { _scaleX = val; UpdateScale(); } public float GetScaleX() { return _scaleX; } //@} // Y scale //@{ public void SetScaleY(float val) { _scaleY = val; UpdateScale(); } public float GetScaleY() { return _scaleY; } //@} // Z scale //@{ public void SetScaleZ(float val) { _scaleZ = val; UpdateScale(); } public float GetScaleZ() { return _scaleZ; } //@} // X position //@{ public void SetPosX(float val) { _posX = val; UpdatePos(); } public float GetPosX() { return _posX; } //@} // Y position //@{ public void SetPosY(float val) { _posY = val; UpdatePos(); } public float GetPosY() { return _posY; } //@} // Z position //@{ public void SetPosZ(float val) { _posZ = val; UpdatePos(); } public float GetPosZ() { return _posZ; } //@} private void UpdatePos() { Pos = String.Format("Position: (X:{0:0.00}, Y:{1:0.00}, Z:{2:0.00})", _posX, _posY, _posZ); } private void UpdateScale() { Scale = String.Format("Scale: (X:{0:0.00}, Y:{1:0.00}, Z:{2:0.00})", _scaleX, _scaleY, _scaleZ); } // Type private string _type; // Color private Noesis.SolidColorBrush _color; // Scale string private string _scale; // Position string private string _pos; // Scale private float _scaleX; private float _scaleY; private float _scaleZ; // Position private float _posX; private float _posY; private float _posZ; private GameObject _object; } } //////////////////////////////////////////////////////////////////////////////////////////// public class PrimitivesController : MonoBehaviour { Noesis.FrameworkElement _root; Noesis.UserControls.ColorPicker _colorPicker; Noesis.Slider _x; Noesis.Slider _y; Noesis.Slider _z; Noesis.Slider _scaleX; Noesis.Slider _scaleY; Noesis.Slider _scaleZ; Noesis.Button _typeSphere; Noesis.Button _typeCapsule; Noesis.Button _typeCylinder; Noesis.Button _typeCube; Noesis.Button _typePlane; GameObject _dirLight; GameObject _selectedObject; Noesis.Slider _sunDir; Noesis.Border _updateGB; Noesis.TextBlock _updateGBHeader; Noesis.TextBlock _selectedLabel; Noesis.TranslateTransform _selectedLabelTrans; System.Collections.ObjectModel.ObservableCollection<Noesis.Samples.UnityObject> _unityObjects; System.Collections.Generic.Dictionary<GameObject, Noesis.Samples.UnityObject> _objs; Noesis.ListBox _listBox; //////////////////////////////////////////////////////////////////////////////////////////// // Use this for initialization void Start () { // Access to the NoesisGUIPanel component NoesisGUIPanel noesisGUI = GetComponent<NoesisGUIPanel>(); // Obtain the root of the loaded UI resource, in this case it is a Grid element _root = noesisGUI.GetContent(); _sunDir = (Noesis.Slider)_root.FindName("sliderSun"); _sunDir.ValueChanged += this.OnSunDirChanged; _colorPicker = (Noesis.UserControls.ColorPicker)_root.FindName("ColorPicker"); _colorPicker.ColorChanged += this.OnColorPickerChanged; _x = (Noesis.Slider)_root.FindName("Xval"); _x.ValueChanged += this.OnXPosChanged; _y = (Noesis.Slider)_root.FindName("Yval"); _y.ValueChanged += this.OnYPosChanged; _z = (Noesis.Slider)_root.FindName("Zval"); _z.ValueChanged += this.OnZPosChanged; _scaleX = (Noesis.Slider)_root.FindName("ScaleXval"); _scaleX.ValueChanged += this.OnScaleXChanged; _scaleY = (Noesis.Slider)_root.FindName("ScaleYval"); _scaleY.ValueChanged += this.OnScaleYChanged; _scaleZ = (Noesis.Slider)_root.FindName("ScaleZval"); _scaleZ.ValueChanged += this.OnScaleZChanged; _typeSphere = (Noesis.Button)_root.FindName("TypeSphere"); _typeSphere.Click += this.OnCreateSphere; _typeCapsule = (Noesis.Button)_root.FindName("TypeCapsule"); _typeCapsule.Click += this.OnCreateCapsule; _typeCylinder = (Noesis.Button)_root.FindName("TypeCylinder"); _typeCylinder.Click += this.OnCreateCylinder; _typeCube = (Noesis.Button)_root.FindName("TypeCube"); _typeCube.Click += this.OnCreateCube; _typePlane = (Noesis.Button)_root.FindName("TypePlane"); _typePlane.Click += this.OnCreatePlane; _updateGB = (Noesis.Border)_root.FindName("UpdateGB"); _updateGB.IsEnabled = false; _updateGBHeader = (Noesis.TextBlock)_root.FindName("UpdateGBHeader"); _selectedLabel = (Noesis.TextBlock)_root.FindName("SelectedLbl"); _selectedLabel.Visibility = Noesis.Visibility.Hidden; _selectedLabelTrans = (Noesis.TranslateTransform)_root.FindName("selectLblPos"); _objs = new System.Collections.Generic.Dictionary<GameObject, Noesis.Samples.UnityObject>(); _dirLight = GameObject.Find("Key light"); _selectedObject = null; _listBox = (Noesis.ListBox)_root.FindName("MainLB"); _unityObjects = new System.Collections.ObjectModel.ObservableCollection<Noesis.Samples.UnityObject>(); _listBox.ItemsSource = _unityObjects; _listBox.SelectionMode = Noesis.SelectionMode.Single; _listBox.SelectionChanged += this.OnSelectionChanged; } //////////////////////////////////////////////////////////////////////////////////////////// void OnGUI() { if (Event.current.type == EventType.MouseDown) { RaycastHit hit = new RaycastHit(); Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); if (Physics.Raycast(ray, out hit, 100000.0f)) { _selectedObject = hit.collider.gameObject; _updateGB.IsEnabled = true; _updateGBHeader.Text = _selectedObject.name; _selectedLabel.Visibility = Noesis.Visibility.Visible; UpdateLabelTranslation(_selectedObject.transform.position); FillDataFromSelObj(); Noesis.Samples.UnityObject obj = _objs[_selectedObject]; _listBox.SelectedItem = obj; } else { _selectedObject = null; _updateGB.IsEnabled = false; _selectedLabel.Visibility = Noesis.Visibility.Hidden; _listBox.SelectedItem = null; } } } //////////////////////////////////////////////////////////////////////////////////////////// void OnSunDirChanged(float oldValue, float newValue) { _dirLight.transform.localEulerAngles = new Vector3(50, -newValue, 0); } //////////////////////////////////////////////////////////////////////////////////////////// void OnColorPickerChanged(object sender, Noesis.EventArgs e) { Noesis.Color color = _colorPicker.Color.Color; UnityEngine.Renderer renderer = _selectedObject.GetComponent<UnityEngine.Renderer>(); renderer.material.SetColor("_Color", new UnityEngine.Color( color.R, color.G, color.B, color.A)); } //////////////////////////////////////////////////////////////////////////////////////////// void OnXPosChanged(float oldValue, float newValue) { if (_selectedObject != null) { Noesis.Samples.UnityObject obj = _objs[_selectedObject]; obj.SetPosX(newValue); Vector3 newPos = new Vector3(newValue, obj.GetPosY(), obj.GetPosZ()); _selectedObject.transform.position = newPos; UpdateLabelTranslation(newPos); } } //////////////////////////////////////////////////////////////////////////////////////////// void OnYPosChanged(float oldValue, float newValue) { if (_selectedObject != null) { Noesis.Samples.UnityObject obj = _objs[_selectedObject]; obj.SetPosY(newValue); Vector3 newPos = new Vector3(obj.GetPosX(), newValue, obj.GetPosZ()); _selectedObject.transform.position = newPos; UpdateLabelTranslation(newPos); } } //////////////////////////////////////////////////////////////////////////////////////////// void OnZPosChanged(float oldValue, float newValue) { if (_selectedObject != null) { Noesis.Samples.UnityObject obj = _objs[_selectedObject]; obj.SetPosZ(newValue); Vector3 newPos = new Vector3(obj.GetPosX(), obj.GetPosY(), newValue); _selectedObject.transform.position = newPos; UpdateLabelTranslation(newPos); } } void UpdateLabelTranslation(Vector3 pos) { Vector3 scPos = Camera.main.WorldToScreenPoint(pos); _selectedLabelTrans.X = scPos.x - 28; _selectedLabelTrans.Y = Camera.main.pixelHeight - scPos.y - 7; } //////////////////////////////////////////////////////////////////////////////////////////// void OnScaleXChanged(float oldValue, float newValue) { if (_selectedObject != null) { Noesis.Samples.UnityObject obj = _objs[_selectedObject]; obj.SetScaleX(newValue); _selectedObject.transform.localScale = new Vector3( newValue, obj.GetScaleY(), obj.GetScaleZ()); } } //////////////////////////////////////////////////////////////////////////////////////////// void OnScaleYChanged(float oldValue, float newValue) { if (_selectedObject != null) { Noesis.Samples.UnityObject obj = _objs[_selectedObject]; obj.SetScaleY(newValue); _selectedObject.transform.localScale = new Vector3( obj.GetScaleX(), newValue, obj.GetScaleZ()); } } //////////////////////////////////////////////////////////////////////////////////////////// void OnScaleZChanged(float oldValue, float newValue) { if (_selectedObject != null) { Noesis.Samples.UnityObject obj = _objs[_selectedObject]; obj.SetScaleZ(newValue); _selectedObject.transform.localScale = new Vector3( obj.GetScaleX(), obj.GetScaleY(), newValue); } } //////////////////////////////////////////////////////////////////////////////////////////// void OnCreateSphere(object sender, Noesis.RoutedEventArgs e) { CreatePrimitiveObject(PrimitiveType.Sphere); } //////////////////////////////////////////////////////////////////////////////////////////// void OnCreateCapsule(object sender, Noesis.RoutedEventArgs e) { CreatePrimitiveObject(PrimitiveType.Capsule); } //////////////////////////////////////////////////////////////////////////////////////////// void OnCreateCylinder(object sender, Noesis.RoutedEventArgs e) { CreatePrimitiveObject(PrimitiveType.Cylinder); } //////////////////////////////////////////////////////////////////////////////////////////// void OnCreateCube(object sender, Noesis.RoutedEventArgs e) { CreatePrimitiveObject(PrimitiveType.Cube); } //////////////////////////////////////////////////////////////////////////////////////////// void OnCreatePlane(object sender, Noesis.RoutedEventArgs e) { CreatePrimitiveObject(PrimitiveType.Plane); } //////////////////////////////////////////////////////////////////////////////////////////// void CreatePrimitiveObject(PrimitiveType primitiveType) { GameObject obj = GameObject.CreatePrimitive(primitiveType); obj.transform.position = new Vector3(0, 0, 0); obj.transform.localScale = new Vector3(30, 30, 30); UnityEngine.Renderer renderer = obj.GetComponent<UnityEngine.Renderer>(); renderer.material = (Material)Resources.Load("PrimitivesMaterial"); renderer.material.SetColor("_Color", UnityEngine.Color.white); Noesis.Samples.UnityObject myObj = new Noesis.Samples.UnityObject(); myObj.Color = new Noesis.SolidColorBrush(new Noesis.Color(255, 255, 255, 255)); myObj.SetScaleX(30); myObj.SetScaleY(30); myObj.SetScaleZ(30); myObj.SetPosX(0); myObj.SetPosY(0); myObj.SetPosZ(0); myObj.Type = obj.name; myObj.MyObject = obj; _objs.Add(obj, myObj); _unityObjects.Add(myObj); } //////////////////////////////////////////////////////////////////////////////////////////// void FillDataFromSelObj() { _colorPicker.Color = _objs[_selectedObject].Color; _x.Value = _selectedObject.transform.position.x; _y.Value = _selectedObject.transform.position.y; _z.Value = _selectedObject.transform.position.z; _scaleX.Value = _selectedObject.transform.localScale.x; _scaleY.Value = _selectedObject.transform.localScale.y; _scaleZ.Value = _selectedObject.transform.localScale.z; } //////////////////////////////////////////////////////////////////////////////////////////// void OnSelectionChanged(object sender, Noesis.SelectionChangedEventArgs args) { int idxSel = _listBox.SelectedIndex; if (idxSel < 0) { _selectedObject = null; _updateGB.IsEnabled = false; _selectedLabel.Visibility = Noesis.Visibility.Hidden; } else { _selectedObject = ((Noesis.Samples.UnityObject)_listBox.SelectedItem).MyObject; this.FillDataFromSelObj(); _updateGB.IsEnabled = true; _updateGBHeader.Text = _selectedObject.name; _selectedLabel.Visibility = Noesis.Visibility.Visible; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.ComponentModel; using System.Drawing; using System.Runtime.InteropServices; using System.Diagnostics.Contracts; namespace System.Windows.Forms { // Summary: // Represents a control consisting of a movable bar that divides a container's // display area into two resizable panels. // [Designer("System.Windows.Forms.Design.SplitContainerDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] // [ClassInterface(ClassInterfaceType.AutoDispatch)] // [DefaultEvent("SplitterMoved")] // [Docking(DockingBehavior.AutoDock)] // [ComVisible(true)] public class SplitContainer //: ContainerControl { // Summary: // Initializes a new instance of the System.Windows.Forms.SplitContainer class. //public SplitContainer(); // Summary: // When overridden in a derived class, gets or sets a value indicating whether // scroll bars automatically appear if controls are placed outside the System.Windows.Forms.SplitContainer // client area. This property is not relevant to this class. // // Returns: // true if scroll bars to automatically appear when controls are placed outside // the System.Windows.Forms.SplitContainer client area; otherwise, false. The // default is false. // [EditorBrowsable(EditorBrowsableState.Never)] // [Localizable(true)] // [DefaultValue(false)] // [Browsable(false)] //public override bool AutoScroll { get; set; } // // Summary: // Gets or sets the size of the auto-scroll margin. This property is not relevant // to this class. This property is not relevant to this class. // // Returns: // A System.Drawing.Size value that represents the height and width, in pixels, // of the auto-scroll margin. // [EditorBrowsable(EditorBrowsableState.Never)] // [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] // [Browsable(false)] //public System.Drawing.Size AutoScrollMargin { get; set; } // // Summary: // Gets or sets the minimum size of the scroll bar. This property is not relevant // to this class. // // Returns: // A System.Drawing.Size that represents the minimum height and width of the // scroll bar, in pixels. // [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] // [EditorBrowsable(EditorBrowsableState.Never)] // [Browsable(false)] //public System.Drawing.Size AutoScrollMinSize { get; set; } // // Summary: // This property is not relevant to this class. // // Returns: // A System.Drawing.Point value. // [EditorBrowsable(EditorBrowsableState.Never)] // [Browsable(false)] //public override System.Drawing.Point AutoScrollOffset { get; set; } // // Summary: // This property is not relevant to this class. // // Returns: // A System.Drawing.Point value. // [Browsable(false)] // [EditorBrowsable(EditorBrowsableState.Never)] // [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] //public System.Drawing.Point AutoScrollPosition { get; set; } // // Summary: // Gets or sets a value indicating whether the System.Windows.Forms.SplitContainer // is automatically resized to display its entire contents. This property is // not relevant to this class. // // Returns: // true if the System.Windows.Forms.SplitContainer is automatically resized; // otherwise, false. // [EditorBrowsable(EditorBrowsableState.Never)] // [Browsable(false)] // [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] //public override bool AutoSize { get; set; } // // Summary: // Gets or sets the background image displayed in the control. // // Returns: // An System.Drawing.Image that represents the image to display in the background // of the control. // [Browsable(true)] // [EditorBrowsable(EditorBrowsableState.Always)] //public override System.Drawing.Image BackgroundImage { get; set; } // // Summary: // This property is not relevant to this class. // // Returns: // An System.Windows.Forms.ImageLayout value. // [Browsable(false)] // [EditorBrowsable(EditorBrowsableState.Never)] //public override ImageLayout BackgroundImageLayout { get; set; } // // Summary: // Gets or sets the System.Windows.Forms.BindingContext for the System.Windows.Forms.SplitContainer. // // Returns: // A System.Windows.Forms.BindingContext for the control. // [Browsable(false)] //public override BindingContext BindingContext { get; set; } // // Summary: // Gets or sets the style of border for the System.Windows.Forms.SplitContainer. // // Returns: // One of the System.Windows.Forms.BorderStyle values. The default is System.Windows.Forms.BorderStyle.Fixed3D. // // Exceptions: // System.ComponentModel.InvalidEnumArgumentException: // The value of the property is not one of the System.Windows.Forms.BorderStyle // values. // [DispId(-504)] //public BorderStyle BorderStyle { get; set; } // // Summary: // Gets a collection of child controls. This property is not relevant to this // class. // // Returns: // An object of type System.Windows.Forms.Control.ControlCollection that contains // the child controls. // [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] // [EditorBrowsable(EditorBrowsableState.Never)] //public Control.ControlCollection Controls { get; } // // Summary: // Gets the default size of the System.Windows.Forms.SplitContainer. // // Returns: // A System.Drawing.Size that represents the size of the System.Windows.Forms.SplitContainer. // protected override System.Drawing.Size DefaultSize { get; } // // Summary: // Gets or sets which System.Windows.Forms.SplitContainer borders are attached // to the edges of the container. // // Returns: // One of the System.Windows.Forms.DockStyle values. The default value is None. //public DockStyle Dock { get; set; } // // Summary: // Gets or sets which System.Windows.Forms.SplitContainer panel remains the // same size when the container is resized. // // Returns: // One of the values of System.Windows.Forms.FixedPanel. The default value is // None. // // Exceptions: // System.ComponentModel.InvalidEnumArgumentException: // The assigned value is not one of the System.Windows.Forms.FixedPanel values. //public FixedPanel FixedPanel { get; set; } // // Summary: // Gets or sets a value indicating whether the splitter is fixed or movable. // // Returns: // true if the splitter is fixed; otherwise, false. The default is false. // [DefaultValue(false)] // [Localizable(true)] //public bool IsSplitterFixed { get; set; } // // Summary: // Gets or sets a value indicating the horizontal or vertical orientation of // the System.Windows.Forms.SplitContainer panels. // // Returns: // One of the System.Windows.Forms.Orientation values. The default is Vertical. // // Exceptions: // System.ComponentModel.InvalidEnumArgumentException: // The assigned value is not one of the System.Windows.Forms.Orientation values. // [Localizable(true)] //public Orientation Orientation { get; set; } // // Summary: // Gets or sets the interior spacing, in pixels, between the edges of a System.Windows.Forms.SplitterPanel // and its contents. This property is not relevant to this class. // // Returns: // An object of type System.Windows.Forms.Padding representing the interior // spacing. // [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] // [Browsable(false)] // [EditorBrowsable(EditorBrowsableState.Never)] //public Padding Padding { get; set; } // // Summary: // Gets the left or top panel of the System.Windows.Forms.SplitContainer, depending // on System.Windows.Forms.SplitContainer.Orientation. // // Returns: // If System.Windows.Forms.SplitContainer.Orientation is Vertical, the left // panel of the System.Windows.Forms.SplitContainer. If System.Windows.Forms.SplitContainer.Orientation // is Horizontal, the top panel of the System.Windows.Forms.SplitContainer. // [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] // [Localizable(false)] public SplitterPanel Panel1 { get { Contract.Ensures(Contract.Result<SplitterPanel>() != null); return default(SplitterPanel); } } // // Summary: // Gets or sets a value determining whether System.Windows.Forms.SplitContainer.Panel1 // is collapsed or expanded. // // Returns: // true if System.Windows.Forms.SplitContainer.Panel1 is collapsed; otherwise, // false. The default is false. // [DefaultValue(false)] //public bool Panel1Collapsed { get; set; } // // Summary: // Gets or sets the minimum distance in pixels of the splitter from the left // or top edge of System.Windows.Forms.SplitContainer.Panel1. // // Returns: // An System.Int32 representing the minimum distance in pixels of the splitter // from the left or top edge of System.Windows.Forms.SplitContainer.Panel1. // The default value is 25 pixels, regardless of System.Windows.Forms.SplitContainer.Orientation. // // Exceptions: // System.ArgumentOutOfRangeException: // The specified value is incompatible with the orientation. // [RefreshProperties(RefreshProperties.All)] // [DefaultValue(25)] // [Localizable(true)] //public int Panel1MinSize { get; set; } // // Summary: // Gets the right or bottom panel of the System.Windows.Forms.SplitContainer, // depending on System.Windows.Forms.SplitContainer.Orientation. // // Returns: // If System.Windows.Forms.SplitContainer.Orientation is Vertical, the right // panel of the System.Windows.Forms.SplitContainer. If System.Windows.Forms.SplitContainer.Orientation // is Horizontal, the bottom panel of the System.Windows.Forms.SplitContainer. // [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] // [Localizable(false)] //public SplitterPanel Panel2 { get; } // // Summary: // Gets or sets a value determining whether System.Windows.Forms.SplitContainer.Panel2 // is collapsed or expanded. // // Returns: // true if System.Windows.Forms.SplitContainer.Panel2 is collapsed; otherwise, // false. The default is false. // [DefaultValue(false)] //public bool Panel2Collapsed { get; set; } // // Summary: // Gets or sets the minimum distance in pixels of the splitter from the right // or bottom edge of System.Windows.Forms.SplitContainer.Panel2. // // Returns: // An System.Int32 representing the minimum distance in pixels of the splitter // from the right or bottom edge of System.Windows.Forms.SplitContainer.Panel2. // The default value is 25 pixels, regardless of System.Windows.Forms.SplitContainer.Orientation. // // Exceptions: // System.ArgumentOutOfRangeException: // The specified value is incompatible with the orientation. // [RefreshProperties(RefreshProperties.All)] // [DefaultValue(25)] // [Localizable(true)] //public int Panel2MinSize { get; set; } // // Summary: // Gets or sets the location of the splitter, in pixels, from the left or top // edge of the System.Windows.Forms.SplitContainer. // // Returns: // An System.Int32 representing the location of the splitter, in pixels, from // the left or top edge of the System.Windows.Forms.SplitContainer. The default // value is 50 pixels. // // Exceptions: // System.ArgumentOutOfRangeException: // The value is less than zero. // // System.InvalidOperationException: // The value is incompatible with the orientation. // [DefaultValue(50)] // [Localizable(true)] // [SettingsBindable(true)] extern public int SplitterDistance { get; set; } // // Summary: // Gets or sets a value representing the increment of splitter movement in pixels. // // Returns: // An System.Int32 representing the increment of splitter movement in pixels. // The default value is one pixel. // // Exceptions: // System.ArgumentOutOfRangeException: // The value is less than one. // [Localizable(true)] // [DefaultValue(1)] //public int SplitterIncrement { get; set; } // // Summary: // Gets the size and location of the splitter relative to the System.Windows.Forms.SplitContainer. // // Returns: // A System.Drawing.Rectangle that specifies the size and location of the splitter // relative to the System.Windows.Forms.SplitContainer. // [Browsable(false)] //public System.Drawing.Rectangle SplitterRectangle { get; } // // Summary: // Gets or sets the width of the splitter in pixels. // // Returns: // An System.Int32 representing the width of the splitter, in pixels. The default // is four pixels. // // Exceptions: // System.ArgumentOutOfRangeException: // The value is less than one or is incompatible with the orientation. // [Localizable(true)] // [DefaultValue(4)] //public int SplitterWidth { get; set; } // // Summary: // Gets or sets a value indicating whether the user can give the focus to the // splitter using the TAB key. // // Returns: // true if the user can give the focus to the splitter using the TAB key; otherwise, // false. The default is true. // [DefaultValue(true)] // [DispId(-516)] //public bool TabStop { get; set; } // // Summary: // This property is not relevant to this class. // // Returns: // A string. // [Bindable(false)] // [Browsable(false)] // [EditorBrowsable(EditorBrowsableState.Never)] //public override string Text { get; set; } // Summary: // Occurs when the value of the System.Windows.Forms.SplitContainer.AutoSize // property changes. This property is not relevant to this class. // [Browsable(false)] // [EditorBrowsable(EditorBrowsableState.Never)] // public event EventHandler AutoSizeChanged; // // Summary: // Occurs when the System.Windows.Forms.SplitContainer.BackgroundImage property // changes. // [EditorBrowsable(EditorBrowsableState.Always)] // [Browsable(true)] // public event EventHandler BackgroundImageChanged; // // Summary: // Occurs when the System.Windows.Forms.SplitContainer.BackgroundImageLayout // property changes. This event is not relevant to this class. // [Browsable(false)] // [EditorBrowsable(EditorBrowsableState.Never)] // public event EventHandler BackgroundImageLayoutChanged; // // Summary: // This event is not relevant to this class. // [EditorBrowsable(EditorBrowsableState.Never)] // [Browsable(false)] // public event ControlEventHandler ControlAdded; // // Summary: // This event is not relevant to this class. // [EditorBrowsable(EditorBrowsableState.Never)] // [Browsable(false)] // public event ControlEventHandler ControlRemoved; // // Summary: // This event is not relevant to this class. // [Browsable(false)] // [EditorBrowsable(EditorBrowsableState.Never)] // public event EventHandler PaddingChanged; // // Summary: // Occurs when the splitter control is moved. // public event SplitterEventHandler SplitterMoved; // // Summary: // Occurs when the splitter control is in the process of moving. // public event SplitterCancelEventHandler SplitterMoving; // // Summary: // This event is not relevant to this class. // [EditorBrowsable(EditorBrowsableState.Never)] // [Browsable(false)] // public event EventHandler TextChanged; // Summary: // Creates a new instance of the control collection for the control. // // Returns: // A new instance of System.Windows.Forms.Control.ControlCollection assigned // to the control. // [EditorBrowsable(EditorBrowsableState.Advanced)] // protected override Control.ControlCollection CreateControlsInstance(); // // Summary: // Raises the System.Windows.Forms.Control.GotFocus event. // // Parameters: // e: // An System.EventArgs that contains the event data. // protected override void OnGotFocus(EventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.KeyDown event. // // Parameters: // e: // A System.Windows.Forms.KeyEventArgs that contains the event data. // protected override void OnKeyDown(KeyEventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.KeyUp event. // // Parameters: // e: // A System.Windows.Forms.KeyEventArgs that contains the event data. // protected override void OnKeyUp(KeyEventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.Layout event. // // Parameters: // e: // A System.Windows.Forms.LayoutEventArgs that contains the event data. // protected override void OnLayout(LayoutEventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.LostFocus event. // // Parameters: // e: // An System.EventArgs that contains the event data. // protected override void OnLostFocus(EventArgs e); // // // Parameters: // e: // An System.EventArgs that contains the event data. // protected override void OnMouseCaptureChanged(EventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.MouseDown event. // // Parameters: // e: // A System.Windows.Forms.MouseEventArgs that contains the event data. // protected override void OnMouseDown(MouseEventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.MouseLeave event. // // Parameters: // e: // An System.EventArgs that contains the event data. // protected override void OnMouseLeave(EventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.MouseMove event. // // Parameters: // e: // A System.Windows.Forms.MouseEventArgs that contains the event data. // [EditorBrowsable(EditorBrowsableState.Advanced)] // protected override void OnMouseMove(MouseEventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.MouseUp event. // // Parameters: // e: // A System.Windows.Forms.MouseEventArgs that contains the event data. // protected override void OnMouseUp(MouseEventArgs e); // protected override void OnMove(EventArgs e); // // Summary: // Raises the System.Windows.Forms.Control.Paint event. // // Parameters: // e: // A System.Windows.Forms.PaintEventArgs that contains the event data. // protected override void OnPaint(PaintEventArgs e); // // [EditorBrowsable(EditorBrowsableState.Advanced)] // protected override void OnRightToLeftChanged(EventArgs e); // // Summary: // Raises the System.Windows.Forms.SplitContainer.SplitterMoved event. // // Parameters: // e: // A System.Windows.Forms.SplitterEventArgs that contains the event data. //public void OnSplitterMoved(SplitterEventArgs e); // // Summary: // Raises the System.Windows.Forms.SplitContainer.SplitterMoving event. // // Parameters: // e: // A System.Windows.Forms.SplitterEventArgs that contains the event data. //public void OnSplitterMoving(SplitterCancelEventArgs e); // // Summary: // Processes a dialog box key. // // Parameters: // keyData: // One of the System.Windows.Forms.Keys values that represents the key to process. // // Returns: // true if the key was processed by the control; otherwise, false. // protected override bool ProcessDialogKey(Keys keyData); // // Summary: // Selects the next available control and makes it the active control. // // Parameters: // forward: // true to cycle forward through the controls in the System.Windows.Forms.ContainerControl; // otherwise, false. // // Returns: // true if a control is selected; otherwise, false. // protected override bool ProcessTabKey(bool forward); // // [EditorBrowsable(EditorBrowsableState.Advanced)] // protected override void ScaleControl(System.Drawing.SizeF factor, BoundsSpecified specified); // // protected override void Select(bool directed, bool forward); // // // Parameters: // x: // The new System.Windows.Forms.Control.Left property value of the control. // // y: // The new System.Windows.Forms.Control.Top property value of the control. // // width: // The new System.Windows.Forms.Control.Width property value of the control. // // height: // The new System.Windows.Forms.Control.Height property value of the control. // // specified: // A bitwise combination of the System.Windows.Forms.BoundsSpecified values. // protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified); // // Summary: // Processes Windows messages. // // Parameters: // msg: // The Windows System.Windows.Forms.Message to process. // protected override void WndProc(ref Message msg); } }
// // Tuples.cs // // Authors: // Zoltan Varga (vargaz@gmail.com) // Marek Safar (marek.safar@gmail.com) // // Copyright (C) 2009 Novell // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #if !NET40PLUS using System; using System.Collections; using System.Collections.Generic; namespace Antlr4.Runtime.Sharpen { internal partial class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> { public Tuple (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; this.item5 = item5; this.item6 = item6; this.item7 = item7; this.rest = rest; bool ok = true; if (!typeof (TRest).IsGenericType) ok = false; if (ok) { Type t = typeof (TRest).GetGenericTypeDefinition (); if (!(t == typeof (Tuple<>) || t == typeof (Tuple<,>) || t == typeof (Tuple<,,>) || t == typeof (Tuple<,,,>) || t == typeof (Tuple<,,,,>) || t == typeof (Tuple <,,,,,>) || t == typeof (Tuple<,,,,,,>) || t == typeof (Tuple<,,,,,,,>))) ok = false; } if (!ok) throw new ArgumentException ("rest", "The last element of an eight element tuple must be a Tuple."); } } /* The rest is generated by the script at the bottom */ [Serializable] internal class Tuple<T1> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; public Tuple (T1 item1) { this.item1 = item1; } public T1 Item1 { get { return item1; } } int IComparable.CompareTo (object obj) { return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo (object other, IComparer comparer) { var t = other as Tuple<T1>; if (t == null) { if (other == null) return 1; throw new ArgumentException ("other"); } return comparer.Compare (item1, t.item1); } public override bool Equals (object obj) { return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer) { var t = other as Tuple<T1>; if (t == null) return false; return comparer.Equals (item1, t.item1); } public override int GetHashCode () { return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode (IEqualityComparer comparer) { return comparer.GetHashCode (item1); } public override string ToString () { return String.Format ("({0})", item1); } } [Serializable] public class Tuple<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; public Tuple (T1 item1, T2 item2) { this.item1 = item1; this.item2 = item2; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } int IComparable.CompareTo (object obj) { return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo (object other, IComparer comparer) { var t = other as Tuple<T1, T2>; if (t == null) { if (other == null) return 1; throw new ArgumentException ("other"); } int res = comparer.Compare (item1, t.item1); if (res != 0) return res; return comparer.Compare (item2, t.item2); } public override bool Equals (object obj) { return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2>; if (t == null) return false; return comparer.Equals (item1, t.item1) && comparer.Equals (item2, t.item2); } public override int GetHashCode () { return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode (IEqualityComparer comparer) { int h = comparer.GetHashCode (item1); h = (h << 5) - h + comparer.GetHashCode (item2); return h; } public override string ToString () { return String.Format ("({0}, {1})", item1, item2); } } [Serializable] internal class Tuple<T1, T2, T3> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; public Tuple (T1 item1, T2 item2, T3 item3) { this.item1 = item1; this.item2 = item2; this.item3 = item3; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } int IComparable.CompareTo (object obj) { return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo (object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3>; if (t == null) { if (other == null) return 1; throw new ArgumentException ("other"); } int res = comparer.Compare (item1, t.item1); if (res != 0) return res; res = comparer.Compare (item2, t.item2); if (res != 0) return res; return comparer.Compare (item3, t.item3); } public override bool Equals (object obj) { return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3>; if (t == null) return false; return comparer.Equals (item1, t.item1) && comparer.Equals (item2, t.item2) && comparer.Equals (item3, t.item3); } public override int GetHashCode () { return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode (IEqualityComparer comparer) { int h = comparer.GetHashCode (item1); h = (h << 5) - h + comparer.GetHashCode (item2); h = (h << 5) - h + comparer.GetHashCode (item3); return h; } public override string ToString () { return String.Format ("({0}, {1}, {2})", item1, item2, item3); } } [Serializable] internal class Tuple<T1, T2, T3, T4> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; public Tuple (T1 item1, T2 item2, T3 item3, T4 item4) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } int IComparable.CompareTo (object obj) { return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo (object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4>; if (t == null) { if (other == null) return 1; throw new ArgumentException ("other"); } int res = comparer.Compare (item1, t.item1); if (res != 0) return res; res = comparer.Compare (item2, t.item2); if (res != 0) return res; res = comparer.Compare (item3, t.item3); if (res != 0) return res; return comparer.Compare (item4, t.item4); } public override bool Equals (object obj) { return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4>; if (t == null) return false; return comparer.Equals (item1, t.item1) && comparer.Equals (item2, t.item2) && comparer.Equals (item3, t.item3) && comparer.Equals (item4, t.item4); } public override int GetHashCode () { return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode (IEqualityComparer comparer) { int h = comparer.GetHashCode (item1); h = (h << 5) - h + comparer.GetHashCode (item2); h = (h << 5) - h + comparer.GetHashCode (item3); h = (h << 5) - h + comparer.GetHashCode (item4); return h; } public override string ToString () { return String.Format ("({0}, {1}, {2}, {3})", item1, item2, item3, item4); } } [Serializable] internal class Tuple<T1, T2, T3, T4, T5> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; T5 item5; public Tuple (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; this.item5 = item5; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } public T5 Item5 { get { return item5; } } int IComparable.CompareTo (object obj) { return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo (object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5>; if (t == null) { if (other == null) return 1; throw new ArgumentException ("other"); } int res = comparer.Compare (item1, t.item1); if (res != 0) return res; res = comparer.Compare (item2, t.item2); if (res != 0) return res; res = comparer.Compare (item3, t.item3); if (res != 0) return res; res = comparer.Compare (item4, t.item4); if (res != 0) return res; return comparer.Compare (item5, t.item5); } public override bool Equals (object obj) { return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5>; if (t == null) return false; return comparer.Equals (item1, t.item1) && comparer.Equals (item2, t.item2) && comparer.Equals (item3, t.item3) && comparer.Equals (item4, t.item4) && comparer.Equals (item5, t.item5); } public override int GetHashCode () { return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode (IEqualityComparer comparer) { int h = comparer.GetHashCode (item1); h = (h << 5) - h + comparer.GetHashCode (item2); h = (h << 5) - h + comparer.GetHashCode (item3); h = (h << 5) - h + comparer.GetHashCode (item4); h = (h << 5) - h + comparer.GetHashCode (item5); return h; } public override string ToString () { return String.Format ("({0}, {1}, {2}, {3}, {4})", item1, item2, item3, item4, item5); } } [Serializable] internal class Tuple<T1, T2, T3, T4, T5, T6> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; T5 item5; T6 item6; public Tuple (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; this.item5 = item5; this.item6 = item6; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } public T5 Item5 { get { return item5; } } public T6 Item6 { get { return item6; } } int IComparable.CompareTo (object obj) { return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo (object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6>; if (t == null) { if (other == null) return 1; throw new ArgumentException ("other"); } int res = comparer.Compare (item1, t.item1); if (res != 0) return res; res = comparer.Compare (item2, t.item2); if (res != 0) return res; res = comparer.Compare (item3, t.item3); if (res != 0) return res; res = comparer.Compare (item4, t.item4); if (res != 0) return res; res = comparer.Compare (item5, t.item5); if (res != 0) return res; return comparer.Compare (item6, t.item6); } public override bool Equals (object obj) { return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6>; if (t == null) return false; return comparer.Equals (item1, t.item1) && comparer.Equals (item2, t.item2) && comparer.Equals (item3, t.item3) && comparer.Equals (item4, t.item4) && comparer.Equals (item5, t.item5) && comparer.Equals (item6, t.item6); } public override int GetHashCode () { return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode (IEqualityComparer comparer) { int h = comparer.GetHashCode (item1); h = (h << 5) - h + comparer.GetHashCode (item2); h = (h << 5) - h + comparer.GetHashCode (item3); h = (h << 5) - h + comparer.GetHashCode (item4); h = (h << 5) - h + comparer.GetHashCode (item5); h = (h << 5) - h + comparer.GetHashCode (item6); return h; } public override string ToString () { return String.Format ("({0}, {1}, {2}, {3}, {4}, {5})", item1, item2, item3, item4, item5, item6); } } [Serializable] internal class Tuple<T1, T2, T3, T4, T5, T6, T7> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; T5 item5; T6 item6; T7 item7; public Tuple (T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7) { this.item1 = item1; this.item2 = item2; this.item3 = item3; this.item4 = item4; this.item5 = item5; this.item6 = item6; this.item7 = item7; } public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } public T5 Item5 { get { return item5; } } public T6 Item6 { get { return item6; } } public T7 Item7 { get { return item7; } } int IComparable.CompareTo (object obj) { return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo (object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7>; if (t == null) { if (other == null) return 1; throw new ArgumentException ("other"); } int res = comparer.Compare (item1, t.item1); if (res != 0) return res; res = comparer.Compare (item2, t.item2); if (res != 0) return res; res = comparer.Compare (item3, t.item3); if (res != 0) return res; res = comparer.Compare (item4, t.item4); if (res != 0) return res; res = comparer.Compare (item5, t.item5); if (res != 0) return res; res = comparer.Compare (item6, t.item6); if (res != 0) return res; return comparer.Compare (item7, t.item7); } public override bool Equals (object obj) { return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7>; if (t == null) return false; return comparer.Equals (item1, t.item1) && comparer.Equals (item2, t.item2) && comparer.Equals (item3, t.item3) && comparer.Equals (item4, t.item4) && comparer.Equals (item5, t.item5) && comparer.Equals (item6, t.item6) && comparer.Equals (item7, t.item7); } public override int GetHashCode () { return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode (IEqualityComparer comparer) { int h = comparer.GetHashCode (item1); h = (h << 5) - h + comparer.GetHashCode (item2); h = (h << 5) - h + comparer.GetHashCode (item3); h = (h << 5) - h + comparer.GetHashCode (item4); h = (h << 5) - h + comparer.GetHashCode (item5); h = (h << 5) - h + comparer.GetHashCode (item6); h = (h << 5) - h + comparer.GetHashCode (item7); return h; } public override string ToString () { return String.Format ("({0}, {1}, {2}, {3}, {4}, {5}, {6})", item1, item2, item3, item4, item5, item6, item7); } } [Serializable] internal partial class Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> : IStructuralEquatable, IStructuralComparable, IComparable { T1 item1; T2 item2; T3 item3; T4 item4; T5 item5; T6 item6; T7 item7; TRest rest; public T1 Item1 { get { return item1; } } public T2 Item2 { get { return item2; } } public T3 Item3 { get { return item3; } } public T4 Item4 { get { return item4; } } public T5 Item5 { get { return item5; } } public T6 Item6 { get { return item6; } } public T7 Item7 { get { return item7; } } public TRest Rest { get { return rest; } } int IComparable.CompareTo (object obj) { return ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default); } int IStructuralComparable.CompareTo (object other, IComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>; if (t == null) { if (other == null) return 1; throw new ArgumentException ("other"); } int res = comparer.Compare (item1, t.item1); if (res != 0) return res; res = comparer.Compare (item2, t.item2); if (res != 0) return res; res = comparer.Compare (item3, t.item3); if (res != 0) return res; res = comparer.Compare (item4, t.item4); if (res != 0) return res; res = comparer.Compare (item5, t.item5); if (res != 0) return res; res = comparer.Compare (item6, t.item6); if (res != 0) return res; res = comparer.Compare (item7, t.item7); if (res != 0) return res; return comparer.Compare (rest, t.rest); } public override bool Equals (object obj) { return ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default); } bool IStructuralEquatable.Equals (object other, IEqualityComparer comparer) { var t = other as Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>; if (t == null) return false; return comparer.Equals (item1, t.item1) && comparer.Equals (item2, t.item2) && comparer.Equals (item3, t.item3) && comparer.Equals (item4, t.item4) && comparer.Equals (item5, t.item5) && comparer.Equals (item6, t.item6) && comparer.Equals (item7, t.item7) && comparer.Equals (rest, t.rest); } public override int GetHashCode () { return ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default); } int IStructuralEquatable.GetHashCode (IEqualityComparer comparer) { int h = comparer.GetHashCode (item1); h = (h << 5) - h + comparer.GetHashCode (item2); h = (h << 5) - h + comparer.GetHashCode (item3); h = (h << 5) - h + comparer.GetHashCode (item4); h = (h << 5) - h + comparer.GetHashCode (item5); h = (h << 5) - h + comparer.GetHashCode (item6); h = (h << 5) - h + comparer.GetHashCode (item7); h = (h << 5) - h + comparer.GetHashCode (rest); return h; } public override string ToString () { return String.Format ("({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7})", item1, item2, item3, item4, item5, item6, item7, rest); } } } #endif #if FALSE // // generator script // using System; using System.Text; public class TupleGen { public static void Main () { for (int arity = 1; arity < 9; ++arity) { string type_name = GetTypeName (arity); Console.WriteLine ("\t[Serializable]"); Console.Write ("\tpublic {0}class ", arity < 8 ? null : "partial "); Console.Write (type_name); Console.WriteLine (" : IStructuralEquatable, IStructuralComparable, IComparable"); Console.WriteLine ("\t{"); for (int i = 1; i <= arity; ++i) Console.WriteLine ("\t\t{0} {1};", GetItemTypeName (i), GetItemName (i)); if (arity < 8) { Console.WriteLine (); Console.Write ("\t\tpublic Tuple ("); for (int i = 1; i <= arity; ++i) { Console.Write ("{0} {1}", GetItemTypeName (i), GetItemName (i)); if (i < arity) Console.Write (", "); } Console.WriteLine (")"); Console.WriteLine ("\t\t{"); for (int i = 1; i <= arity; ++i) Console.WriteLine ("\t\t\t this.{0} = {0};", GetItemName (i)); Console.WriteLine ("\t\t}"); } for (int i = 1; i <= arity; ++i) { Console.WriteLine (); Console.WriteLine ("\t\tpublic {0} {1} {{", GetItemTypeName (i), System.Globalization.CultureInfo.InvariantCulture.TextInfo.ToTitleCase (GetItemName (i))); Console.Write ("\t\t\tget { "); Console.WriteLine ("return {0}; }}", GetItemName (i)); Console.WriteLine ("\t\t}"); } Console.WriteLine (); Console.WriteLine ("\t\tint IComparable.CompareTo (object obj)"); Console.WriteLine ("\t\t{"); Console.WriteLine ("\t\t\treturn ((IStructuralComparable) this).CompareTo (obj, Comparer<object>.Default);"); Console.WriteLine ("\t\t}"); Console.WriteLine (); Console.WriteLine ("\t\tint IStructuralComparable.CompareTo (object other, IComparer comparer)"); Console.WriteLine ("\t\t{"); Console.WriteLine ("\t\t\tvar t = other as {0};", type_name); Console.WriteLine ("\t\t\tif (t == null) {"); Console.WriteLine ("\t\t\t\tif (other == null) return 1;"); Console.WriteLine ("\t\t\t\tthrow new ArgumentException ("other");"); Console.WriteLine ("\t\t\t}"); Console.WriteLine (); for (int i = 1; i < arity; ++i) { Console.Write ("\t\t\t"); if (i == 1) Console.Write ("int "); Console.WriteLine ("res = comparer.Compare ({0}, t.{0});", GetItemName (i)); Console.WriteLine ("\t\t\tif (res != 0) return res;"); } Console.WriteLine ("\t\t\treturn comparer.Compare ({0}, t.{0});", GetItemName (arity)); Console.WriteLine ("\t\t}"); Console.WriteLine (); Console.WriteLine ("\t\tpublic override bool Equals (object obj)"); Console.WriteLine ("\t\t{"); Console.WriteLine ("\t\t\treturn ((IStructuralEquatable) this).Equals (obj, EqualityComparer<object>.Default);"); Console.WriteLine ("\t\t}"); Console.WriteLine (); Console.WriteLine ("\t\tbool IStructuralEquatable.Equals (object other, IEqualityComparer comparer)"); Console.WriteLine ("\t\t{"); Console.WriteLine ("\t\t\tvar t = other as {0};", type_name); Console.WriteLine ("\t\t\tif (t == null)"); Console.WriteLine ("\t\t\t\treturn false;"); Console.WriteLine (); Console.Write ("\t\t\treturn"); for (int i = 1; i <= arity; ++i) { if (i == 1) Console.Write (" "); else Console.Write ("\t\t\t\t"); Console.Write ("comparer.Equals ({0}, t.{0})", GetItemName (i)); if (i != arity) Console.WriteLine (" &&"); else Console.WriteLine (";"); } Console.WriteLine ("\t\t}"); Console.WriteLine (); Console.WriteLine ("\t\tpublic override int GetHashCode ()"); Console.WriteLine ("\t\t{"); Console.WriteLine ("\t\t\treturn ((IStructuralEquatable) this).GetHashCode (EqualityComparer<object>.Default);"); Console.WriteLine ("\t\t}"); Console.WriteLine (); Console.WriteLine ("\t\tint IStructuralEquatable.GetHashCode (IEqualityComparer comparer)"); Console.WriteLine ("\t\t{"); if (arity == 1) { Console.WriteLine ("\t\t\treturn comparer.GetHashCode ({0});", GetItemName (arity)); } else { Console.WriteLine ("\t\t\tint h = comparer.GetHashCode ({0});", GetItemName (1)); for (int i = 2; i <= arity; ++i) Console.WriteLine ("\t\t\th = (h << 5) - h + comparer.GetHashCode ({0});", GetItemName (i)); Console.WriteLine ("\t\t\treturn h;"); } Console.WriteLine ("\t\t}"); Console.WriteLine (); Console.WriteLine ("\t\tpublic override string ToString ()"); Console.WriteLine ("\t\t{"); Console.Write ("\t\t\treturn String.Format (\"("); for (int i = 1; i <= arity; ++i) { Console.Write ("{" + (i - 1) + "}"); if (i < arity) Console.Write (", "); } Console.Write (")\", "); for (int i = 1; i <= arity; ++i) { Console.Write (GetItemName (i)); if (i < arity) Console.Write (", "); } Console.WriteLine (");"); Console.WriteLine ("\t\t}"); Console.WriteLine ("\t}\n"); } } static string GetTypeName (int arity) { StringBuilder sb = new StringBuilder (); sb.Append ("Tuple<"); for (int i = 1; i <= arity; ++i) { sb.Append (GetItemTypeName (i)); if (i < arity) sb.Append (", "); } sb.Append (">"); return sb.ToString (); } static string GetItemName (int arity) { return arity < 8 ? "item" + arity.ToString () : "rest"; } static string GetItemTypeName (int arity) { return arity < 8 ? "T" + arity.ToString () : "TRest"; } } #endif
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // 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 System.Globalization; using YamlDotNet.Core; using YamlDotNet.Core.Events; namespace YamlDotNet.RepresentationModel { /// <summary> /// Represents an YAML document. /// </summary> [Serializable] public class YamlDocument { /// <summary> /// Gets or sets the root node. /// </summary> /// <value>The root node.</value> public YamlNode RootNode { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="YamlDocument"/> class. /// </summary> public YamlDocument(YamlNode rootNode) { RootNode = rootNode; } /// <summary> /// Initializes a new instance of the <see cref="YamlDocument"/> class with a single scalar node. /// </summary> public YamlDocument(string rootNode) { RootNode = new YamlScalarNode(rootNode); } /// <summary> /// Initializes a new instance of the <see cref="YamlDocument"/> class. /// </summary> /// <param name="events">The events.</param> internal YamlDocument(EventReader events) { DocumentLoadingState state = new DocumentLoadingState(); events.Expect<DocumentStart>(); while (!events.Accept<DocumentEnd>()) { Debug.Assert(RootNode == null); RootNode = YamlNode.ParseNode(events, state); if (RootNode is YamlAliasNode) { throw new YamlException(); } } state.ResolveAliases(); #if DEBUG foreach (var node in AllNodes) { if (node is YamlAliasNode) { throw new InvalidOperationException("Error in alias resolution."); } } #endif events.Expect<DocumentEnd>(); } #pragma warning disable 618 /// <summary> /// Visitor that assigns anchors to nodes that are referenced more than once but have no anchor. /// </summary> private class AnchorAssigningVisitor : YamlVisitor #pragma warning restore 618 { private readonly HashSet<string> existingAnchors = new HashSet<string>(); private readonly Dictionary<YamlNode, bool> visitedNodes = new Dictionary<YamlNode, bool>(); public void AssignAnchors(YamlDocument document) { existingAnchors.Clear(); visitedNodes.Clear(); document.Accept(this); Random random = new Random(); foreach (var visitedNode in visitedNodes) { if (visitedNode.Value) { string anchor; do { anchor = random.Next().ToString(CultureInfo.InvariantCulture); } while (existingAnchors.Contains(anchor)); existingAnchors.Add(anchor); visitedNode.Key.Anchor = anchor; } } } private void VisitNode(YamlNode node) { if (string.IsNullOrEmpty(node.Anchor)) { bool isDuplicate; if (visitedNodes.TryGetValue(node, out isDuplicate)) { if (!isDuplicate) { visitedNodes[node] = true; } } else { visitedNodes.Add(node, false); } } else { existingAnchors.Add(node.Anchor); } } protected override void Visit(YamlScalarNode scalar) { VisitNode(scalar); } protected override void Visit(YamlMappingNode mapping) { VisitNode(mapping); } protected override void Visit(YamlSequenceNode sequence) { VisitNode(sequence); } } private void AssignAnchors() { AnchorAssigningVisitor visitor = new AnchorAssigningVisitor(); visitor.AssignAnchors(this); } internal void Save(IEmitter emitter, bool assignAnchors = true) { if (assignAnchors) { AssignAnchors(); } emitter.Emit(new DocumentStart()); RootNode.Save(emitter, new EmitterState()); emitter.Emit(new DocumentEnd(false)); } /// <summary> /// Accepts the specified visitor by calling the appropriate Visit method on it. /// </summary> /// <param name="visitor"> /// A <see cref="IYamlVisitor"/>. /// </param> public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } /// <summary> /// Gets all nodes from the document. /// </summary> public IEnumerable<YamlNode> AllNodes { get { return RootNode.AllNodes; } } } }
// 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 Xunit; public static class MathTests { [Fact] public static void Cos() { Assert.Equal(0.54030230586814, Math.Cos(1.0), 10); Assert.Equal(1.0, Math.Cos(0.0)); Assert.Equal(0.54030230586814, Math.Cos(-1.0), 10); Assert.Equal(double.NaN, Math.Cos(double.NaN)); Assert.Equal(double.NaN, Math.Cos(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Cos(double.NegativeInfinity)); } [Fact] public static void Sin() { Assert.Equal(0.841470984807897, Math.Sin(1.0), 10); Assert.Equal(0.0, Math.Sin(0.0)); Assert.Equal(-0.841470984807897, Math.Sin(-1.0), 10); Assert.Equal(double.NaN, Math.Sin(double.NaN)); Assert.Equal(double.NaN, Math.Sin(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Sin(double.NegativeInfinity)); } [Fact] public static void Tan() { Assert.Equal(1.5574077246549, Math.Tan(1.0), 10); Assert.Equal(0.0, Math.Tan(0.0)); Assert.Equal(-1.5574077246549, Math.Tan(-1.0), 10); Assert.Equal(double.NaN, Math.Tan(double.NaN)); Assert.Equal(double.NaN, Math.Tan(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Tan(double.NegativeInfinity)); } [Fact] public static void Cosh() { Assert.Equal(1.54308063481524, Math.Cosh(1.0), 10); Assert.Equal(1.0, Math.Cosh(0.0)); Assert.Equal(1.54308063481524, Math.Cosh(-1.0), 10); Assert.Equal(double.NaN, Math.Cosh(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Cosh(double.PositiveInfinity)); Assert.Equal(double.PositiveInfinity, Math.Cosh(double.NegativeInfinity)); } [Fact] public static void Sinh() { Assert.Equal(1.1752011936438, Math.Sinh(1.0), 10); Assert.Equal(0.0, Math.Sinh(0.0)); Assert.Equal(-1.1752011936438, Math.Sinh(-1.0), 10); Assert.Equal(double.NaN, Math.Sinh(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Sinh(double.PositiveInfinity)); Assert.Equal(double.NegativeInfinity, Math.Sinh(double.NegativeInfinity)); } [Fact] public static void Tanh() { Assert.Equal(0.761594155955765, Math.Tanh(1.0), 10); Assert.Equal(0.0, Math.Tanh(0.0)); Assert.Equal(-0.761594155955765, Math.Tanh(-1.0), 10); Assert.Equal(double.NaN, Math.Tanh(double.NaN)); Assert.Equal(1.0, Math.Tanh(double.PositiveInfinity)); Assert.Equal(-1.0, Math.Tanh(double.NegativeInfinity)); } [Fact] public static void Acos() { Assert.Equal(0.0, Math.Acos(1.0)); Assert.Equal(1.5707963267949, Math.Acos(0.0), 10); Assert.Equal(3.14159265358979, Math.Acos(-1.0), 10); Assert.Equal(double.NaN, Math.Acos(double.NaN)); Assert.Equal(double.NaN, Math.Acos(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Acos(double.NegativeInfinity)); } [Fact] public static void Asin() { Assert.Equal(1.5707963267949, Math.Asin(1.0), 10); Assert.Equal(0.0, Math.Asin(0.0)); Assert.Equal(-1.5707963267949, Math.Asin(-1.0), 10); Assert.Equal(double.NaN, Math.Asin(double.NaN)); Assert.Equal(double.NaN, Math.Asin(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Asin(double.NegativeInfinity)); } [Fact] public static void Atan() { Assert.Equal(0.785398163397448, Math.Atan(1.0), 10); Assert.Equal(0.0, Math.Atan(0.0)); Assert.Equal(-0.785398163397448, Math.Atan(-1.0), 10); Assert.Equal(double.NaN, Math.Atan(double.NaN)); Assert.Equal(1.5707963267949, Math.Atan(double.PositiveInfinity), 4); Assert.Equal(-1.5707963267949, Math.Atan(double.NegativeInfinity), 4); } [Fact] public static void Atan2() { Assert.Equal(0.0, Math.Atan2(0.0, 0.0)); Assert.Equal(1.5707963267949, Math.Atan2(1.0, 0.0), 10); Assert.Equal(0.588002603547568, Math.Atan2(2.0, 3.0), 10); Assert.Equal(0.0, Math.Atan2(0.0, 3.0)); Assert.Equal(-0.588002603547568, Math.Atan2(-2.0, 3.0), 10); Assert.Equal(double.NaN, Math.Atan2(double.NaN, 1.0)); Assert.Equal(double.NaN, Math.Atan2(1.0, double.NaN)); Assert.Equal(1.5707963267949, Math.Atan2(double.PositiveInfinity, 1.0), 10); Assert.Equal(-1.5707963267949, Math.Atan2(double.NegativeInfinity, 1.0), 10); Assert.Equal(0.0, Math.Atan2(1.0, double.PositiveInfinity)); Assert.Equal(3.14159265358979, Math.Atan2(1.0, double.NegativeInfinity), 10); } [Fact] public static void Ceiling_Decimal() { Assert.Equal(2.0m, Math.Ceiling(1.1m)); Assert.Equal(2.0m, Math.Ceiling(1.9m)); Assert.Equal(-1.0m, Math.Ceiling(-1.1m)); } [Fact] public static void Ceiling_Double() { Assert.Equal(2.0, Math.Ceiling(1.1)); Assert.Equal(2.0, Math.Ceiling(1.9)); Assert.Equal(-1.0, Math.Ceiling(-1.1)); Assert.Equal(double.NaN, Math.Ceiling(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Ceiling(double.PositiveInfinity)); Assert.Equal(double.NegativeInfinity, Math.Ceiling(double.NegativeInfinity)); } [Fact] public static void Floor_Decimal() { Assert.Equal(1.0m, Math.Floor(1.1m)); Assert.Equal(1.0m, Math.Floor(1.9m)); Assert.Equal(-2.0m, Math.Floor(-1.1m)); } [Fact] public static void Floor_Double() { Assert.Equal(1.0, Math.Floor(1.1)); Assert.Equal(1.0, Math.Floor(1.9)); Assert.Equal(-2.0, Math.Floor(-1.1)); Assert.Equal(double.NaN, Math.Floor(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Floor(double.PositiveInfinity)); Assert.Equal(double.NegativeInfinity, Math.Floor(double.NegativeInfinity)); } [Fact] public static void Round_Decimal() { Assert.Equal(0.0m, Math.Round(0.0m)); Assert.Equal(1.0m, Math.Round(1.4m)); Assert.Equal(2.0m, Math.Round(1.5m)); Assert.Equal(2e16m, Math.Round(2e16m)); Assert.Equal(0.0m, Math.Round(-0.0m)); Assert.Equal(-1.0m, Math.Round(-1.4m)); Assert.Equal(-2.0m, Math.Round(-1.5m)); Assert.Equal(-2e16m, Math.Round(-2e16m)); } [Fact] public static void Round_Decimal_Digits() { Assert.Equal(3.422m, Math.Round(3.42156m, 3, MidpointRounding.AwayFromZero)); Assert.Equal(-3.422m, Math.Round(-3.42156m, 3, MidpointRounding.AwayFromZero)); Assert.Equal(Decimal.Zero, Math.Round(Decimal.Zero, 3, MidpointRounding.AwayFromZero)); } [Fact] public static void Round_Double() { Assert.Equal(0.0, Math.Round(0.0)); Assert.Equal(1.0, Math.Round(1.4)); Assert.Equal(2.0, Math.Round(1.5)); Assert.Equal(2e16, Math.Round(2e16)); Assert.Equal(0.0, Math.Round(-0.0)); Assert.Equal(-1.0, Math.Round(-1.4)); Assert.Equal(-2.0, Math.Round(-1.5)); Assert.Equal(-2e16, Math.Round(-2e16)); } [Fact] public static void Round_Double_Digits() { Assert.Equal(3.422, Math.Round(3.42156, 3, MidpointRounding.AwayFromZero), 10); Assert.Equal(-3.422, Math.Round(-3.42156, 3, MidpointRounding.AwayFromZero), 10); Assert.Equal(0.0, Math.Round(0.0, 3, MidpointRounding.AwayFromZero)); Assert.Equal(double.NaN, Math.Round(double.NaN, 3, MidpointRounding.AwayFromZero)); Assert.Equal(double.PositiveInfinity, Math.Round(double.PositiveInfinity, 3, MidpointRounding.AwayFromZero)); Assert.Equal(double.NegativeInfinity, Math.Round(double.NegativeInfinity, 3, MidpointRounding.AwayFromZero)); } [Fact] public static void Sqrt() { Assert.Equal(1.73205080756888, Math.Sqrt(3.0), 10); Assert.Equal(0.0, Math.Sqrt(0.0)); Assert.Equal(double.NaN, Math.Sqrt(-3.0)); Assert.Equal(double.NaN, Math.Sqrt(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Sqrt(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Sqrt(double.NegativeInfinity)); } [Fact] public static void Log() { Assert.Equal(1.09861228866811, Math.Log(3.0), 10); Assert.Equal(double.NegativeInfinity, Math.Log(0.0)); Assert.Equal(double.NaN, Math.Log(-3.0)); Assert.Equal(double.NaN, Math.Log(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Log(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Log(double.NegativeInfinity)); } [Fact] public static void LogWithBase() { Assert.Equal(1.0, Math.Log(3.0, 3.0)); Assert.Equal(2.40217350273, Math.Log(14, 3.0), 10); Assert.Equal(double.NegativeInfinity, Math.Log(0.0, 3.0)); Assert.Equal(double.NaN, Math.Log(-3.0, 3.0)); Assert.Equal(double.NaN, Math.Log(double.NaN, 3.0)); Assert.Equal(double.PositiveInfinity, Math.Log(double.PositiveInfinity, 3.0)); Assert.Equal(double.NaN, Math.Log(double.NegativeInfinity, 3.0)); } [Fact] public static void Log10() { Assert.Equal(0.477121254719662, Math.Log10(3.0), 10); Assert.Equal(double.NegativeInfinity, Math.Log10(0.0)); Assert.Equal(double.NaN, Math.Log10(-3.0)); Assert.Equal(double.NaN, Math.Log10(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Log10(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Log10(double.NegativeInfinity)); } [Fact] public static void Pow() { Assert.Equal(1.0, Math.Pow(0.0, 0.0)); Assert.Equal(1.0, Math.Pow(1.0, 0.0)); Assert.Equal(8.0, Math.Pow(2.0, 3.0)); Assert.Equal(0.0, Math.Pow(0.0, 3.0)); Assert.Equal(-8.0, Math.Pow(-2.0, 3.0)); Assert.Equal(double.NaN, Math.Pow(double.NaN, 1.0)); Assert.Equal(double.NaN, Math.Pow(1.0, double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Pow(double.PositiveInfinity, 1.0)); Assert.Equal(double.NegativeInfinity, Math.Pow(double.NegativeInfinity, 1.0)); Assert.Equal(1.0, Math.Pow(1.0, double.PositiveInfinity)); Assert.Equal(1.0, Math.Pow(1.0, double.NegativeInfinity)); Assert.Equal(double.NaN, Math.Pow(-1.0, double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Pow(-1.0, double.NegativeInfinity)); Assert.Equal(double.PositiveInfinity, Math.Pow(1.1, double.PositiveInfinity)); Assert.Equal(0.0, Math.Pow(1.1, double.NegativeInfinity)); } [Fact] public static void Abs_Decimal() { Assert.Equal(3.0m, Math.Abs(3.0m)); Assert.Equal(0.0m, Math.Abs(0.0m)); Assert.Equal(0.0m, Math.Abs(-0.0m)); Assert.Equal(3.0m, Math.Abs(-3.0m)); Assert.Equal(Decimal.MaxValue, Math.Abs(Decimal.MinValue)); } [Fact] public static void Abs_Double() { Assert.Equal(3.0, Math.Abs(3.0)); Assert.Equal(0.0, Math.Abs(0.0)); Assert.Equal(3.0, Math.Abs(-3.0)); Assert.Equal(double.NaN, Math.Abs(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Abs(double.PositiveInfinity)); Assert.Equal(double.PositiveInfinity, Math.Abs(double.NegativeInfinity)); } [Fact] public static void Abs_Short() { Assert.Equal((short)3, Math.Abs((short)3)); Assert.Equal((short)0, Math.Abs((short)0)); Assert.Equal((short)3, Math.Abs((short)(-3))); Assert.Throws<OverflowException>(() => Math.Abs(short.MinValue)); } [Fact] public static void Abs_Int() { Assert.Equal(3, Math.Abs(3)); Assert.Equal(0, Math.Abs(0)); Assert.Equal(3, Math.Abs(-3)); Assert.Throws<OverflowException>(() => Math.Abs(int.MinValue)); } [Fact] public static void Abs_Long() { Assert.Equal(3L, Math.Abs(3L)); Assert.Equal(0L, Math.Abs(0L)); Assert.Equal(3L, Math.Abs(-3L)); Assert.Throws<OverflowException>(() => Math.Abs(long.MinValue)); } [Fact] public static void Abs_SByte() { Assert.Equal((sbyte)3, Math.Abs((sbyte)3)); Assert.Equal((sbyte)0, Math.Abs((sbyte)0)); Assert.Equal((sbyte)3, Math.Abs((sbyte)(-3))); Assert.Throws<OverflowException>(() => Math.Abs(sbyte.MinValue)); } [Fact] public static void Abs_Float() { Assert.Equal(3.0, Math.Abs(3.0f)); Assert.Equal(0.0, Math.Abs(0.0f)); Assert.Equal(3.0, Math.Abs(-3.0f)); Assert.Equal(float.NaN, Math.Abs(float.NaN)); Assert.Equal(float.PositiveInfinity, Math.Abs(float.PositiveInfinity)); Assert.Equal(float.PositiveInfinity, Math.Abs(float.NegativeInfinity)); } [Fact] public static void Exp() { Assert.Equal(20.0855369231877, Math.Exp(3.0), 10); Assert.Equal(1.0, Math.Exp(0.0)); Assert.Equal(0.0497870683678639, Math.Exp(-3.0), 10); Assert.Equal(double.NaN, Math.Exp(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Exp(double.PositiveInfinity)); Assert.Equal(0.0, Math.Exp(double.NegativeInfinity)); } [Fact] public static void IEEERemainder() { Assert.Equal(-1.0, Math.IEEERemainder(3, 2)); Assert.Equal(0.0, Math.IEEERemainder(4, 2)); Assert.Equal(1.0, Math.IEEERemainder(10, 3)); Assert.Equal(-1.0, Math.IEEERemainder(11, 3)); Assert.Equal(-2.0, Math.IEEERemainder(28, 5)); Assert.Equal(1.8, Math.IEEERemainder(17.8, 4), 10); Assert.Equal(1.4, Math.IEEERemainder(17.8, 4.1), 10); Assert.Equal(0.0999999999999979, Math.IEEERemainder(-16.3, 4.1), 10); Assert.Equal(1.4, Math.IEEERemainder(17.8, -4.1), 10); Assert.Equal(-1.4, Math.IEEERemainder(-17.8, -4.1), 10); } [Fact] public static void Min_Byte() { Assert.Equal((byte)2, Math.Min((byte)3, (byte)2)); Assert.Equal(byte.MinValue, Math.Min(byte.MinValue, byte.MaxValue)); } [Fact] public static void Min_Decimal() { Assert.Equal(-2.0m, Math.Min(3.0m, -2.0m)); Assert.Equal(decimal.MinValue, Math.Min(decimal.MinValue, decimal.MaxValue)); } [Fact] public static void Min_Double() { Assert.Equal(-2.0, Math.Min(3.0, -2.0)); Assert.Equal(double.MinValue, Math.Min(double.MinValue, double.MaxValue)); Assert.Equal(double.NegativeInfinity, Math.Min(double.NegativeInfinity, double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Min(double.NegativeInfinity, double.NaN)); Assert.Equal(double.NaN, Math.Min(double.NaN, double.NaN)); } [Fact] public static void Min_Short() { Assert.Equal((short)(-2), Math.Min((short)3, (short)(-2))); Assert.Equal(short.MinValue, Math.Min(short.MinValue, short.MaxValue)); } [Fact] public static void Min_Int() { Assert.Equal(-2, Math.Min(3, -2)); Assert.Equal(int.MinValue, Math.Min(int.MinValue, int.MaxValue)); } [Fact] public static void Min_Long() { Assert.Equal(-2L, Math.Min(3L, -2L)); Assert.Equal(long.MinValue, Math.Min(long.MinValue, long.MaxValue)); } [Fact] public static void Min_SByte() { Assert.Equal((sbyte)(-2), Math.Min((sbyte)3, (sbyte)(-2))); Assert.Equal(sbyte.MinValue, Math.Min(sbyte.MinValue, sbyte.MaxValue)); } [Fact] public static void Min_Float() { Assert.Equal(-2.0f, Math.Min(3.0f, -2.0f)); Assert.Equal(float.MinValue, Math.Min(float.MinValue, float.MaxValue)); Assert.Equal(float.NegativeInfinity, Math.Min(float.NegativeInfinity, float.PositiveInfinity)); Assert.Equal(float.NaN, Math.Min(float.NegativeInfinity, float.NaN)); Assert.Equal(float.NaN, Math.Min(float.NaN, float.NaN)); } [Fact] public static void Min_UShort() { Assert.Equal((ushort)2, Math.Min((ushort)3, (ushort)2)); Assert.Equal(ushort.MinValue, Math.Min(ushort.MinValue, ushort.MaxValue)); } [Fact] public static void Min_UInt() { Assert.Equal((uint)2, Math.Min((uint)3, (uint)2)); Assert.Equal(uint.MinValue, Math.Min(uint.MinValue, uint.MaxValue)); } [Fact] public static void Min_ULong() { Assert.Equal((ulong)2, Math.Min((ulong)3, (ulong)2)); Assert.Equal(ulong.MinValue, Math.Min(ulong.MinValue, ulong.MaxValue)); } [Fact] public static void Max_Byte() { Assert.Equal((byte)3, Math.Max((byte)2, (byte)3)); Assert.Equal(byte.MaxValue, Math.Max(byte.MinValue, byte.MaxValue)); } [Fact] public static void Max_Decimal() { Assert.Equal(3.0m, Math.Max(-2.0m, 3.0m)); Assert.Equal(decimal.MaxValue, Math.Max(decimal.MinValue, decimal.MaxValue)); } [Fact] public static void Max_Double() { Assert.Equal(3.0, Math.Max(3.0, -2.0)); Assert.Equal(double.MaxValue, Math.Max(double.MinValue, double.MaxValue)); Assert.Equal(double.PositiveInfinity, Math.Max(double.NegativeInfinity, double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Max(double.PositiveInfinity, double.NaN)); Assert.Equal(double.NaN, Math.Max(double.NaN, double.NaN)); } [Fact] public static void Max_Short() { Assert.Equal((short)3, Math.Max((short)(-2), (short)3)); Assert.Equal(short.MaxValue, Math.Max(short.MinValue, short.MaxValue)); } [Fact] public static void Max_Int() { Assert.Equal(3, Math.Max(-2, 3)); Assert.Equal(int.MaxValue, Math.Max(int.MinValue, int.MaxValue)); } [Fact] public static void Max_Long() { Assert.Equal(3L, Math.Max(-2L, 3L)); Assert.Equal(long.MaxValue, Math.Max(long.MinValue, long.MaxValue)); } [Fact] public static void Max_SByte() { Assert.Equal((sbyte)3, Math.Max((sbyte)(-2), (sbyte)3)); Assert.Equal(sbyte.MaxValue, Math.Max(sbyte.MinValue, sbyte.MaxValue)); } [Fact] public static void Max_Float() { Assert.Equal(3.0f, Math.Max(3.0f, -2.0f)); Assert.Equal(float.MaxValue, Math.Max(float.MinValue, float.MaxValue)); Assert.Equal(float.PositiveInfinity, Math.Max(float.NegativeInfinity, float.PositiveInfinity)); Assert.Equal(float.NaN, Math.Max(float.PositiveInfinity, float.NaN)); Assert.Equal(float.NaN, Math.Max(float.NaN, float.NaN)); } [Fact] public static void Max_UShort() { Assert.Equal((ushort)3, Math.Max((ushort)2, (ushort)3)); Assert.Equal(ushort.MaxValue, Math.Max(ushort.MinValue, ushort.MaxValue)); } [Fact] public static void Max_UInt() { Assert.Equal((uint)3, Math.Max((uint)2, (uint)3)); Assert.Equal(uint.MaxValue, Math.Max(uint.MinValue, uint.MaxValue)); } [Fact] public static void Max_ULong() { Assert.Equal((ulong)3, Math.Max((ulong)2, (ulong)3)); Assert.Equal(ulong.MaxValue, Math.Max(ulong.MinValue, ulong.MaxValue)); } [Fact] public static void Sign_Decimal() { Assert.Equal(0, Math.Sign(0.0m)); Assert.Equal(0, Math.Sign(-0.0m)); Assert.Equal(-1, Math.Sign(-3.14m)); Assert.Equal(1, Math.Sign(3.14m)); } [Fact] public static void Sign_Double() { Assert.Equal(0, Math.Sign(0.0)); Assert.Equal(0, Math.Sign(-0.0)); Assert.Equal(-1, Math.Sign(-3.14)); Assert.Equal(1, Math.Sign(3.14)); Assert.Equal(-1, Math.Sign(double.NegativeInfinity)); Assert.Equal(1, Math.Sign(double.PositiveInfinity)); Assert.Throws<ArithmeticException>(() => Math.Sign(double.NaN)); } [Fact] public static void Sign_Short() { Assert.Equal(0, Math.Sign((short)0)); Assert.Equal(-1, Math.Sign((short)(-3))); Assert.Equal(1, Math.Sign((short)3)); } [Fact] public static void Sign_Int() { Assert.Equal(0, Math.Sign(0)); Assert.Equal(-1, Math.Sign(-3)); Assert.Equal(1, Math.Sign(3)); } [Fact] public static void Sign_Long() { Assert.Equal(0, Math.Sign(0)); Assert.Equal(-1, Math.Sign(-3)); Assert.Equal(1, Math.Sign(3)); } [Fact] public static void Sign_SByte() { Assert.Equal(0, Math.Sign((sbyte)0)); Assert.Equal(-1, Math.Sign((sbyte)(-3))); Assert.Equal(1, Math.Sign((sbyte)3)); } [Fact] public static void Sign_Float() { Assert.Equal(0, Math.Sign(0.0f)); Assert.Equal(0, Math.Sign(-0.0f)); Assert.Equal(-1, Math.Sign(-3.14f)); Assert.Equal(1, Math.Sign(3.14f)); Assert.Equal(-1, Math.Sign(float.NegativeInfinity)); Assert.Equal(1, Math.Sign(float.PositiveInfinity)); Assert.Throws<ArithmeticException>(() => Math.Sign(float.NaN)); } [Fact] public static void Truncate_Decimal() { Assert.Equal(0.0m, Math.Truncate(0.12345m)); Assert.Equal(3.0m, Math.Truncate(3.14159m)); Assert.Equal(-3.0m, Math.Truncate(-3.14159m)); } [Fact] public static void Truncate_Double() { Assert.Equal(0.0, Math.Truncate(0.12345)); Assert.Equal(3.0, Math.Truncate(3.14159)); Assert.Equal(-3.0, Math.Truncate(-3.14159)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableHashSetBuilderTest : ImmutablesTestBase { [Fact] public void CreateBuilder() { var builder = ImmutableHashSet.CreateBuilder<string>(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); builder = ImmutableHashSet.CreateBuilder<string>(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); } [Fact] public void ToBuilder() { var builder = ImmutableHashSet<int>.Empty.ToBuilder(); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(2, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set = builder.ToImmutable(); Assert.Equal(builder.Count, set.Count); Assert.True(builder.Add(8)); Assert.Equal(3, builder.Count); Assert.Equal(2, set.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); } [Fact] public void BuilderFromSet() { var set = ImmutableHashSet<int>.Empty.Add(1); var builder = set.ToBuilder(); Assert.True(builder.Contains(1)); Assert.True(builder.Add(3)); Assert.True(builder.Add(5)); Assert.False(builder.Add(5)); Assert.Equal(3, builder.Count); Assert.True(builder.Contains(3)); Assert.True(builder.Contains(5)); Assert.False(builder.Contains(7)); var set2 = builder.ToImmutable(); Assert.Equal(builder.Count, set2.Count); Assert.True(set2.Contains(1)); Assert.True(builder.Add(8)); Assert.Equal(4, builder.Count); Assert.Equal(3, set2.Count); Assert.True(builder.Contains(8)); Assert.False(set.Contains(8)); Assert.False(set2.Contains(8)); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableHashSet<int>.Empty.Union(Enumerable.Range(1, 10)).ToBuilder(); CollectionAssertAreEquivalent(Enumerable.Range(1, 10).ToArray(), builder.ToArray()); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11); // Verify that a new enumerator will succeed. CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray()); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. CollectionAssertAreEquivalent(Enumerable.Range(1, 11).ToArray(), builder.ToArray()); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableHashSet<int>.Empty.Add(1); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void EnumeratorTest() { var builder = ImmutableHashSet.Create(1).ToBuilder(); ManuallyEnumerateTest(new[] { 1 }, ((IEnumerable<int>)builder).GetEnumerator()); } [Fact] public void Clear() { var set = ImmutableHashSet.Create(1); var builder = set.ToBuilder(); builder.Clear(); Assert.Equal(0, builder.Count); } [Fact] public void KeyComparer() { var builder = ImmutableHashSet.Create("a", "B").ToBuilder(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); Assert.True(builder.Contains("a")); Assert.False(builder.Contains("A")); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); Assert.Equal(2, builder.Count); Assert.True(builder.Contains("a")); Assert.True(builder.Contains("A")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void KeyComparerCollisions() { var builder = ImmutableHashSet.Create("a", "A").ToBuilder(); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Equal(1, builder.Count); Assert.True(builder.Contains("a")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); Assert.Equal(1, set.Count); Assert.True(set.Contains("a")); } [Fact] public void KeyComparerEmptyCollection() { var builder = ImmutableHashSet.Create<string>().ToBuilder(); Assert.Same(EqualityComparer<string>.Default, builder.KeyComparer); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void UnionWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.UnionWith(null)); builder.UnionWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void ExceptWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.ExceptWith(null)); builder.ExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1 }, builder); } [Fact] public void SymmetricExceptWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.SymmetricExceptWith(null)); builder.SymmetricExceptWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 1, 4 }, builder); } [Fact] public void IntersectWith() { var builder = ImmutableHashSet.Create(1, 2, 3).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IntersectWith(null)); builder.IntersectWith(new[] { 2, 3, 4 }); Assert.Equal(new[] { 2, 3 }, builder); } [Fact] public void IsProperSubsetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsProperSubsetOf(null)); Assert.False(builder.IsProperSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsProperSupersetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsProperSupersetOf(null)); Assert.False(builder.IsProperSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsProperSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void IsSubsetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsSubsetOf(null)); Assert.False(builder.IsSubsetOf(Enumerable.Range(1, 2))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSubsetOf(Enumerable.Range(1, 5))); } [Fact] public void IsSupersetOf() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.IsSupersetOf(null)); Assert.False(builder.IsSupersetOf(Enumerable.Range(1, 4))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 3))); Assert.True(builder.IsSupersetOf(Enumerable.Range(1, 2))); } [Fact] public void Overlaps() { var builder = ImmutableHashSet.CreateRange(Enumerable.Range(1, 3)).ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.Overlaps(null)); Assert.True(builder.Overlaps(Enumerable.Range(3, 2))); Assert.False(builder.Overlaps(Enumerable.Range(4, 3))); } [Fact] public void Remove() { var builder = ImmutableHashSet.Create("a").ToBuilder(); Assert.False(builder.Remove("b")); Assert.True(builder.Remove("a")); } [Fact] public void SetEquals() { var builder = ImmutableHashSet.Create("a").ToBuilder(); AssertExtensions.Throws<ArgumentNullException>("other", () => builder.SetEquals(null)); Assert.False(builder.SetEquals(new[] { "b" })); Assert.True(builder.SetEquals(new[] { "a" })); Assert.True(builder.SetEquals(builder)); } [Fact] public void ICollectionOfTMethods() { ICollection<string> builder = ImmutableHashSet.Create("a").ToBuilder(); builder.Add("b"); Assert.True(builder.Contains("b")); var array = new string[3]; builder.CopyTo(array, 1); Assert.Null(array[0]); CollectionAssertAreEquivalent(new[] { null, "a", "b" }, array); Assert.False(builder.IsReadOnly); CollectionAssertAreEquivalent(new[] { "a", "b" }, builder.ToArray()); // tests enumerator } [Fact] public void NullHandling() { var builder = ImmutableHashSet<string>.Empty.ToBuilder(); Assert.True(builder.Add(null)); Assert.False(builder.Add(null)); Assert.True(builder.Contains(null)); Assert.True(builder.Remove(null)); builder.UnionWith(new[] { null, "a" }); Assert.True(builder.IsSupersetOf(new[] { null, "a" })); Assert.True(builder.IsSubsetOf(new[] { null, "a" })); Assert.True(builder.IsProperSupersetOf(new[] { default(string) })); Assert.True(builder.IsProperSubsetOf(new[] { null, "a", "b" })); builder.IntersectWith(new[] { default(string) }); Assert.Equal(1, builder.Count); builder.ExceptWith(new[] { default(string) }); Assert.False(builder.Remove(null)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableHashSet.CreateBuilder<int>()); } } }
/* * 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. */ namespace ParquetSharp.Column { using System; using ParquetSharp.Bytes; using ParquetSharp.Column.Impl; using ParquetSharp.Column.Page; using ParquetSharp.Column.Values; using ParquetSharp.Column.Values.BitPacking; using ParquetSharp.Column.Values.BoundedInt; using ParquetSharp.Column.Values.Delta; using ParquetSharp.Column.Values.DeltaLengthByteArray; using ParquetSharp.Column.Values.DeltaStrings; using ParquetSharp.Column.Values.Dictionary; using ParquetSharp.Column.Values.Plain; using ParquetSharp.Column.Values.Rle; using ParquetSharp.IO; using ParquetSharp.Schema; /** * encoding of the data * * @author Julien Le Dem * */ public abstract class Encoding { public static readonly PlainEncoding PLAIN = new PlainEncoding(); public static readonly RleEncoding RLE = new RleEncoding(); public static readonly BitPackedEncoding BIT_PACKED = new BitPackedEncoding(); public static readonly PlainDictionaryEncoding PLAIN_DICTIONARY = new PlainDictionaryEncoding(); public static readonly DeltaBinaryPackedEncoding DELTA_BINARY_PACKED = new DeltaBinaryPackedEncoding(); public static readonly DeltaLengthByteArrayEncoding DELTA_LENGTH_BYTE_ARRAY = new DeltaLengthByteArrayEncoding(); public static readonly DeltaByteArrayEncoding DELTA_BYTE_ARRAY = new DeltaByteArrayEncoding(); public static readonly RleDictionaryEncoding RLE_DICTIONARY = new RleDictionaryEncoding(); sealed public class PlainEncoding : Encoding { public override string name() { return "PLAIN"; } public override ValuesReader getValuesReader(ColumnDescriptor descriptor, ValuesType valuesType) { switch (descriptor.getType().Name) { case PrimitiveType.Name.BOOLEAN: return new BooleanPlainValuesReader(); case PrimitiveType.Name.BINARY: return new BinaryPlainValuesReader(); case PrimitiveType.Name.FLOAT: return new PlainValuesReader.FloatPlainValuesReader(); case PrimitiveType.Name.DOUBLE: return new PlainValuesReader.DoublePlainValuesReader(); case PrimitiveType.Name.INT32: return new PlainValuesReader.IntegerPlainValuesReader(); case PrimitiveType.Name.INT64: return new PlainValuesReader.LongPlainValuesReader(); case PrimitiveType.Name.INT96: return new FixedLenByteArrayPlainValuesReader(12); case PrimitiveType.Name.FIXED_LEN_BYTE_ARRAY: return new FixedLenByteArrayPlainValuesReader(descriptor.getTypeLength()); default: throw new ParquetDecodingException("no plain reader for type " + descriptor.getType()); } } public override Dictionary initDictionary(ColumnDescriptor descriptor, DictionaryPage dictionaryPage) { switch (descriptor.getType().Name) { case PrimitiveType.Name.BINARY: return new PlainValuesDictionary.PlainBinaryDictionary(dictionaryPage); case PrimitiveType.Name.FIXED_LEN_BYTE_ARRAY: return new PlainValuesDictionary.PlainBinaryDictionary(dictionaryPage, descriptor.getTypeLength()); case PrimitiveType.Name.INT96: return new PlainValuesDictionary.PlainBinaryDictionary(dictionaryPage, 12); case PrimitiveType.Name.INT64: return new PlainValuesDictionary.PlainLongDictionary(dictionaryPage); case PrimitiveType.Name.DOUBLE: return new PlainValuesDictionary.PlainDoubleDictionary(dictionaryPage); case PrimitiveType.Name.INT32: return new PlainValuesDictionary.PlainIntegerDictionary(dictionaryPage); case PrimitiveType.Name.FLOAT: return new PlainValuesDictionary.PlainFloatDictionary(dictionaryPage); default: throw new ParquetDecodingException("Dictionary encoding not supported for type: " + descriptor.getType()); } } } /** * Actually a combination of bit packing and run length encoding. * TODO: Should we rename this to be more clear? */ sealed public class RleEncoding : Encoding { public override string name() { return "RLE"; } public override ValuesReader getValuesReader(ColumnDescriptor descriptor, ValuesType valuesType) { int bitWidth = BytesUtils.getWidthFromMaxInt(getMaxLevel(descriptor, valuesType)); if (bitWidth == 0) { return new ZeroIntegerValuesReader(); } return new RunLengthBitPackingHybridValuesReader(bitWidth); } } /** * @deprecated This is no longer used, and has been replaced by {@link #RLE} * which is combination of bit packing and rle */ [Obsolete] sealed public class BitPackedEncoding : Encoding { public override string name() { return "BIT_PACKED"; } public override ValuesReader getValuesReader(ColumnDescriptor descriptor, ValuesType valuesType) { return new ByteBitPackingValuesReader(getMaxLevel(descriptor, valuesType), Packer.BIG_ENDIAN); } } /** * @deprecated now replaced by RLE_DICTIONARY for the data page encoding and PLAIN for the dictionary page encoding */ [Obsolete] sealed public class PlainDictionaryEncoding : Encoding { public override string name() { return "PLAIN_DICTIONARY"; } public override ValuesReader getDictionaryBasedValuesReader(ColumnDescriptor descriptor, ValuesType valuesType, Dictionary dictionary) { return RLE_DICTIONARY.getDictionaryBasedValuesReader(descriptor, valuesType, dictionary); } public override Dictionary initDictionary(ColumnDescriptor descriptor, DictionaryPage dictionaryPage) { return PLAIN.initDictionary(descriptor, dictionaryPage); } public override bool usesDictionary() { return true; } } /** * Delta encoding for integers. This can be used for int columns and works best * on sorted data */ sealed public class DeltaBinaryPackedEncoding : Encoding { public override string name() { return "DELTA_BINARY_PACKED"; } public override ValuesReader getValuesReader(ColumnDescriptor descriptor, ValuesType valuesType) { if (descriptor.getType() != PrimitiveType.PrimitiveTypeName.INT32) { throw new ParquetDecodingException("Encoding DELTA_BINARY_PACKED is only supported for type INT32"); } return new DeltaBinaryPackingValuesReader(); } } /** * Encoding for byte arrays to separate the length values and the data. The lengths * are encoded using DELTA_BINARY_PACKED */ sealed public class DeltaLengthByteArrayEncoding : Encoding { public override string name() { return "DELTA_LENGTH_BYTE_ARRAY"; } public override ValuesReader getValuesReader(ColumnDescriptor descriptor, ValuesType valuesType) { if (descriptor.getType() != PrimitiveType.PrimitiveTypeName.BINARY) { throw new ParquetDecodingException("Encoding DELTA_LENGTH_BYTE_ARRAY is only supported for type BINARY"); } return new DeltaLengthByteArrayValuesReader(); } } /** * Incremental-encoded byte array. Prefix lengths are encoded using DELTA_BINARY_PACKED. * Suffixes are stored as delta length byte arrays. */ sealed public class DeltaByteArrayEncoding : Encoding { public override string name() { return "DELTA_BYTE_ARRAY"; } public override ValuesReader getValuesReader(ColumnDescriptor descriptor, ValuesType valuesType) { if (descriptor.getType() != PrimitiveType.PrimitiveTypeName.BINARY && descriptor.getType() != PrimitiveType.PrimitiveTypeName.FIXED_LEN_BYTE_ARRAY) { throw new ParquetDecodingException("Encoding DELTA_BYTE_ARRAY is only supported for type BINARY and FIXED_LEN_BYTE_ARRAY"); } return new DeltaByteArrayReader(); } } /** * Dictionary encoding: the ids are encoded using the RLE encoding */ sealed public class RleDictionaryEncoding : Encoding { public override string name() { return "RLE_DICTIONARY"; } public override ValuesReader getDictionaryBasedValuesReader(ColumnDescriptor descriptor, ValuesType valuesType, Dictionary dictionary) { switch (descriptor.getType().Name) { case PrimitiveType.Name.BINARY: case PrimitiveType.Name.FIXED_LEN_BYTE_ARRAY: case PrimitiveType.Name.INT96: case PrimitiveType.Name.INT64: case PrimitiveType.Name.DOUBLE: case PrimitiveType.Name.INT32: case PrimitiveType.Name.FLOAT: return new DictionaryValuesReader(dictionary); default: throw new ParquetDecodingException("Dictionary encoding not supported for type: " + descriptor.getType()); } } public override bool usesDictionary() { return true; } } public abstract string name(); int getMaxLevel(ColumnDescriptor descriptor, ValuesType valuesType) { int maxLevel; switch (valuesType) { case ValuesType.REPETITION_LEVEL: maxLevel = descriptor.getMaxRepetitionLevel(); break; case ValuesType.DEFINITION_LEVEL: maxLevel = descriptor.getMaxDefinitionLevel(); break; case ValuesType.VALUES: if (descriptor.getType() == PrimitiveType.PrimitiveTypeName.BOOLEAN) { maxLevel = 1; break; } goto default; default: throw new ParquetDecodingException("Unsupported encoding for values: " + this); } return maxLevel; } /** * @return whether this encoding requires a dictionary */ public virtual bool usesDictionary() { return false; } /** * initializes a dictionary from a page * @param dictionaryPage * @return the corresponding dictionary */ public virtual Dictionary initDictionary(ColumnDescriptor descriptor, DictionaryPage dictionaryPage) { throw new NotSupportedException(this.name() + " does not support dictionary"); } /** * To read decoded values that don't require a dictionary * * @param descriptor the column to read * @param valuesType the type of values * @return the proper values reader for the given column * @throw {@link UnsupportedOperationException} if the encoding is dictionary based */ public virtual ValuesReader getValuesReader(ColumnDescriptor descriptor, ValuesType valuesType) { throw new NotSupportedException("Error decoding " + descriptor + ". " + this.name() + " is dictionary based"); } /** * To read decoded values that require a dictionary * * @param descriptor the column to read * @param valuesType the type of values * @param dictionary the dictionary * @return the proper values reader for the given column * @throw {@link UnsupportedOperationException} if the encoding is not dictionary based */ public virtual ValuesReader getDictionaryBasedValuesReader(ColumnDescriptor descriptor, ValuesType valuesType, Dictionary dictionary) { throw new NotSupportedException(this.name() + " is not dictionary based"); } } }
using CompactView.Data; using CompactView.Helpers; using CompactView.Models; using CompactView.Services; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Windows.ApplicationModel.Core; using Windows.ApplicationModel.DataTransfer; using Windows.UI.Core; using Windows.UI.Popups; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace CompactView.Views { public sealed partial class WebViewPage : Page, INotifyPropertyChanged { private static DependencyProperty s_websiteProperty = DependencyProperty.Register("Website", typeof(WebsiteViewModel), typeof(WebViewPage), new PropertyMetadata(null)); public static DependencyProperty WebsiteProperty { get { return s_websiteProperty; } } public WebsiteViewModel Website { get { return (WebsiteViewModel)GetValue(s_websiteProperty); } set { SetValue(s_websiteProperty, value); } } public Uri uri; public WebViewPage() { InitializeComponent(); //Checks if the OS version is supporting CompactOverlay. if (ApplicationView.GetForCurrentView().IsViewModeSupported(ApplicationViewMode.CompactOverlay)) { MiniMode.Visibility = Visibility.Visible; } //replaces the Title Bar with a custom version. Taken from: //https://www.eternalcoding.com/?p=1952 CoreApplicationViewTitleBar coreTitleBar = CoreApplication.GetCurrentView().TitleBar; coreTitleBar.ExtendViewIntoTitleBar = true; TitleBar.Height = coreTitleBar.Height; Window.Current.SetTitleBar(MainTitleBar); Window.Current.Activated += Current_Activated; coreTitleBar.IsVisibleChanged += CoreTitleBar_IsVisibleChanged; coreTitleBar.LayoutMetricsChanged += CoreTitleBar_LayoutMetricsChanged; if (Website == null) { Website = WebsiteViewModel.FromWebsite(WebsiteDataSource.GetDefault()); } } public event PropertyChangedEventHandler PropertyChanged; //Checks for the Navigation Parameter and changes the WebView.Source to the requested Website. protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); long iD; try { iD = Convert.ToInt64(e.Parameter); Website = WebsiteViewModel.FromWebsite(WebsiteDataSource.GetWebsite(iD)); } catch { Website = WebsiteViewModel.FromWebsite(WebsiteDataSource.GetDefault()); } } private void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null) { if (Equals(storage, value)) { return; } storage = value; OnPropertyChanged(propertyName); } private void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); private void Current_Activated(object sender, WindowActivatedEventArgs e) { ModeChanged(); IsActive(e); } private void IsActive(WindowActivatedEventArgs e) { if (e.WindowActivationState != CoreWindowActivationState.Deactivated) { BackButtonGrid.Visibility = Visibility.Visible; MainTitleBar.Opacity = 1; TitleBar.Visibility = Visibility.Visible; } else { BackButtonGrid.Visibility = Visibility.Collapsed; MainTitleBar.Opacity = 0.5; var view = ApplicationView.GetForCurrentView(); if (IsCompactview()) { TitleBar.Visibility = Visibility.Collapsed; } } } void CoreTitleBar_IsVisibleChanged(CoreApplicationViewTitleBar titleBar, object args) { if (!IsCompactview()) { TitleBar.Visibility = titleBar.IsVisible ? Visibility.Visible : Visibility.Collapsed; } } private void CoreTitleBar_LayoutMetricsChanged(CoreApplicationViewTitleBar sender, object args) { TitleBar.Height = sender.Height; RightMask.Width = sender.SystemOverlayRightInset; } private async void MiniView_Click(object sender, RoutedEventArgs e) { await EnterMiniView(); } public async Task EnterMiniView() { var view = ApplicationView.GetForCurrentView(); if (!IsCompactview()) { ViewModePreferences compactOptions = ViewModePreferences.CreateDefault(ApplicationViewMode.CompactOverlay); compactOptions.CustomSize = new Windows.Foundation.Size(500, 281.25); bool modeSwitched = await ApplicationView.GetForCurrentView().TryEnterViewModeAsync(ApplicationViewMode.CompactOverlay, compactOptions); } else { //Should not be reached. } ModeChanged(); } private void Fullscreen_Click(object sender, RoutedEventArgs e) { var view = ApplicationView.GetForCurrentView(); if (IsFullscreen()) { view.ExitFullScreenMode(); ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.Auto; // The SizeChanged event will be raised when the exit from full-screen mode is complete. } else { if (view.TryEnterFullScreenMode()) { ApplicationView.PreferredLaunchWindowingMode = ApplicationViewWindowingMode.FullScreen; // The SizeChanged event will be raised when the entry to full-screen mode is complete. } } ModeChanged(); } private async void Normal_Click(object sender, RoutedEventArgs e) { var view = ApplicationView.GetForCurrentView(); if (!IsNormalscreen()) { bool modeSwitched = await ApplicationView.GetForCurrentView().TryEnterViewModeAsync(ApplicationViewMode.Default); } else { //Should not be reached. } ModeChanged(); } private void Grid_SizeChanged(object sender, SizeChangedEventArgs e) { ModeChanged(); } private bool IsFullscreen() { var view = ApplicationView.GetForCurrentView(); if (view.IsFullScreenMode) { return true; } else { return false; } } private bool IsCompactview() { var view = ApplicationView.GetForCurrentView(); if (view.ViewMode.ToString() == "CompactOverlay") { return true; } else { return false; } } private bool IsNormalscreen() { var view = ApplicationView.GetForCurrentView(); if (!IsFullscreen() && !IsCompactview()) { return true; } else { return false; } } //This method ensures that only the options for the not current mode are available in the UI. private void ModeChanged() { //FocuseMode if (!IsFullscreen()) { FullscreenMode.Visibility = Visibility.Visible; } else { FullscreenMode.Visibility = Visibility.Collapsed; } //MiniMode if (!IsCompactview()) { MiniMode.Visibility = Visibility.Visible; UrlTextBox.Visibility = Visibility.Visible; Go.Visibility = Visibility.Visible; SpaceForHamburger.Width = new GridLength(0, GridUnitType.Star); } else { MiniMode.Visibility = Visibility.Collapsed; UrlTextBox.Visibility = Visibility.Collapsed; Go.Visibility = Visibility.Collapsed; SpaceForHamburger.Width = new GridLength(48, GridUnitType.Pixel); } //NormalMode if (!IsNormalscreen()) { NormalMode.Visibility = Visibility.Visible; } else { NormalMode.Visibility = Visibility.Collapsed; } } private async Task SourceUpdated() { bool validUri = true; string newUri = UrlTextBox.Text.ToString(); try { uri = new Uri(newUri); } catch { // Create the message dialog and set its content DisplayDialog("Error", "The URL entered was not a valid URL. A URL has to look like http://www.bing.com "); validUri = false; uri = webView.Source; } if (validUri) { webView.Source = uri; WebsiteDataSource.SetTempSite(uri.Host.ToString(), uri); } } private void Go_Click(object sender, RoutedEventArgs e) { SourceUpdated(); } private async void PastAndGo_ClickAsync(object sender, RoutedEventArgs e) { var dataPackageView = Clipboard.GetContent(); if (dataPackageView.Contains(StandardDataFormats.Text)) { try { var text = await dataPackageView.GetTextAsync(); UrlTextBox.Text = text.ToString(); await SourceUpdated(); } catch (Exception ex) { DisplayDialog("Error", "Could not get the URL from the Clipboard."); } } else { } } private void UrlTextBox_KeyUp(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e) { if (e.Key == Windows.System.VirtualKey.Enter) { SourceUpdated(); } } private async void DisplayDialog(string title, string content) { ContentDialog noWifiDialog = new ContentDialog { Title = title, Content = content, CloseButtonText = "Ok" }; ContentDialogResult result = await noWifiDialog.ShowAsync(); } private void WebView1_SizeChanged(object sender, SizeChangedEventArgs e) { ModeChanged(); } } }
using Foundation; using System; using System.Threading.Tasks; using System.Collections.Generic; using UIKit; using zsquared; namespace vitaadmin { public partial class VC_ShowNotifications : UIViewController { C_Global Global; C_VitaUser LoggedInUser; List<C_Notification> _Notifications; C_Notification SelectedNotification; C_NotificationsTableSource NotificationsTableSource; C_NotificationsTableDelegate NotificationsTableDelegate; bool killChanges; public VC_ShowNotifications (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); AppDelegate myAppDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate; Global = myAppDelegate.Global; LoggedInUser = Global.GetUserFromCacheNoFetch(Global.LoggedInUserId); B_Back.TouchUpInside += (sender, e) => PerformSegue("Segue_NotificationsToMain", this); TV_Message.Changed += (sender, e) => { if (killChanges) return; SelectedNotification.Dirty = true; B_Send.Enabled = ValidMessage(); B_Save.Enabled = SelectedNotification.Dirty; }; SC_Audience.ValueChanged += (sender, e) => { if (killChanges) return; SelectedNotification.Dirty = true; B_Send.Enabled = ValidMessage(); B_Save.Enabled = SelectedNotification.Dirty; }; B_Save.TouchUpInside += async (sender, e) => { AI_Busy.StartAnimating(); EnableUI(false); EnableNotificationUI(false); SelectedNotification.Message = TV_Message.Text; SelectedNotification.Audience = SC_Audience.SelectedSegment == 0 ? E_NotificationAudience.Volunteers : E_NotificationAudience.SiteCoordinators; //bool success = await SelectedNotification.UpdateNotifications(LoggedInUser.Token); C_IOResult ior = await Global.UpdateNotification(SelectedNotification, LoggedInUser.Token); AI_Busy.StopAnimating(); EnableUI(true); EnableNotificationUI(true); if (!ior.Success) { C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, C_MessageBox.E_MessageBoxButtons.Ok); } else { B_Save.Enabled = false; TV_Notifications.ReloadData(); } }; B_Send.TouchUpInside += async (sender, e) => { if (SelectedNotification.id == -1) { C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Error", "The notification must be saved first.", C_MessageBox.E_MessageBoxButtons.Ok); return; } AI_Busy.StartAnimating(); EnableUI(false); EnableNotificationUI(false); SelectedNotification.Message = TV_Message.Text; SelectedNotification.Audience = SC_Audience.SelectedSegment == 0 ? E_NotificationAudience.Volunteers : E_NotificationAudience.SiteCoordinators; TV_Notifications.ReloadData(); C_IOResult ior = await Global.SendNotification(SelectedNotification, LoggedInUser.Token); AI_Busy.StopAnimating(); EnableUI(true); EnableNotificationUI(true); if (!ior.Success) { C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, C_MessageBox.E_MessageBoxButtons.Ok); } }; B_CreateNew.TouchUpInside += (sender, e) => { C_Notification note = new C_Notification(); SelectedNotification = note; EnableNotificationUI(true); TB_Created.Text = SelectedNotification.CreatedDT.ToString("G"); TB_Updated.Text = SelectedNotification.UpdatedDT.ToString("G"); TB_Sent.Text = SelectedNotification.SentDT.ToString("G"); TV_Message.Text = SelectedNotification.Message; SC_Audience.SelectedSegment = SelectedNotification.Audience == E_NotificationAudience.Volunteers ? 0 : 1; B_Save.Enabled = ValidMessage(); B_Send.Enabled = ValidMessage(); _Notifications.Add(note); TV_Notifications.ReloadData(); }; EnableNotificationUI(false); B_Save.Enabled = false; B_Send.Enabled = false; TB_Created.UserInteractionEnabled = false; TB_Updated.UserInteractionEnabled = false; TB_Sent.UserInteractionEnabled = false; AI_Busy.StartAnimating(); EnableUI(false); Task.Run(async () => { _Notifications = await Global.FetchAllNotifications(LoggedInUser.Token); UIApplication.SharedApplication.InvokeOnMainThread( new Action(() => { AI_Busy.StopAnimating(); EnableUI(true); NotificationsTableSource = new C_NotificationsTableSource(_Notifications); TV_Notifications.Source = NotificationsTableSource; NotificationsTableDelegate = new C_NotificationsTableDelegate(this, NotificationsTableSource); TV_Notifications.Delegate = NotificationsTableDelegate; NotificationsTableDelegate.NotificationsTableRowSelect += NotificationsTableDelegate_NotificationsTableRowSelect; NotificationsTableDelegate.NotificationsTableRowDeselect += NotificationsTableDelegate_NotificationsTableRowDeselect; NotificationsTableDelegate.NotificationsTableRowRemove += NotificationsTableDelegate_NotificationsTableRowRemove; TV_Notifications.ReloadData(); })); }); } private void EnableUI(bool en) { TV_Notifications.UserInteractionEnabled = en; } private void EnableNotificationUI(bool en) { SC_Audience.Enabled = en; TB_Created.Enabled = en; TB_Updated.Enabled = en; TB_Sent.Enabled = en; TV_Message.UserInteractionEnabled = en; } void NotificationsTableDelegate_NotificationsTableRowSelect(object sender, C_NotificationsTableEvent a) { SelectedNotification = a.Notification; EnableNotificationUI(true); TB_Created.Text = SelectedNotification.CreatedDT.ToString("G"); TB_Updated.Text = SelectedNotification.UpdatedDT.ToString("G"); TB_Sent.Text = SelectedNotification.SentDT.ToString("G"); killChanges = true; TV_Message.Text = SelectedNotification.Message; SC_Audience.SelectedSegment = SelectedNotification.Audience == E_NotificationAudience.Volunteers ? 0 : 1; killChanges = false; B_Save.Enabled = SelectedNotification.Dirty; B_Send.Enabled = ValidMessage(); } void NotificationsTableDelegate_NotificationsTableRowDeselect(object sender, C_NotificationsTableEvent a) { if (SelectedNotification.Dirty) { C_Notification selNote = SelectedNotification; // save a pointer to the item being deselected in case foreground wants to change it UIApplication.SharedApplication.InvokeOnMainThread( new Action(async () => { C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Not Saved", "The notification has been changed. Save?", C_MessageBox.E_MessageBoxButtons.YesNo); if (mbres == C_MessageBox.E_MessageBoxResults.No) { selNote.Dirty = false; return; } AI_Busy.StartAnimating(); EnableUI(false); EnableNotificationUI(false); selNote.Message = TV_Message.Text; selNote.Audience = SC_Audience.SelectedSegment == 0 ? E_NotificationAudience.Volunteers : E_NotificationAudience.SiteCoordinators; TV_Notifications.ReloadData(); C_IOResult ior = await Global.UpdateNotification(selNote, LoggedInUser.Token); AI_Busy.StopAnimating(); EnableUI(true); EnableNotificationUI(true); if (!ior.Success) { C_MessageBox.E_MessageBoxResults mbresx = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, C_MessageBox.E_MessageBoxButtons.Ok); } else { B_Save.Enabled = false; DePopulateNotification(); } })); } DePopulateNotification(); } void NotificationsTableDelegate_NotificationsTableRowRemove(object sender, C_NotificationsTableEvent a) { C_Notification selNote = a.Notification; UIApplication.SharedApplication.InvokeOnMainThread( new Action(async () => { C_MessageBox.E_MessageBoxResults mbres = await C_MessageBox.MessageBox(this, "Delete?", "Permanentaly delete the notification?", C_MessageBox.E_MessageBoxButtons.YesNo); if (mbres == C_MessageBox.E_MessageBoxResults.No) return; AI_Busy.StartAnimating(); EnableUI(false); EnableNotificationUI(false); B_Save.Enabled = false; B_Send.Enabled = false; C_IOResult ior = await Global.RemoveNotification(selNote, LoggedInUser.Token); AI_Busy.StopAnimating();; EnableUI(true); EnableNotificationUI(true); B_Save.Enabled = SelectedNotification.Dirty; B_Send.Enabled = true; if (!ior.Success) { C_MessageBox.E_MessageBoxResults mbresx = await C_MessageBox.MessageBox(this, "Error", ior.ErrorMessage, C_MessageBox.E_MessageBoxButtons.Ok); } else { _Notifications.Remove(selNote); TV_Notifications.ReloadData(); } })); } private bool ValidMessage() { return TV_Message.Text.Length != 0; } private void DePopulateNotification() { TB_Created.Text = ""; TB_Updated.Text = ""; TB_Sent.Text = ""; killChanges = true; SC_Audience.SelectedSegment = 0; TV_Message.Text = ""; killChanges = false; } public class C_NotificationsTableDelegate : UITableViewDelegate { readonly UIViewController OurVC; readonly C_NotificationsTableSource TableSource; public event NotificationTableEventHandler NotificationsTableRowSelect; public event NotificationTableEventHandler NotificationsTableRowDeselect; public event NotificationTableEventHandler NotificationsTableRowRemove; public C_NotificationsTableDelegate(UIViewController vc, C_NotificationsTableSource tsource) { OurVC = vc; TableSource = tsource; } public override UITableViewRowAction[] EditActionsForRow(UITableView tableView, NSIndexPath indexPath) { UITableViewRowAction hiButton = UITableViewRowAction.Create(UITableViewRowActionStyle.Default, "Remove", delegate { NotificationsTableRowRemove?.Invoke(this, new C_NotificationsTableEvent(TableSource.Notifications[indexPath.Row])); }); return new UITableViewRowAction[] { hiButton }; } public override void RowDeselected(UITableView tableView, NSIndexPath indexPath) { NotificationsTableRowDeselect?.Invoke(this, new C_NotificationsTableEvent(TableSource.Notifications[indexPath.Row])); } public override void RowSelected(UITableView tableView, NSIndexPath indexPath) { NotificationsTableRowSelect?.Invoke(this, new C_NotificationsTableEvent(TableSource.Notifications[indexPath.Row])); } } public class C_NotificationsTableEvent : EventArgs { public C_Notification Notification; public C_NotificationsTableEvent(C_Notification notification) { Notification = notification; } } public delegate void NotificationTableEventHandler(object sender, C_NotificationsTableEvent a); public class C_NotificationsTableSource : UITableViewSource { const string CellIdentifier = "TableCell_NotificationsTableSource"; public List<C_Notification> Notifications; public C_NotificationsTableSource(List<C_Notification> notifications) { Notifications = notifications; } public override nint RowsInSection(UITableView tableview, nint section) { return Notifications.Count; } public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell(CellIdentifier); //---- if there are no cells to reuse, create a new one if (cell == null) cell = new UITableViewCell(UITableViewCellStyle.Subtitle, CellIdentifier); C_Notification not = Notifications[indexPath.Row]; cell.TextLabel.Text = not.Message; cell.DetailTextLabel.Text = not.SentDT.ToString(); return cell; } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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.Drawing; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; using Axiom.Core; using Axiom.Graphics; using Axiom.Input; using Axiom.RenderSystems.DirectX9; using log4net; namespace Multiverse.Web { /// <summary> /// The Web.Browser lets you create a 2D web browser that overlays /// the rendering of the 3D scene like a user interface element. /// While there are scripting functions to work with the browser, /// most of the browser creation and destruction will happen in /// the FrameXML. /// </summary> public class Browser : ContainerControl { #region Public API /// <summary> /// Create a new, empty, hidden web browser. Use Open() to /// load a URL. /// </summary> public Browser() { b = null; url = null; BackColor = DEFAULT_BACKGROUND; LocationChanged += new EventHandler(Browser_LocationChanged); SizeChanged += new EventHandler(Browser_SizeChanged); } protected override void Dispose(bool disposing) { if (b != null) { b = null; } Form f = FindForm(); if (f != null) { f.Focus(); } base.Dispose(disposing); } /// <summary> /// Gets the URL of the currently loaded web page. To go to /// a new URL, use Open(). /// </summary> public string URL { get { return url; } } /// <summary> /// Sets the location of the browser on the screen relative to the upper /// left corner of the window. The browser window will be clipped to /// the client window if it goes offscreen. /// </summary> /// <param name="x"> /// The X position of the browser, relative to the upper left corner /// of the window. /// </param> /// <param name="y"> /// The Y position of the browser, relative to the upper left corner /// of the window. Note that this position starts at 0 and goes down, /// as opposed to the FrameXML, which starts from the bottom of the /// window and goes up. /// </param> public void SetLocation(int x, int y) { BrowserLocation = new Point(x, y); } /// <summary> /// Sets the size of the browser window in pixels. /// </summary> /// <param name="w"> /// The width of the window in pixels. /// </param> /// <param name="h"> /// The height of the window in pixels. /// </param> public void SetSize(int w, int h) { BrowserSize = new Size(w, h); } /// <summary> /// Sets an empty space around the browser window, in pixels. The /// browser window will position itself offset from the upper left /// corner by this border width. /// </summary> /// <param name="w"> /// The size of the border in pixels. The border will be added to /// all four sides (the top, left, bottom, and right.) /// </param> public void SetBorder(int w) { BrowserBorder = w; } /// <summary> /// Draws a black border line around the browser window with this width. /// This line is applied after the border is applied, and is cumulative. /// </summary> /// <param name="w"> /// The width of the line around the browser, in pixels. /// </param> public void SetLine(int w) { BrowserLine = w; } /// <summary> /// Whether or not the browser will create scrollbars if the display size /// is greater than the browser window size. Note that plugins and Flash /// for example may still create scrollbars. /// </summary> /// <param name="enabled"> /// Whether or not scrollbars are enabled. /// </param> public void EnableScrollbars(bool enabled) { BrowserScrollbars = enabled; } /// <summary> /// Whether or not the embedded browser will bring up dialog boxes when /// script errors occur. This is useful for debugging but probably /// should be turned off in production. /// </summary> /// <param name="enabled"> /// Whether or not errors are enabled. /// </param> public void EnableErrors(bool enabled) { BrowserErrors = enabled; } /// <summary> /// Loads a new URL into the browser window. Returns true if the action /// succeeded, or false if it didn't. Note that embedded objects like /// Quicktime movies or loading Flash apps directly may require some /// extra HTML to not generate an IE error. /// </summary> /// <param name="u"> /// The URL to open, for example, "http://www.multiverse.net" /// </param> /// <returns> /// Whether or not the URL was loaded. Does not wait for the document /// to load, so it may display a 404. (In fact, there aren't very many /// ways this can return false right now.) /// </returns> public bool Open(string u) { url = u; if (b == null) { SetupBrowser(); } b.Navigate(URL); // XXXMLM - loading screen // XXXMLM - fullscreen is dodgy // XXXMLM - onclose make no warning, close control b.ScrollBarsEnabled = BrowserScrollbars; b.ScriptErrorsSuppressed = !BrowserErrors; b.AllowNavigation = true; // b.Focus(); b.WebBrowserShortcutsEnabled = true; return true; } #endregion // Create a logger for use in this class public static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Browser)); public static int DEFAULT_BORDER = 50; public static int DEFAULT_LINE = 0; public static Color DEFAULT_BACKGROUND = Color.Black; private WebBrowser b; private Label dummy; // dummy label used to 'unfocus' the browser private string url; private Point browserLocation = Point.Empty; private Size browserSize = Size.Empty; private int browserBorder = DEFAULT_BORDER; private int browserLine = DEFAULT_LINE; private bool browserScrollbars = true; private bool browserErrors = false; void Browser_LocationChanged(object sender, EventArgs e) { if (b != null) { PositionBrowser(); } } void Browser_SizeChanged(object sender, EventArgs e) { if (b != null) { PositionBrowser(); } } public static bool RegisterForScripting() { return true; } public Point BrowserLocation { get { return browserLocation; } set { browserLocation = value; } } public Size BrowserSize { get { return browserSize; } set { browserSize = value; } } public int BrowserBorder { get { return browserBorder; } set { browserBorder = value; } } public int BrowserLine { get { return browserLine; } set { browserLine = value; } } public bool BrowserScrollbars { get { return browserScrollbars; } set { browserScrollbars = value; } } public bool BrowserErrors { get { return browserErrors; } set { browserErrors = value; } } public object ObjectForScripting { get { return b.ObjectForScripting; } set { b.ObjectForScripting = value; } } public void SetupBrowser() { RenderWindow rw = (Root.Instance.RenderSystem as D3D9RenderSystem).PrimaryWindow; Control c = (Control)rw.GetCustomAttribute("HWND"); // dummy label used to 'unfocus' the browser dummy = new Label(); dummy.Size = new Size(1, 1); dummy.Location = new Point(1, 1); Controls.Add(dummy); dummy.CreateControl(); b = new WebBrowser(); PositionBrowser(); Controls.Add(b); b.CreateControl(); b.BringToFront(); c.Controls.Add(this); CreateControl(); } public void PositionBrowser() { int w, h; int x, y; if (BrowserSize != Size.Empty) { w = BrowserSize.Width; h = BrowserSize.Height; } else { RenderWindow rw = (Root.Instance.RenderSystem as D3D9RenderSystem).PrimaryWindow; Control c = (Control)rw.GetCustomAttribute("HWND"); w = (c.Width) - (BrowserBorder * 2); h = (c.Height) - (BrowserBorder * 2); } if (BrowserLocation != Point.Empty) { x = BrowserLocation.X; y = BrowserLocation.Y; } else { RenderWindow rw = (Root.Instance.RenderSystem as D3D9RenderSystem).PrimaryWindow; Control c = (Control)rw.GetCustomAttribute("HWND"); x = (c.Width - w) / 2; y = (c.Height - h) / 2; } Size = new Size(w, h); Location = new Point(x, y); b.Size = new Size(w - (BrowserLine * 2), h - (BrowserLine * 2)); b.Location = new Point(BrowserLine, BrowserLine); } public void GetFocus() { b.BringToFront(); b.Select(); } public void Losefocus() { dummy.Select(); } /// <summary> /// Invoke a javascript method, using the browser control. /// </summary> /// <remarks> /// This should only be called from the thread that created the /// browser control /// </remarks> /// <param name="method"></param> /// <param name="args"></param> /// <returns></returns> public object InvokeScript(string method, IEnumerable<object> args) { object[] scriptingArgs = GetScriptingArgs(args); lock (this) { try { return b.Document.InvokeScript(method, scriptingArgs); } catch (Exception e) { string formattedScriptCall = FormatScriptCall(method, scriptingArgs); log.WarnFormat("Failed to invoke script: {0} -- {1}", formattedScriptCall, e); throw; } } } /// <summary> /// Convert the argument array in a form that is usable from javascript /// </summary> /// <returns></returns> protected static object[] GetScriptingArgs(IEnumerable<object> args) { // We put the arguments in a list List<object> argumentList = new List<object>(); foreach (object obj in args) { if (obj is long) { long val = (long)obj; argumentList.Add((double)val); } else { argumentList.Add(obj); } } return argumentList.ToArray(); } /// <summary> /// This is mostly intended to help with debugging. If our script /// fails, we will use this to display the call. /// </summary> /// <param name="method"></param> /// <param name="args"></param> /// <returns></returns> protected static string FormatScriptCall(string method, object[] args) { StringBuilder msg = new StringBuilder(); msg.AppendFormat("{0}(", method); for (int i = 0; i < args.Length; ++i) { if (i == (args.Length - 1)) msg.AppendFormat("'{0}'", args[i]); else msg.AppendFormat("'{0}', ", args[i]); } msg.Append(")"); return msg.ToString(); } } }
// 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.Text; using System.Net.Http; using System.Diagnostics; namespace System.Net.Mime { /// <summary> /// This stream performs in-place decoding of quoted-printable /// encoded streams. Encoding requires copying into a separate /// buffer as the data being encoded will most likely grow. /// Encoding and decoding is done transparently to the caller. /// </summary> internal class QEncodedStream : DelegatingStream, IEncodableStream { //folding takes up 3 characters "\r\n " private const int SizeOfFoldingCRLF = 3; private static readonly byte[] s_hexDecodeMap = new byte[] { // 0 1 2 3 4 5 6 7 8 9 A B C D E F 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 0 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 1 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 2 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,255,255,255,255,255,255, // 3 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 4 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 5 255, 10, 11, 12, 13, 14, 15,255,255,255,255,255,255,255,255,255, // 6 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 7 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 8 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // 9 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // A 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // B 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // C 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // D 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // E 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, // F }; //bytes that correspond to the hex char representations in ASCII (0-9, A-F) private static readonly byte[] s_hexEncodeMap = new byte[] { 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70 }; private ReadStateInfo _readState; private WriteStateInfoBase _writeState; internal QEncodedStream(WriteStateInfoBase wsi) : base(new MemoryStream()) { _writeState = wsi; } private ReadStateInfo ReadState => _readState ?? (_readState = new ReadStateInfo()); internal WriteStateInfoBase WriteState => _writeState; public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (offset + count > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } WriteAsyncResult result = new WriteAsyncResult(this, buffer, offset, count, callback, state); result.Write(); return result; } protected override void Dispose(bool disposing) { FlushInternal(); base.Dispose(disposing); } public unsafe int DecodeBytes(byte[] buffer, int offset, int count) { fixed (byte* pBuffer = buffer) { byte* start = pBuffer + offset; byte* source = start; byte* dest = start; byte* end = start + count; // if the last read ended in a partially decoded // sequence, pick up where we left off. if (ReadState.IsEscaped) { // this will be -1 if the previous read ended // with an escape character. if (ReadState.Byte == -1) { // if we only read one byte from the underlying // stream, we'll need to save the byte and // ask for more. if (count == 1) { ReadState.Byte = *source; return 0; } // '=\r\n' means a soft (aka. invisible) CRLF sequence... if (source[0] != '\r' || source[1] != '\n') { byte b1 = s_hexDecodeMap[source[0]]; byte b2 = s_hexDecodeMap[source[1]]; if (b1 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b1)); if (b2 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b2)); *dest++ = (byte)((b1 << 4) + b2); } source += 2; } else { // '=\r\n' means a soft (aka. invisible) CRLF sequence... if (ReadState.Byte != '\r' || *source != '\n') { byte b1 = s_hexDecodeMap[ReadState.Byte]; byte b2 = s_hexDecodeMap[*source]; if (b1 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b1)); if (b2 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b2)); *dest++ = (byte)((b1 << 4) + b2); } source++; } // reset state for next read. ReadState.IsEscaped = false; ReadState.Byte = -1; } // Here's where most of the decoding takes place. // We'll loop around until we've inspected all the // bytes read. while (source < end) { // if the source is not an escape character, then // just copy as-is. if (*source != '=') { if (*source == '_') { *dest++ = (byte)' '; source++; } else { *dest++ = *source++; } } else { // determine where we are relative to the end // of the data. If we don't have enough data to // decode the escape sequence, save off what we // have and continue the decoding in the next // read. Otherwise, decode the data and copy // into dest. switch (end - source) { case 2: ReadState.Byte = source[1]; goto case 1; case 1: ReadState.IsEscaped = true; goto EndWhile; default: if (source[1] != '\r' || source[2] != '\n') { byte b1 = s_hexDecodeMap[source[1]]; byte b2 = s_hexDecodeMap[source[2]]; if (b1 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b1)); if (b2 == 255) throw new FormatException(SR.Format(SR.InvalidHexDigit, b2)); *dest++ = (byte)((b1 << 4) + b2); } source += 3; break; } } } EndWhile: return (int)(dest - start); } } public int EncodeBytes(byte[] buffer, int offset, int count) { // Add Encoding header, if any. e.g. =?encoding?b? _writeState.AppendHeader(); // Scan one character at a time looking for chars that need to be encoded. int cur = offset; for (; cur < count + offset; cur++) { if ( // Fold if we're before a whitespace and encoding another character would be too long ((WriteState.CurrentLineLength + SizeOfFoldingCRLF + WriteState.FooterLength >= WriteState.MaxLineLength) && (buffer[cur] == ' ' || buffer[cur] == '\t' || buffer[cur] == '\r' || buffer[cur] == '\n')) // Or just adding the footer would be too long. || (WriteState.CurrentLineLength + _writeState.FooterLength >= WriteState.MaxLineLength) ) { WriteState.AppendCRLF(true); } // We don't need to worry about RFC 2821 4.5.2 (encoding first dot on a line), // it is done by the underlying 7BitStream //always encode CRLF if (buffer[cur] == '\r' && cur + 1 < count + offset && buffer[cur + 1] == '\n') { cur++; //the encoding for CRLF is =0D=0A WriteState.Append((byte)'=', (byte)'0', (byte)'D', (byte)'=', (byte)'0', (byte)'A'); } else if (buffer[cur] == ' ') { //spaces should be escaped as either '_' or '=20' and //we have chosen '_' for parity with other email client //behavior WriteState.Append((byte)'_'); } // RFC 2047 Section 5 part 3 also allows for !*+-/ but these arn't required in headers. // Conservatively encode anything but letters or digits. else if (IsAsciiLetterOrDigit((char)buffer[cur])) { // Just a regular printable ascii char. WriteState.Append(buffer[cur]); } else { //append an = to indicate an encoded character WriteState.Append((byte)'='); //shift 4 to get the first four bytes only and look up the hex digit WriteState.Append(s_hexEncodeMap[buffer[cur] >> 4]); //clear the first four bytes to get the last four and look up the hex digit WriteState.Append(s_hexEncodeMap[buffer[cur] & 0xF]); } } WriteState.AppendFooter(); return cur - offset; } private static bool IsAsciiLetterOrDigit(char character) => IsAsciiLetter(character) || (character >= '0' && character <= '9'); private static bool IsAsciiLetter(char character) => (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z'); public Stream GetStream() => this; public string GetEncodedString() => Encoding.ASCII.GetString(WriteState.Buffer, 0, WriteState.Length); public override void EndWrite(IAsyncResult asyncResult) => WriteAsyncResult.End(asyncResult); public override void Flush() { FlushInternal(); base.Flush(); } private void FlushInternal() { if (_writeState != null && _writeState.Length > 0) { base.Write(WriteState.Buffer, 0, WriteState.Length); WriteState.Reset(); } } public override void Write(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (offset + count > buffer.Length) { throw new ArgumentOutOfRangeException(nameof(count)); } int written = 0; for (;;) { written += EncodeBytes(buffer, offset + written, count - written); if (written < count) { FlushInternal(); } else { break; } } } private sealed class ReadStateInfo { internal bool IsEscaped { get; set; } internal short Byte { get; set; } = -1; } private class WriteAsyncResult : LazyAsyncResult { private readonly static AsyncCallback s_onWrite = OnWrite; private readonly QEncodedStream _parent; private readonly byte[] _buffer; private readonly int _offset; private readonly int _count; private int _written; internal WriteAsyncResult(QEncodedStream parent, byte[] buffer, int offset, int count, AsyncCallback callback, object state) : base(null, state, callback) { _parent = parent; _buffer = buffer; _offset = offset; _count = count; } private void CompleteWrite(IAsyncResult result) { _parent.BaseStream.EndWrite(result); _parent.WriteState.Reset(); } internal static void End(IAsyncResult result) { WriteAsyncResult thisPtr = (WriteAsyncResult)result; thisPtr.InternalWaitForCompletion(); Debug.Assert(thisPtr._written == thisPtr._count); } private static void OnWrite(IAsyncResult result) { if (!result.CompletedSynchronously) { WriteAsyncResult thisPtr = (WriteAsyncResult)result.AsyncState; try { thisPtr.CompleteWrite(result); thisPtr.Write(); } catch (Exception e) { thisPtr.InvokeCallback(e); } } } internal void Write() { for (;;) { _written += _parent.EncodeBytes(_buffer, _offset + _written, _count - _written); if (_written < _count) { IAsyncResult result = _parent.BaseStream.BeginWrite(_parent.WriteState.Buffer, 0, _parent.WriteState.Length, s_onWrite, this); if (!result.CompletedSynchronously) { break; } CompleteWrite(result); } else { InvokeCallback(); break; } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection.Emit; namespace System.Linq.Expressions.Compiler { /// <summary> /// Contains compiler state corresponding to a LabelTarget /// See also LabelScopeInfo. /// </summary> internal sealed class LabelInfo { // The tree node representing this label private readonly LabelTarget _node; // The IL label, will be mutated if Node is redefined private Label _label; private bool _labelDefined; internal Label Label { get { EnsureLabelAndValue(); return _label; } } // The local that carries the label's value, if any private LocalBuilder _value; // The blocks where this label is defined. If it has more than one item, // the blocks can't be jumped to except from a child block private readonly HashSet<LabelScopeInfo> _definitions = new HashSet<LabelScopeInfo>(); // Blocks that jump to this block private readonly List<LabelScopeInfo> _references = new List<LabelScopeInfo>(); // True if this label is the last thing in this block // (meaning we can emit a direct return) private readonly bool _canReturn; // True if at least one jump is across blocks // If we have any jump across blocks to this label, then the // LabelTarget can only be defined in one place private bool _acrossBlockJump; // Until we have more information, default to a leave instruction, // which always works. Note: leave spills the stack, so we need to // ensure that StackSpiller has guaranteed us an empty stack at this // point. Otherwise Leave and Branch are not equivalent private OpCode _opCode = OpCodes.Leave; private readonly ILGenerator _ilg; internal LabelInfo(ILGenerator il, LabelTarget node, bool canReturn) { _ilg = il; _node = node; _canReturn = canReturn; } internal bool CanReturn { get { return _canReturn; } } /// <summary> /// Indicates if it is legal to emit a "branch" instruction based on /// currently available information. Call the Reference method before /// using this property. /// </summary> internal bool CanBranch { get { return _opCode != OpCodes.Leave; } } internal void Reference(LabelScopeInfo block) { _references.Add(block); if (_definitions.Count > 0) { ValidateJump(block); } } // Returns true if the label was successfully defined // or false if the label is now ambiguous internal void Define(LabelScopeInfo block) { // Prevent the label from being shadowed, which enforces cleaner // trees. Also we depend on this for simplicity (keeping only one // active IL Label per LabelInfo) for (LabelScopeInfo j = block; j != null; j = j.Parent) { if (j.ContainsTarget(_node)) { throw Error.LabelTargetAlreadyDefined(_node.Name); } } _definitions.Add(block); block.AddLabelInfo(_node, this); // Once defined, validate all jumps if (_definitions.Count == 1) { foreach (var r in _references) { ValidateJump(r); } } else { // Was just redefined, if we had any across block jumps, they're // now invalid if (_acrossBlockJump) { throw Error.AmbiguousJump(_node.Name); } // For local jumps, we need a new IL label // This is okay because: // 1. no across block jumps have been made or will be made // 2. we don't allow the label to be shadowed _labelDefined = false; } } private void ValidateJump(LabelScopeInfo reference) { // Assume we can do a ret/branch _opCode = _canReturn ? OpCodes.Ret : OpCodes.Br; // look for a simple jump out for (LabelScopeInfo j = reference; j != null; j = j.Parent) { if (_definitions.Contains(j)) { // found it, jump is valid! return; } if (j.Kind == LabelScopeKind.Finally || j.Kind == LabelScopeKind.Filter) { break; } if (j.Kind == LabelScopeKind.Try || j.Kind == LabelScopeKind.Catch) { _opCode = OpCodes.Leave; } } _acrossBlockJump = true; if (_node != null && _node.Type != typeof(void)) { throw Error.NonLocalJumpWithValue(_node.Name); } if (_definitions.Count > 1) { throw Error.AmbiguousJump(_node.Name); } // We didn't find an outward jump. Look for a jump across blocks LabelScopeInfo def = _definitions.First(); LabelScopeInfo common = Helpers.CommonNode(def, reference, b => b.Parent); // Assume we can do a ret/branch _opCode = _canReturn ? OpCodes.Ret : OpCodes.Br; // Validate that we aren't jumping across a finally for (LabelScopeInfo j = reference; j != common; j = j.Parent) { if (j.Kind == LabelScopeKind.Finally) { throw Error.ControlCannotLeaveFinally(); } if (j.Kind == LabelScopeKind.Filter) { throw Error.ControlCannotLeaveFilterTest(); } if (j.Kind == LabelScopeKind.Try || j.Kind == LabelScopeKind.Catch) { _opCode = OpCodes.Leave; } } // Validate that we aren't jumping into a catch or an expression for (LabelScopeInfo j = def; j != common; j = j.Parent) { if (!j.CanJumpInto) { if (j.Kind == LabelScopeKind.Expression) { throw Error.ControlCannotEnterExpression(); } else { throw Error.ControlCannotEnterTry(); } } } } internal void ValidateFinish() { // Make sure that if this label was jumped to, it is also defined if (_references.Count > 0 && _definitions.Count == 0) { throw Error.LabelTargetUndefined(_node.Name); } } internal void EmitJump() { // Return directly if we can if (_opCode == OpCodes.Ret) { _ilg.Emit(OpCodes.Ret); } else { StoreValue(); _ilg.Emit(_opCode, Label); } } private void StoreValue() { EnsureLabelAndValue(); if (_value != null) { _ilg.Emit(OpCodes.Stloc, _value); } } internal void Mark() { if (_canReturn) { // Don't mark return labels unless they were actually jumped to // (returns are last so we know for sure if anyone jumped to it) if (!_labelDefined) { // We don't even need to emit the "ret" because // LambdaCompiler does that for us. return; } // Otherwise, emit something like: // ret // <marked label>: // ldloc <value> _ilg.Emit(OpCodes.Ret); } else { // For the normal case, we emit: // stloc <value> // <marked label>: // ldloc <value> StoreValue(); } MarkWithEmptyStack(); } // Like Mark, but assumes the stack is empty internal void MarkWithEmptyStack() { _ilg.MarkLabel(Label); if (_value != null) { // We always read the value from a local, because we don't know // if there will be a "leave" instruction targeting it ("branch" // preserves its stack, but "leave" empties the stack) _ilg.Emit(OpCodes.Ldloc, _value); } } private void EnsureLabelAndValue() { if (!_labelDefined) { _labelDefined = true; _label = _ilg.DefineLabel(); if (_node != null && _node.Type != typeof(void)) { _value = _ilg.DeclareLocal(_node.Type); } } } } internal enum LabelScopeKind { // any "statement like" node that can be jumped into Statement, // these correspond to the node of the same name Block, Switch, Lambda, Try, // these correspond to the part of the try block we're in Catch, Finally, Filter, // the catch-all value for any other expression type // (means we can't jump into it) Expression, } // // Tracks scoping information for LabelTargets. Logically corresponds to a // "label scope". Even though we have arbitrary goto support, we still need // to track what kinds of nodes that gotos are jumping through, both to // emit property IL ("leave" out of a try block), and for validation, and // to allow labels to be duplicated in the tree, as long as the jumps are // considered "up only" jumps. // // We create one of these for every Expression that can be jumped into, as // well as creating them for the first expression we can't jump into. The // "Kind" property indicates what kind of scope this is. // internal sealed class LabelScopeInfo { private Dictionary<LabelTarget, LabelInfo> _labels; // lazily allocated, we typically use this only once every 6th-7th block internal readonly LabelScopeKind Kind; internal readonly LabelScopeInfo Parent; internal LabelScopeInfo(LabelScopeInfo parent, LabelScopeKind kind) { Parent = parent; Kind = kind; } /// <summary> /// Returns true if we can jump into this node /// </summary> internal bool CanJumpInto { get { switch (Kind) { case LabelScopeKind.Block: case LabelScopeKind.Statement: case LabelScopeKind.Switch: case LabelScopeKind.Lambda: return true; } return false; } } internal bool ContainsTarget(LabelTarget target) { if (_labels == null) { return false; } return _labels.ContainsKey(target); } internal bool TryGetLabelInfo(LabelTarget target, out LabelInfo info) { if (_labels == null) { info = null; return false; } return _labels.TryGetValue(target, out info); } internal void AddLabelInfo(LabelTarget target, LabelInfo info) { Debug.Assert(CanJumpInto); if (_labels == null) { _labels = new Dictionary<LabelTarget, LabelInfo>(); } _labels.Add(target, info); } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, 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.Targets.Wrappers { using System; using System.Collections.Generic; using NLog.Common; using NLog.Conditions; using NLog.Config; using NLog.Internal; /// <summary> /// Filters buffered log entries based on a set of conditions that are evaluated on a group of events. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/PostFilteringWrapper-target">Documentation on NLog Wiki</seealso> /// <remarks> /// PostFilteringWrapper must be used with some type of buffering target or wrapper, such as /// AsyncTargetWrapper, BufferingWrapper or ASPNetBufferingWrapper. /// </remarks> /// <example> /// <p> /// This example works like this. If there are no Warn,Error or Fatal messages in the buffer /// only Info messages are written to the file, but if there are any warnings or errors, /// the output includes detailed trace (levels &gt;= Debug). You can plug in a different type /// of buffering wrapper (such as ASPNetBufferingWrapper) to achieve different /// functionality. /// </p> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/PostFilteringWrapper/NLog.config" /> /// <p> /// The above examples assume just one target and a single rule. See below for /// a programmatic configuration that's equivalent to the above config file: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/PostFilteringWrapper/Simple/Example.cs" /> /// </example> [Target("PostFilteringWrapper", IsWrapper = true)] public class PostFilteringTargetWrapper : WrapperTargetBase { private static object boxedTrue = true; /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> public PostFilteringTargetWrapper() : this(null) { this.Rules = new List<FilteringRule>(); } /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> public PostFilteringTargetWrapper(Target wrappedTarget) { this.Rules = new List<FilteringRule>(); this.WrappedTarget = wrappedTarget; } /// <summary> /// Initializes a new instance of the <see cref="PostFilteringTargetWrapper" /> class. /// </summary> /// <param name="name">Name of the target.</param> /// <param name="wrappedTarget">The wrapped target.</param> public PostFilteringTargetWrapper(string name, Target wrappedTarget) : this(wrappedTarget) { this.Name = name; } /// <summary> /// Gets or sets the default filter to be applied when no specific rule matches. /// </summary> /// <docgen category='Filtering Options' order='10' /> public ConditionExpression DefaultFilter { get; set; } /// <summary> /// Gets the collection of filtering rules. The rules are processed top-down /// and the first rule that matches determines the filtering condition to /// be applied to log events. /// </summary> /// <docgen category='Filtering Rules' order='10' /> [ArrayParameter(typeof(FilteringRule), "when")] public IList<FilteringRule> Rules { get; private set; } /// <summary> /// NOTE! Obsolete, instead override Write(IList{AsyncLogEventInfo} logEvents) /// /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Write" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> [Obsolete("Instead override Write(IList<AsyncLogEventInfo> logEvents. Marked obsolete on NLog 4.5")] protected override void Write(AsyncLogEventInfo[] logEvents) { Write((IList<AsyncLogEventInfo>)logEvents); } /// <summary> /// Evaluates all filtering rules to find the first one that matches. /// The matching rule determines the filtering condition to be applied /// to all items in a buffer. If no condition matches, default filter /// is applied to the array of log events. /// </summary> /// <param name="logEvents">Array of log events to be post-filtered.</param> protected override void Write(IList<AsyncLogEventInfo> logEvents) { ConditionExpression resultFilter = null; InternalLogger.Trace("Running {0} on {1} events", this, logEvents.Count); // evaluate all the rules to get the filtering condition for (int i = 0; i < logEvents.Count; ++i) { foreach (FilteringRule rule in this.Rules) { object v = rule.Exists.Evaluate(logEvents[i].LogEvent); if (boxedTrue.Equals(v)) { InternalLogger.Trace("Rule matched: {0}", rule.Exists); resultFilter = rule.Filter; break; } } if (resultFilter != null) { break; } } if (resultFilter == null) { resultFilter = this.DefaultFilter; } if (resultFilter == null) { this.WrappedTarget.WriteAsyncLogEvents(logEvents); } else { InternalLogger.Trace("Filter to apply: {0}", resultFilter); // apply the condition to the buffer var resultBuffer = new List<AsyncLogEventInfo>(); for (int i = 0; i < logEvents.Count; ++i) { object v = resultFilter.Evaluate(logEvents[i].LogEvent); if (boxedTrue.Equals(v)) { resultBuffer.Add(logEvents[i]); } else { // anything not passed down will be notified about successful completion logEvents[i].Continuation(null); } } InternalLogger.Trace("After filtering: {0} events.", resultBuffer.Count); if (resultBuffer.Count > 0) { InternalLogger.Trace("Sending to {0}", this.WrappedTarget); this.WrappedTarget.WriteAsyncLogEvents(resultBuffer); } } } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using Gallio.Common.Diagnostics; using Gallio.Runtime.Conversions; using Gallio.Runtime.Formatting; using Gallio.Common.Reflection; namespace Gallio.Framework.Data { /// <summary> /// Encapsulates a specification for invoking a method given values for /// its generic parameters and formal parameters. /// </summary> public sealed class MethodInvocationSpec : DataBindingSpec { private readonly IMethodInfo method; private readonly Type resolvedType; private MethodInfo resolvedMethod; private Type[] resolvedGenericArguments; private object[] resolvedArguments; /// <summary> /// Creates a new method specification. /// </summary> /// <param name="resolvedType">The non-generic type or generic type instantiation /// that declares the method to be invoked or is a subtype of the declaring type. /// This parameter is used to resolve the method to its declaring type.</param> /// <param name="method">The method or generic method definition to be instantiated.</param> /// <param name="slotValues">The slot values.</param> /// <param name="converter">The converter to use for converting slot values /// to the required types.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="resolvedType"/>, /// <paramref name="method"/>, <paramref name="slotValues"/> or <paramref name="converter"/> is null.</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="slotValues" /> contains /// slots that are declared by different methods or have incompatible values.</exception> public MethodInvocationSpec(Type resolvedType, IMethodInfo method, IEnumerable<KeyValuePair<ISlotInfo, object>> slotValues, IConverter converter) : base(slotValues, converter) { if (resolvedType == null) throw new ArgumentNullException("resolvedType"); if (method == null) throw new ArgumentNullException("method"); ValidateSlots(method, slotValues); this.resolvedType = resolvedType; this.method = method; ResolveMethod(); ResolveArguments(); } /// <summary> /// Gets the method or generic method definition to be invoked. /// </summary> public IMethodInfo Method { get { return method; } } /// <summary> /// Gets the resolved type that declares the method. /// </summary> public Type ResolvedType { get { return resolvedType; } } /// <summary> /// Gets the resolved method given any generic method arguments that may have /// been provided as slot values. /// </summary> public MethodInfo ResolvedMethod { get { return resolvedMethod; } } /// <summary> /// Gets the resolved method arguments. /// </summary> /// <remarks> /// <para> /// The values have already been converted to appropriate types for invoking the method. /// </para> /// </remarks> public object[] ResolvedArguments { get { return resolvedArguments; } } /// <summary> /// Invokes the method. /// </summary> /// <param name="obj">The object on which to invoke the method. This value is ignored /// if the method is static.</param> /// <returns>The method result value.</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="obj"/> is /// null but the method is non-static.</exception> /// <exception cref="Exception">Any exception thrown by the invoked method.</exception> [DebuggerHidden, DebuggerStepThrough] public object Invoke(object obj) { if (obj == null && !resolvedMethod.IsStatic) throw new ArgumentNullException("obj", "The object must not be null if the method is non-static."); return ExceptionUtils.InvokeMethodWithoutTargetInvocationException(resolvedMethod, obj, resolvedArguments); } /// <inheritdoc /> protected override string FormatImpl(string entity, IFormatter formatter) { StringBuilder str = new StringBuilder(entity); AppendFormattedGenericArguments(str, resolvedGenericArguments, formatter); AppendFormattedMethodArguments(str, resolvedArguments, formatter); return str.ToString(); } private void ResolveMethod() { int genericParameterCount = method.IsGenericMethodDefinition ? method.GenericArguments.Count : 0; resolvedGenericArguments = new Type[genericParameterCount]; int seen = 0; foreach (KeyValuePair<ISlotInfo, object> slotValue in SlotValues) { IGenericParameterInfo genericParameter = slotValue.Key as IGenericParameterInfo; if (genericParameter != null) { resolvedGenericArguments[genericParameter.Position] = (Type)Converter.Convert(slotValue.Value, typeof(Type)); seen += 1; } } if (genericParameterCount != seen) throw new ArgumentException(String.Format("The method has {0} generic parameters but the bindings only provide values for {1} of them.", genericParameterCount, seen)); resolvedMethod = ResolveMember(resolvedType, method.Resolve(true)); if (genericParameterCount != 0) resolvedMethod = resolvedMethod.MakeGenericMethod(resolvedGenericArguments); } private void ResolveArguments() { ParameterInfo[] resolvedParameters = resolvedMethod.GetParameters(); resolvedArguments = new object[resolvedParameters.Length]; int seen = 0; foreach (KeyValuePair<ISlotInfo, object> slotValue in SlotValues) { IParameterInfo parameter = slotValue.Key as IParameterInfo; if (parameter != null) { int position = parameter.Position; resolvedArguments[position] = Converter.Convert(slotValue.Value, resolvedParameters[position].ParameterType); seen += 1; } } if (resolvedParameters.Length != seen) throw new ArgumentException(String.Format("The method has {0} parameters but the bindings only provide values for {1} of them.", resolvedParameters.Length, seen)); } private static void ValidateSlots(IMethodInfo method, IEnumerable<KeyValuePair<ISlotInfo, object>> slotValues) { foreach (KeyValuePair<ISlotInfo, object> slotValue in slotValues) { ISlotInfo slot = slotValue.Key; switch (slot.Kind) { case CodeElementKind.GenericParameter: IGenericParameterInfo genericParameter = (IGenericParameterInfo)slot; if (method.Equals(genericParameter.DeclaringMethod)) continue; break; case CodeElementKind.Parameter: IParameterInfo parameter = (IParameterInfo)slot; if (method.Equals(parameter.Member)) continue; break; } throw new ArgumentException(String.Format("Slot '{0}' is not valid for invoking method '{1}'.", slot, method), "slotValues"); } } } }
using System; using Raksha.Utilities; using Raksha.Crypto.Macs; using Raksha.Crypto.Parameters; namespace Raksha.Crypto.Modes { /** * A Two-Pass Authenticated-Encryption Scheme Optimized for Simplicity and * Efficiency - by M. Bellare, P. Rogaway, D. Wagner. * * http://www.cs.ucdavis.edu/~rogaway/papers/eax.pdf * * EAX is an AEAD scheme based on CTR and OMAC1/CMAC, that uses a single block * cipher to encrypt and authenticate data. It's on-line (the length of a * message isn't needed to begin processing it), has good performances, it's * simple and provably secure (provided the underlying block cipher is secure). * * Of course, this implementations is NOT thread-safe. */ public class EaxBlockCipher : IAeadBlockCipher { private enum Tag : byte { N, H, C }; private SicBlockCipher cipher; private bool forEncryption; private int blockSize; private IMac mac; private byte[] nonceMac; private byte[] associatedTextMac; private byte[] macBlock; private int macSize; private byte[] bufBlock; private int bufOff; /** * Constructor that accepts an instance of a block cipher engine. * * @param cipher the engine to use */ public EaxBlockCipher( IBlockCipher cipher) { blockSize = cipher.GetBlockSize(); mac = new CMac(cipher); macBlock = new byte[blockSize]; bufBlock = new byte[blockSize * 2]; associatedTextMac = new byte[mac.GetMacSize()]; nonceMac = new byte[mac.GetMacSize()]; this.cipher = new SicBlockCipher(cipher); } public virtual string AlgorithmName { get { return cipher.GetUnderlyingCipher().AlgorithmName + "/EAX"; } } public virtual int GetBlockSize() { return cipher.GetBlockSize(); } public virtual void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; byte[] nonce, associatedText; ICipherParameters keyParam; if (parameters is AeadParameters) { AeadParameters param = (AeadParameters) parameters; nonce = param.GetNonce(); associatedText = param.GetAssociatedText(); macSize = param.MacSize / 8; keyParam = param.Key; } else if (parameters is ParametersWithIV) { ParametersWithIV param = (ParametersWithIV) parameters; nonce = param.GetIV(); associatedText = new byte[0]; macSize = mac.GetMacSize() / 2; keyParam = param.Parameters; } else { throw new ArgumentException("invalid parameters passed to EAX"); } byte[] tag = new byte[blockSize]; mac.Init(keyParam); tag[blockSize - 1] = (byte) Tag.H; mac.BlockUpdate(tag, 0, blockSize); mac.BlockUpdate(associatedText, 0, associatedText.Length); mac.DoFinal(associatedTextMac, 0); tag[blockSize - 1] = (byte) Tag.N; mac.BlockUpdate(tag, 0, blockSize); mac.BlockUpdate(nonce, 0, nonce.Length); mac.DoFinal(nonceMac, 0); tag[blockSize - 1] = (byte) Tag.C; mac.BlockUpdate(tag, 0, blockSize); cipher.Init(true, new ParametersWithIV(keyParam, nonceMac)); } private void calculateMac() { byte[] outC = new byte[blockSize]; mac.DoFinal(outC, 0); for (int i = 0; i < macBlock.Length; i++) { macBlock[i] = (byte)(nonceMac[i] ^ associatedTextMac[i] ^ outC[i]); } } public virtual void Reset() { Reset(true); } private void Reset( bool clearMac) { cipher.Reset(); mac.Reset(); bufOff = 0; Array.Clear(bufBlock, 0, bufBlock.Length); if (clearMac) { Array.Clear(macBlock, 0, macBlock.Length); } byte[] tag = new byte[blockSize]; tag[blockSize - 1] = (byte) Tag.C; mac.BlockUpdate(tag, 0, blockSize); } public virtual int ProcessByte( byte input, byte[] outBytes, int outOff) { return process(input, outBytes, outOff); } public virtual int ProcessBytes( byte[] inBytes, int inOff, int len, byte[] outBytes, int outOff) { int resultLen = 0; for (int i = 0; i != len; i++) { resultLen += process(inBytes[inOff + i], outBytes, outOff + resultLen); } return resultLen; } public virtual int DoFinal( byte[] outBytes, int outOff) { int extra = bufOff; byte[] tmp = new byte[bufBlock.Length]; bufOff = 0; if (forEncryption) { cipher.ProcessBlock(bufBlock, 0, tmp, 0); cipher.ProcessBlock(bufBlock, blockSize, tmp, blockSize); Array.Copy(tmp, 0, outBytes, outOff, extra); mac.BlockUpdate(tmp, 0, extra); calculateMac(); Array.Copy(macBlock, 0, outBytes, outOff + extra, macSize); Reset(false); return extra + macSize; } else { if (extra > macSize) { mac.BlockUpdate(bufBlock, 0, extra - macSize); cipher.ProcessBlock(bufBlock, 0, tmp, 0); cipher.ProcessBlock(bufBlock, blockSize, tmp, blockSize); Array.Copy(tmp, 0, outBytes, outOff, extra - macSize); } calculateMac(); if (!verifyMac(bufBlock, extra - macSize)) throw new InvalidCipherTextException("mac check in EAX failed"); Reset(false); return extra - macSize; } } public virtual byte[] GetMac() { byte[] mac = new byte[macSize]; Array.Copy(macBlock, 0, mac, 0, macSize); return mac; } public virtual int GetUpdateOutputSize( int len) { return ((len + bufOff) / blockSize) * blockSize; } public virtual int GetOutputSize( int len) { if (forEncryption) { return len + bufOff + macSize; } return len + bufOff - macSize; } private int process( byte b, byte[] outBytes, int outOff) { bufBlock[bufOff++] = b; if (bufOff == bufBlock.Length) { int size; if (forEncryption) { size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff); mac.BlockUpdate(outBytes, outOff, blockSize); } else { mac.BlockUpdate(bufBlock, 0, blockSize); size = cipher.ProcessBlock(bufBlock, 0, outBytes, outOff); } bufOff = blockSize; Array.Copy(bufBlock, blockSize, bufBlock, 0, blockSize); return size; } return 0; } private bool verifyMac(byte[] mac, int off) { for (int i = 0; i < macSize; i++) { if (macBlock[i] != mac[off + i]) { return false; } } return true; } } }
// Tree.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa and Microsoft Corporation. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-October-28 13:29:50> // // ------------------------------------------------------------------ // // This module defines classes for zlib compression and // decompression. This code is derived from the jzlib implementation of // zlib. In keeping with the license for jzlib, the copyright to that // code is below. // // ------------------------------------------------------------------ // // Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // 2. 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. // // 3. The names of the authors may not be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT, // INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, // OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, // EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // ----------------------------------------------------------------------- // // This program is based on zlib-1.1.3; credit to authors // Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu) // and contributors of zlib. // // ----------------------------------------------------------------------- using System; namespace Zlib.Portable { sealed class Tree { private static readonly int HEAP_SIZE = (2 * InternalConstants.L_CODES + 1); // extra bits for each length code internal static readonly int[] ExtraLengthBits = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; // extra bits for each distance code internal static readonly int[] ExtraDistanceBits = new int[] { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; // extra bits for each bit length code internal static readonly int[] extra_blbits = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7}; internal static readonly sbyte[] bl_order = new sbyte[]{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; // The lengths of the bit length codes are sent in order of decreasing // probability, to avoid transmitting the lengths for unused bit // length codes. internal const int Buf_size = 8 * 2; // see definition of array dist_code below //internal const int DIST_CODE_LEN = 512; private static readonly sbyte[] _dist_code = new sbyte[] { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 }; internal static readonly sbyte[] LengthCode = new sbyte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 }; internal static readonly int[] LengthBase = new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 0 }; internal static readonly int[] DistanceBase = new int[] { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 }; /// <summary> /// Map from a distance to a distance code. /// </summary> /// <remarks> /// No side effects. _dist_code[256] and _dist_code[257] are never used. /// </remarks> internal static int DistanceCode(int dist) { return (dist < 256) ? _dist_code[dist] : _dist_code[256 + SharedUtils.URShift(dist, 7)]; } internal short[] dyn_tree; // the dynamic tree internal int max_code; // largest code with non zero frequency internal StaticTree staticTree; // the corresponding static tree // Compute the optimal bit lengths for a tree and update the total bit length // for the current block. // IN assertion: the fields freq and dad are set, heap[heap_max] and // above are the tree nodes sorted by increasing frequency. // OUT assertions: the field len is set to the optimal bit length, the // array bl_count contains the frequencies for each bit length. // The length opt_len is updated; static_len is also updated if stree is // not null. internal void gen_bitlen(DeflateManager s) { short[] tree = dyn_tree; short[] stree = staticTree.treeCodes; int[] extra = staticTree.extraBits; int base_Renamed = staticTree.extraBase; int max_length = staticTree.maxLength; int h; // heap index int n, m; // iterate over the tree elements int bits; // bit length int xbits; // extra bits short f; // frequency int overflow = 0; // number of elements with bit length too large for (bits = 0; bits <= InternalConstants.MAX_BITS; bits++) s.bl_count[bits] = 0; // In a first pass, compute the optimal bit lengths (which may // overflow in the case of the bit length tree). tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1] * 2 + 1] + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1] = (short) bits; // We overwrite tree[n*2+1] which is no longer needed if (n > max_code) continue; // not a leaf node s.bl_count[bits]++; xbits = 0; if (n >= base_Renamed) xbits = extra[n - base_Renamed]; f = tree[n * 2]; s.opt_len += f * (bits + xbits); if (stree != null) s.static_len += f * (stree[n * 2 + 1] + xbits); } if (overflow == 0) return ; // This happens for example on obj2 and pic of the Calgary corpus // Find the first bit length which could increase: do { bits = max_length - 1; while (s.bl_count[bits] == 0) bits--; s.bl_count[bits]--; // move one leaf down the tree s.bl_count[bits + 1] = (short) (s.bl_count[bits + 1] + 2); // move one overflow item as its brother s.bl_count[max_length]--; // The brother of the overflow item also moves one step up, // but this does not affect bl_count[max_length] overflow -= 2; } while (overflow > 0); for (bits = max_length; bits != 0; bits--) { n = s.bl_count[bits]; while (n != 0) { m = s.heap[--h]; if (m > max_code) continue; if (tree[m * 2 + 1] != bits) { s.opt_len = (int) (s.opt_len + ((long) bits - (long) tree[m * 2 + 1]) * (long) tree[m * 2]); tree[m * 2 + 1] = (short) bits; } n--; } } } // Construct one Huffman tree and assigns the code bit strings and lengths. // Update the total bit length for the current block. // IN assertion: the field freq is set for all tree elements. // OUT assertions: the fields len and code are set to the optimal bit length // and corresponding code. The length opt_len is updated; static_len is // also updated if stree is not null. The field max_code is set. internal void build_tree(DeflateManager s) { short[] tree = dyn_tree; short[] stree = staticTree.treeCodes; int elems = staticTree.elems; int n, m; // iterate over heap elements int max_code = -1; // largest code with non zero frequency int node; // new node being created // Construct the initial heap, with least frequent element in // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. // heap[0] is not used. s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2] != 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1] = 0; } } // The pkzip format requires that at least one distance code exists, // and that at least one bit should be sent even if there is only one // possible code. So to avoid special checks later on we force at least // two codes of non zero frequency. while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2?++max_code:0); tree[node * 2] = 1; s.depth[node] = 0; s.opt_len--; if (stree != null) s.static_len -= stree[node * 2 + 1]; // node is 0 or 1 so it does not have extra bits } this.max_code = max_code; // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, // establish sub-heaps of increasing lengths: for (n = s.heap_len / 2; n >= 1; n--) s.pqdownheap(tree, n); // Construct the Huffman tree by repeatedly combining the least two // frequent nodes. node = elems; // next internal node of the tree do { // n = node of least frequency n = s.heap[1]; s.heap[1] = s.heap[s.heap_len--]; s.pqdownheap(tree, 1); m = s.heap[1]; // m = node of next least frequency s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency s.heap[--s.heap_max] = m; // Create a new node father of n and m tree[node * 2] = unchecked((short) (tree[n * 2] + tree[m * 2])); s.depth[node] = (sbyte) (System.Math.Max((byte) s.depth[n], (byte) s.depth[m]) + 1); tree[n * 2 + 1] = tree[m * 2 + 1] = (short) node; // and insert the new node in the heap s.heap[1] = node++; s.pqdownheap(tree, 1); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1]; // At this point, the fields freq and dad are set. We can now // generate the bit lengths. gen_bitlen(s); // The field len is now set, we can generate the bit codes gen_codes(tree, max_code, s.bl_count); } // Generate the codes for a given tree and bit counts (which need not be // optimal). // IN assertion: the array bl_count contains the bit length statistics for // the given tree and the field len is set for all tree elements. // OUT assertion: the field code is set for all tree elements of non // zero code length. internal static void gen_codes(short[] tree, int max_code, short[] bl_count) { short[] next_code = new short[InternalConstants.MAX_BITS + 1]; // next code value for each bit length short code = 0; // running code value int bits; // bit index int n; // code index // The distribution counts are first used to generate the code values // without bit reversal. for (bits = 1; bits <= InternalConstants.MAX_BITS; bits++) unchecked { next_code[bits] = code = (short) ((code + bl_count[bits - 1]) << 1); } // Check that the bit counts in bl_count are consistent. The last code // must be all ones. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { int len = tree[n * 2 + 1]; if (len == 0) continue; // Now reverse the bits tree[n * 2] = unchecked((short) (bi_reverse(next_code[len]++, len))); } } // Reverse the first len bits of a code, using straightforward code (a faster // method would use a table) // IN assertion: 1 <= len <= 15 internal static int bi_reverse(int code, int len) { int res = 0; do { res |= code & 1; code >>= 1; //SharedUtils.URShift(code, 1); res <<= 1; } while (--len > 0); return res >> 1; } } }
//------------------------------------------------------------------------------ // <copyright file="DataGridViewSelectedColumnCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System.Diagnostics; using System; using System.Collections; using System.Windows.Forms; using System.ComponentModel; using System.Globalization; using System.Diagnostics.CodeAnalysis; /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection"]/*' /> [ ListBindable(false), SuppressMessage("Microsoft.Design", "CA1010:CollectionsShouldImplementGenericInterface") // Consider adding an IList<DataGridViewSelectedColumnCollection> implementation ] public class DataGridViewSelectedColumnCollection : BaseCollection, IList { ArrayList items = new ArrayList(); /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.Add"]/*' /> /// <internalonly/> int IList.Add(object value) { throw new NotSupportedException(SR.GetString(SR.DataGridView_ReadOnlyCollection)); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.Clear"]/*' /> /// <internalonly/> void IList.Clear() { throw new NotSupportedException(SR.GetString(SR.DataGridView_ReadOnlyCollection)); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.Contains"]/*' /> /// <internalonly/> bool IList.Contains(object value) { return this.items.Contains(value); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.IndexOf"]/*' /> /// <internalonly/> int IList.IndexOf(object value) { return this.items.IndexOf(value); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.Insert"]/*' /> /// <internalonly/> void IList.Insert(int index, object value) { throw new NotSupportedException(SR.GetString(SR.DataGridView_ReadOnlyCollection)); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.Remove"]/*' /> /// <internalonly/> void IList.Remove(object value) { throw new NotSupportedException(SR.GetString(SR.DataGridView_ReadOnlyCollection)); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.RemoveAt"]/*' /> /// <internalonly/> void IList.RemoveAt(int index) { throw new NotSupportedException(SR.GetString(SR.DataGridView_ReadOnlyCollection)); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.IsFixedSize"]/*' /> /// <internalonly/> bool IList.IsFixedSize { get { return true; } } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.IsReadOnly"]/*' /> /// <internalonly/> bool IList.IsReadOnly { get { return true; } } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IList.this"]/*' /> /// <internalonly/> object IList.this[int index] { get { return this.items[index]; } set { throw new NotSupportedException(SR.GetString(SR.DataGridView_ReadOnlyCollection)); } } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.ICollection.CopyTo"]/*' /> /// <internalonly/> void ICollection.CopyTo(Array array, int index) { this.items.CopyTo(array, index); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.ICollection.Count"]/*' /> /// <internalonly/> int ICollection.Count { get { return this.items.Count; } } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.ICollection.IsSynchronized"]/*' /> /// <internalonly/> bool ICollection.IsSynchronized { get { return false; } } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.ICollection.SyncRoot"]/*' /> /// <internalonly/> object ICollection.SyncRoot { get { return this; } } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.IEnumerable.GetEnumerator"]/*' /> /// <internalonly/> IEnumerator IEnumerable.GetEnumerator() { return this.items.GetEnumerator(); } internal DataGridViewSelectedColumnCollection() { } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.List"]/*' /> protected override ArrayList List { get { return this.items; } } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.this"]/*' /> public DataGridViewColumn this[int index] { get { return (DataGridViewColumn) this.items[index]; } } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.Add"]/*' /> /// <devdoc> /// <para>Adds a <see cref='System.Windows.Forms.DataGridViewCell'/> to this collection.</para> /// </devdoc> internal int Add(DataGridViewColumn dataGridViewColumn) { return this.items.Add(dataGridViewColumn); } /* Unused at this point internal void AddRange(DataGridViewColumn[] dataGridViewColumns) { Debug.Assert(dataGridViewColumns != null); foreach(DataGridViewColumn dataGridViewColumn in dataGridViewColumns) { this.items.Add(dataGridViewColumn); } } */ /* Unused at this point internal void AddColumnCollection(DataGridViewColumnCollection dataGridViewColumns) { Debug.Assert(dataGridViewColumns != null); foreach(DataGridViewColumn dataGridViewColumn in dataGridViewColumns) { this.items.Add(dataGridViewColumn); } } */ /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.Clear"]/*' /> [ EditorBrowsable(EditorBrowsableState.Never) ] public void Clear() { throw new NotSupportedException(SR.GetString(SR.DataGridView_ReadOnlyCollection)); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.Contains"]/*' /> /// <devdoc> /// Checks to see if a DataGridViewCell is contained in this collection. /// </devdoc> public bool Contains(DataGridViewColumn dataGridViewColumn) { return this.items.IndexOf(dataGridViewColumn) != -1; } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.CopyTo"]/*' /> public void CopyTo(DataGridViewColumn[] array, int index) { this.items.CopyTo(array, index); } /// <include file='doc\DataGridViewSelectedColumnCollection.uex' path='docs/doc[@for="DataGridViewSelectedColumnCollection.Insert"]/*' /> [ EditorBrowsable(EditorBrowsableState.Never), SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters") ] public void Insert(int index, DataGridViewColumn dataGridViewColumn) { throw new NotSupportedException(SR.GetString(SR.DataGridView_ReadOnlyCollection)); } } }
namespace app.web.Services { using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Text; using System.Threading.Tasks; using app.web.Models; using app.web.Repositories; public class ProfileService : IProfileService { private IDatabaseRepository _databaseRepository; private ISkillService _skillService; private ICharacteristicService _characteristicService; private IPositionService _positionService; public ProfileService( IDatabaseRepository databaseRepository = null, ISkillService skillService = null, ICharacteristicService characteristicService = null, IPositionService positionService = null) { this._databaseRepository = databaseRepository; this._skillService = skillService; this._characteristicService = characteristicService; this._positionService = positionService; } public IDatabaseRepository DatabaseRepository { set { this._databaseRepository = value; } } public ICharacteristicService CharacteristicService { set { this._characteristicService = value; } } public ISkillService SkillService { set { this._skillService = value; } } public IPositionService PositionService { set { this._positionService = value; } } public async Task<ProfileViewModel> GetProfileViewModelAsync(int id) { var positions = await this._positionService.GetPositionsAsync(); var allCharacteristics = await this._characteristicService.GetCharacteristicsAsync(); var allSkills = await this._skillService.GetSkillsAsync(); var profile = await this.GetProfileAsync(id); return new ProfileViewModel() { Positions = positions, Profile = profile, AllCharacteristics = allCharacteristics, AllSkills = allSkills }; } private async Task<Profile> GetProfileAsync(int id) { string commandText = @"SELECT id , firstname , lastname , position_id , start_date , status FROM `profile` pr WHERE (pr.status = @active) AND pr.id = @id ORDER BY pr.id"; var parameters = new Dictionary<string, object>(); parameters.Add("@id", id); parameters.Add("@active", Status.Active); var profile = await this._databaseRepository.ExecuteRead<Profile>( commandText, parameters, this.ReadProfile); if (profile != null) { profile.Characteristics = await this._characteristicService.GetCharacteristicsByProfileIdAsync(id); profile.Skills = await this._skillService.GetSkillsByProfileIdAsync(id); } return profile; } public async Task<ProfileViewModel> GetProfilesViewModelsAsync() { var positions = await this._positionService.GetPositionsAsync(); var profiles = await this.GetProfilesAsync(); return new ProfileViewModel() { Positions = positions, Profiles = profiles }; } public async Task<List<Profile>> GetProfilesAsync() { string commandText = @"SELECT pr.id , pr.firstname , pr.lastname , pr.position_id , pr.start_date , pr.status FROM `profile` pr WHERE (pr.status = @active) ORDER BY pr.id"; var parameters = new Dictionary<string, object>(); parameters.Add("@active", Status.Active); var profiles = await this._databaseRepository.ExecuteReadList<Profile>( commandText, parameters, this.ReadProfileList); return profiles; } public async Task<int> CreateProfileAsync(Profile profile) { if (profile == null) { return -1; } string commandText = @"INSERT INTO `profile` (firstname, lastname, start_date, position_id, status) VALUES(@firstname, @lastname, @startDate, @position, @status)"; var parameters = new Dictionary<string, object>(); parameters.Add("@firstname", profile.FirstName); parameters.Add("@lastname", profile.LastName); parameters.Add("@startDate", profile.StartDate); parameters.Add("@position", profile.Position); parameters.Add("@status", Status.Active); var insertedId = await this._databaseRepository.ExecuteUpdate( commandText, parameters, true); if (insertedId > 0) { await this._characteristicService.UpdateProfileCharacteristicsAsync(profile.Characteristics, insertedId); await this._skillService.UpdateProfileSkillsAsync(profile.Skills, insertedId); } return insertedId; } public async Task<bool> UpdateProfileAsync(Profile profile) { if (profile == null || profile.Id < 1) { return false; } string commandText = @"UPDATE `profile` SET firstname = @firstname, lastname = @lastname, start_date = @startDate, position_id = @position WHERE (id = @id)"; var parameters = new Dictionary<string, object>(); parameters.Add("@firstname", profile.FirstName); parameters.Add("@lastname", profile.LastName); parameters.Add("@startDate", profile.StartDate); parameters.Add("@position", profile.Position); parameters.Add("@id", profile.Id); var columnUpdated = await this._databaseRepository.ExecuteUpdate( commandText, parameters, false); await this._characteristicService.UpdateProfileCharacteristicsAsync(profile.Characteristics, profile.Id); await this._skillService.UpdateProfileSkillsAsync(profile.Skills, profile.Id); return columnUpdated == 1; } private void ReadProfileList(DbDataReader reader, List<Profile> profiles) { profiles.Add(this.ReadProfile(reader)); } private Profile ReadProfile(DbDataReader reader) { var profile = new Profile(); profile.Id = reader.GetInt32(reader.GetOrdinal("id")); profile.FirstName = reader.GetString(reader.GetOrdinal("firstname")); profile.LastName = reader.GetString(reader.GetOrdinal("lastname")); profile.StartDate = reader.GetDateTime(reader.GetOrdinal("start_date")); profile.Position = reader.GetInt32(reader.GetOrdinal("position_id")); profile.Status = (Status)reader.GetInt32(reader.GetOrdinal("status")); return profile; } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERCLevel; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D07_RegionColl (editable child list).<br/> /// This is a generated base class of <see cref="D07_RegionColl"/> business object. /// </summary> /// <remarks> /// This class is child of <see cref="D06_Country"/> editable child object.<br/> /// The items of the collection are <see cref="D08_Region"/> objects. /// </remarks> [Serializable] public partial class D07_RegionColl : BusinessListBase<D07_RegionColl, D08_Region> { #region Collection Business Methods /// <summary> /// Removes a <see cref="D08_Region"/> item from the collection. /// </summary> /// <param name="region_ID">The Region_ID of the item to be removed.</param> public void Remove(int region_ID) { foreach (var d08_Region in this) { if (d08_Region.Region_ID == region_ID) { Remove(d08_Region); break; } } } /// <summary> /// Determines whether a <see cref="D08_Region"/> item is in the collection. /// </summary> /// <param name="region_ID">The Region_ID of the item to search for.</param> /// <returns><c>true</c> if the D08_Region is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int region_ID) { foreach (var d08_Region in this) { if (d08_Region.Region_ID == region_ID) { return true; } } return false; } /// <summary> /// Determines whether a <see cref="D08_Region"/> item is in the collection's DeletedList. /// </summary> /// <param name="region_ID">The Region_ID of the item to search for.</param> /// <returns><c>true</c> if the D08_Region is a deleted collection item; otherwise, <c>false</c>.</returns> public bool ContainsDeleted(int region_ID) { foreach (var d08_Region in DeletedList) { if (d08_Region.Region_ID == region_ID) { return true; } } return false; } #endregion #region Find Methods /// <summary> /// Finds a <see cref="D08_Region"/> item of the <see cref="D07_RegionColl"/> collection, based on a given Region_ID. /// </summary> /// <param name="region_ID">The Region_ID.</param> /// <returns>A <see cref="D08_Region"/> object.</returns> public D08_Region FindD08_RegionByRegion_ID(int region_ID) { for (var i = 0; i < this.Count; i++) { if (this[i].Region_ID.Equals(region_ID)) { return this[i]; } } return null; } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D07_RegionColl"/> collection. /// </summary> /// <returns>A reference to the created <see cref="D07_RegionColl"/> collection.</returns> internal static D07_RegionColl NewD07_RegionColl() { return DataPortal.CreateChild<D07_RegionColl>(); } /// <summary> /// Factory method. Loads a <see cref="D07_RegionColl"/> collection, based on given parameters. /// </summary> /// <param name="parent_Country_ID">The Parent_Country_ID parameter of the D07_RegionColl to fetch.</param> /// <returns>A reference to the fetched <see cref="D07_RegionColl"/> collection.</returns> internal static D07_RegionColl GetD07_RegionColl(int parent_Country_ID) { return DataPortal.FetchChild<D07_RegionColl>(parent_Country_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D07_RegionColl"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D07_RegionColl() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = true; AllowEdit = true; AllowRemove = true; RaiseListChangedEvents = rlce; } #endregion #region Data Access /// <summary> /// Loads a <see cref="D07_RegionColl"/> collection from the database, based on given criteria. /// </summary> /// <param name="parent_Country_ID">The Parent Country ID.</param> protected void Child_Fetch(int parent_Country_ID) { var args = new DataPortalHookArgs(parent_Country_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<ID07_RegionCollDal>(); var data = dal.Fetch(parent_Country_ID); LoadCollection(data); } OnFetchPost(args); foreach (var item in this) { item.FetchChildren(); } } private void LoadCollection(IDataReader data) { using (var dr = new SafeDataReader(data)) { Fetch(dr); } } /// <summary> /// Loads all <see cref="D07_RegionColl"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(D08_Region.GetD08_Region(dr)); } RaiseListChangedEvents = rlce; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
/* BehaviourBase.cs * ---------------------------- * Copyright Eddie Cameron & Grasshopper NYC 2013 (MIT licenced) * ---------------------------- * Replacement for stock MonoBehaviour. To be used for all scripts * - Make sure to override (rather than hide with 'new') any unity methods like Start() or Update(), so * that any future code here will be executed */ using UnityEngine; using System.Collections; using System.Collections.Generic; public class BehaviourBase : MonoBehaviour { Transform _transform; public new Transform transform { get { if ( !_transform ) _transform = GetComponent<Transform>(); return _transform; } } Renderer _renderer; public new Renderer renderer { get { if ( !_renderer ) _renderer = GetComponent<Renderer>(); return _renderer; } } AudioSource _audioSource; public new AudioSource audio { get { if ( !_audioSource ) _audioSource = GetComponent<AudioSource>(); return _audioSource; } } Camera _camera; public new Camera camera { get { if ( !_camera ) _camera = GetComponent<Camera>(); return _camera; } } NetworkView _networkView; public new NetworkView networkView { get { if ( !_networkView ) _networkView = GetComponent<NetworkView>(); return _networkView; } } protected virtual void Awake() { } protected virtual void Start() { } protected virtual void OnEnable() { } protected virtual void OnDisable() { } protected virtual void Update() { } protected virtual void LateUpdate() { } protected virtual void FixedUpdate() { } /// <summary> /// Use to do stuff with a gradually changing value /// </summary> /// <param name="from">Value to start from</param> /// <param name="to">Value to end at</param> /// <param name="time">Time for value to change</param> /// <param name="lerpedFunction">Function that does something with T. Called each frame and given the updated value</param> /// <param name="finishFunction">Function called when change is finished</param> protected IEnumerator LerpValue( float from, float to, float time, System.Action<float> lerpedFunction, System.Action finishFunction = null ) { float amount = 0; while ( amount < 1f ) { yield return 0; amount += Time.deltaTime / time; lerpedFunction( Mathf.Lerp( from, to, amount ) ); } if ( finishFunction != null ) finishFunction(); } /// <summary> /// Use to do stuff with a gradually changing vector /// </summary> /// <param name="from">Vector to start from</param> /// <param name="to">Vector to end at</param> /// <param name="time">Time for vector to change</param> /// <param name="lerpedFunction">Function that does something with vector. Called each frame and given the updated value of the vector</param> /// <param name="finishFunction">Function called when change is finished</param> protected IEnumerator LerpVector( Vector3 from, Vector3 to, float time, System.Action<Vector3> lerpedFunction, System.Action finishFunction = null ) { float amount = 0; while ( amount < 1f ) { yield return 0; amount += Time.deltaTime / time; lerpedFunction( Vector3.Lerp( from, to, amount ) ); } if ( finishFunction != null ) finishFunction(); } protected IEnumerator LerpVectorActionTime( Vector3 from, Vector3 to, float time, System.Action<Vector3> lerpedFunction, System.Action finishFunction = null ) { yield return StartCoroutine( LerpFunctionActionTime( time, f => lerpedFunction( Vector3.Lerp( from, to, f ) ) ) ); if ( finishFunction != null ) finishFunction(); } protected IEnumerator LerpQuaternion( Quaternion from, Quaternion to, float time, System.Action<Quaternion> lerpedFunction, System.Action finishFunction = null ) { float amount = 0; while ( amount < 1f ) { yield return 0; amount += Time.deltaTime / time; lerpedFunction( Quaternion.Lerp( from, to, amount ) ); } if ( finishFunction != null ) finishFunction(); } protected IEnumerator LerpFunctionRealTime( float time, System.Action<float> lerpResultFunction ) { float amount = 0; while ( amount < 1f ) { lerpResultFunction( amount ); yield return 0; amount += Time.deltaTime / time; } lerpResultFunction( 1f ); } protected IEnumerator LerpFunctionActionTime( float time, System.Action<float> lerpResultFunction ) { float amount = 0; while ( amount < 1f ) { lerpResultFunction( amount ); yield return ActionTime.WaitOneActionFrame(); amount += ActionTime.deltaTime / time; } lerpResultFunction( 1f ); } } /// <summary> /// Base class for all Singletons, T is the actual type /// eg: public class MyClass : StaticBehaviour<MyClass> {...} /// ------- /// Use when there will only be one instance of a script in the scene. Makes access to non-static variables from static methods easy (with instance.fieldName) /// </summary> public class StaticBehaviour<T> : BehaviourBase where T : BehaviourBase { static T _instance; protected static T instance { get { if ( !_instance ) UpdateInstance(); return _instance; } } protected override void Awake() { if ( _instance ) { DebugExtras.LogWarning( "Duplicate instance of " + GetType() + " found. Removing " + name ); Destroy( this ); return; } UpdateInstance(); base.Awake(); } static void UpdateInstance() { _instance = GameObject.FindObjectOfType( typeof( T ) ) as T; if ( !_instance ) { DebugExtras.LogWarning( "No object of type : " + typeof( T ) + " found in scene. Creating" ); _instance = new GameObject( typeof( T ).ToString() ).AddComponent<T>(); } } } /// <summary> /// Base class for a nullable type, so you can use " if ( myClass ) {...} " to check for null /// </summary> public class Nullable { public static implicit operator bool( Nullable me ) { return me != null; } }
using System; using System.Text; namespace OctoTorrent.Common { /// <summary> /// This is the base class for the files available to download from within a .torrent. /// This should be inherited by both Client and Tracker "TorrentFile" classes /// </summary> public class TorrentFile : IEquatable<TorrentFile> { #region Private Fields private readonly BitField bitfield; private BitField selector; private readonly byte[] ed2k; private readonly int endPiece; private string fullPath; private readonly long length; private byte[] md5; private readonly string path; private Priority priority; private readonly byte[] sha1; private readonly int startPiece; #endregion Private Fields #region Member Variables /// <summary> /// The number of pieces which have been successfully downloaded which are from this file /// </summary> public BitField BitField { get { return bitfield; } } public long BytesDownloaded { get { return (long)(BitField.PercentComplete * Length / 100.0); } } /// <summary> /// The ED2K hash of the file /// </summary> public byte[] ED2K { get { return ed2k; } } /// <summary> /// The index of the last piece of this file /// </summary> public int EndPieceIndex { get { return endPiece; } } public string FullPath { get { return fullPath; } internal set { fullPath = value; } } /// <summary> /// The length of the file in bytes /// </summary> public long Length { get { return length; } } /// <summary> /// The MD5 hash of the file /// </summary> public byte[] MD5 { get { return this.md5; } internal set { md5 = value; } } /// <summary> /// In the case of a single torrent file, this is the name of the file. /// In the case of a multi-file torrent this is the relative path of the file /// (including the filename) from the base directory /// </summary> public string Path { get { return path; } } /// <summary> /// The priority of this torrent file /// </summary> public Priority Priority { get { return this.priority; } set { this.priority = value; } } /// <summary> /// The SHA1 hash of the file /// </summary> public byte[] SHA1 { get { return this.sha1; } } /// <summary> /// The index of the first piece of this file /// </summary> public int StartPieceIndex { get { return this.startPiece; } } #endregion #region Constructors public TorrentFile(string path, long length) : this(path, length, path) { } public TorrentFile (string path, long length, string fullPath) : this (path, length, fullPath, 0, 0) { } public TorrentFile (string path, long length, int startIndex, int endIndex) : this (path, length, path, startIndex, endIndex) { } public TorrentFile(string path, long length, string fullPath, int startIndex, int endIndex) : this(path, length, fullPath, startIndex, endIndex, null, null, null) { } public TorrentFile(string path, long length, string fullPath, int startIndex, int endIndex, byte[] md5, byte[] ed2k, byte[] sha1) { this.bitfield = new BitField(endIndex - startIndex + 1); this.ed2k = ed2k; this.endPiece = endIndex; this.fullPath = fullPath; this.length = length; this.md5 = md5; this.path = path; this.priority = Priority.Normal; this.sha1 = sha1; this.startPiece = startIndex; } #endregion #region Methods public override bool Equals(object obj) { return Equals(obj as TorrentFile); } public bool Equals(TorrentFile other) { return other == null ? false : path == other.path && length == other.length; ; } public override int GetHashCode() { return path.GetHashCode(); } internal BitField GetSelector(int totalPieces) { if (selector != null) return selector; selector = new BitField(totalPieces); for (int i = StartPieceIndex; i <= EndPieceIndex; i++) selector[i] = true; return selector; } public override string ToString() { StringBuilder sb = new StringBuilder(32); sb.Append("File: "); sb.Append(path); sb.Append(" StartIndex: "); sb.Append(StartPieceIndex); sb.Append(" EndIndex: "); sb.Append(EndPieceIndex); return sb.ToString(); } #endregion Methods } }
using System; using System.Threading.Tasks; using System.Collections.Generic; using System.Numerics; using Nethereum.Hex.HexTypes; using Nethereum.ABI.FunctionEncoding.Attributes; using Nethereum.Web3; using Nethereum.RPC.Eth.DTOs; using Nethereum.Contracts.CQS; using Nethereum.Contracts.ContractHandlers; using Nethereum.Contracts; using System.Threading; using Nethereum.ENS.ENSRegistry.ContractDefinition; namespace Nethereum.ENS { public partial class ENSRegistryService { public static Task<TransactionReceipt> DeployContractAndWaitForReceiptAsync(Nethereum.Web3.Web3 web3, ENSRegistryDeployment eNSRegistryDeployment, CancellationTokenSource cancellationTokenSource = null) { return web3.Eth.GetContractDeploymentHandler<ENSRegistryDeployment>().SendRequestAndWaitForReceiptAsync(eNSRegistryDeployment, cancellationTokenSource); } public static Task<string> DeployContractAsync(Nethereum.Web3.Web3 web3, ENSRegistryDeployment eNSRegistryDeployment) { return web3.Eth.GetContractDeploymentHandler<ENSRegistryDeployment>().SendRequestAsync(eNSRegistryDeployment); } public static async Task<ENSRegistryService> DeployContractAndGetServiceAsync(Nethereum.Web3.Web3 web3, ENSRegistryDeployment eNSRegistryDeployment, CancellationTokenSource cancellationTokenSource = null) { var receipt = await DeployContractAndWaitForReceiptAsync(web3, eNSRegistryDeployment, cancellationTokenSource); return new ENSRegistryService(web3, receipt.ContractAddress); } protected Nethereum.Web3.Web3 Web3{ get; } public ContractHandler ContractHandler { get; } public ENSRegistryService(Nethereum.Web3.Web3 web3, string contractAddress) { Web3 = web3; ContractHandler = web3.Eth.GetContractHandler(contractAddress); } public Task<string> ResolverQueryAsync(ResolverFunction resolverFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<ResolverFunction, string>(resolverFunction, blockParameter); } public Task<string> ResolverQueryAsync(byte[] node, BlockParameter blockParameter = null) { var resolverFunction = new ResolverFunction(); resolverFunction.Node = node; return ContractHandler.QueryAsync<ResolverFunction, string>(resolverFunction, blockParameter); } public Task<string> OwnerQueryAsync(OwnerFunction ownerFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<OwnerFunction, string>(ownerFunction, blockParameter); } public Task<string> OwnerQueryAsync(byte[] node, BlockParameter blockParameter = null) { var ownerFunction = new OwnerFunction(); ownerFunction.Node = node; return ContractHandler.QueryAsync<OwnerFunction, string>(ownerFunction, blockParameter); } public Task<string> SetSubnodeOwnerRequestAsync(SetSubnodeOwnerFunction setSubnodeOwnerFunction) { return ContractHandler.SendRequestAsync(setSubnodeOwnerFunction); } public Task<TransactionReceipt> SetSubnodeOwnerRequestAndWaitForReceiptAsync(SetSubnodeOwnerFunction setSubnodeOwnerFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(setSubnodeOwnerFunction, cancellationToken); } public Task<string> SetSubnodeOwnerRequestAsync(byte[] node, byte[] label, string owner) { var setSubnodeOwnerFunction = new SetSubnodeOwnerFunction(); setSubnodeOwnerFunction.Node = node; setSubnodeOwnerFunction.Label = label; setSubnodeOwnerFunction.Owner = owner; return ContractHandler.SendRequestAsync(setSubnodeOwnerFunction); } public Task<TransactionReceipt> SetSubnodeOwnerRequestAndWaitForReceiptAsync(byte[] node, byte[] label, string owner, CancellationTokenSource cancellationToken = null) { var setSubnodeOwnerFunction = new SetSubnodeOwnerFunction(); setSubnodeOwnerFunction.Node = node; setSubnodeOwnerFunction.Label = label; setSubnodeOwnerFunction.Owner = owner; return ContractHandler.SendRequestAndWaitForReceiptAsync(setSubnodeOwnerFunction, cancellationToken); } public Task<string> SetTTLRequestAsync(SetTTLFunction setTTLFunction) { return ContractHandler.SendRequestAsync(setTTLFunction); } public Task<TransactionReceipt> SetTTLRequestAndWaitForReceiptAsync(SetTTLFunction setTTLFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(setTTLFunction, cancellationToken); } public Task<string> SetTTLRequestAsync(byte[] node, ulong ttl) { var setTTLFunction = new SetTTLFunction(); setTTLFunction.Node = node; setTTLFunction.Ttl = ttl; return ContractHandler.SendRequestAsync(setTTLFunction); } public Task<TransactionReceipt> SetTTLRequestAndWaitForReceiptAsync(byte[] node, ulong ttl, CancellationTokenSource cancellationToken = null) { var setTTLFunction = new SetTTLFunction(); setTTLFunction.Node = node; setTTLFunction.Ttl = ttl; return ContractHandler.SendRequestAndWaitForReceiptAsync(setTTLFunction, cancellationToken); } public Task<ulong> TtlQueryAsync(TtlFunction ttlFunction, BlockParameter blockParameter = null) { return ContractHandler.QueryAsync<TtlFunction, ulong>(ttlFunction, blockParameter); } public Task<ulong> TtlQueryAsync(byte[] node, BlockParameter blockParameter = null) { var ttlFunction = new TtlFunction(); ttlFunction.Node = node; return ContractHandler.QueryAsync<TtlFunction, ulong>(ttlFunction, blockParameter); } public Task<string> SetResolverRequestAsync(SetResolverFunction setResolverFunction) { return ContractHandler.SendRequestAsync(setResolverFunction); } public Task<TransactionReceipt> SetResolverRequestAndWaitForReceiptAsync(SetResolverFunction setResolverFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(setResolverFunction, cancellationToken); } public Task<string> SetResolverRequestAsync(byte[] node, string resolver) { var setResolverFunction = new SetResolverFunction(); setResolverFunction.Node = node; setResolverFunction.Resolver = resolver; return ContractHandler.SendRequestAsync(setResolverFunction); } public Task<TransactionReceipt> SetResolverRequestAndWaitForReceiptAsync(byte[] node, string resolver, CancellationTokenSource cancellationToken = null) { var setResolverFunction = new SetResolverFunction(); setResolverFunction.Node = node; setResolverFunction.Resolver = resolver; return ContractHandler.SendRequestAndWaitForReceiptAsync(setResolverFunction, cancellationToken); } public Task<string> SetOwnerRequestAsync(SetOwnerFunction setOwnerFunction) { return ContractHandler.SendRequestAsync(setOwnerFunction); } public Task<TransactionReceipt> SetOwnerRequestAndWaitForReceiptAsync(SetOwnerFunction setOwnerFunction, CancellationTokenSource cancellationToken = null) { return ContractHandler.SendRequestAndWaitForReceiptAsync(setOwnerFunction, cancellationToken); } public Task<string> SetOwnerRequestAsync(byte[] node, string owner) { var setOwnerFunction = new SetOwnerFunction(); setOwnerFunction.Node = node; setOwnerFunction.Owner = owner; return ContractHandler.SendRequestAsync(setOwnerFunction); } public Task<TransactionReceipt> SetOwnerRequestAndWaitForReceiptAsync(byte[] node, string owner, CancellationTokenSource cancellationToken = null) { var setOwnerFunction = new SetOwnerFunction(); setOwnerFunction.Node = node; setOwnerFunction.Owner = owner; return ContractHandler.SendRequestAndWaitForReceiptAsync(setOwnerFunction, cancellationToken); } } }
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // 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 Jim Heising 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.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.IO; using WOSI.Utilities.Sound; using WOSI.CallButler.Data; namespace CallButler.Manager.Controls { public partial class GreetingControl : UserControl { private bool lockCheck = false; WOSI.CallButler.ManagementInterface.CallButlerManagementInterfaceClientBase managementClient; WOSI.CallButler.ManagementInterface.CallButlerAuthInfo authInfo; //public event EventHandler<EventArgs> OnSoundChanged; public event EventHandler<TextChangedEventArgs> OnTextChanged; private WOSI.CallButler.Data.CallButlerDataset.LocalizedGreetingsRow greetingRow; public GreetingControl() { Initialize(); } public GreetingControl(WOSI.CallButler.ManagementInterface.CallButlerManagementInterfaceClientBase managementClient, WOSI.CallButler.ManagementInterface.CallButlerAuthInfo authInfo) { this.managementClient = managementClient; this.authInfo = authInfo; Initialize(); } private void Initialize() { InitializeComponent(); //if (this.managementClient == null) mnuCall.Visible = false; GreetingType = GreetingType.SoundGreeting; wzdGreeting.PageIndex = 0; speechControl.ShowSuggestTextButton = true; speechControl.ShowVoiceSelection = true; speechControl.TextChanged += new EventHandler(speechControl_TextChanged); } void speechControl_TextChanged(object sender, EventArgs e) { FireOnTextChangedEvent(); } private void FireOnSoundChangedEvent() { /*if (OnSoundChanged != null) { OnSoundChanged(this, new EventArgs()); }*/ } private void FireOnTextChangedEvent() { if (OnTextChanged != null) { OnTextChanged(this, new TextChangedEventArgs(speechControl.SpeechText)); } } public void LoadGreeting(WOSI.CallButler.Data.CallButlerDataset.LocalizedGreetingsRow greeting, string greetingSoundCache) { recordingControl.Reset(); speechControl.SpeechText = ""; greetingRow = greeting; if (greeting != null) { this.GreetingType = (WOSI.CallButler.Data.GreetingType)greetingRow.Type; if (this.GreetingType == GreetingType.TextGreeting) { speechControl.SpeechText = greetingRow.Data; speechControl.Voice = greetingRow.Voice; } else if (this.GreetingType == GreetingType.SoundGreeting) { recordingControl.LoadSoundFile(greetingSoundCache + "\\" + greetingRow.LanguageID + "\\" + greetingRow.GreetingID.ToString() + ".snd"); } } } public void SaveGreeting(string greetingSoundCache, WOSI.CallButler.Data.CallButlerDataset.LocalizedGreetingsRow localizedGreeting) { StopSounds(); localizedGreeting.Type = (short)this.GreetingType; if (this.GreetingType == GreetingType.TextGreeting) { localizedGreeting.Data = speechControl.SpeechText; localizedGreeting.Voice = speechControl.Voice; } else if (this.GreetingType == GreetingType.SoundGreeting) { if (mnuCall.Checked) { localizedGreeting.Voice = ""; localizedGreeting.Data = "CallRecording"; } else if (recordingControl.NewFile && File.Exists(recordingControl.WorkingFile)) { localizedGreeting.Voice = ""; string greetingDirectory = greetingSoundCache + "\\" + localizedGreeting.LanguageID; string greetingSoundFile = greetingDirectory + "\\" + localizedGreeting.GreetingID + ".snd"; if (!Directory.Exists(greetingDirectory)) Directory.CreateDirectory(greetingDirectory); if (string.Compare(recordingControl.WorkingFile, greetingSoundFile, true) != 0) { File.Copy(recordingControl.WorkingFile, greetingSoundFile, true); File.SetAttributes(greetingSoundFile, FileAttributes.Normal); } // Fill in our file checksum localizedGreeting.Data = WOSI.Utilities.CryptoUtils.GetFileChecksum(greetingSoundFile); } } } public void StopSounds() { recordingControl.StopSounds(); speechControl.StopSpeaking(); } public void LoadVoices(string[] voices) { speechControl.LoadVoices(voices); } public void SaveGreeting( string greetingSoundCache) { SaveGreeting(greetingSoundCache, greetingRow); } [Browsable(false), DefaultValue("")] public string SuggestedText { get { return speechControl.SuggestedText; } set { speechControl.SuggestedText = value; recordingControl.SuggestedText = value; } } [DefaultValue(typeof(GreetingType), "GreetingType.SoundGreeting")] private GreetingType GreetingType { get { if (mnuSpeak.Checked) return GreetingType.TextGreeting; else return GreetingType.SoundGreeting; } set { if (value == GreetingType.SoundGreeting) { mnuRecord.Checked = true; } else if (value == GreetingType.TextGreeting) { mnuSpeak.Checked = true; } } } [Browsable(false)] public bool CallForRecording { get { return mnuCall.Checked; } } [Browsable(false)] public string CallToNumber { get { return txtCallTo.Text; } set { txtCallTo.Text = value; } } private void btnVoices_Click(object sender, EventArgs e) { System.Diagnostics.Process.Start(Properties.Settings.Default.VoicesURL); } private void mnuGreetingType_CheckedChanged(object sender, EventArgs e) { if (!lockCheck) { lockCheck = true; StopSounds(); ToolStripMenuItem senderItem = (ToolStripMenuItem)sender; foreach (ToolStripMenuItem item in mnuGreetingType.DropDownItems) { if (item != senderItem && item.Checked) item.Checked = false; } if (senderItem.Checked) { mnuGreetingType.Image = senderItem.Image; mnuGreetingType.Text = senderItem.Text; } lockCheck = false; } } private void mnuRecord_CheckedChanged(object sender, EventArgs e) { mnuGreetingType_CheckedChanged(sender, e); if(((ToolStripMenuItem)sender).Checked) wzdGreeting.PageIndex = 0; } private void mnuCall_CheckedChanged(object sender, EventArgs e) { mnuGreetingType_CheckedChanged(sender, e); if (((ToolStripMenuItem)sender).Checked) wzdGreeting.PageIndex = 2; } private void mnuSpeak_CheckedChanged(object sender, EventArgs e) { mnuGreetingType_CheckedChanged(sender, e); if (((ToolStripMenuItem)sender).Checked) wzdGreeting.PageIndex = 1; } private void btnPlaceCall_Click(object sender, EventArgs e) { managementClient.ManagementInterface.PlaceGreetingRecordCall(authInfo, txtCallTo.Text, greetingRow.GreetingID, greetingRow.LanguageID); } } public class GreetingInfo { public bool NewRecording = false; public string GreetingID = ""; public string SoundFilePath = ""; public string SpeechText = ""; public string SpeechVoice = ""; public GreetingType GreetingType; } public class TextChangedEventArgs : System.EventArgs { private string _text; public TextChangedEventArgs( string text ) { Text = text; } public string Text { get { return _text; } private set { _text = value; } } } }
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { /// <summary>Provides access to a file system object, using Shell32.</summary> public static class Shell32 { /// <summary>Provides information for the IQueryAssociations interface methods, used by Shell32.</summary> [Flags] public enum AssociationAttributes { /// <summary>None.</summary> None = 0, /// <summary>Instructs not to map CLSID values to ProgID values.</summary> InitNoRemapClsid = 1, /// <summary>Identifies the value of the supplied file parameter (3rd parameter of function GetFileAssociation()) as an executable file name.</summary> /// <remarks>If this flag is not set, the root key will be set to the ProgID associated with the .exe key instead of the executable file's ProgID.</remarks> InitByExeName = 2, /// <summary>Specifies that when an IQueryAssociation method does not find the requested value under the root key, it should attempt to retrieve the comparable value from the * subkey.</summary> InitDefaultToStar = 4, /// <summary>Specifies that when an IQueryAssociation method does not find the requested value under the root key, it should attempt to retrieve the comparable value from the Folder subkey.</summary> InitDefaultToFolder = 8, /// <summary>Specifies that only HKEY_CLASSES_ROOT should be searched, and that HKEY_CURRENT_USER should be ignored.</summary> NoUserSettings = 16, /// <summary>Specifies that the return string should not be truncated. Instead, return an error value and the required size for the complete string.</summary> NoTruncate = 32, /// <summary> /// Instructs IQueryAssociations methods to verify that data is accurate. /// This setting allows IQueryAssociations methods to read data from the user's hard disk for verification. /// For example, they can check the friendly name in the registry against the one stored in the .exe file. /// </summary> /// <remarks>Setting this flag typically reduces the efficiency of the method.</remarks> Verify = 64, /// <summary> /// Instructs IQueryAssociations methods to ignore Rundll.exe and return information about its target. /// Typically IQueryAssociations methods return information about the first .exe or .dll in a command string. /// If a command uses Rundll.exe, setting this flag tells the method to ignore Rundll.exe and return information about its target. /// </summary> RemapRunDll = 128, /// <summary>Instructs IQueryAssociations methods not to fix errors in the registry, such as the friendly name of a function not matching the one found in the .exe file.</summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FixUps")] NoFixUps = 256, /// <summary>Specifies that the BaseClass value should be ignored.</summary> IgnoreBaseClass = 512, /// <summary>Specifies that the "Unknown" ProgID should be ignored; instead, fail.</summary> /// <remarks>Introduced in Windows 7.</remarks> InitIgnoreUnknown = 1024, /// <summary>Specifies that the supplied ProgID should be mapped using the system defaults, rather than the current user defaults.</summary> /// <remarks>Introduced in Windows 8.</remarks> InitFixedProgId = 2048, /// <summary>Specifies that the value is a protocol, and should be mapped using the current user defaults.</summary> /// <remarks>Introduced in Windows 8.</remarks> IsProtocol = 4096 } //internal enum AssociationData //{ // MsiDescriptor = 1, // NoActivateHandler = 2 , // QueryClassStore = 3, // HasPerUserAssoc = 4, // EditFlags = 5, // Value = 6 //} //internal enum AssociationKey //{ // ShellExecClass = 1, // App = 2, // Class = 3, // BaseClass = 4 //} /// <summary>ASSOCSTR enumeration - Used by the AssocQueryString() function to define the type of string that is to be returned.</summary> public enum AssociationString { /// <summary>None.</summary> None = 0, /// <summary>A command string associated with a Shell verb.</summary> Command = 1, /// <summary> /// An executable from a Shell verb command string. /// For example, this string is found as the (Default) value for a subkey such as HKEY_CLASSES_ROOT\ApplicationName\shell\Open\command. /// If the command uses Rundll.exe, set the <see cref="AssociationAttributes.RemapRunDll"/> flag in the attributes parameter of IQueryAssociations::GetString to retrieve the target executable. /// </summary> Executable = 2, /// <summary>The friendly name of a document type.</summary> FriendlyDocName = 3, /// <summary>The friendly name of an executable file.</summary> FriendlyAppName = 4, /// <summary>Ignore the information associated with the open subkey.</summary> NoOpen = 5, /// <summary>Look under the ShellNew subkey.</summary> ShellNewValue = 6, /// <summary>A template for DDE commands.</summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] DdeCommand = 7, /// <summary>The DDE command to use to create a process.</summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] DdeIfExec = 8, /// <summary>The application name in a DDE broadcast.</summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] DdeApplication = 9, /// <summary>The topic name in a DDE broadcast.</summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] DdeTopic = 10, /// <summary> /// Corresponds to the InfoTip registry value. /// Returns an info tip for an item, or list of properties in the form of an IPropertyDescriptionList from which to create an info tip, such as when hovering the cursor over a file name. /// The list of properties can be parsed with PSGetPropertyDescriptionListFromString. /// </summary> InfoTip = 11, /// <summary> /// Corresponds to the QuickTip registry value. This is the same as <see cref="InfoTip"/>, except that it always returns a list of property names in the form of an IPropertyDescriptionList. /// The difference between this value and <see cref="InfoTip"/> is that this returns properties that are safe for any scenario that causes slow property retrieval, such as offline or slow networks. /// Some of the properties returned from <see cref="InfoTip"/> might not be appropriate for slow property retrieval scenarios. /// The list of properties can be parsed with PSGetPropertyDescriptionListFromString. /// </summary> QuickTip = 12, /// <summary> /// Corresponds to the TileInfo registry value. Contains a list of properties to be displayed for a particular file type in a Windows Explorer window that is in tile view. /// This is the same as <see cref="InfoTip"/>, but, like <see cref="QuickTip"/>, it also returns a list of property names in the form of an IPropertyDescriptionList. /// The list of properties can be parsed with PSGetPropertyDescriptionListFromString. /// </summary> TileInfo = 13, /// <summary> /// Describes a general type of MIME file association, such as image and bmp, /// so that applications can make general assumptions about a specific file type. /// </summary> ContentType = 14, /// <summary> /// Returns the path to the icon resources to use by default for this association. /// Positive numbers indicate an index into the dll's resource table, while negative numbers indicate a resource ID. /// An example of the syntax for the resource is "c:\myfolder\myfile.dll,-1". /// </summary> DefaultIcon = 15, /// <summary> /// For an object that has a Shell extension associated with it, /// you can use this to retrieve the CLSID of that Shell extension object by passing a string representation /// of the IID of the interface you want to retrieve as the pwszExtra parameter of IQueryAssociations::GetString. /// For example, if you want to retrieve a handler that implements the IExtractImage interface, /// you would specify "{BB2E617C-0920-11d1-9A0B-00C04FC2D6C1}", which is the IID of IExtractImage. /// </summary> ShellExtension = 16, /// <summary> /// For a verb invoked through COM and the IDropTarget interface, you can use this flag to retrieve the IDropTarget object's CLSID. /// This CLSID is registered in the DropTarget subkey. /// The verb is specified in the supplied file parameter in the call to IQueryAssociations::GetString. /// </summary> DropTarget = 17, /// <summary> /// For a verb invoked through COM and the IExecuteCommand interface, you can use this flag to retrieve the IExecuteCommand object's CLSID. /// This CLSID is registered in the verb's command subkey as the DelegateExecute entry. /// The verb is specified in the supplied file parameter in the call to IQueryAssociations::GetString. /// </summary> DelegateExecute = 18, /// <summary>(No description available on MSDN)</summary> /// <remarks>Introduced in Windows 8.</remarks> SupportedUriProtocols = 19, /// <summary>The maximum defined <see cref="AssociationString"/> value, used for validation purposes.</summary> Max = 20 } /// <summary>Shell32 FileAttributes structure, used to retrieve the different types of a file system object.</summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Design", "CA1008:EnumsShouldHaveZeroValue")] [Flags] public enum FileAttributes { /// <summary>0x000000000 - Get file system object large icon.</summary> /// <remarks>The <see cref="Icon"/> flag must also be set.</remarks> LargeIcon = 0, /// <summary>0x000000001 - Get file system object small icon.</summary> /// <remarks>The <see cref="Icon"/> flag must also be set.</remarks> SmallIcon = 1, /// <summary>0x000000002 - Get file system object open icon.</summary> /// <remarks>A container object displays an open icon to indicate that the container is open.</remarks> /// <remarks>The <see cref="Icon"/> and/or <see cref="SysIconIndex"/> flag must also be set.</remarks> OpenIcon = 2, /// <summary>0x000000004 - Get file system object Shell-sized icon.</summary> /// <remarks>If this attribute is not specified the function sizes the icon according to the system metric values.</remarks> ShellIconSize = 4, /// <summary>0x000000008 - Get file system object by its PIDL.</summary> /// <remarks>Indicate that the given file contains the address of an ITEMIDLIST structure rather than a path name.</remarks> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Pidl")] Pidl = 8, /// <summary>0x000000010 - Indicates that the given file should not be accessed. Rather, it should act as if the given file exists and use the supplied attributes.</summary> /// <remarks>This flag cannot be combined with the <see cref="Attributes"/>, <see cref="ExeType"/> or <see cref="Pidl"/> attributes.</remarks> UseFileAttributes = 16, /// <summary>0x000000020 - Apply the appropriate overlays to the file's icon.</summary> /// <remarks>The <see cref="Icon"/> flag must also be set.</remarks> AddOverlays = 32, /// <summary>0x000000040 - Returns the index of the overlay icon.</summary> /// <remarks>The value of the overlay index is returned in the upper eight bits of the iIcon member of the structure specified by psfi.</remarks> OverlayIndex = 64, /// <summary>0x000000100 - Retrieve the handle to the icon that represents the file and the index of the icon within the system image list. The handle is copied to the <see cref="FileInfo.IconHandle"/> member of the structure, and the index is copied to the <see cref="FileInfo.IconIndex"/> member.</summary> Icon = 256, /// <summary>0x000000200 - Retrieve the display name for the file. The name is copied to the <see cref="FileInfo.DisplayName"/> member of the structure.</summary> /// <remarks>The returned display name uses the long file name, if there is one, rather than the 8.3 form of the file name.</remarks> DisplayName = 512, /// <summary>0x000000400 - Retrieve the string that describes the file's type.</summary> TypeName = 1024, /// <summary>0x000000800 - Retrieve the item attributes. The attributes are copied to the <see cref="FileInfo.Attributes"/> member of the structure.</summary> /// <remarks>Will touch every file, degrading performance.</remarks> Attributes = 2048, /// <summary>0x000001000 - Retrieve the name of the file that contains the icon representing the file specified by pszPath. The name of the file containing the icon is copied to the <see cref="FileInfo.DisplayName"/> member of the structure. The icon's index is copied to that structure's <see cref="FileInfo.IconIndex"/> member.</summary> IconLocation = 4096, /// <summary>0x000002000 - Retrieve the type of the executable file if pszPath identifies an executable file.</summary> /// <remarks>This flag cannot be specified with any other attributes.</remarks> ExeType = 8192, /// <summary>0x000004000 - Retrieve the index of a system image list icon.</summary> SysIconIndex = 16384, /// <summary>0x000008000 - Add the link overlay to the file's icon.</summary> /// <remarks>The <see cref="Icon"/> flag must also be set.</remarks> LinkOverlay = 32768, /// <summary>0x000010000 - Blend the file's icon with the system highlight color.</summary> Selected = 65536, /// <summary>0x000020000 - Modify <see cref="Attributes"/> to indicate that <see cref="FileInfo.Attributes"/> contains specific attributes that are desired.</summary> /// <remarks>This flag cannot be specified with the <see cref="Icon"/> attribute. Will touch every file, degrading performance.</remarks> AttributesSpecified = 131072 } /// <summary>SHFILEINFO structure, contains information about a file system object.</summary> [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public struct FileInfo { /// <summary>A handle to the icon that represents the file.</summary> /// <remarks>Caller is responsible for destroying this handle with DestroyIcon() when no longer needed.</remarks> [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] public readonly IntPtr IconHandle; /// <summary>The index of the icon image within the system image list.</summary> [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] public int IconIndex; /// <summary>An array of values that indicates the attributes of the file object.</summary> [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [MarshalAs(UnmanagedType.U4)] public readonly GetAttributesOf Attributes; /// <summary>The name of the file as it appears in the Windows Shell, or the path and file name of the file that contains the icon representing the file.</summary> [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = NativeMethods.MaxPath)] public string DisplayName; /// <summary>The type of file.</summary> [SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields")] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] public string TypeName; } /// <summary>SFGAO - Attributes that can be retrieved from a file system object.</summary> [SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags"), SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Sh")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Sh")] [SuppressMessage("Microsoft.Naming", "CA1714:FlagsEnumsShouldHavePluralNames")] [Flags] public enum GetAttributesOf { /// <summary>0x00000000 - None.</summary> None = 0, /// <summary>0x00000001 - The specified items can be copied.</summary> CanCopy = 1, /// <summary>0x00000002 - The specified items can be moved.</summary> CanMove = 2, /// <summary>0x00000004 - Shortcuts can be created for the specified items.</summary> CanLink = 4, /// <summary>0x00000008 - The specified items can be bound to an IStorage object through IShellFolder::BindToObject. For more information about namespace manipulation capabilities, see IStorage.</summary> Storage = 8, /// <summary>0x00000010 - The specified items can be renamed. Note that this value is essentially a suggestion; not all namespace clients allow items to be renamed. However, those that do must have this attribute set.</summary> CanRename = 16, /// <summary>0x00000020 - The specified items can be deleted.</summary> CanDelete = 32, /// <summary>0x00000040 - The specified items have property sheets.</summary> HasPropSheet = 64, /// <summary>0x00000100 - The specified items are drop targets.</summary> DropTarget = 256, /// <summary>0x00001000 - The specified items are system items.</summary> /// <remarks>Windows 7 and later.</remarks> System = 4096, /// <summary>0x00002000 - The specified items are encrypted and might require special presentation.</summary> Encrypted = 8192, /// <summary>0x00004000 - Accessing the item (through IStream or other storage interfaces) is expected to be a slow operation.</summary> IsSlow = 16384, /// <summary>0x00008000 - The specified items are shown as dimmed and unavailable to the user.</summary> Ghosted = 32768, /// <summary>0x00010000 - The specified items are shortcuts.</summary> Link = 65536, /// <summary>0x00020000 - The specified objects are shared.</summary> Share = 131072, /// <summary>0x00040000 - The specified items are read-only. In the case of folders, this means that new items cannot be created in those folders.</summary> ReadOnly = 262144, /// <summary>0x00080000 - The item is hidden and should not be displayed unless the Show hidden files and folders option is enabled in Folder Settings.</summary> Hidden = 524288, /// <summary>0x00100000 - The items are nonenumerated items and should be hidden. They are not returned through an enumerator such as that created by the IShellFolder::EnumObjects method.</summary> NonEnumerated = 1048576, /// <summary>0x00200000 - The items contain new content, as defined by the particular application.</summary> NewContent = 2097152, /// <summary>0x00400000 - Indicates that the item has a stream associated with it.</summary> Stream = 4194304, /// <summary>0x00800000 - Children of this item are accessible through IStream or IStorage.</summary> StorageAncestor = 8388608, /// <summary>0x01000000 - When specified as input, instructs the folder to validate that the items contained in a folder or Shell item array exist.</summary> Validate = 16777216, /// <summary>0x02000000 - The specified items are on removable media or are themselves removable devices.</summary> Removable = 33554432, /// <summary>0x04000000 - The specified items are compressed.</summary> Compressed = 67108864, /// <summary>0x08000000 - The specified items can be hosted inside a web browser or Windows Explorer frame.</summary> Browsable = 134217728, /// <summary>0x10000000 - The specified folders are either file system folders or contain at least one descendant (child, grandchild, or later) that is a file system folder.</summary> FileSysAncestor = 268435456, /// <summary>0x20000000 - The specified items are folders.</summary> Folder = 536870912, /// <summary>0x40000000 - The specified folders or files are part of the file system (that is, they are files, directories, or root directories).</summary> FileSystem = 1073741824, /// <summary>0x80000000 - The specified folders have subfolders.</summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubFolder")] HasSubFolder = unchecked((int)0x80000000) } /// <summary>Used by method UrlIs() to define a URL type.</summary> public enum UrlType { /// <summary>Is the URL valid?</summary> IsUrl = 0, /// <summary>Is the URL opaque?</summary> IsOpaque = 1, /// <summary>Is the URL a URL that is not typically tracked in navigation history?</summary> IsNoHistory = 2, /// <summary>Is the URL a file URL?</summary> IsFileUrl = 3, /// <summary>Attempt to determine a valid scheme for the URL.</summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Appliable")] IsAppliable = 4, /// <summary>Does the URL string end with a directory?</summary> IsDirectory = 5, /// <summary>Does the URL have an appended query string?</summary> IsHasQuery = 6 } #region Methods /// <summary>Destroys an icon and frees any memory the icon occupied.</summary> /// <param name="iconHandle">An <see cref="IntPtr"/> handle to an icon.</param> public static void DestroyIcon(IntPtr iconHandle) { if (IntPtr.Zero != iconHandle) NativeMethods.DestroyIcon(iconHandle); } /// <summary>Gets the file or protocol that is associated with <paramref name="path"/> from the registry.</summary> /// <param name="path">A path to the file.</param> /// <returns>The associated file- or protocol-related string from the registry or <c>string.Empty</c> if no association can be found.</returns> [SecurityCritical] public static string GetFileAssociation(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.Executable); } /// <summary>Gets the content-type that is associated with <paramref name="path"/> from the registry.</summary> /// <param name="path">A path to the file.</param> /// <returns>The associated file- or protocol-related content-type from the registry or <c>string.Empty</c> if no association can be found.</returns> [SecurityCritical] public static string GetFileContentType(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.ContentType); } /// <summary>Gets the default icon that is associated with <paramref name="path"/> from the registry.</summary> /// <param name="path">A path to the file.</param> /// <returns>The associated file- or protocol-related default icon from the registry or <c>string.Empty</c> if no association can be found.</returns> [SecurityCritical] public static string GetFileDefaultIcon(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.DefaultIcon); } /// <summary>Gets the friendly application name that is associated with <paramref name="path"/> from the registry.</summary> /// <param name="path">A path to the file.</param> /// <returns>The associated file- or protocol-related friendly application name from the registry or <c>string.Empty</c> if no association can be found.</returns> [SecurityCritical] public static string GetFileFriendlyAppName(string path) { return GetFileAssociationCore(path, AssociationAttributes.InitByExeName, AssociationString.FriendlyAppName); } /// <summary>Gets the friendly document name that is associated with <paramref name="path"/> from the registry.</summary> /// <param name="path">A path to the file.</param> /// <returns>The associated file- or protocol-related friendly document name from the registry or <c>string.Empty</c> if no association can be found.</returns> [SecurityCritical] public static string GetFileFriendlyDocName(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.FriendlyDocName); } /// <summary>Gets an <see cref="IntPtr"/> handle to the Shell icon that represents the file.</summary> /// <remarks>Caller is responsible for destroying this handle with DestroyIcon() when no longer needed.</remarks> /// <param name="filePath"> /// The path to the file system object which should not exceed maximum path length. Both absolute and /// relative paths are valid. /// </param> /// <param name="iconAttributes"> /// Icon size <see cref="Shell32.FileAttributes.SmallIcon"/> or <see cref="Shell32.FileAttributes.LargeIcon"/>. Can also be combined /// with <see cref="Shell32.FileAttributes.AddOverlays"/> and others. /// </param> /// <returns>An <see cref="IntPtr"/> handle to the Shell icon that represents the file, or IntPtr.Zero on failure.</returns> [SecurityCritical] public static IntPtr GetFileIcon(string filePath, FileAttributes iconAttributes) { if (Utils.IsNullOrWhiteSpace(filePath)) return IntPtr.Zero; var fileInfo = GetFileInfoCore(filePath, System.IO.FileAttributes.Normal, FileAttributes.Icon | iconAttributes, true, true); return fileInfo.IconHandle == IntPtr.Zero ? IntPtr.Zero : fileInfo.IconHandle; } /// <summary>Retrieves information about an object in the file system, such as a file, folder, directory, or drive root.</summary> /// <returns>A <see cref="FileInfo"/> struct instance.</returns> /// <remarks> /// <para>You should call this function from a background thread.</para> /// <para>Failure to do so could cause the UI to stop responding.</para> /// <para>Unicode path are supported.</para> /// </remarks> /// <param name="filePath">The path to the file system object which should not exceed the maximum path length. Both absolute and relative paths are valid.</param> /// <param name="attributes">A <see cref="System.IO.FileAttributes"/> attribute.</param> /// <param name="fileAttributes">One ore more <see cref="FileAttributes"/> attributes.</param> /// <param name="continueOnException"> /// <para><c>true</c> suppress any Exception that might be thrown as a result from a failure,</para> /// <para>such as ACLs protected directories or non-accessible reparse points.</para> /// </param> [SecurityCritical] public static FileInfo GetFileInfo(string filePath, System.IO.FileAttributes attributes, FileAttributes fileAttributes, bool continueOnException) { return GetFileInfoCore(filePath, attributes, fileAttributes, true, continueOnException); } /// <summary>Retrieves an instance of <see cref="Shell32Info"/> containing information about the specified file.</summary> /// <param name="path">A path to the file.</param> /// <returns>A <see cref="Shell32Info"/> class instance.</returns> [SecurityCritical] public static Shell32Info GetShell32Info(string path) { return new Shell32Info(path); } /// <summary>Retrieves an instance of <see cref="Shell32Info"/> containing information about the specified file.</summary> /// <param name="path">A path to the file.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> /// <returns>A <see cref="Shell32Info"/> class instance.</returns> [SecurityCritical] public static Shell32Info GetShell32Info(string path, PathFormat pathFormat) { return new Shell32Info(path, pathFormat); } /// <summary>Gets the "Open With" command that is associated with <paramref name="path"/> from the registry.</summary> /// <param name="path">A path to the file.</param> /// <returns>The associated file- or protocol-related "Open With" command from the registry or <c>string.Empty</c> if no association can be found.</returns> [SecurityCritical] public static string GetFileOpenWithAppName(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.FriendlyAppName); } /// <summary>Gets the Shell command that is associated with <paramref name="path"/> from the registry.</summary> /// <param name="path">A path to the file.</param> /// <returns>The associated file- or protocol-related Shell command from the registry or <c>string.Empty</c> if no association can be found.</returns> [SecurityCritical] public static string GetFileVerbCommand(string path) { return GetFileAssociationCore(path, AssociationAttributes.Verify, AssociationString.Command); } /// <summary>Converts a file URL to a Microsoft MS-DOS path.</summary> /// <param name="urlPath">The file URL.</param> /// <returns> /// <para>The Microsoft MS-DOS path. If no path can be created, <c>string.Empty</c> is returned.</para> /// <para>If <paramref name="urlPath"/> is <c>null</c>, <c>null</c> will also be returned.</para> /// </returns> [SecurityCritical] internal static string PathCreateFromUrl(string urlPath) { if (urlPath == null) return null; var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); var bufferSize = (uint)buffer.Capacity; var lastError = NativeMethods.PathCreateFromUrl(urlPath, buffer, ref bufferSize, 0); // Don't throw exception, but return string.Empty; return lastError == Win32Errors.S_OK ? buffer.ToString() : string.Empty; } /// <summary>Creates a path from a file URL.</summary> /// <returns> /// <para>The file path. If no path can be created, <c>string.Empty</c> is returned.</para> /// <para>If <paramref name="urlPath"/> is <c>null</c>, <c>null</c> will also be returned.</para> /// </returns> /// <exception cref="PlatformNotSupportedException">The operating system is older than Windows Vista.</exception> /// <param name="urlPath">The URL.</param> [SecurityCritical] internal static string PathCreateFromUrlAlloc(string urlPath) { if (!NativeMethods.IsAtLeastWindowsVista) throw new PlatformNotSupportedException(new Win32Exception((int)Win32Errors.ERROR_OLD_WIN_VERSION).Message); if (urlPath == null) return null; StringBuilder buffer; var lastError = NativeMethods.PathCreateFromUrlAlloc(urlPath, out buffer, 0); // Don't throw exception, but return string.Empty; return lastError == Win32Errors.S_OK ? buffer.ToString() : string.Empty; } /// <summary>Determines whether a path to a file system object such as a file or folder is valid.</summary> /// <param name="path">The full path of maximum length the maximum path length to the object to verify.</param> /// <returns><c>true</c> if the file exists; <c>false</c> otherwise</returns> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "lastError")] [SecurityCritical] public static bool PathFileExists(string path) { // PathFileExists() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. return !Utils.IsNullOrWhiteSpace(path) && NativeMethods.PathFileExists(Path.GetFullPathCore(null, false, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck | GetFullPathOptions.ContinueOnNonExist)); } /// <summary>Tests whether a URL is a specified type.</summary> /// <param name="url">The URL.</param> /// <param name="urlType"></param> /// <returns> /// For all but one of the URL types, UrlIs returns <c>true</c> if the URL is the specified type, or <c>false</c> otherwise. /// If UrlIs is set to <see cref="UrlType.IsAppliable"/>, UrlIs will attempt to determine the URL scheme. /// If the function is able to determine a scheme, it returns <c>true</c>, or <c>false</c> otherwise. /// </returns> [SecurityCritical] internal static bool UrlIs(string url, UrlType urlType) { return NativeMethods.UrlIs(url, urlType); } /// <summary>Converts a Microsoft MS-DOS path to a canonicalized URL.</summary> /// <param name="path">The full MS-DOS path of maximum length <see cref="NativeMethods.MaxPath"/>.</param> /// <returns> /// <para>The URL. If no URL can be created <c>string.Empty</c> is returned.</para> /// <para>If <paramref name="path"/> is <c>null</c>, <c>null</c> will also be returned.</para> /// </returns> [SecurityCritical] internal static string UrlCreateFromPath(string path) { if (path == null) return null; // UrlCreateFromPath does not support extended paths. var pathRp = Path.GetRegularPathCore(path, GetFullPathOptions.CheckInvalidPathChars, false); var buffer = new StringBuilder(NativeMethods.MaxPathUnicode); var bufferSize = (uint)buffer.Capacity; var lastError = NativeMethods.UrlCreateFromPath(pathRp, buffer, ref bufferSize, 0); // Don't throw exception, but return null; var url = buffer.ToString(); if (Utils.IsNullOrWhiteSpace(url)) url = string.Empty; return lastError == Win32Errors.S_OK ? url : string.Empty; } /// <summary>Tests a URL to determine if it is a file URL.</summary> /// <param name="url">The URL.</param> /// <returns><c>true</c> if the URL is a file URL, or <c>false</c> otherwise.</returns> [SecurityCritical] internal static bool UrlIsFileUrl(string url) { return NativeMethods.UrlIs(url, UrlType.IsFileUrl); } /// <summary>Returns whether a URL is a URL that browsers typically do not include in navigation history.</summary> /// <param name="url">The URL.</param> /// <returns><c>true</c> if the URL is a URL that is not included in navigation history, or <c>false</c> otherwise.</returns> [SecurityCritical] internal static bool UrlIsNoHistory(string url) { return NativeMethods.UrlIs(url, UrlType.IsNoHistory); } /// <summary>Returns whether a URL is opaque.</summary> /// <param name="url">The URL.</param> /// <returns><c>true</c> if the URL is opaque, or <c>false</c> otherwise.</returns> [SecurityCritical] internal static bool UrlIsOpaque(string url) { return NativeMethods.UrlIs(url, UrlType.IsOpaque); } #region Internal Methods /// <summary>Searches for and retrieves a file or protocol association-related string from the registry.</summary> /// <param name="path">A path to a file.</param> /// <param name="attributes">One or more <see cref="AssociationAttributes"/> attributes. Only one "InitXXX" attribute can be used.</param> /// <param name="associationType">A <see cref="AssociationString"/> attribute.</param> /// <returns>The associated file- or protocol-related string from the registry or <c>string.Empty</c> if no association can be found.</returns> /// <exception cref="ArgumentNullException"/> [SecurityCritical] private static string GetFileAssociationCore(string path, AssociationAttributes attributes, AssociationString associationType) { if (Utils.IsNullOrWhiteSpace(path)) throw new ArgumentNullException("path"); attributes = attributes | AssociationAttributes.NoTruncate | AssociationAttributes.RemapRunDll; uint bufferSize = NativeMethods.MaxPath; StringBuilder buffer; uint retVal; do { buffer = new StringBuilder((int)bufferSize); // AssocQueryString() // 2014-02-05: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2015-07-17: This function does not support long paths. retVal = NativeMethods.AssocQueryString(attributes, associationType, path, null, buffer, out bufferSize); // No Exception is thrown, just return empty string on error. //switch (retVal) //{ // // 0x80070483: No application is associated with the specified file for this operation. // case 2147943555: // case Win32Errors.E_POINTER: // case Win32Errors.S_OK: // break; // default: // NativeError.ThrowException(retVal); // break; //} } while (retVal == Win32Errors.E_POINTER); return buffer.ToString(); } /// <summary>Retrieve information about an object in the file system, such as a file, folder, directory, or drive root.</summary> /// <returns>A <see cref="FileInfo"/> struct instance.</returns> /// <remarks> /// <para>You should call this function from a background thread.</para> /// <para>Failure to do so could cause the UI to stop responding.</para> /// <para>Unicode path are not supported.</para> /// </remarks> /// <param name="path">The path to the file system object which should not exceed the maximum path length in length. Both absolute and relative paths are valid.</param> /// <param name="attributes">A <see cref="System.IO.FileAttributes"/> attribute.</param> /// <param name="fileAttributes">A <see cref="FileAttributes"/> attribute.</param> /// <param name="checkInvalidPathChars">Checks that the path contains only valid path-characters.</param> /// <param name="continueOnException"> /// <para><c>true</c> suppress any Exception that might be thrown as a result from a failure,</para> /// <para>such as ACLs protected directories or non-accessible reparse points.</para> /// </param> [SecurityCritical] internal static FileInfo GetFileInfoCore(string path, System.IO.FileAttributes attributes, FileAttributes fileAttributes, bool checkInvalidPathChars, bool continueOnException) { // Prevent possible crash. var fileInfo = new FileInfo { DisplayName = string.Empty, TypeName = string.Empty, IconIndex = 0 }; if (!Utils.IsNullOrWhiteSpace(path)) { // ShGetFileInfo() // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists. // 2015-07-17: This function does not support long paths. var shGetFileInfo = NativeMethods.ShGetFileInfo(Path.GetRegularPathCore(path, checkInvalidPathChars ? GetFullPathOptions.CheckInvalidPathChars : 0, false), attributes, out fileInfo, (uint)Marshal.SizeOf(fileInfo), fileAttributes); if (shGetFileInfo == IntPtr.Zero && !continueOnException) NativeError.ThrowException(Marshal.GetLastWin32Error(), path); } return fileInfo; } #endregion // Internal Methods #endregion // Methods } }
// // 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; namespace Microsoft.Azure.Management.Resources { public static partial class DeploymentOperationsExtensions { /// <summary> /// Begin deleting deployment.To determine whether the operation has /// finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment to be deleted. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginDeleting(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).BeginDeletingAsync(resourceGroupName, deploymentName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Begin deleting deployment.To determine whether the operation has /// finished processing the request, call /// GetLongRunningOperationStatus. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment to be deleted. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginDeletingAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return operations.BeginDeletingAsync(resourceGroupName, deploymentName, CancellationToken.None); } /// <summary> /// Cancel a currently running template deployment. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Cancel(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).CancelAsync(resourceGroupName, deploymentName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Cancel a currently running template deployment. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CancelAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return operations.CancelAsync(resourceGroupName, deploymentName, CancellationToken.None); } /// <summary> /// Checks whether deployment exists. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group to check. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <returns> /// Deployment information. /// </returns> public static DeploymentExistsResult CheckExistence(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).CheckExistenceAsync(resourceGroupName, deploymentName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks whether deployment exists. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group to check. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <returns> /// Deployment information. /// </returns> public static Task<DeploymentExistsResult> CheckExistenceAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return operations.CheckExistenceAsync(resourceGroupName, deploymentName, CancellationToken.None); } /// <summary> /// Create a named template deployment using a template. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='parameters'> /// Required. Additional parameters supplied to the operation. /// </param> /// <returns> /// Template deployment operation create result. /// </returns> public static DeploymentOperationsCreateResult CreateOrUpdate(this IDeploymentOperations operations, string resourceGroupName, string deploymentName, Deployment parameters) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).CreateOrUpdateAsync(resourceGroupName, deploymentName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a named template deployment using a template. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='parameters'> /// Required. Additional parameters supplied to the operation. /// </param> /// <returns> /// Template deployment operation create result. /// </returns> public static Task<DeploymentOperationsCreateResult> CreateOrUpdateAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName, Deployment parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, deploymentName, parameters, CancellationToken.None); } /// <summary> /// Delete deployment and all of its resources. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment to be deleted. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).DeleteAsync(resourceGroupName, deploymentName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete deployment and all of its resources. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment to be deleted. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return operations.DeleteAsync(resourceGroupName, deploymentName, CancellationToken.None); } /// <summary> /// Get a deployment. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group to get. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <returns> /// Template deployment information. /// </returns> public static DeploymentGetResult Get(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).GetAsync(resourceGroupName, deploymentName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a deployment. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group to get. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <returns> /// Template deployment information. /// </returns> public static Task<DeploymentGetResult> GetAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName) { return operations.GetAsync(resourceGroupName, deploymentName, CancellationToken.None); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group to filter by. The name is /// case insensitive. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all /// deployments. /// </param> /// <returns> /// List of deployments. /// </returns> public static DeploymentListResult List(this IDeploymentOperations operations, string resourceGroupName, DeploymentListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).ListAsync(resourceGroupName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group to filter by. The name is /// case insensitive. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all /// deployments. /// </param> /// <returns> /// List of deployments. /// </returns> public static Task<DeploymentListResult> ListAsync(this IDeploymentOperations operations, string resourceGroupName, DeploymentListParameters parameters) { return operations.ListAsync(resourceGroupName, parameters, CancellationToken.None); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of deployments. /// </returns> public static DeploymentListResult ListNext(this IDeploymentOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of deployments. /// </returns> public static Task<DeploymentListResult> ListNextAsync(this IDeploymentOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Validate a deployment template. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='parameters'> /// Required. Deployment to validate. /// </param> /// <returns> /// Information from validate template deployment response. /// </returns> public static DeploymentValidateResponse Validate(this IDeploymentOperations operations, string resourceGroupName, string deploymentName, Deployment parameters) { return Task.Factory.StartNew((object s) => { return ((IDeploymentOperations)s).ValidateAsync(resourceGroupName, deploymentName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Validate a deployment template. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IDeploymentOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment. /// </param> /// <param name='parameters'> /// Required. Deployment to validate. /// </param> /// <returns> /// Information from validate template deployment response. /// </returns> public static Task<DeploymentValidateResponse> ValidateAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName, Deployment parameters) { return operations.ValidateAsync(resourceGroupName, deploymentName, parameters, CancellationToken.None); } } }
// 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void DivideScalarSingle() { var test = new SimpleBinaryOpTest__DivideScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__DivideScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__DivideScalarSingle testClass) { var result = Sse.DivideScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__DivideScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.DivideScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__DivideScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__DivideScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.DivideScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.DivideScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.DivideScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.DivideScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.DivideScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.DivideScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.DivideScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.DivideScalar( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.DivideScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.DivideScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.DivideScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__DivideScalarSingle(); var result = Sse.DivideScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__DivideScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.DivideScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.DivideScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.DivideScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.DivideScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.DivideScalar( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(left[0] / right[0]) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.DivideScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }