context
stringlengths
2.52k
185k
gt
stringclasses
1 value
//----------------------------------------------------------------------------- // <copyright file="DropboxApiTests.cs" company="Dropbox Inc"> // Copyright (c) Dropbox Inc. All rights reserved. // </copyright> //----------------------------------------------------------------------------- namespace Dropbox.Api.Tests { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Dropbox.Api.Auth; using Dropbox.Api.Common; using Dropbox.Api.Files; using Dropbox.Api.Users; using Microsoft.Extensions.Configuration; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// The test class for Dropbox API. /// </summary> [TestClass] public class DropboxApiTests { private static readonly string TestingPath = "/Testing/Dropbox.Api.Tests"; /// <summary> /// The user access token. /// </summary> private static string userAccessToken; /// <summary> /// The user refresh token. /// </summary> private static string userRefreshToken; /// <summary> /// The app key. /// </summary> private static string appKey; /// <summary> /// The app secret. /// </summary> private static string appSecret; /// <summary> /// The Dropbox client. /// </summary> private static DropboxClient client; /// <summary> /// The Dropbox team client. /// </summary> private static DropboxTeamClient teamClient; /// <summary> /// The Dropbox app client. /// </summary> private static DropboxAppClient appClient; /// <summary> /// Set up Dropbox clients. /// </summary> /// <param name="context">The VSTest context.</param> [ClassInitialize] public static void ClassInitialize(TestContext context) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json", optional: true) .AddEnvironmentVariables(prefix: "DROPBOX_INTEGRATION_") .Build(); appKey = config["appKey"]; appSecret = config["appSecret"]; userRefreshToken = config["userRefreshToken"]; userAccessToken = config["userAccessToken"]; client = new DropboxClient(userAccessToken); var teamToken = config["teamAccessToken"]; teamClient = new DropboxTeamClient(teamToken); appClient = new DropboxAppClient(appKey, appSecret); } /// <summary> /// Ensure that the rest folder exissts and is empty before test execution. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> [TestInitialize] public async Task Initialize() { try { var result = await client.Files.ListFolderAsync(TestingPath); Assert.AreEqual(0, result.Entries.Count); } catch (ApiException<ListFolderError>) { // create folder if it doesn't exist var result = client.Files.CreateFolderV2Async(TestingPath).Result; Assert.AreEqual(TestingPath, result.Metadata.PathDisplay); } } /// <summary> /// Cleans up created files after test execution. /// </summary> [TestCleanup] public void Cleanup() { var result = client.Files.ListFolderAsync(TestingPath).Result; foreach (var entry in result.Entries) { client.Files.DeleteV2Async(entry.PathLower).Wait(); } } /// <summary> /// Tests creating a client with only refresh token and /// ensuring the client refreshed the token before making a call. /// </summary> /// <returns>The <see cref="Task" />.</returns> [TestMethod] public async Task TestRefreshClient() { var client = new DropboxClient(userRefreshToken, appKey, appSecret); var result = await client.Users.GetCurrentAccountAsync(); Assert.IsNotNull(result.Email); } /// <summary> /// Test get metadata. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestGetMetadata() { await client.Files.UploadAsync(TestingPath + "/Foo.txt", body: GetStream("abc")); var metadata = await client.Files.GetMetadataAsync(TestingPath + "/Foo.txt"); Assert.AreEqual("Foo.txt", metadata.Name); Assert.AreEqual(TestingPath.ToLower() + "/foo.txt", metadata.PathLower); Assert.AreEqual(TestingPath + "/Foo.txt", metadata.PathDisplay); Assert.IsTrue(metadata.IsFile); var file = metadata.AsFile; Assert.AreEqual(3, (int)file.Size); } /// <summary> /// Test get metadata. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestListFolder() { var files = new HashSet<string> { "a.txt", "b.txt", "c.txt" }; foreach (var file in files) { await client.Files.UploadAsync(TestingPath + "/" + file, body: GetStream("abc")); } var response = await client.Files.ListFolderAsync(TestingPath); Assert.AreEqual(files.Count, response.Entries.Count); foreach (var entry in response.Entries) { Assert.IsTrue(files.Contains(entry.Name)); Assert.IsTrue(entry.IsFile); var file = entry.AsFile; Assert.AreEqual(3, (int)file.Size); } } /// <summary> /// Test upload. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestUpload() { var response = await client.Files.UploadAsync(TestingPath + "/Foo.txt", body: GetStream("abc")); Assert.AreEqual(response.Name, "Foo.txt"); Assert.AreEqual(response.PathLower, TestingPath.ToLower() + "/foo.txt"); Assert.AreEqual(response.PathDisplay, TestingPath + "/Foo.txt"); var downloadResponse = await client.Files.DownloadAsync(TestingPath + "/Foo.txt"); var content = await downloadResponse.GetContentAsStringAsync(); Assert.AreEqual("abc", content); } /// <summary> /// Test upload with retry. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestUploadRetry() { var count = 0; var mockHandler = new MockHttpMessageHandler((r, s) => { if (count++ < 2) { var error = new HttpResponseMessage(HttpStatusCode.InternalServerError) { Content = new StringContent("Error"), }; return Task.FromResult(error); } return s(r); }); var mockClient = new HttpClient(mockHandler); var client = new DropboxClient( userAccessToken, new DropboxClientConfig { HttpClient = mockClient, MaxRetriesOnError = 10 }); var response = await client.Files.UploadAsync(TestingPath + "/Foo.txt", body: GetStream("abc")); var downloadResponse = await DropboxApiTests.client.Files.DownloadAsync(TestingPath + "/Foo.txt"); var content = await downloadResponse.GetContentAsStringAsync(); Assert.AreEqual("abc", content); } /// <summary> /// Test upload. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestDownload() { await client.Files.UploadAsync(TestingPath + "/Foo.txt", body: GetStream("abc")); var downloadResponse = await client.Files.DownloadAsync(TestingPath + "/Foo.txt"); var content = await downloadResponse.GetContentAsStringAsync(); Assert.AreEqual("abc", content); var response = downloadResponse.Response; Assert.AreEqual(response.Name, "Foo.txt"); Assert.AreEqual(response.PathLower, TestingPath.ToLower() + "/foo.txt"); Assert.AreEqual(response.PathDisplay, TestingPath + "/Foo.txt"); } /// <summary> /// Test rate limit error handling. /// </summary> /// <returns>A <see cref="Task"/> representing the result of the asynchronous operation.</returns> [TestMethod] public async Task TestRateLimit() { var body = "{\"error_summary\": \"too_many_requests/..\", \"error\": {\"reason\": {\".tag\": \"too_many_requests\"}, \"retry_after\": 100}}"; var mockResponse = new HttpResponseMessage((HttpStatusCode)429) { Content = new StringContent(body, Encoding.UTF8, "application/json"), }; mockResponse.Headers.Add("X-Dropbox-Request-Id", "123"); var mockHandler = new MockHttpMessageHandler((r, s) => Task.FromResult(mockResponse)); var mockClient = new HttpClient(mockHandler); var client = new DropboxClient("dummy", new DropboxClientConfig { HttpClient = mockClient }); try { await client.Files.GetMetadataAsync(TestingPath + "/a.txt"); } catch (RateLimitException ex) { Assert.AreEqual((int)ex.ErrorResponse.RetryAfter, 100); Assert.AreEqual(ex.RetryAfter, 100); Assert.IsTrue(ex.ErrorResponse.Reason.IsTooManyRequests); } } /// <summary> /// Test request id handling. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestRequestId() { var funcs = new List<Func<Task>> { () => client.Files.GetMetadataAsync("/noob"), // 409 () => client.Files.GetMetadataAsync("/"), // 400 }; foreach (var func in funcs) { try { await func(); } catch (DropboxException ex) { Assert.IsTrue(ex.ToString().Contains("Request Id")); } } } /// <summary> /// Test team auth. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestTeamAuth() { var result = await teamClient.Team.GetInfoAsync(); Assert.IsNotNull(result.TeamId); Assert.IsNotNull(result.Name); } /// <summary> /// Test team auth select user. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestTeamAuthSelectUser() { var result = await teamClient.Team.MembersListAsync(); var memberId = result.Members[0].Profile.TeamMemberId; var userClient = teamClient.AsMember(memberId); var account = await userClient.Users.GetCurrentAccountAsync(); Assert.AreEqual(account.TeamMemberId, memberId); } /// <summary> /// Test team auth select admin. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestTeamAuthSelectAdmin() { var result = await teamClient.Team.MembersListAsync(); var adminId = result.Members.Where(m => m.Role.IsTeamAdmin).First().Profile.TeamMemberId; var userClient = teamClient.AsAdmin(adminId); var account = await userClient.Users.GetCurrentAccountAsync(); Assert.AreEqual(account.TeamMemberId, adminId); // TODO: Add permission specific tests. } /// <summary> /// Test team auth select admin. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestPathRoot() { await client.Files.UploadAsync(TestingPath + "/Foo.txt", body: GetStream("abc")); var pathRootClient = client.WithPathRoot(PathRoot.Home.Instance); var metadata = await pathRootClient.Files.GetMetadataAsync(TestingPath + "/Foo.txt"); Assert.AreEqual(TestingPath.ToLower() + "/foo.txt", metadata.PathLower); pathRootClient = client.WithPathRoot(new PathRoot.Root("123")); var exceptionRaised = false; try { await pathRootClient.Files.GetMetadataAsync(TestingPath + "/Foo.txt"); } catch (PathRootException e) { exceptionRaised = true; var error = e.ErrorResponse; Assert.IsTrue(error.IsInvalidRoot); } Assert.IsTrue(exceptionRaised); } /// <summary> /// Test app auth. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestAppAuth() { try { var result = await appClient.Auth.TokenFromOauth1Async("foo", "bar"); } catch (ApiException<TokenFromOAuth1Error>) { } } /// <summary> /// Test no auth. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestNoAuth() { var result = await client.Files.ListFolderAsync(string.Empty, recursive: true); var cursor = result.Cursor; var task = client.Files.ListFolderLongpollAsync(cursor); await client.Files.UploadAsync(TestingPath + "/foo.txt", body: GetStream("abc")); var response = await task; Assert.IsTrue(response.Changes); } /// <summary> /// Test APM flow. /// </summary> [TestMethod] public void TaskAPM() { var result = client.Users.BeginGetCurrentAccount(null); var account = client.Users.EndGetCurrentAccount(result); var accountId = account.AccountId; result = client.Users.BeginGetAccountBatch(new string[] { accountId }, null); var accounts = client.Users.EndGetAccountBatch(result); Assert.AreEqual(accounts.Count, 1); Assert.AreEqual(accounts[0].AccountId, accountId); } /// <summary> /// Test User-Agent header is set with default values. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestUserAgentDefault() { HttpRequestMessage lastRequest = null; var mockHandler = new MockHttpMessageHandler((r, s) => { lastRequest = r; return s(r); }); var mockClient = new HttpClient(mockHandler); var client = new DropboxClient(userAccessToken, new DropboxClientConfig { HttpClient = mockClient }); await client.Users.GetCurrentAccountAsync(); Assert.IsTrue(lastRequest.Headers.UserAgent.ToString().Contains("OfficialDropboxDotNetSDKv2")); } /// <summary> /// Test User-Agent header is populated with user supplied value in DropboxClientConfig. /// </summary> /// <returns>The <see cref="Task"/>.</returns> [TestMethod] public async Task TestUserAgentUserSupplied() { HttpRequestMessage lastRequest = null; var mockHandler = new MockHttpMessageHandler((r, s) => { lastRequest = r; return s(r); }); var mockClient = new HttpClient(mockHandler); var userAgent = "UserAgentTest"; var client = new DropboxClient(userAccessToken, new DropboxClientConfig { HttpClient = mockClient, UserAgent = userAgent }); await client.Users.GetCurrentAccountAsync(); Assert.IsTrue(lastRequest.Headers.UserAgent.ToString().Contains(userAgent)); } /// <summary> /// Test cancel request of Dispose DropboxClient. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [TestMethod] public async Task TestDropboxClientDispose() { var canceled = false; Task<FullAccount> task; using (var client = new DropboxClient(userAccessToken)) { task = client.Users.GetCurrentAccountAsync(); } try { await task; } catch (TaskCanceledException) { canceled = true; } Assert.IsTrue(canceled); } /// <summary> /// Test upload with a date-time format file name. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [TestMethod] public async Task TestUploadWithDateName() { var fileNameWithDateFormat = DateTime.Now.ToString("s"); var response = await client.Files.UploadAsync($"{TestingPath}/{fileNameWithDateFormat}", body: GetStream("abc")); Assert.AreEqual(response.Name, fileNameWithDateFormat); Assert.AreEqual(response.PathLower, $"{TestingPath.ToLower()}/{fileNameWithDateFormat.ToLowerInvariant()}"); Assert.AreEqual(response.PathDisplay, $"{TestingPath}/{fileNameWithDateFormat}"); var downloadResponse = await client.Files.DownloadAsync($"{TestingPath}/{fileNameWithDateFormat}"); var content = await downloadResponse.GetContentAsStringAsync(); Assert.AreEqual("abc", content); } /// <summary> /// Test folder creation with a date-time format folder name. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns> [TestMethod] public async Task TestCreateFolderWithDateFormat() { var folderNameWithDateFormat = DateTime.Now.ToString("s"); var response = await client.Files.CreateFolderAsync($"{TestingPath}/{folderNameWithDateFormat}"); Assert.AreEqual(response.Name, folderNameWithDateFormat); Assert.AreEqual(response.PathLower, $"{TestingPath.ToLower()}/{folderNameWithDateFormat.ToLowerInvariant()}"); Assert.AreEqual(response.PathDisplay, $"{TestingPath}/{folderNameWithDateFormat}"); var folders = await client.Files.ListFolderAsync($"/{TestingPath}"); Assert.IsTrue(folders.Entries.Any(f => f.Name == folderNameWithDateFormat)); } /// <summary> /// Converts string to a memory stream. /// </summary> /// <param name="content">The string content.</param> /// <returns>The memory stream.</returns> private static MemoryStream GetStream(string content) { var buffer = Encoding.UTF8.GetBytes(content); return new MemoryStream(buffer); } } }
// <copyright file="IPlayGamesClient.cs" company="Google Inc."> // Copyright (C) 2014 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. // </copyright> // Modified by Jan Ivar Z. Carlsen. // Added OnAuthenticatedProxy event #if UNITY_ANDROID namespace GooglePlayGames.BasicApi { using System; using UnityEngine.SocialPlatforms; /// <summary> /// Defines an abstract interface for a Play Games Client. /// </summary> /// <remarks>Concrete implementations /// might be, for example, the client for Android or for iOS. One fundamental concept /// that implementors of this class must adhere to is stable authentication state. /// This means that once Authenticate() returns true through its callback, the user is /// considered to be forever after authenticated while the app is running. The implementation /// must make sure that this is the case -- for example, it must try to silently /// re-authenticate the user if authentication is lost or wait for the authentication /// process to get fixed if it is temporarily in a bad state (such as when the /// Activity in Android has just been brought to the foreground and the connection to /// the Games services hasn't yet been established). To the user of this /// interface, once the user is authenticated, they're forever authenticated. /// Unless, of course, there is an unusual permanent failure such as the underlying /// service dying, in which it's acceptable that API method calls will fail. /// /// <para>All methods can be called from the game thread. The user of this interface /// DOES NOT NEED to call them from the UI thread of the game. Transferring to the UI /// thread when necessary is a responsibility of the implementors of this interface.</para> /// /// <para>CALLBACKS: all callbacks must be invoked in Unity's main thread. /// Implementors of this interface must guarantee that (suggestion: use /// <see cref="PlayGamesHelperObject.RunOnGameThread(System.Action)"/>).</para> /// </remarks> public interface IPlayGamesClient { event Action OnAuthenticatedProxy; /// <summary> /// Starts the authentication process. /// </summary> /// <remarks>If silent == true, no UIs will be shown /// (if UIs are needed, it will fail rather than show them). If silent == false, /// this may show UIs, consent dialogs, etc. /// At the end of the process, callback will be invoked to notify of the result. /// Once the callback returns true, the user is considered to be authenticated /// forever after. /// </remarks> /// <param name="silent">If set to <c>true</c> silent.</param> /// <param name="callback">Callback</param> void Authenticate(bool silent, Action<SignInStatus> callback); /// <summary> /// Returns whether or not user is authenticated. /// </summary> /// <returns><c>true</c> if the user is authenticated; otherwise, <c>false</c>.</returns> bool IsAuthenticated(); /// <summary> /// Signs the user out. /// </summary> void SignOut(); /// <summary> /// Returns the authenticated user's ID. Note that this value may change if a user signs /// on and signs in with a different account. /// </summary> /// <returns>The user's ID, <code>null</code> if the user is not logged in.</returns> string GetUserId(); /// <summary> /// Loads friends of the authenticated user. This loads the entire list of friends. /// </summary> /// <param name="callback">Callback invoked when complete. bool argument /// indicates success.</param> void LoadFriends(Action<bool> callback); /// <summary> /// Returns a human readable name for the user, if they are logged in. /// </summary> /// <returns>The user's human-readable name. <code>null</code> if they are not logged /// in</returns> string GetUserDisplayName(); /// <summary> /// Returns an id token, which can be verified server side, if they are logged in. /// </summary> string GetIdToken(); /// <summary> /// The server auth code for this client. /// </summary> /// <remarks> /// Note: This function is currently only implemented for Android. /// </remarks> string GetServerAuthCode(); /// <summary> /// Gets another server auth code. /// </summary> /// <remarks>This method should be called after authenticating, and exchanging /// the initial server auth code for a token. This is implemented by signing in /// silently, which if successful returns almost immediately and with a new /// server auth code. /// </remarks> /// <param name="reAuthenticateIfNeeded">Calls Authenticate if needed when /// retrieving another auth code. </param> /// <param name="callback">Callback returning the auth code, or null if there /// was a problem. NOTE: This callback can be called immediately.</param> void GetAnotherServerAuthCode(bool reAuthenticateIfNeeded, Action<string> callback); /// <summary> /// Gets the user's email. /// </summary> /// <remarks>The email address returned is selected by the user from the accounts present /// on the device. There is no guarantee this uniquely identifies the player. /// For unique identification use the id property of the local player. /// The user can also choose to not select any email address, meaning it is not /// available. /// </remarks> /// <returns>The user email or null if not authenticated or the permission is /// not available.</returns> string GetUserEmail(); /// <summary> /// Returns the user's avatar url, if they are logged in and have an avatar. /// </summary> /// <returns>The URL to load the avatar image. <code>null</code> if they are not logged /// in</returns> string GetUserImageUrl(); /// <summary>Gets the player stats.</summary> /// <param name="callback">Callback for response.</param> void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback); /// <summary> /// Loads the users specified. This is mainly used by the leaderboard /// APIs to get the information of a high scorer. /// </summary> /// <param name="userIds">User identifiers.</param> /// <param name="callback">Callback.</param> void LoadUsers(string[] userIds, Action<IUserProfile[]> callback); /// <summary> /// Loads the achievements for the current signed in user and invokes /// the callback. /// </summary> void LoadAchievements(Action<Achievement[]> callback); /// <summary> /// Unlocks the achievement with the passed identifier. /// </summary> /// <remarks>If the operation succeeds, the callback /// will be invoked on the game thread with <code>true</code>. If the operation fails, the /// callback will be invoked with <code>false</code>. This operation will immediately fail if /// the user is not authenticated (i.e. the callback will immediately be invoked with /// <code>false</code>). If the achievement is already unlocked, this call will /// succeed immediately. /// </remarks> /// <param name="achievementId">The ID of the achievement to unlock.</param> /// <param name="successOrFailureCalllback">Callback used to indicate whether the operation /// succeeded or failed.</param> void UnlockAchievement(string achievementId, Action<bool> successOrFailureCalllback); /// <summary> /// Reveals the achievement with the passed identifier. /// </summary> /// <remarks>If the operation succeeds, the callback /// will be invoked on the game thread with <code>true</code>. If the operation fails, the /// callback will be invoked with <code>false</code>. This operation will immediately fail if /// the user is not authenticated (i.e. the callback will immediately be invoked with /// <code>false</code>). If the achievement is already in a revealed state, this call will /// succeed immediately. /// </remarks> /// <param name="achievementId">The ID of the achievement to reveal.</param> /// <param name="successOrFailureCalllback">Callback used to indicate whether the operation /// succeeded or failed.</param> void RevealAchievement(string achievementId, Action<bool> successOrFailureCalllback); /// <summary> /// Increments the achievement with the passed identifier. /// </summary> /// <remarks>If the operation succeeds, the /// callback will be invoked on the game thread with <code>true</code>. If the operation fails, /// the callback will be invoked with <code>false</code>. This operation will immediately fail /// if the user is not authenticated (i.e. the callback will immediately be invoked with /// <code>false</code>). /// </remarks> /// <param name="achievementId">The ID of the achievement to increment.</param> /// <param name="steps">The number of steps to increment by.</param> /// <param name="successOrFailureCalllback">Callback used to indicate whether the operation /// succeeded or failed.</param> void IncrementAchievement(string achievementId, int steps, Action<bool> successOrFailureCalllback); /// <summary> /// Set an achievement to have at least the given number of steps completed. /// </summary> /// <remarks> /// Calling this method while the achievement already has more steps than /// the provided value is a no-op. Once the achievement reaches the /// maximum number of steps, the achievement is automatically unlocked, /// and any further mutation operations are ignored. /// </remarks> /// <param name="achId">Ach identifier.</param> /// <param name="steps">Steps.</param> /// <param name="callback">Callback.</param> void SetStepsAtLeast(string achId, int steps, Action<bool> callback); /// <summary> /// Shows the appropriate platform-specific achievements UI. /// <param name="callback">The callback to invoke when complete. If null, /// no callback is called. </param> /// </summary> void ShowAchievementsUI(Action<UIStatus> callback); /// <summary> /// Shows the appropriate platform-specific friends sharing UI. /// <param name="callback">The callback to invoke when complete. If null, /// no callback is called. </param> /// </summary> void AskForLoadFriendsResolution(Action<UIStatus> callback); /// <summary> /// Returns the latest LoadFriendsStatus obtained from loading friends. /// </summary> LoadFriendsStatus GetLastLoadFriendsStatus(); /// <summary> /// Shows the Play Games Player Profile UI for a specific user identifier. /// </summary> /// <param name="otherUserId">User Identifier.</param> /// <param name="otherPlayerInGameName"> /// The game's own display name of the player referred to by userId. /// </param> /// <param name="currentPlayerInGameName"> /// The game's own display name of the current player. /// </param> /// <param name="callback">Callback invoked upon completion.</param> void ShowCompareProfileWithAlternativeNameHintsUI( string otherUserId, string otherPlayerInGameName, string currentPlayerInGameName, Action<UIStatus> callback); /// <summary> /// Returns if the user has allowed permission for the game to access the friends list. /// </summary> /// <param name="forceReload">If true, this call will clear any locally cached data and /// attempt to fetch the latest data from the server. Normally, this should be set to {@code /// false} to gain advantages of data caching.</param> <param name="callback">Callback /// invoked upon completion.</param> void GetFriendsListVisibility(bool forceReload, Action<FriendsListVisibilityStatus> callback); /// <summary> /// Loads the first page of the user's friends /// </summary> /// <param name="pageSize"> /// The number of entries to request for this initial page. Note that if cached /// data already exists, the returned buffer may contain more than this size, but it is /// guaranteed to contain at least this many if the collection contains enough records. /// </param> /// <param name="forceReload"> /// If true, this call will clear any locally cached data and attempt to /// fetch the latest data from the server. This would commonly be used for something like a /// user-initiated refresh. Normally, this should be set to {@code false} to gain advantages /// of data caching.</param> /// <param name="callback">Callback invoked upon completion.</param> void LoadFriends(int pageSize, bool forceReload, Action<LoadFriendsStatus> callback); /// <summary> /// Loads the friends list page /// </summary> /// <param name="pageSize"> /// The number of entries to request for this page. Note that if cached data already /// exists, the returned buffer may contain more than this size, but it is guaranteed /// to contain at least this many if the collection contains enough records. /// </param> /// <param name="callback"></param> void LoadMoreFriends(int pageSize, Action<LoadFriendsStatus> callback); /// <summary> /// Shows the leaderboard UI for a specific leaderboard. /// </summary> /// <remarks>If the passed ID is <code>null</code>, all leaderboards are displayed. /// </remarks> /// <param name="leaderboardId">The leaderboard to display. <code>null</code> to display /// all.</param> /// <param name="span">Timespan to display for the leaderboard</param> /// <param name="callback">If non-null, the callback to invoke when the /// leaderboard is dismissed. /// </param> void ShowLeaderboardUI(string leaderboardId, LeaderboardTimeSpan span, Action<UIStatus> callback); /// <summary> /// Loads the score data for the given leaderboard. /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="start">Start indicating the top scores or player centric</param> /// <param name="rowCount">max number of scores to return. non-positive indicates /// no rows should be returned. This causes only the summary info to /// be loaded. This can be limited /// by the SDK.</param> /// <param name="collection">leaderboard collection: public or social</param> /// <param name="timeSpan">leaderboard timespan</param> /// <param name="callback">callback with the scores, and a page token. /// The token can be used to load next/prev pages.</param> void LoadScores(string leaderboardId, LeaderboardStart start, int rowCount, LeaderboardCollection collection, LeaderboardTimeSpan timeSpan, Action<LeaderboardScoreData> callback); /// <summary> /// Loads the more scores for the leaderboard. /// </summary> /// <remarks>The token is accessed /// by calling LoadScores() with a positive row count. /// </remarks> /// <param name="token">Token for tracking the score loading.</param> /// <param name="rowCount">max number of scores to return. /// This can be limited by the SDK.</param> /// <param name="callback">Callback.</param> void LoadMoreScores(ScorePageToken token, int rowCount, Action<LeaderboardScoreData> callback); /// <summary> /// Returns the max number of scores returned per call. /// </summary> /// <returns>The max results.</returns> int LeaderboardMaxResults(); /// <summary> /// Submits the passed score to the passed leaderboard. /// </summary> /// <remarks>This operation will immediately fail /// if the user is not authenticated (i.e. the callback will immediately be invoked with /// <code>false</code>). /// </remarks> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="score">Score.</param> /// <param name="successOrFailureCalllback">Callback used to indicate whether the operation /// succeeded or failed.</param> void SubmitScore(string leaderboardId, long score, Action<bool> successOrFailureCalllback); /// <summary> /// Submits the score for the currently signed-in player. /// </summary> /// <param name="score">Score.</param> /// <param name="leaderboardId">leaderboard id.</param> /// <param name="metadata">metadata about the score.</param> /// <param name="successOrFailureCalllback">Callback upon completion.</param> void SubmitScore(string leaderboardId, long score, string metadata, Action<bool> successOrFailureCalllback); /// <summary> /// Asks user to give permissions for the given scopes. /// </summary> /// <param name="scopes">list of scopes to ask permission for</param> /// <param name="callback">Callback used to indicate the outcome of the operation.</param> void RequestPermissions(string[] scopes, Action<SignInStatus> callback); /// <summary> /// Returns whether or not user has given permissions for given scopes /// </summary> /// <seealso cref="GooglePlayGames.BasicApi.IPlayGamesClient.HasPermissions"/> /// <param name="scopes">list of scopes</param> /// <returns><c>true</c>, if given, <c>false</c> otherwise.</returns> bool HasPermissions(string[] scopes); /// <summary> /// Gets the saved game client. /// </summary> /// <returns>The saved game client.</returns> SavedGame.ISavedGameClient GetSavedGameClient(); /// <summary> /// Gets the events client. /// </summary> /// <returns>The events client.</returns> Events.IEventsClient GetEventsClient(); /// <summary> /// Gets the video client. /// </summary> /// <returns>The video client.</returns> Video.IVideoClient GetVideoClient(); IUserProfile[] GetFriends(); /// <summary> /// Sets the gravity for popups (Android only). /// </summary> /// <remarks>This can only be called after authentication. It affects /// popups for achievements and other game services elements.</remarks> /// <param name="gravity">Gravity for the popup.</param> void SetGravityForPopups(Gravity gravity); } } #endif
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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.Linq; using Newtonsoft.Json; using NUnit.Framework; using QuantConnect.Data.Market; using QuantConnect.Packets; using QuantConnect.Securities; namespace QuantConnect.Tests.Common.Securities { [TestFixture] public class CashBookTests { [Test] public void JsonRoundTrip() { var cashBook = new CashBook { AccountCurrency = Currencies.EUR }; cashBook.Add(Currencies.USD, 10, 1.2m); cashBook.Add(Currencies.EUR, 10, 1m); var expected = new LiveResult { CashBook = cashBook }; var serialized = JsonConvert.SerializeObject(expected); var result = JsonConvert.DeserializeObject<LiveResult>(serialized); Assert.AreEqual(expected.AccountCurrency, result.AccountCurrency); Assert.AreEqual(expected.AccountCurrencySymbol, result.AccountCurrencySymbol); Assert.AreEqual(expected.Cash.Count, result.Cash.Count); Assert.AreEqual(expected.Cash[Currencies.USD].Amount, result.Cash[Currencies.USD].Amount); Assert.AreEqual(expected.Cash[Currencies.USD].ConversionRate, result.Cash[Currencies.USD].ConversionRate); Assert.AreEqual(expected.Cash[Currencies.EUR].Amount, result.Cash[Currencies.EUR].Amount); Assert.AreEqual(expected.Cash[Currencies.EUR].ConversionRate, result.Cash[Currencies.EUR].ConversionRate); } [Test] public void InitializesWithAccountCurrencyAdded() { var book = new CashBook(); Assert.AreEqual(1, book.Count); var cash = book.Single().Value; Assert.AreEqual(Currencies.USD, cash.Symbol); Assert.AreEqual(0, cash.Amount); Assert.AreEqual(1m, cash.ConversionRate); } [Test] public void ComputesValueInAccountCurrency() { var book = new CashBook(); book[Currencies.USD].SetAmount(1000); book.Add("JPY", 1000, 1/100m); book.Add("GBP", 1000, 2m); decimal expected = book[Currencies.USD].ValueInAccountCurrency + book["JPY"].ValueInAccountCurrency + book["GBP"].ValueInAccountCurrency; Assert.AreEqual(expected, book.TotalValueInAccountCurrency); } [Test] public void ConvertsProperly() { var book = new CashBook(); book.Add("EUR", 0, 1.10m); book.Add("GBP", 0, 0.71m); var expected = 1549.2957746478873239436619718m; var actual = book.Convert(1000, "EUR", "GBP"); Assert.AreEqual(expected, actual); } [Test] public void ConvertsToAccountCurrencyProperly() { var book = new CashBook(); book.Add("EUR", 0, 1.10m); var expected = 1100m; var actual = book.ConvertToAccountCurrency(1000, "EUR"); Assert.AreEqual(expected, actual); } [Test] public void ConvertsToEurFromAccountCurrencyProperly() { var book = new CashBook(); book.Add("EUR", 0, 1.20m); var expected = 1000m; var actual = book.Convert(1200, book.AccountCurrency, "EUR"); Assert.AreEqual(expected, actual); } [Test] public void ConvertsToJpyFromAccountCurrencyProperly() { var book = new CashBook(); book.Add("JPY", 0, 1/100m); var expected = 100000m; var actual = book.Convert(1000, book.AccountCurrency, "JPY"); Assert.AreEqual(expected, actual); } [Test] public void WontAddNullCurrencyCash() { var book = new CashBook {{Currencies.NullCurrency, 1, 1}}; Assert.AreEqual(1, book.Count); var cash = book.Single().Value; Assert.AreEqual(Currencies.USD, cash.Symbol); book.Add(Currencies.NullCurrency, 1, 1); Assert.AreEqual(1, book.Count); cash = book.Single().Value; Assert.AreEqual(Currencies.USD, cash.Symbol); book.Add(Currencies.NullCurrency, new Cash(Currencies.NullCurrency, 1, 1)); Assert.AreEqual(1, book.Count); cash = book.Single().Value; Assert.AreEqual(Currencies.USD, cash.Symbol); book[Currencies.NullCurrency] = new Cash(Currencies.NullCurrency, 1, 1); Assert.AreEqual(1, book.Count); cash = book.Single().Value; Assert.AreEqual(Currencies.USD, cash.Symbol); } [Test] public void WillThrowIfGetNullCurrency() { Assert.Throws<InvalidOperationException>(() => { var symbol = new CashBook()[Currencies.NullCurrency].Symbol; }); } [Test] public void UpdatedAddedCalledOnlyForNewSymbols() { var cashBook = new CashBook(); var called = false; var cash = new Cash(Currencies.USD, 1, 1); cashBook.Add(cash.Symbol, cash); cashBook.Updated += (sender, updateType) => { if (updateType == CashBook.UpdateType.Added) { called = true; } }; cashBook.Add(cash.Symbol, cash); Assert.IsFalse(called); } [Test] public void UpdateEventCalledForCashUpdatesWhenAccessingConversionRate() { var cashBook = new CashBook(); var called = false; var cash = new Cash(Currencies.USD, 1, 1); cashBook.Add(cash.Symbol, cash); cashBook.Updated += (sender, updateType) => { if (updateType == CashBook.UpdateType.Updated) { called = true; } }; cash.Update(); var conversionRate = cash.ConversionRate; Assert.IsTrue(called); } [Test] public void UpdateEventCalledForAddMethod() { var cashBook = new CashBook(); // we remove default USD cash cashBook.Clear(); var called = false; var cash = new Cash(Currencies.USD, 1, 1); cashBook.Updated += (sender, updateType) => { if (updateType == CashBook.UpdateType.Added) { called = true; } }; cashBook.Add(cash.Symbol, cash); Assert.IsTrue(called); } [Test] public void UpdateEventCalledForAdd() { var cashBook = new CashBook(); // we remove default USD cash cashBook.Clear(); var called = false; var cash = new Cash(Currencies.USD, 1, 1); cashBook.Updated += (sender, updateType) => { if (updateType == CashBook.UpdateType.Added) { called = true; } }; cashBook[cash.Symbol] = cash; Assert.IsTrue(called); } [Test] public void UpdateEventCalledForRemove() { var cashBook = new CashBook(); var called = false; var cash = new Cash(Currencies.USD, 1, 1); cashBook.Add(cash.Symbol, cash); cashBook.Updated += (sender, updateType) => { if (updateType == CashBook.UpdateType.Removed) { called = true; } }; cashBook.Remove(Currencies.USD); Assert.IsTrue(called); } [Test] public void UpdateEventNotCalledForCashUpdatesAfterRemoved() { var cashBook = new CashBook(); var called = false; var cash = new Cash(Currencies.USD, 1, 1); cashBook.Add(cash.Symbol, cash); cashBook.Remove(Currencies.USD); cashBook.Updated += (sender, args) => { called = true; }; cash.Update(); Assert.IsFalse(called); } [Test] public void UpdateEventNotCalledForCashUpdatesAfterSteppedOn() { var cashBook = new CashBook(); var called = false; var updatedCalled = false; var cash = new Cash(Currencies.USD, 1, 1); var cash2 = new Cash(Currencies.USD, 1, 1); cashBook.Add(cash.Symbol, cash); cashBook.Add(cash.Symbol, cash2); cashBook.Updated += (sender, updateType) => { called = true; updatedCalled = updateType == CashBook.UpdateType.Updated; }; cash.Update(); var conversionRate = cash.ConversionRate; Assert.IsFalse(called); cash2.Update(); var conversionRate2 = cash2.ConversionRate; Assert.IsTrue(updatedCalled); } [Test] public void UpdateEventCalledForAddExistingValueCalledOnce() { var cashBook = new CashBook(); var called = 0; var calledUpdated = false; var cash = new Cash(Currencies.USD, 1, 1); cashBook.Add(cash.Symbol, cash); cashBook.Updated += (sender, updateType) => { called++; calledUpdated = updateType == CashBook.UpdateType.Updated; }; cashBook.Add(cash.Symbol, cash); Assert.AreEqual(1, called); Assert.IsTrue(calledUpdated); } [Test] public void UpdateEventCalledForClear() { var cashBook = new CashBook(); var called = false; var cash = new Cash(Currencies.USD, 1, 1); cashBook.Add(cash.Symbol, cash); cashBook.Updated += (sender, updateType) => { called = updateType == CashBook.UpdateType.Removed; }; cashBook.Clear(); Assert.IsTrue(called); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="HeavyLoad.cs" company="Exit Games GmbH"> // Copyright (c) Exit Games GmbH. All rights reserved. // </copyright> // <summary> // The heavy load. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Photon.MmoDemo.Tests.Disconnected { using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using ExitGames.Concurrency.Fibers; using ExitGames.Logging; using ExitGames.Threading; using NUnit.Framework; using Photon.MmoDemo.Common; using Photon.MmoDemo.Server; using SocketServer; using SocketServer.Diagnostics; using SocketServer.Mmo.Messages; using Settings = Tests.Settings; /// <summary> /// The heavy load. /// </summary> [TestFixture] [Explicit] public class HeavyLoad { /// <summary> /// The logger. /// </summary> private static readonly ILogger log = LogManager.GetCurrentClassLogger(); /// <summary> /// The clients. /// </summary> private static int clientCount; /// <summary> /// Tests the client setup. /// </summary> [Test] public void SetupClients() { MmoWorld world; MmoWorldCache.Instance.Clear(); MmoWorldCache.Instance.TryCreate("TestWorld", (new[] { 0f, 0f }).ToVector(), (new[] { 399f, 399f }).ToVector(), (new[] { 10f, 10f }).ToVector(), out world); for (int i = 0; i < 10; i++) { List<Client> clients = SetupClients(world); DisconnectClients(clients); } } /// <summary> /// The run test. /// </summary> [Test] public void Run() { MmoWorld world; MmoWorldCache.Instance.Clear(); MmoWorldCache.Instance.TryCreate("TestWorld", (new[] { 0f, 0f }).ToVector(), (new[] { 299f, 299f }).ToVector(), (new[] { 10f, 10f }).ToVector(), out world); List<Client> clients = SetupClients(world); Stopwatch t = Stopwatch.StartNew(); using (var fiber = new PoolFiber(new FailSafeBatchExecutor())) { fiber.Start(); fiber.ScheduleOnInterval(() => PrintStatsPerSecond(t), 1000, 1000); MoveClients(clients); PrintStats(t); MoveClients(clients); PrintStats(t); MoveClients(clients); PrintStats(t); MoveClients(clients); PrintStats(t); MoveClients(clients); PrintStats(t); log.Info("move completed"); Assert.AreEqual(0, Client.Exceptions, "Exceptions occured at exit"); DisconnectClients(clients); } } /// <summary> /// The run for time. /// </summary> [Test] public void RunForTime() { MmoWorldCache.Instance.Clear(); MmoWorld world; MmoWorldCache.Instance.TryCreate("TestWorld", (new[] { 0f, 0f }).ToVector(), (new[] { 299f, 299f }).ToVector(), (new[] { 10f, 10f }).ToVector(), out world); List<Client> clients = SetupClients(world); Stopwatch t = Stopwatch.StartNew(); using (var fiber = new PoolFiber(new FailSafeBatchExecutor())) { fiber.Start(); fiber.ScheduleOnInterval(() => PrintStatsPerSecond(t), 1000, 1000); while (t.ElapsedMilliseconds < 10000) { MoveClients(clients); PrintStats(t); } } DisconnectClients(clients); } /// <summary> /// The begin receive event. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="eventCode"> /// The event code. /// </param> /// <param name="checkAction"> /// The check action. /// </param> private static void BeginReceiveEvent(Client client, EventCode eventCode, Func<EventData, bool> checkAction) { client.BeginReceiveEvent(eventCode, checkAction); } /// <summary> /// The begin receive event. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="eventCode"> /// The event code. /// </param> private static void BeginReceiveEvent(Client client, EventCode eventCode) { client.BeginReceiveEvent(eventCode, d => true); } /// <summary> /// The disconnect clients. /// </summary> /// <param name="clients"> /// The clients. /// </param> private static void DisconnectClients(List<Client> clients) { Stopwatch t = Stopwatch.StartNew(); clients.ForEach(ExitWorldBegin); clients.ForEach(ExitWorldEnd); log.Info("exit completed"); PrintStats(t); Assert.AreEqual(0, Client.Exceptions, "Exceptions occured at exit"); t = Stopwatch.StartNew(); clients.ForEach(c => c.Disconnect()); Thread.Sleep(100); log.Info("disconnect completed"); PrintStats(t); Assert.AreEqual(0, Client.Exceptions, "Exceptions occured at exit"); } /// <summary> /// The end receive event. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="eventCode"> /// The event EventCode. /// </param> /// <returns> /// the received event /// </returns> private static EventData EndReceiveEvent(Client client, EventCode eventCode) { EventData data; Assert.IsTrue(client.EndReceiveEvent(Settings.WaitTime, out data), "Event not received"); Assert.AreEqual(eventCode, (EventCode)data.Code); return data; } /// <summary> /// The enter world. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="world"> /// The world. /// </param> /// <param name="position"> /// The position. /// </param> private static void EnterWorldBegin(Client client, MmoWorld world, float[] position) { var viewDistanceEnter = new[] { 1f, 1f }; var viewDistanceExit = new[] { 2f, 2f }; client.Position = position; ThreadPoolEnqueue( client, () => { client.SendOperation(Operations.EnterWorld(world.Name, client.Username, null, position, viewDistanceEnter, viewDistanceExit)); client.BeginReceiveResponse(); }); } /// <summary> /// The enter world end. /// </summary> /// <param name="client"> /// The client. /// </param> private static void EnterWorldEnd(Client client) { OperationResponse data; Assert.IsTrue(client.EndReceiveResponse(Settings.WaitTime, out data)); Assert.AreEqual(0, data.ReturnCode); } /// <summary> /// The exit world begin. /// </summary> /// <param name="client"> /// The client. /// </param> private static void ExitWorldBegin(Client client) { ThreadPoolEnqueue( client, () => { client.SendOperation(Operations.ExitWorld()); BeginReceiveEvent(client, EventCode.WorldExited); }); } /// <summary> /// The exit world end. /// </summary> /// <param name="client"> /// The client. /// </param> private static void ExitWorldEnd(Client client) { EndReceiveEvent(client, EventCode.WorldExited); } /// <summary> /// The client movement. /// </summary> /// <param name="client"> /// The client. /// </param> private static void Move(Client client) { client.Peer.RequestFiber.Enqueue(() => MoveAction(client, 1)); } /// <summary> /// The move action. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="number"> /// The number. /// </param> private static void MoveAction(Client client, int number) { float[] pos = client.Position; client.SendOperation(Operations.Move(null, null, pos)); number++; if (number < 6) { client.Peer.RequestFiber.Schedule(() => MoveAction(client, number), 100); } } /// <summary> /// The move clients. /// </summary> /// <param name="clients"> /// The clients. /// </param> private static void MoveClients(List<Client> clients) { clients.ForEach( c => { Move(c); BeginReceiveEvent(c, EventCode.ItemMoved); }); clients.ForEach(c => EndReceiveEvent(c, EventCode.ItemMoved)); Thread.Sleep(100); clients.ForEach(c => BeginReceiveEvent(c, EventCode.ItemMoved)); clients.ForEach(c => EndReceiveEvent(c, EventCode.ItemMoved)); Thread.Sleep(100); clients.ForEach(c => BeginReceiveEvent(c, EventCode.ItemMoved)); clients.ForEach(c => EndReceiveEvent(c, EventCode.ItemMoved)); Thread.Sleep(100); clients.ForEach(c => BeginReceiveEvent(c, EventCode.ItemMoved)); clients.ForEach(c => EndReceiveEvent(c, EventCode.ItemMoved)); Thread.Sleep(100); clients.ForEach(c => BeginReceiveEvent(c, EventCode.ItemMoved)); clients.ForEach(c => EndReceiveEvent(c, EventCode.ItemMoved)); } /// <summary> /// The print stats. /// </summary> /// <param name="t"> /// The stopwatch. /// </param> private static void PrintStats(Stopwatch t) { log.InfoFormat( "{7:00000} Client({8}): {9} operations, {0} fast events in {1:0.00}ms avg, {2} middle events in {3:0.00}ms avg, {4} slow events in {5:0.00}ms avg, {6:0.00}ms max - {10} exceptions", Client.EventsReceivedFast, Client.EventsReceivedTimeTotalFast / (double)Client.EventsReceivedFast, Client.EventsReceivedMiddle, Client.EventsReceivedTimeTotalMiddle / (double)Client.EventsReceivedMiddle, Client.EventsReceivedSlow, Client.EventsReceivedTimeTotalSlow / (double)Client.EventsReceivedSlow, Client.EventsReceivedTimeMax, t.ElapsedMilliseconds, clientCount, Client.OperationsSent, Client.Exceptions); Client.ResetStats(); } /// <summary> /// The print stats per second. /// </summary> /// <param name="t"> /// The stopwatch. /// </param> private static void PrintStatsPerSecond(Stopwatch t) { log.InfoFormat( "{4:00000} Operations: {0:0.00} fast, {1:0.00} middle, {2:0.00} slow ({3}ms max)", PhotonCounter.OperationsFast.GetNextValue(), PhotonCounter.OperationsMiddle.GetNextValue(), PhotonCounter.OperationsSlow.GetNextValue(), PhotonCounter.OperationsMaxTime.RawValue, t.ElapsedMilliseconds); PhotonCounter.OperationsMaxTime.RawValue = 0; log.InfoFormat( "{2:00000} Itemessages: {0:0.00} sent, {1:0.00} received", MessageCounters.CounterSend.GetNextValue(), MessageCounters.CounterReceive.GetNextValue(), t.ElapsedMilliseconds); } /// <summary> /// The setup clients. creates 2 clients per region. /// </summary> /// <param name="world"> /// The world. /// </param> /// <returns> /// the list of created clients /// </returns> private static List<Client> SetupClients(MmoWorld world) { Stopwatch t = Stopwatch.StartNew(); var clients = new List<Client>(); for (int x = world.Area.Min.X + (world.TileDimensions.X / 2); x < world.Area.Max.X; x += world.TileDimensions.X) { for (int y = world.Area.Min.Y + (world.TileDimensions.Y / 2); y < world.Area.Max.Y; y += world.TileDimensions.Y) { string name = string.Format("MyUsername{0}/{1}", x, y); var client = new Client(name); EnterWorldBegin(client, world, new[] { x / 100f, y / 100f }); clients.Add(client); clientCount++; Sleep(); } for (int y = world.Area.Min.Y + (world.TileDimensions.Y / 2) + 1; y < world.Area.Max.Y; y += world.TileDimensions.Y) { string name = string.Format("MyUsername{0}/{1}", x + 1, y); var client = new Client(name); EnterWorldBegin(client, world, new[] { (x + 1) / 100f, y / 100f }); clients.Add(client); clientCount++; Sleep(); } } clients.ForEach(EnterWorldEnd); clients.ForEach(c => BeginReceiveEvent(c, EventCode.ItemSubscribed, d => true)); clients.ForEach(c => EndReceiveEvent(c, EventCode.ItemSubscribed)); PrintStats(t); Assert.AreEqual(0, Client.Exceptions, "Exceptions occured at start"); log.Info("enter completed"); Assert.AreEqual(0, Client.Exceptions, "Exceptions occured at exit"); return clients; } /// <summary> /// The sleep. /// </summary> private static void Sleep() { ////Thread.Sleep(1); } /////// <summary> /////// The receive event. /////// </summary> /////// <param name="client"> /////// The client. /////// </param> /////// <param name="eventCode"> /////// The event code. /////// </param> /////// <param name="checkAction"> /////// The check action. /////// </param> /////// <returns> /////// </returns> ////private static EventData ReceiveEvent(Client client, Code eventCode, Func<EventData, bool> checkAction) ////{ //// BeginReceiveEvent(client, eventCode, checkAction); //// return EndReceiveEvent(client); ////} /////// <summary> /////// The receive event. /////// </summary> /////// <param name="client"> /////// The client. /////// </param> /////// <param name="eventCode"> /////// The event code. /////// </param> /////// <returns> /////// </returns> ////private static EventData ReceiveEvent(Client client, Code eventCode) ////{ //// return ReceiveEvent(client, eventCode, d => true); ////} /////// <summary> /////// The receive operation response. /////// </summary> /////// <param name="client"> /////// The client. /////// </param> /////// <param name="operationCode"> /////// The operation code. /////// </param> /////// <returns> /////// </returns> ////private static EventData ReceiveOperationResponse(Client client, OperationCode operationCode) ////{ //// Func<EventData, bool> checkAction = //// d => (byte)d.Parameters[(short)ParameterCode.OperationCode] == (byte)operationCode; //// EventData data = ReceiveEvent(client, EventCode.OperationSuccess, checkAction); //// var eventCode = (EventCode)(byte)data.Code; //// Assert.IsTrue(eventCode == EventCode.OperationSuccess || eventCode == EventCode.OperationError); //// Assert.AreEqual((OperationCode)(byte)data.Parameters[(short)ParameterCode.OperationCode], operationCode); //// return data; ////} /// <summary> /// The thread pool enqueue. /// </summary> /// <param name="client"> /// The client. /// </param> /// <param name="action"> /// The action. /// </param> private static void ThreadPoolEnqueue(Client client, Action action) { ThreadPool.QueueUserWorkItem( o => { try { action(); } catch (Exception e) { client.HandleException(e); } }); } } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class Aisle : IEquatable<Aisle> { /// <summary> /// Initializes a new instance of the <see cref="Aisle" /> class. /// Initializes a new instance of the <see cref="Aisle" />class. /// </summary> /// <param name="WarehouseId">WarehouseId (required).</param> /// <param name="Address">Address (required).</param> /// <param name="CustomFields">CustomFields.</param> public Aisle(int? WarehouseId = null, string Address = null, Dictionary<string, Object> CustomFields = null) { // to ensure "WarehouseId" is required (not null) if (WarehouseId == null) { throw new InvalidDataException("WarehouseId is a required property for Aisle and cannot be null"); } else { this.WarehouseId = WarehouseId; } // to ensure "Address" is required (not null) if (Address == null) { throw new InvalidDataException("Address is a required property for Aisle and cannot be null"); } else { this.Address = Address; } this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets WarehouseId /// </summary> [DataMember(Name="warehouseId", EmitDefaultValue=false)] public int? WarehouseId { get; set; } /// <summary> /// Gets or Sets Address /// </summary> [DataMember(Name="address", EmitDefaultValue=false)] public string Address { get; set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { 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 Aisle {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n"); sb.Append(" Address: ").Append(Address).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).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 Aisle); } /// <summary> /// Returns true if Aisle instances are equal /// </summary> /// <param name="other">Instance of Aisle to be compared</param> /// <returns>Boolean</returns> public bool Equals(Aisle other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.WarehouseId == other.WarehouseId || this.WarehouseId != null && this.WarehouseId.Equals(other.WarehouseId) ) && ( this.Address == other.Address || this.Address != null && this.Address.Equals(other.Address) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <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.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.WarehouseId != null) hash = hash * 59 + this.WarehouseId.GetHashCode(); if (this.Address != null) hash = hash * 59 + this.Address.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
using System; using System.Collections; using csmatio.types; using csmatio.common; using System.Runtime.InteropServices; namespace csmatio.types { /// <summary> /// Abstract class for numeric arrays. /// </summary> /// <author>David Zier (david.zier@gmail.com)</author> public abstract class MLNumericArray<T> : MLArray, IGenericArrayCreator<T>, IByteStorageSupport { private ByteBuffer _real; private ByteBuffer _imaginary; private byte[] _bytes; #region Contructors /// <summary> /// Constructs an abstract MLNumericArray class object /// </summary> /// <param name="Name">The name of the numeric array.</param> /// <param name="Dims">The dimensions of the numeric array.</param> /// <param name="Type">The Matlab Array Class type for this array.</param> /// <param name="Attributes">Any attributes associated with this array.</param> protected MLNumericArray(string Name, int[] Dims, int Type, int Attributes) : base(Name, Dims, Type, Attributes) { _real = new ByteBuffer(Size * GetBytesAllocated); if (IsComplex) _imaginary = new ByteBuffer(Size * GetBytesAllocated); _bytes = new byte[GetBytesAllocated]; } /// <summary> /// <a href="http://math.nist.gov/javanumerics/jama/">Jama</a> [math.nist.gov] style: /// construct a 2D real matrix from a one-dimensional packed array. /// </summary> /// <param name="Name">The name of the numeric array.</param> /// <param name="Type">The Matlab Array Class type for this array.</param> /// <param name="Vals">One-dimensional array of doubles, packed by columns.</param> /// <param name="M">The number of rows.</param> protected MLNumericArray(string Name, int Type, T[] Vals, int M) : this(Name, new int[] { M, Vals.Length / M }, Type, 0) { // Fill in the array for (int i = 0; i < Vals.Length; i++) Set(Vals[i], i); } /// <summary> /// <a href="http://math.nist.gov/javanumerics/jama/">Jama</a> [math.nist.gov] style: /// construct a 2D imaginary matrix from a one-dimensional packed array. /// </summary> /// <param name="Name">The name of the numeric array.</param> /// <param name="Type">The Matlab Array Class type for this array.</param> /// <param name="RealVals">One-dimensional array of doubles for the <i>real</i> part, /// packed by columns</param> /// <param name="ImagVals">One-dimensional array of doubles for the <i>imaginary</i> part, /// packed by columns</param> /// <param name="M">The number of columns</param> protected MLNumericArray(string Name, int Type, T[] RealVals, T[] ImagVals, int M) : this(Name, new int[] { M, RealVals.Length / M }, Type, MLArray.mtFLAG_COMPLEX) { if (ImagVals.Length != RealVals.Length) throw new ArgumentException("Attempting to create an imaginary numeric array where the " + "imaginary array is _not_ the same size as the real array."); // Fill in the imaginary array for (int i = 0; i < ImagVals.Length; i++) { SetReal(RealVals[i], i); SetImaginary(ImagVals[i], i); } } #endregion /// <summary>Gets the flags for this array.</summary> public override int Flags { get { return (int)((uint)(base._type & MLArray.mtFLAG_TYPE) | (uint)(base._attributes & 0xFFFFFF00)); } } /// <summary> /// Gets a single real array element of A(m,n). /// </summary> /// <param name="M">Row index</param> /// <param name="N">Column index</param> /// <returns>Array Element</returns> public virtual T GetReal(int M, int N) { return GetReal(GetIndex(M, N)); } /// <summary> /// Gets the <c>ByteBuffer</c> for the Real Numbers. /// </summary> /// <returns>The real buffer</returns> public ByteBuffer GetReal() { return _real; } /// <summary> /// Get a single real array element /// </summary> /// <param name="Index">Column-packed vector index.</param> /// <returns>Array Element.</returns> public virtual T GetReal(int Index) { return _Get(_real, Index); } /// <summary> /// Sets a single real array element. /// </summary> /// <param name="Val">The element value.</param> /// <param name="M">The row index.</param> /// <param name="N">The column index.</param> public virtual void SetReal(T Val, int M, int N) { SetReal(Val, GetIndex(M, N)); } /// <summary> /// Sets a single real array element. /// </summary> /// <param name="Val">The element value.</param> /// <param name="Index">Column-packed vector index.</param> public virtual void SetReal(T Val, int Index) { _Set(_real, Val, Index); } ///// <summary> ///// Sets real part of the matrix. ///// </summary> ///// <exception cref="ArgumentException">When the <c>Vector</c> is not the ///// same length as the Numeric Array.</exception> ///// <param name="Vector">A column-packed vector of elements.</param> //public void SetReal( T[] Vector ) //{ // if( Vector.Length != Size ) // throw new ArgumentException("Matrix dimensions do not match. " + Size + " not " + Vector.Length ); // //Array.Copy( Vector, 0, _real, 0, Vector.Length ); // _real.CopyFrom(Vector); //} /// <summary> /// Sets a single imaginary array element. /// </summary> /// <param name="Val">Element value.</param> /// <param name="M">Row Index.</param> /// <param name="N">Column Index.</param> public virtual void SetImaginary(T Val, int M, int N) { if (IsComplex) SetImaginary(Val, GetIndex(M, N)); } /// <summary> /// Sets a single imaginary array element. /// </summary> /// <param name="Val">Element Value</param> /// <param name="Index">Column-packed vector index.</param> public virtual void SetImaginary(T Val, int Index) { if (IsComplex) _Set(_imaginary, Val, Index); } /// <summary> /// Gets a single imaginary array element of A(m,n) /// </summary> /// <param name="M">Row index</param> /// <param name="N">Column index</param> /// <returns>Array element</returns> public virtual T GetImaginary(int M, int N) { return GetImaginary(GetIndex(M, N)); } /// <summary> /// Gets a single imaginary array element. /// </summary> /// <param name="Index">Column-packed vector index</param> /// <returns>Array Element</returns> public virtual T GetImaginary(int Index) { return _Get(_imaginary, Index); } /// <summary> /// Gets the <c>ByteBuffer</c> for the Real Numbers. /// </summary> /// <returns>The real buffer</returns> public ByteBuffer GetImaginary() { if (IsComplex) return _imaginary; else return null; } /// <summary> /// Does the same as <c>SetReal</c>. /// </summary> /// <param name="Val">Element Value</param> /// <param name="M">Row index</param> /// <param name="N">Column index</param> public void Set(T Val, int M, int N) { if (IsComplex) throw new MethodAccessException("Cannot use this method for Complex matrices"); SetReal(Val, M, N); } /// <summary> /// Does the same as <c>SetReal</c>. /// </summary> /// <param name="Val">Element Value</param> /// <param name="Index">Column-packed vector index</param> public void Set(T Val, int Index) { if (IsComplex) throw new MethodAccessException("Cannot use this method for Complex matrices"); SetReal(Val, Index); } /// <summary> /// Does the same as <c>GetReal</c>. /// </summary> /// <param name="M">Row index</param> /// <param name="N">Column index</param> /// <returns>An array element value.</returns> public T Get(int M, int N) { if (IsComplex) throw new MethodAccessException("Cannot use this method for Complex matrices"); return GetReal(M, N); } /// <summary> /// Does the same as <c>GetReal</c>. /// </summary> /// <param name="Index">Column-packed vector index</param> /// <returns>An array element value.</returns> public T Get(int Index) { if (IsComplex) throw new MethodAccessException("Cannot use this method for Complex matrices"); return GetReal(Index); } ///// <summary> ///// Does the same as <c>SetReal</c> ///// </summary> ///// <param name="Vector">A column-packed vector of elements.</param> //public void Set( T[] Vector ) //{ // if( IsComplex ) // throw new MethodAccessException("Cannot use this method for Complex matrices"); // SetReal( Vector ); //} private int _GetByteOffset(int Index) { return Index * GetBytesAllocated; } /// <summary> /// Gets a single objects data from a <c>ByteBuffer</c>. /// </summary> /// <param name="Buffer">The <c>ByteBuffer</c> object.</param> /// <param name="Index">A column-packed index.</param> /// <returns>The object data.</returns> protected virtual T _Get(ByteBuffer Buffer, int Index) { Buffer.Position(_GetByteOffset(Index)); Buffer.Get(ref _bytes, 0, _bytes.Length); return (T)BuildFromBytes(_bytes); } /// <summary> /// Sets a single object data into a <c>ByteBuffer</c> /// </summary> /// <param name="Buffer">The <c>ByteBuffer</c> to where the object data will be stored.</param> /// <param name="Val">The object data.</param> /// <param name="Index">A column-packed index</param> protected void _Set(ByteBuffer Buffer, T Val, int Index) { Buffer.Position(_GetByteOffset(Index)); Buffer.Put(GetByteArray(Val)); } /// <summary> /// Gets a two-dimensional array. /// </summary> /// <returns>2D array.</returns> public T[][] GetArray() { T[][] result = new T[M][]; for (int m = 0; m < M; m++) { result[m] = new T[N]; for (int n = 0; n < N; n++) { result[m][n] = GetReal(m, n); } } return result; } /// <summary> /// Gets the imaginary part of the number array. /// </summary> public ByteBuffer ImaginaryByteBuffer { get { return _imaginary; } set { if (!IsComplex) throw new MethodAccessException("Array is not complex"); _imaginary.Rewind(); _imaginary.Put(value); } } /// <summary> /// Gets the <c>ByteBuffer</c> for the real numbers in the /// array. /// </summary> public ByteBuffer RealByteBuffer { get { return _real; } set { _real.Rewind(); _real.Put(value); } } /// <summary> /// Get a string representation for the content of the array. /// See <see cref="csmatio.types.MLArray.ContentToString()"/> /// </summary> /// <returns>A string representation.</returns> public override string ContentToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.Append(Name + " = \n"); if (Size > 1000) { // sb.Append("Cannot display variables with more than 1000 elements."); sb.Append(this.ToString()); return sb.ToString(); } for (int m = 0; m < M; m++) { sb.Append("\t"); for (int n = 0; n < N; n++) { sb.Append(GetReal(m, n)); if (IsComplex) sb.Append("+" + GetImaginary(m, n)); sb.Append("\t"); } sb.Append("\n"); } return sb.ToString(); } /// <summary> /// Overridden equals operator, see <see cref="System.Object.Equals(System.Object)"/> /// </summary> /// <param name="o">A <c>System.Object</c> to be compared with.</param> /// <returns>True if the object match.</returns> public override bool Equals(object o) { if (o.GetType() == typeof(MLNumericArray<T>)) { bool result = DirectByteBufferEquals(_real, ((MLNumericArray<T>)o).GetReal()) && Array.Equals(Dimensions, ((MLNumericArray<T>)o).Dimensions); if (IsComplex && result) result &= DirectByteBufferEquals(_imaginary, ((MLNumericArray<T>)o).GetImaginary()); return result; } return base.Equals(o); } /// <summary> /// Serves as a hash function for an MLNumericArray. /// </summary> /// <returns>A hashcode for this object</returns> public override int GetHashCode() { return base.GetHashCode(); } /// <summary> /// Equals implementation for a direct <c>ByteBuffer</c> /// </summary> /// <param name="buffa">The source buffer to be compared.</param> /// <param name="buffb">The destination buffer to be compared.</param> /// <returns><c>true</c> if buffers are equal in terms of content.</returns> private static bool DirectByteBufferEquals(ByteBuffer buffa, ByteBuffer buffb) { if (buffa == buffb) return true; if (buffa == null || buffb == null) return false; buffa.Rewind(); buffb.Rewind(); int length = buffa.Remaining; if (buffb.Remaining != length) return false; for (int i = 0; i < length; i++) if (buffa.Get() != buffb.Get()) return false; return true; } #region GenericArrayCreator Members /// <summary> /// Creates a generic array. /// </summary> /// <param name="m">The number of columns in the array</param> /// <param name="n">The number of rows in the array</param> /// <returns>A generic array.</returns> public virtual T[] CreateArray(int m, int n) { return new T[m * n]; } #endregion #region ByteStorageSupport Members /// <summary> /// Gets the number of bytes allocated for a type /// </summary> public virtual int GetBytesAllocated { get { int retval; Type tt = typeof(T); if (tt.IsValueType) { retval = Marshal.SizeOf(tt); } else { // tt is a reference type, so the size in memory is the pointer size. // We could return "retval = IntPtr.Size", but probably thats not what the user wants? // So tell him something went wrong. retval = -1; } return retval; } } /// <summary> /// Builds a numeric object from a byte array. /// </summary> /// <param name="bytes">A byte array containing the data.</param> /// <returns>A numeric object</returns> public virtual object BuildFromBytes(byte[] bytes) { if (bytes.Length != GetBytesAllocated) { throw new ArgumentException( "To build from a byte array, I need an array of size: " + GetBytesAllocated); } return BuildFromBytes2(bytes); } /// <summary> /// Gets a byte array from a numeric object. /// </summary> /// <param name="val">The numeric object to convert into a byte array.</param> public abstract byte[] GetByteArray(object val); /// <summary> /// Gets the type of numeric object that this byte storage represents /// </summary> public virtual Type GetStorageType { get { return typeof(T); } } /// <summary> /// Builds a numeric object from a byte array. /// </summary> /// <param name="bytes">A byte array containing the data.</param> /// <returns>A numeric object</returns> protected abstract object BuildFromBytes2(byte[] bytes); #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using bv.common.Core; using eidss.model.AVR.Db; using eidss.model.Resources; using Trace = bv.common.Trace; namespace eidss.avr.db.DBService.Access { public class AccessDataAdapter { private readonly string m_DBFileName; private readonly string m_ConnectionString; //Important!! //As I found OleDbCommand and OleDbDataReader don't release resources after it's using. //Each OleDbCommand must be disposed exlicitly //Each OleDbDataReader must be closed and disposed exlicitly public AccessDataAdapter(string dbFileName) { WindowsLogHelper.WriteToEventLogWindows("Creating DataAdapter for MS Access", EventLogEntryType.Information); //Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter(): Creating DataAdapter for MS Access."); //Utils.CheckNotNullOrEmpty(dbFileName, "dbFileName"); m_DBFileName = dbFileName; m_ConnectionString = ComposeConnectionString(dbFileName); WindowsLogHelper.WriteToEventLogWindows(String.Format("Connection String = {0}", m_ConnectionString), EventLogEntryType.Information); if (!File.Exists(dbFileName)) { throw new ArgumentException(string.Format("File '{0}' not found.", dbFileName)); } try { using (var connection = new OleDbConnection(m_ConnectionString)) { WindowsLogHelper.WriteToEventLogWindows("Testing MS Access connection with connectionstring", EventLogEntryType.Information); Trace.WriteLine(Trace.Kind.Undefine, "AccessDataAdapter(): Testing MS Access connection with connectionstring.", m_ConnectionString); connection.Open(); connection.Close(); } } catch (Exception ex) { string errStr = String.Format(EidssMessages.Get("msgCannotConnectToAccess"), m_DBFileName); WindowsLogHelper.WriteToEventLogWindows(errStr, EventLogEntryType.Error); Trace.WriteLine(ex); throw new AvrDbException(errStr, ex); } } public static void QueryLineListToAccess(string fileName, DataTable originalTable, bool shouldModifyOriginalTable = true) { var adapter = new AccessDataAdapter(fileName); adapter.ExportTableToAccess(originalTable, shouldModifyOriginalTable); } internal string ComposeConnectionString(string dbFileName) { return string.Format("Data Source={0}; Provider=Microsoft.ACE.OLEDB.12.0;", dbFileName); } internal string DbFileName { get { return m_DBFileName; } } internal bool IsTableExistInAccess(string tableName) { Utils.CheckNotNullOrEmpty(tableName, "tableName"); Trace.WriteLine(Trace.Kind.Undefine, "AccessDataAdapter.IsTableExistInAccess(): Checking is table '{0}' exists.", tableName); using (var connection = new OleDbConnection(m_ConnectionString)) { connection.Open(); bool isTableExist = IsTableExist(connection, null, tableName); connection.Close(); return isTableExist; } } internal void ExportTableToAccess(DataTable originalTable, bool shouldModifyOriginalTable) { WindowsLogHelper.WriteToEventLogWindows("Start ExportTableToAccess", EventLogEntryType.Information); Utils.CheckNotNull(originalTable, "originalTable"); string mess = String.Format("AccessDataAdapter().ExportTableToAccess: Exporting table '{0}' to MS Access Database '{1}'.", originalTable.TableName, m_DBFileName); WindowsLogHelper.WriteToEventLogWindows(mess, EventLogEntryType.Information); Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter().ExportTableToAccess: Exporting table '{0}' to MS Access Database '{1}'.", originalTable.TableName, m_DBFileName); DataTable dataTable = ConvertTable(originalTable, shouldModifyOriginalTable); using (var connection = new OleDbConnection(m_ConnectionString)) { connection.Open(); OleDbTransaction transaction = connection.BeginTransaction(); try { DropTableIfExists(connection, transaction, dataTable.TableName); CreateTable(connection, transaction, dataTable); InsertData(connection, transaction, dataTable); transaction.Commit(); } catch (Exception ex) { Trace.WriteLine(ex); transaction.Rollback(); throw new AvrDbException(EidssMessages.Get("msgCannotExportToAccess"), ex); } finally { connection.Close(); //Important!! //Release connection pool here. In other case IIS may lock mdb file for downloading //I didn't find how to do this better Thread.Sleep(500); OleDbConnection.ReleaseObjectPool(); GC.WaitForPendingFinalizers(); GC.Collect(); } } } internal static DataTable ConvertTable(DataTable originalTable, bool shouldModifyOriginalTable) { Utils.CheckNotNull(originalTable, "originalTable"); if (originalTable.Columns.Count == 0) { throw new AvrDbException("Eporting table has no columns"); } DataTable dataTable = shouldModifyOriginalTable ? originalTable : originalTable.Copy(); if (string.IsNullOrEmpty(dataTable.TableName)) { dataTable.TableName = "NO_NAME"; } dataTable.TableName = AccessTypeConverter.ConvertName(dataTable.TableName); var captions = new Dictionary<string, int>(); foreach (DataColumn column in dataTable.Columns) { string caption = AccessTypeConverter.ConvertName(column.Caption); column.Caption = caption; if (captions.ContainsKey(caption)) { captions[caption] ++; } else { captions.Add(caption, 1); } } foreach (DataColumn column in dataTable.Columns) { string newName = column.Caption; if (captions[newName] > 1) { int matches = 1; for (int index = 0; index < column.Ordinal; index++) { if (dataTable.Columns[index].Caption == newName) { matches++; } } newName += matches.ToString(); } column.ColumnName = newName; } return dataTable; } internal static bool IsTableExist(OleDbConnection connection, OleDbTransaction transaction, string tableName) { Utils.CheckNotNull(connection, "connection"); Utils.CheckNotNullOrEmpty(tableName, "tableName"); DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] {null, null, null, "TABLE"}); var dataView = new DataView(schemaTable) { RowFilter = string.Format("TABLE_NAME = '{0}'", tableName) }; return dataView.Count > 0; } internal static void DropTableIfExists (OleDbConnection connection, OleDbTransaction transaction, string tableName) { Utils.CheckNotNull(connection, "connection"); Utils.CheckNotNullOrEmpty(tableName, "tableName"); bool isTableExists = IsTableExist(connection, transaction, tableName); if (isTableExists) { Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter.DropTableIfExists: Dropping table '{0}'.", tableName); using (OleDbCommand command = connection.CreateCommand()) { command.Transaction = transaction; command.CommandText = string.Format("DROP TABLE {0}", tableName); command.ExecuteNonQuery(); } } } internal static void CreateTable(OleDbConnection connection, OleDbTransaction transaction, DataTable table) { Utils.CheckNotNull(connection, "connection"); Utils.CheckNotNull(table, "table"); Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter.CreateTable: Creating table '{0}'.", table.TableName); using (OleDbCommand command = connection.CreateCommand()) { command.Transaction = transaction; command.CommandText = CreateTableCommandText(table); command.ExecuteNonQuery(); } } internal static void InsertData(OleDbConnection connection, OleDbTransaction transaction, DataTable table) { Utils.CheckNotNull(connection, "connection"); Utils.CheckNotNull(table, "table"); Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter.InsertData: Inserting data into table '{0}'.", table.TableName); bool isTableExists = IsTableExist(connection, transaction, table.TableName); if (!isTableExists) { throw new ApplicationException(string.Format("Table {0} doesn't exist", table.TableName)); } using (var adapter = new OleDbDataAdapter()) { adapter.SelectCommand = new OleDbCommand(SelectCommandText(table), connection) {Transaction = transaction}; adapter.InsertCommand = new OleDbCommand(InsertCommandText(table), connection) {Transaction = transaction}; foreach (DataColumn column in table.Columns) { OleDbType dbType = AccessTypeConverter.ConverTypeToDb(column); OleDbParameter dbParameter = adapter.InsertCommand.Parameters.Add("@" + column.ColumnName, dbType); dbParameter.SourceColumn = column.ColumnName; } var rowList = new List<DataRow>(); foreach (DataRow row in table.Rows) { if (row.RowState == DataRowState.Unchanged) { row.SetAdded(); } rowList.Add(row); } adapter.Update(rowList.ToArray()); adapter.SelectCommand.Dispose(); adapter.InsertCommand.Dispose(); } } #region command text internal static string CreateTableCommandText(DataTable table) { Utils.CheckNotNull(table, "table"); Utils.CheckNotNullOrEmpty(table.TableName, "table.TableName"); var sbCreate = new StringBuilder(@"CREATE TABLE ["); sbCreate.Append(table.TableName); sbCreate.AppendLine("]("); bool isFirstColumn = true; foreach (DataColumn column in table.Columns) { if (!isFirstColumn) { sbCreate.AppendLine(","); } isFirstColumn = false; string dataTypeName = AccessTypeConverter.ConvertTypeToDbName(column); string columnName = column.ColumnName; // if (columnName.Length > 64) // { // columnName = columnName.Substring(0, 60) + Guid.NewGuid().ToString().Substring(0, 4); // } sbCreate.AppendFormat("[{0}] {1}", columnName, dataTypeName); } sbCreate.AppendLine(); sbCreate.Append(")"); return sbCreate.ToString(); } internal static string SelectCommandText(DataTable table) { Utils.CheckNotNull(table, "table"); Utils.CheckNotNullOrEmpty(table.TableName, "table.TableName"); var sbCreate = new StringBuilder(@"SELECT "); sbCreate.AppendLine(); bool isFirstColumn = true; foreach (DataColumn column in table.Columns) { if (!isFirstColumn) { sbCreate.AppendLine(","); } isFirstColumn = false; sbCreate.AppendFormat("[{0}]", column.ColumnName); } sbCreate.AppendLine(); sbCreate.AppendFormat("FROM [{0}]", table.TableName); return sbCreate.ToString(); } internal static string InsertCommandText(DataTable table) { Utils.CheckNotNull(table, "table"); Utils.CheckNotNullOrEmpty(table.TableName, "table.TableName"); var sbCreate = new StringBuilder(string.Format(@"INSERT INTO [{0}] ", table.TableName)); sbCreate.AppendLine("("); bool isFirstColumn = true; foreach (DataColumn column in table.Columns) { if (!isFirstColumn) { sbCreate.AppendLine(", "); } isFirstColumn = false; sbCreate.AppendFormat("[{0}]", column.ColumnName); } sbCreate.AppendLine(")"); sbCreate.AppendLine("Values("); for (int i = 0; i < table.Columns.Count; i++) { if (i > 0) { sbCreate.Append(", "); } sbCreate.Append("?"); } sbCreate.Append(")"); return sbCreate.ToString(); } #endregion } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing.Design; using System.Windows.Forms.Design; using System.Windows.Forms.ComponentModel; namespace SoftLogik.Win { namespace UI { [Designer(typeof(SPRadioButtonListDesigner))][ToolboxBitmap(typeof(SPRadioButtonListDesigner))][DefaultEvent("SelectedIndexChanged")]public partial class SPRadioButtonList { public enum RadioLayoutStyles { @Horizontal, @Vertical, @Table } public delegate void SelectedIndexChangedEventHandler(object sender, System.EventArgs e); private SelectedIndexChangedEventHandler SelectedIndexChangedEvent; public event SelectedIndexChangedEventHandler SelectedIndexChanged { add { SelectedIndexChangedEvent = (SelectedIndexChangedEventHandler) System.Delegate.Combine(SelectedIndexChangedEvent, value); } remove { SelectedIndexChangedEvent = (SelectedIndexChangedEventHandler) System.Delegate.Remove(SelectedIndexChangedEvent, value); } } private SPRadioButtonItemCollection _RadioList = new SPRadioButtonItemCollection(); private RadioLayoutStyles _radioLayoutStyle; private int _SelectedIndex = - 1; private object _SelectedValue = null; #region Overrides protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); try { this.RadioGroupBox.Text = this.Text; BuildRadioTable(); } catch (Exception) { } } protected void OnCheckedChanged(System.Object sender, System.EventArgs e) { } #endregion #region Properties [Category("Behavior")][Description("Gets or Sets the Radio Buttons Layout Style")]public RadioLayoutStyles LayoutStyle { get { return _radioLayoutStyle; } set { _radioLayoutStyle = value; } } [Category("Behavior"), Browsable(true), EditorAttribute(typeof(SPRadioButtonListItemsEditor), typeof(System.Drawing.Design.UITypeEditor))]public SPRadioButtonItemCollection Items { get { return this._RadioList; } set { this._RadioList = value; BuildRadioTable(); } } #endregion #region Methods public void Add(string Name, string Text, bool Selected) { this._RadioList.Add(new SPRadioButtonItem(Name, Text, Selected)); } public void Remove(string Name) { this._RadioList.Remove(this._RadioList[Name]); } #endregion #region Data Binding private CurrencyManager m_currencyManager = null; private string m_ValueMember; private string m_DisplayMember; private object m_oDataSource; [Category("Data")]public object DataSource { get { return m_oDataSource; } set { if (value == null) { this.m_currencyManager = null; this.Controls.Clear(); } else { if (!(value is IList|| m_oDataSource is IListSource)) { throw (new System.Exception("Invalid DataSource")); } else { if (value is IListSource) { IListSource myListSource = (IListSource) value; if (myListSource.ContainsListCollection == true) { throw (new System.Exception("Invalid DataSource")); } } this.m_oDataSource = value; this.m_currencyManager = (CurrencyManager) (this.BindingContext[value]); BuildRadioTable(); } } } } // end of DataSource property [Category("Data")]public string ValueMember { get { return this.m_ValueMember; } set { this.m_ValueMember = value; } } [Category("Data")]public string DisplayMember { get { return this.m_DisplayMember; } set { this.m_DisplayMember = value; } } public object GetValue(int index) { IList innerList = this.m_currencyManager.List; if (innerList != null) { if ((this.ValueMember != "") && (index >= 0 && 0 < innerList.Count)) { PropertyDescriptor pdValueMember; pdValueMember = this.m_currencyManager.GetItemProperties()[this.ValueMember]; return pdValueMember.GetValue(innerList[index]); } } return null; } public object GetDisplay(int index) { IList innerList = this.m_currencyManager.List; if (innerList != null) { if ((this.DisplayMember != "") && (index >= 0 && 0 < innerList.Count)) { PropertyDescriptor pdDisplayMember; pdDisplayMember = this.m_currencyManager.GetItemProperties()[this.ValueMember]; return pdDisplayMember.GetValue(innerList[index]); } } return null; } #endregion #region Building the Radio Button List public void BuildRadioTable() { TableLayoutPanel radioTable = this.RadioTableLayout; radioTable.Controls.Clear(); radioTable.RowStyles.Clear(); radioTable.ColumnStyles.Clear(); radioTable.RowStyles.Add(new RowStyle(SizeType.AutoSize)); radioTable.ColumnStyles.Add(new ColumnStyle(SizeType.AutoSize)); switch (this._radioLayoutStyle) { case RadioLayoutStyles.Horizontal: radioTable.ColumnCount = 1; radioTable.RowCount = this._RadioList.Count; break; case RadioLayoutStyles.Vertical: radioTable.ColumnCount = this._RadioList.Count; radioTable.RowCount = 1; break; case RadioLayoutStyles.Table: radioTable.ColumnCount = (this._RadioList.Count) / 2; radioTable.RowCount = radioTable.ColumnCount; break; } SPRadioButtonItem[,] tempItems = ArrangeItems(radioTable.RowCount, radioTable.ColumnCount); // Fill in the TableLayoutPanel. FillTable(tempItems, radioTable.RowCount, radioTable.ColumnCount, this.RadioTableLayout); } private SPRadioButtonItem[,] ArrangeItems(int rows, int cols) { // Return array of RadioButtonItem instances that matches // the layout of the control: SPRadioButtonItem[,] items = new SPRadioButtonItem[cols, rows]; // Fill in the items array: int currentItem = 0; for (int col = 0; col <= cols - 1; col++) { for (int row = 0; row <= rows - 1; row++) { if (currentItem < this._RadioList.Count) { items[col, row] = this._RadioList[currentItem]; currentItem++; } } } return items; } private void FillTable(SPRadioButtonItem[,] items, int rows, int cols, TableLayoutPanel tbl) { for (int col = 0; col <= cols - 1; col++) { for (int row = 0; row <= rows - 1; row++) { SPRadioButtonItem radioItem = items[col, row]; if (radioItem != null) { if (! string.IsNullOrEmpty(radioItem.Name)) { RadioButton btn = new RadioButton(); btn.Name = radioItem.Name; btn.Text = radioItem.Text; btn.Dock = DockStyle.Fill; btn.CheckedChanged += new System.EventHandler(OnCheckedChanged); tbl.Controls.Add(btn, col, row); } } } } } #endregion } public class SPRadioButtonItemCollection : List<SPRadioButtonItem> { public SPRadioButtonItem this[string Name] { get { for (int cnt = 0; cnt <= this.Count - 1; cnt++) { if (this[cnt].Name == Name) { return this[cnt]; } } return null; } } } public class SPRadioButtonItem { private string _Name = string.Empty; private bool _Checked = false; private int _ID = - 1; private string _Text = string.Empty; public string Name { get { return _Name; } set { _Name = value; } } public string Text { get { return _Text; } set { _Text = value; } } public bool Checked { get { return _Checked; } set { _Checked = value; } } internal SPRadioButtonItem() { } internal SPRadioButtonItem(string Name, string Text, bool Checked) { this.Name = Name; this.Text = Text; this.Checked = @Checked; } } #region Designer Extensions [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]public class SPRadioButtonListDesigner : System.Windows.Forms.Design.ControlDesigner { private DesignerActionListCollection lists; //Use pull model to populate smart tag menu. public override DesignerActionListCollection ActionLists { get { if (lists == null) { lists = new DesignerActionListCollection(); lists.Add(new SPRadioButtonListActionList(this.Component)); } return lists; } } } ///////////////////////////////////////////////////////////////// //DesignerActionList-derived class defines smart tag entries and // resultant actions. ///////////////////////////////////////////////////////////////// public class SPRadioButtonListActionList : System.ComponentModel.Design.DesignerActionList { private SPRadioButtonList taskView; private DockStyle m_enmDockStyle = DockStyle.None; private DesignerActionUIService designerActionUISvc = null; //The constructor associates the control //with the smart tag list. public SPRadioButtonListActionList(IComponent component) : base(component) { this.taskView = (SPRadioButtonList) component; // Cache a reference to DesignerActionUIService, so the // DesigneractionList can be refreshed. this.designerActionUISvc = (DesignerActionUIService) (GetService(typeof(DesignerActionUIService))); } //Helper method to retrieve control properties. Use of // GetProperties enables undo and menu updates to work properly. private PropertyDescriptor GetPropertyByName(string propName) { PropertyDescriptor prop; prop = TypeDescriptor.GetProperties(taskView)[propName]; if (prop == null) { throw (new ArgumentException("Matching SPRadioButtonList property not found!", propName)); } else { return prop; } } public DockStyle Dock { get { return taskView.Dock; } set { GetPropertyByName("Dock").SetValue(taskView, value); } } //Method that is target of a DesignerActionMethodItem public void EditItems() { //GetPropertyByName("Dock").SetValue(taskView, DockStyle.Fill) } public void EditColumns() { //GetPropertyByName("Dock").SetValue(taskView, DockStyle.Fill) } public void EditGroups() { //GetPropertyByName("Dock").SetValue(taskView, DockStyle.Fill) } public void ParentDock() { if (Dock == DockStyle.Fill) { GetPropertyByName("Dock").SetValue(taskView, DockStyle.None); } else if (Dock == DockStyle.None) { GetPropertyByName("Dock").SetValue(taskView, DockStyle.Fill); } } //Implementation of this virtual method creates smart tag // items, associates their targets, and collects into list. public override DesignerActionItemCollection GetSortedActionItems() { DesignerActionItemCollection items = new DesignerActionItemCollection(); //Define static section header entries. //items.Add(New DesignerActionHeaderItem("-")) items.Add(new DesignerActionHeaderItem("")); //items.Add(New DesignerActionMethodItem( _ //Me, "EditItems", _ //"Edit Items", _ //" ", _ //"Opens the Items Collection Editor")) //items.Add(New DesignerActionMethodItem( _ //Me, "EditColumns", _ //"Edit Columns", _ //" ", _ //"Opens the Columns Collection Editor")) //items.Add(New DesignerActionMethodItem( _ //Me, "EditGroups", _ //"Edit Groups", _ //" ", _ //"Opens the Groups Collection Editor")) if (Dock == DockStyle.None) { items.Add(new DesignerActionMethodItem(this, "ParentDock", "Dock in parent Container", "", "Dock in Parent Container")); } else if (Dock == DockStyle.Fill) { items.Add(new DesignerActionMethodItem(this, "ParentDock", "Undock from parent container", "", "Undock in Parent Container")); } return items; } } [System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]public class SPRadioButtonListItemsEditor : UITypeEditor { private IWindowsFormsEditorService editorService; public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { if ((context != null) && (context.Instance != null) && (provider != null)) { editorService = (IWindowsFormsEditorService) (provider.GetService(typeof(IWindowsFormsEditorService))); if (editorService != null) { SPRadioButtonListEditorUI selectionControl = new SPRadioButtonListEditorUI(((SPRadioButtonItemCollection) value), editorService); editorService.ShowDialog(selectionControl); value = selectionControl.RadioItems; } } return value; } public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) { if ((context != null) && (context.Instance != null)) { return UITypeEditorEditStyle.Modal; } return base.GetEditStyle(context); } } #endregion } }
// snippet-sourcedescription:[ ] // snippet-service:[dynamodb] // snippet-keyword:[dotNET] // snippet-keyword:[Amazon DynamoDB] // snippet-keyword:[Code Sample] // snippet-keyword:[ ] // snippet-sourcetype:[full-example] // snippet-sourcedate:[ ] // snippet-sourceauthor:[AWS] // snippet-start:[dynamodb.dotNET.CodeExample.LowLevelTableExample] /** * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * This file is licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. A copy of * the License is located at * * http://aws.amazon.com/apache2.0/ * * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using Amazon.DynamoDBv2; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; namespace com.amazonaws.codesamples { class LowLevelTableExample { private static AmazonDynamoDBClient client = new AmazonDynamoDBClient(); private static string tableName = "ExampleTable"; static void Main(string[] args) { try { CreateExampleTable(); ListMyTables(); GetTableInformation(); UpdateExampleTable(); DeleteExampleTable(); Console.WriteLine("To continue, press Enter"); Console.ReadLine(); } catch (AmazonDynamoDBException e) { Console.WriteLine(e.Message); } catch (AmazonServiceException e) { Console.WriteLine(e.Message); } catch (Exception e) { Console.WriteLine(e.Message); } } private static void CreateExampleTable() { Console.WriteLine("\n*** Creating table ***"); var request = new CreateTableRequest { AttributeDefinitions = new List<AttributeDefinition>() { new AttributeDefinition { AttributeName = "Id", AttributeType = "N" }, new AttributeDefinition { AttributeName = "ReplyDateTime", AttributeType = "N" } }, KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Id", KeyType = "HASH" //Partition key }, new KeySchemaElement { AttributeName = "ReplyDateTime", KeyType = "RANGE" //Sort key } }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 5, WriteCapacityUnits = 6 }, TableName = tableName }; var response = client.CreateTable(request); var tableDescription = response.TableDescription; Console.WriteLine("{1}: {0} \t ReadsPerSec: {2} \t WritesPerSec: {3}", tableDescription.TableStatus, tableDescription.TableName, tableDescription.ProvisionedThroughput.ReadCapacityUnits, tableDescription.ProvisionedThroughput.WriteCapacityUnits); string status = tableDescription.TableStatus; Console.WriteLine(tableName + " - " + status); WaitUntilTableReady(tableName); } private static void ListMyTables() { Console.WriteLine("\n*** listing tables ***"); string lastTableNameEvaluated = null; do { var request = new ListTablesRequest { Limit = 2, ExclusiveStartTableName = lastTableNameEvaluated }; var response = client.ListTables(request); foreach (string name in response.TableNames) Console.WriteLine(name); lastTableNameEvaluated = response.LastEvaluatedTableName; } while (lastTableNameEvaluated != null); } private static void GetTableInformation() { Console.WriteLine("\n*** Retrieving table information ***"); var request = new DescribeTableRequest { TableName = tableName }; var response = client.DescribeTable(request); TableDescription description = response.Table; Console.WriteLine("Name: {0}", description.TableName); Console.WriteLine("# of items: {0}", description.ItemCount); Console.WriteLine("Provision Throughput (reads/sec): {0}", description.ProvisionedThroughput.ReadCapacityUnits); Console.WriteLine("Provision Throughput (writes/sec): {0}", description.ProvisionedThroughput.WriteCapacityUnits); } private static void UpdateExampleTable() { Console.WriteLine("\n*** Updating table ***"); var request = new UpdateTableRequest() { TableName = tableName, ProvisionedThroughput = new ProvisionedThroughput() { ReadCapacityUnits = 6, WriteCapacityUnits = 7 } }; var response = client.UpdateTable(request); WaitUntilTableReady(tableName); } private static void DeleteExampleTable() { Console.WriteLine("\n*** Deleting table ***"); var request = new DeleteTableRequest { TableName = tableName }; var response = client.DeleteTable(request); Console.WriteLine("Table is being deleted..."); } private static void WaitUntilTableReady(string tableName) { string status = null; // Let us wait until table is created. Call DescribeTable. do { System.Threading.Thread.Sleep(5000); // Wait 5 seconds. try { var res = client.DescribeTable(new DescribeTableRequest { TableName = tableName }); Console.WriteLine("Table name: {0}, status: {1}", res.Table.TableName, res.Table.TableStatus); status = res.Table.TableStatus; } catch (ResourceNotFoundException) { // DescribeTable is eventually consistent. So you might // get resource not found. So we handle the potential exception. } } while (status != "ACTIVE"); } } } // snippet-end:[dynamodb.dotNET.CodeExample.LowLevelTableExample]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; internal static partial class Interop { internal static partial class procfs { internal const string RootPath = "/proc/"; private const string ExeFileName = "/exe"; private const string StatFileName = "/stat"; private const string MapsFileName = "/maps"; private const string FileDescriptorDirectoryName = "/fd/"; private const string TaskDirectoryName = "/task/"; internal const string SelfExeFilePath = RootPath + "self" + ExeFileName; internal const string ProcStatFilePath = RootPath + "stat"; internal struct ParsedStat { // Commented out fields are available in the stat data file but // are currently not used. If/when needed, they can be uncommented, // and the corresponding entry can be added back to StatParser, replacing // the MoveNext() with the appropriate ParseNext* call and assignment. internal int pid; internal string comm; internal char state; internal int ppid; //internal int pgrp; internal int session; //internal int tty_nr; //internal int tpgid; //internal uint flags; //internal ulong minflt; //internal ulong cminflt; //internal ulong majflt; //internal ulong cmajflt; internal ulong utime; internal ulong stime; //internal long cutime; //internal long cstime; //internal long priority; internal long nice; //internal long num_threads; //internal long itrealvalue; internal ulong starttime; internal ulong vsize; internal long rss; internal ulong rsslim; //internal ulong startcode; //internal ulong endcode; //internal ulong startstack; //internal ulong kstkesp; //internal ulong kstkeip; //internal ulong signal; //internal ulong blocked; //internal ulong sigignore; //internal ulong sigcatch; //internal ulong wchan; //internal ulong nswap; //internal ulong cnswap; //internal int exit_signal; //internal int processor; //internal uint rt_priority; //internal uint policy; //internal ulong delayacct_blkio_ticks; //internal ulong guest_time; //internal long cguest_time; } internal struct ParsedMapsModule { internal string FileName; internal KeyValuePair<long, long> AddressRange; } internal static string GetExeFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + ExeFileName; } internal static string GetStatFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + StatFileName; } internal static string GetMapsFilePathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + MapsFileName; } internal static string GetTaskDirectoryPathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + TaskDirectoryName; } internal static string GetFileDescriptorDirectoryPathForProcess(int pid) { return RootPath + pid.ToString(CultureInfo.InvariantCulture) + FileDescriptorDirectoryName; } internal static IEnumerable<ParsedMapsModule> ParseMapsModules(int pid) { try { return ParseMapsModulesCore(File.ReadLines(GetMapsFilePathForProcess(pid))); } catch (IOException) { } catch (UnauthorizedAccessException) { } return Array.Empty<ParsedMapsModule>(); } private static IEnumerable<ParsedMapsModule> ParseMapsModulesCore(IEnumerable<string> lines) { Debug.Assert(lines != null); // Parse each line from the maps file into a ParsedMapsModule result foreach (string line in lines) { // Use a StringParser to avoid string.Split costs var parser = new StringParser(line, separator: ' ', skipEmpty: true); // Parse the address range KeyValuePair<long, long> addressRange = parser.ParseRaw(delegate (string s, ref int start, ref int end) { long startingAddress = 0, endingAddress = 0; int pos = s.IndexOf('-', start, end - start); if (pos > 0) { if (long.TryParse(s.AsSpan(start, pos), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out startingAddress)) { long.TryParse(s.AsSpan(pos + 1, end - (pos + 1)), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out endingAddress); } } return new KeyValuePair<long, long>(startingAddress, endingAddress); }); // Parse the permissions (we only care about entries with 'r' and 'x' set) if (!parser.ParseRaw(delegate (string s, ref int start, ref int end) { bool sawRead = false, sawExec = false; for (int i = start; i < end; i++) { if (s[i] == 'r') sawRead = true; else if (s[i] == 'x') sawExec = true; } return sawRead & sawExec; })) { continue; } // Skip past the offset, dev, and inode fields parser.MoveNext(); parser.MoveNext(); parser.MoveNext(); // Parse the pathname if (!parser.MoveNext()) { continue; } string pathname = parser.ExtractCurrentToEnd(); // We only get here if a we have a non-empty pathname and // the permissions included both readability and executability. // Yield the result. yield return new ParsedMapsModule { FileName = pathname, AddressRange = addressRange }; } } private static string GetStatFilePathForThread(int pid, int tid) { // Perf note: Calling GetTaskDirectoryPathForProcess will allocate a string, // which we then use in another Concat call to produce another string. The straightforward alternative, // though, since we have five input strings, is to use the string.Concat overload that takes a params array. // This results in allocating not only the params array but also a defensive copy inside of Concat, // which means allocating two five-element arrays. This two-string approach will result not only in fewer // allocations, but also typically in less memory allocated, and it's a bit more maintainable. return GetTaskDirectoryPathForProcess(pid) + tid.ToString(CultureInfo.InvariantCulture) + StatFileName; } internal static bool TryReadStatFile(int pid, out ParsedStat result, ReusableTextReader reusableReader) { bool b = TryParseStatFile(GetStatFilePathForProcess(pid), out result, reusableReader); Debug.Assert(!b || result.pid == pid, "Expected process ID from stat file to match supplied pid"); return b; } internal static bool TryReadStatFile(int pid, int tid, out ParsedStat result, ReusableTextReader reusableReader) { bool b = TryParseStatFile(GetStatFilePathForThread(pid, tid), out result, reusableReader); // // This assert currently fails in the Windows Subsystem For Linux. See https://github.com/Microsoft/BashOnWindows/issues/967. // //Debug.Assert(!b || result.pid == tid, "Expected thread ID from stat file to match supplied tid"); return b; } internal static bool TryParseStatFile(string statFilePath, out ParsedStat result, ReusableTextReader reusableReader) { string statFileContents; try { using (var source = new FileStream(statFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1, useAsync: false)) { statFileContents = reusableReader.ReadAllText(source); } } catch (IOException) { // Between the time that we get an ID and the time that we try to read the associated stat // file(s), the process could be gone. result = default(ParsedStat); return false; } var parser = new StringParser(statFileContents, ' '); var results = default(ParsedStat); results.pid = parser.ParseNextInt32(); results.comm = parser.MoveAndExtractNextInOuterParens(); results.state = parser.ParseNextChar(); results.ppid = parser.ParseNextInt32(); parser.MoveNextOrFail(); // pgrp results.session = parser.ParseNextInt32(); parser.MoveNextOrFail(); // tty_nr parser.MoveNextOrFail(); // tpgid parser.MoveNextOrFail(); // flags parser.MoveNextOrFail(); // majflt parser.MoveNextOrFail(); // cmagflt parser.MoveNextOrFail(); // minflt parser.MoveNextOrFail(); // cminflt results.utime = parser.ParseNextUInt64(); results.stime = parser.ParseNextUInt64(); parser.MoveNextOrFail(); // cutime parser.MoveNextOrFail(); // cstime parser.MoveNextOrFail(); // priority results.nice = parser.ParseNextInt64(); parser.MoveNextOrFail(); // num_threads parser.MoveNextOrFail(); // itrealvalue results.starttime = parser.ParseNextUInt64(); results.vsize = parser.ParseNextUInt64(); results.rss = parser.ParseNextInt64(); results.rsslim = parser.ParseNextUInt64(); // The following lines are commented out as there's no need to parse through // the rest of the entry (we've gotten all of the data we need). Should any // of these fields be needed in the future, uncomment all of the lines up // through and including the one that's needed. For now, these are being left // commented to document what's available in the remainder of the entry. //parser.MoveNextOrFail(); // startcode //parser.MoveNextOrFail(); // endcode //parser.MoveNextOrFail(); // startstack //parser.MoveNextOrFail(); // kstkesp //parser.MoveNextOrFail(); // kstkeip //parser.MoveNextOrFail(); // signal //parser.MoveNextOrFail(); // blocked //parser.MoveNextOrFail(); // sigignore //parser.MoveNextOrFail(); // sigcatch //parser.MoveNextOrFail(); // wchan //parser.MoveNextOrFail(); // nswap //parser.MoveNextOrFail(); // cnswap //parser.MoveNextOrFail(); // exit_signal //parser.MoveNextOrFail(); // processor //parser.MoveNextOrFail(); // rt_priority //parser.MoveNextOrFail(); // policy //parser.MoveNextOrFail(); // delayacct_blkio_ticks //parser.MoveNextOrFail(); // guest_time //parser.MoveNextOrFail(); // cguest_time result = results; return true; } } }
// 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.Concurrent; using System.Collections.Generic; using System.Diagnostics.Tracing; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; using System.Threading; namespace System.Diagnostics { /// <summary> /// DiagnosticSourceEventSource serves two purposes /// /// 1) It allows debuggers to inject code via Function evaluation. This is the purpose of the /// BreakPointWithDebuggerFuncEval function in the 'OnEventCommand' method. Basically even in /// release code, debuggers can place a breakpoint in this method and then trigger the /// DiagnosticSourceEventSource via ETW. Thus from outside the process you can get a hook that /// is guaranteed to happen BEFORE any DiangosticSource events (if the process is just starting) /// or as soon as possible afterward if it is on attach. /// /// 2) It provides a 'bridge' that allows DiagnosticSource messages to be forwarded to EventListers /// or ETW. You can do this by enabling the Microsoft-Diagnostics-DiagnosticSource with the /// 'Events' keyword (for diagnostics purposes, you should also turn on the 'Messages' keyword. /// /// This EventSource defines a EventSource argument called 'FilterAndPayloadSpecs' that defines /// what DiagnsoticSources to enable and what parts of the payload to serialize into the key-value /// list that will be forwarded to the EventSource. If it is empty, values of properties of the /// diagnostic source payload are dumped as strings (using ToString()) and forwarded to the EventSource. /// For what people think of as serializable object strings, primitives this gives you want you want. /// (the value of the property in string form) for what people think of as non-serializable objects /// (e.g. HttpContext) the ToString() method is typically not defined, so you get the Object.ToString() /// implementation that prints the type name. This is useful since this is the information you need /// (the type of the property) to discover the field names so you can create a transform specification /// that will pick off the properties you desire. /// /// Once you have the particular values you desire, the implicit payload elements are typically not needed /// anymore and you can prefix the Transform specification with a '-' which suppresses the implicit /// transform (you only get the values of the properties you specifically ask for. /// /// Logically a transform specification is simply a fetching specification X.Y.Z along with a name to give /// it in the output (which defaults to the last name in the fetch specification). /// /// The FilterAndPayloadSpecs is one long string with the following structures /// /// * It is a newline separated list of FILTER_AND_PAYLOAD_SPEC /// * a FILTER_AND_PAYLOAD_SPEC can be /// * EVENT_NAME : TRANSFORM_SPECS /// * EMPTY - turns on all sources with implicit payload elements. /// * an EVENTNAME can be /// * DIAGNOSTIC_SOURCE_NAME / DIAGNOSTC_EVENT_NAME @ EVENT_SOURCE_EVENTNAME - give the name as well as the EventSource event to log it under. /// * DIAGNOSTIC_SOURCE_NAME / DIAGNOSTC_EVENT_NAME /// * DIAGNOSTIC_SOURCE_NAME - which wildcards every event in the Diagnostic source or /// * EMPTY - which turns on all sources /// * TRANSFORM_SPEC is a semicolon separated list of TRANSFORM_SPEC, which can be /// * - TRANSFORM_SPEC - the '-' indicates that implicit payload elements should be suppressed /// * VARIABLE_NAME = PROPERTY_SPEC - indicates that a payload element 'VARIABLE_NAME' is created from PROPERTY_SPEC /// * PROPERTY_SPEC - This is a shortcut where VARIABLE_NAME is the LAST property name /// * a PROPERTY_SPEC is basically a list of names separated by '.' /// * PROPERTY_NAME - fetches a property from the DiagnosticSource payload object /// * PROPERTY_NAME . PROPERTY NAME - fetches a sub-property of the object. /// /// Example1: /// /// "BridgeTestSource1/TestEvent1:cls_Point_X=cls.Point.X;cls_Point_Y=cls.Point.Y\r\n" + /// "BridgeTestSource2/TestEvent2:-cls.Url" /// /// This indicates that two events should be turned on, The 'TestEvent1' event in BridgeTestSource1 and the /// 'TestEvent2' in BridgeTestSource2. In the first case, because the transform did not begin with a - /// any primitive type/string of 'TestEvent1's payload will be serialized into the output. In addition if /// there a property of the payload object called 'cls' which in turn has a property 'Point' which in turn /// has a property 'X' then that data is also put in the output with the name cls_Point_X. Similarly /// if cls.Point.Y exists, then that value will also be put in the output with the name cls_Point_Y. /// /// For the 'BridgeTestSource2/TestEvent2' event, because the - was specified NO implicit fields will be /// generated, but if there is a property call 'cls' which has a property 'Url' then that will be placed in /// the output with the name 'Url' (since that was the last property name used and no Variable= clause was /// specified. /// /// Example: /// /// "BridgeTestSource1\r\n" + /// "BridgeTestSource2" /// /// This will enable all events for the BridgeTestSource1 and BridgeTestSource2 sources. Any string/primitive /// properties of any of the events will be serialized into the output. /// /// Example: /// /// "" /// /// This turns on all DiagnosticSources Any string/primitive properties of any of the events will be serialized /// into the output. This is not likely to be a good idea as it will be very verbose, but is useful to quickly /// discover what is available. /// /// /// * How data is logged in the EventSource /// /// By default all data from DiagnosticSources is logged to the DiagnosticEventSouce event called 'Event' /// which has three fields /// /// string SourceName, /// string EventName, /// IEnumerable[KeyValuePair[string, string]] Argument /// /// However to support start-stop activity tracking, there are six other events that can be used /// /// Activity1Start /// Activity1Stop /// Activity2Start /// Activity2Stop /// RecursiveActivity1Start /// RecursiveActivity1Stop /// /// By using the SourceName/EventName@EventSourceName syntax, you can force particular DiagnosticSource events to /// be logged with one of these EventSource events. This is useful because the events above have start-stop semantics /// which means that they create activity IDs that are attached to all logging messages between the start and /// the stop (see https://blogs.msdn.microsoft.com/vancem/2015/09/14/exploring-eventsource-activity-correlation-and-causation-features/) /// /// For example the specification /// /// "MyDiagnosticSource/RequestStart@Activity1Start\r\n" + /// "MyDiagnosticSource/RequestStop@Activity1Stop\r\n" + /// "MyDiagnosticSource/SecurityStart@Activity2Start\r\n" + /// "MyDiagnosticSource/SecurityStop@Activity2Stop\r\n" /// /// Defines that RequestStart will be logged with the EventSource Event Activity1Start (and the corresponding stop) which /// means that all events caused between these two markers will have an activity ID associated with this start event. /// Similarly SecurityStart is mapped to Activity2Start. /// /// Note you can map many DiangosticSource events to the same EventSource Event (e.g. Activity1Start). As long as the /// activities don't nest, you can reuse the same event name (since the payloads have the DiagnosticSource name which can /// disambiguate). However if they nest you need to use another EventSource event because the rules of EventSource /// activities state that a start of the same event terminates any existing activity of the same name. /// /// As its name suggests RecursiveActivity1Start, is marked as recursive and thus can be used when the activity can nest with /// itself. This should not be a 'top most' activity because it is not 'self healing' (if you miss a stop, then the /// activity NEVER ends). /// /// See the DiagnosticSourceEventSourceBridgeTest.cs for more explicit examples of using this bridge. /// </summary> [EventSource(Name = "Microsoft-Diagnostics-DiagnosticSource")] internal class DiagnosticSourceEventSource : EventSource { public static DiagnosticSourceEventSource Logger = new DiagnosticSourceEventSource(); public class Keywords { /// <summary> /// Indicates diagnostics messages from DiagnosticSourceEventSource should be included. /// </summary> public const EventKeywords Messages = (EventKeywords)0x1; /// <summary> /// Indicates that all events from all diagnostic sources should be forwarded to the EventSource using the 'Event' event. /// </summary> public const EventKeywords Events = (EventKeywords)0x2; // Some ETW logic does not support passing arguments to the EventProvider. To get around // this in common cases, we define some keywords that basically stand in for particular common argumnents // That way at least the common cases can be used by everyone (and it also compresses things). // We start these keywords at 0x1000. See below for the values these keywords represent // Because we want all keywords on to still mean 'dump everything by default' we have another keyword // IgnoreShorcutKeywords which must be OFF in order for the shortcuts to work thus the all 1s keyword // still means what you expect. public const EventKeywords IgnoreShortCutKeywords = (EventKeywords)0x0800; public const EventKeywords AspNetCoreHosting = (EventKeywords)0x1000; public const EventKeywords EntityFrameworkCoreCommands = (EventKeywords)0x2000; }; // Setting AspNetCoreHosting is like having this in the FilterAndPayloadSpecs string // It turns on basic hostig events. private readonly string AspNetCoreHostingKeywordValue = "Microsoft.AspNetCore/Microsoft.AspNetCore.Hosting.BeginRequest@Activity1Start:-" + "httpContext.Request.Method;" + "httpContext.Request.Host;" + "httpContext.Request.Path;" + "httpContext.Request.QueryString" + "\n" + "Microsoft.AspNetCore/Microsoft.AspNetCore.Hosting.EndRequest@Activity1Stop:-" + "httpContext.TraceIdentifier;" + "httpContext.Response.StatusCode"; // Setting EntityFrameworkCoreCommands is like having this in the FilterAndPayloadSpecs string // It turns on basic SQL commands. private readonly string EntityFrameworkCoreCommandsKeywordValue = "Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.BeforeExecuteCommand@Activity2Start:-" + "Command.Connection.DataSource;" + "Command.Connection.Database;" + "Command.CommandText" + "\n" + "Microsoft.EntityFrameworkCore/Microsoft.EntityFrameworkCore.AfterExecuteCommand@Activity2Stop:-"; /// <summary> /// Used to send ad-hoc diagnostics to humans. /// </summary> [Event(1, Keywords = Keywords.Messages)] public void Message(string Message) { WriteEvent(1, Message); } #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT /// <summary> /// Events from DiagnosticSource can be forwarded to EventSource using this event. /// </summary> [Event(2, Keywords = Keywords.Events)] private void Event(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(2, SourceName, EventName, Arguments); } #endif /// <summary> /// This is only used on V4.5 systems that don't have the ability to log KeyValuePairs directly. /// It will eventually go away, but we should always reserve the ID for this. /// </summary> [Event(3, Keywords = Keywords.Events)] private void EventJson(string SourceName, string EventName, string ArgmentsJson) { WriteEvent(3, SourceName, EventName, ArgmentsJson); } #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT /// <summary> /// Used to mark the beginning of an activity /// </summary> [Event(4, Keywords = Keywords.Events)] private void Activity1Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(4, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the end of an activity /// </summary> [Event(5, Keywords = Keywords.Events)] private void Activity1Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(5, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the beginning of an activity /// </summary> [Event(6, Keywords = Keywords.Events)] private void Activity2Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(6, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the end of an activity that can be recursive. /// </summary> [Event(7, Keywords = Keywords.Events)] private void Activity2Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(7, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the beginning of an activity /// </summary> [Event(8, Keywords = Keywords.Events, ActivityOptions = EventActivityOptions.Recursive)] private void RecursiveActivity1Start(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(8, SourceName, EventName, Arguments); } /// <summary> /// Used to mark the end of an activity that can be recursive. /// </summary> [Event(9, Keywords = Keywords.Events, ActivityOptions = EventActivityOptions.Recursive)] private void RecursiveActivity1Stop(string SourceName, string EventName, IEnumerable<KeyValuePair<string, string>> Arguments) { WriteEvent(9, SourceName, EventName, Arguments); } #endif /// <summary> /// Fires when a new DiagnosticSource becomes available. /// </summary> /// <param name="SourceName"></param> [Event(10, Keywords = Keywords.Events)] private void NewDiagnosticListener(string SourceName) { WriteEvent(10, SourceName); } #region private #if NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT /// <summary> /// Converts a keyvalue bag to JSON. Only used on V4.5 EventSources. /// </summary> private static string ToJson(IEnumerable<KeyValuePair<string, string>> keyValues) { StringBuilder sb = new StringBuilder(); sb.AppendLine("{"); bool first = true; foreach (var keyValue in keyValues) { if (!first) sb.Append(',').AppendLine(); first = false; sb.Append('"').Append(keyValue.Key).Append("\":\""); // Write out the value characters, escaping things as needed. foreach(var c in keyValue.Value) { if (Char.IsControl(c)) { if (c == '\n') sb.Append("\\n"); else if (c == '\r') sb.Append("\\r"); else sb.Append("\\u").Append(((int)c).ToString("x").PadLeft(4, '0')); } else { if (c == '"' || c == '\\') sb.Append('\\'); sb.Append(c); } } sb.Append('"'); // Close the string. } sb.AppendLine().AppendLine("}"); return sb.ToString(); } #endif #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT /// <summary> /// This constructor uses EventSourceSettings which is only available on V4.6 and above /// systems. We use the EventSourceSettings to turn on support for complex types. /// </summary> private DiagnosticSourceEventSource() : base(EventSourceSettings.EtwSelfDescribingEventFormat) { } #endif /// <summary> /// Called when the EventSource gets a command from a EventListener or ETW. /// </summary> [NonEvent] protected override void OnEventCommand(EventCommandEventArgs command) { // On every command (which the debugger can force by turning on this EventSource with ETW) // call a function that the debugger can hook to do an arbitrary func evaluation. BreakPointWithDebuggerFuncEval(); lock (this) { if ((command.Command == EventCommand.Update || command.Command == EventCommand.Enable) && IsEnabled(EventLevel.Informational, Keywords.Events)) { string filterAndPayloadSpecs; command.Arguments.TryGetValue("FilterAndPayloadSpecs", out filterAndPayloadSpecs); if (!IsEnabled(EventLevel.Informational, Keywords.IgnoreShortCutKeywords)) { if (IsEnabled(EventLevel.Informational, Keywords.AspNetCoreHosting)) filterAndPayloadSpecs = NewLineSeparate(filterAndPayloadSpecs, AspNetCoreHostingKeywordValue); if (IsEnabled(EventLevel.Informational, Keywords.EntityFrameworkCoreCommands)) filterAndPayloadSpecs = NewLineSeparate(filterAndPayloadSpecs, EntityFrameworkCoreCommandsKeywordValue); } FilterAndTransform.CreateFilterAndTransformList(ref _specs, filterAndPayloadSpecs, this); } else if (command.Command == EventCommand.Update || command.Command == EventCommand.Disable) { FilterAndTransform.DestroyFilterAndTransformList(ref _specs); } } } // trivial helper to allow you to join two strings the first of which can be null. private static string NewLineSeparate(string str1, string str2) { Debug.Assert(str2 != null); if (string.IsNullOrEmpty(str1)) return str2; return str1 + "\n" + str2; } #region debugger hooks private volatile bool _false; // A value that is always false but the compiler does not know this. /// <summary> /// A function which is fully interruptible even in release code so we can stop here and /// do function evaluation in the debugger. Thus this is just a place that is useful /// for the debugger to place a breakpoint where it can inject code with function evaluation /// </summary> [NonEvent, MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] private void BreakPointWithDebuggerFuncEval() { new object(); // This is only here because it helps old desktop runtimes emit a GC safe point at the start of the method while (_false) { _false = false; } } #endregion #region EventSource hooks /// <summary> /// FilterAndTransform represents on transformation specification from a DiagnosticsSource /// to EventSource's 'Event' method. (e.g. MySource/MyEvent:out=prop1.prop2.prop3). /// Its main method is 'Morph' which takes a DiagnosticSource object and morphs it into /// a list of string,string key value pairs. /// /// This method also contains that static 'Create/Destroy FilterAndTransformList, which /// simply parse a series of transformation specifications. /// </summary> internal class FilterAndTransform { /// <summary> /// Parses filterAndPayloadSpecs which is a list of lines each of which has the from /// /// DiagnosticSourceName/EventName:PAYLOAD_SPEC /// /// where PAYLOADSPEC is a semicolon separated list of specifications of the form /// /// OutputName=Prop1.Prop2.PropN /// /// Into linked list of FilterAndTransform that together forward events from the given /// DiagnosticSource's to 'eventSource'. Sets the 'specList' variable to this value /// (destroying anything that was there previously). /// /// By default any serializable properties of the payload object are also included /// in the output payload, however this feature and be tuned off by prefixing the /// PAYLOADSPEC with a '-'. /// </summary> public static void CreateFilterAndTransformList(ref FilterAndTransform specList, string filterAndPayloadSpecs, DiagnosticSourceEventSource eventSource) { DestroyFilterAndTransformList(ref specList); // Stop anything that was on before. if (filterAndPayloadSpecs == null) filterAndPayloadSpecs = ""; // Points just beyond the last point in the string that has yet to be parsed. Thus we start with the whole string. int endIdx = filterAndPayloadSpecs.Length; for (;;) { // Skip trailing whitespace. while (0 < endIdx && char.IsWhiteSpace(filterAndPayloadSpecs[endIdx - 1])) --endIdx; int newlineIdx = filterAndPayloadSpecs.LastIndexOf('\n', endIdx - 1, endIdx); int startIdx = 0; if (0 <= newlineIdx) startIdx = newlineIdx + 1; // starts after the newline, or zero if we don't find one. // Skip leading whitespace while (startIdx < endIdx && char.IsWhiteSpace(filterAndPayloadSpecs[startIdx])) startIdx++; specList = new FilterAndTransform(filterAndPayloadSpecs, startIdx, endIdx, eventSource, specList); endIdx = newlineIdx; if (endIdx < 0) break; } } /// <summary> /// This destroys (turns off) the FilterAndTransform stopping the forwarding started with CreateFilterAndTransformList /// </summary> /// <param name="specList"></param> public static void DestroyFilterAndTransformList(ref FilterAndTransform specList) { var curSpec = specList; specList = null; // Null out the list while (curSpec != null) // Dispose everything in the list. { curSpec.Dispose(); curSpec = curSpec.Next; } } /// <summary> /// Creates one FilterAndTransform specification from filterAndPayloadSpec starting at 'startIdx' and ending just before 'endIdx'. /// This FilterAndTransform will subscribe to DiagnosticSources specified by the specification and forward them to 'eventSource. /// For convenience, the 'Next' field is set to the 'next' parameter, so you can easily form linked lists. /// </summary> public FilterAndTransform(string filterAndPayloadSpec, int startIdx, int endIdx, DiagnosticSourceEventSource eventSource, FilterAndTransform next) { #if DEBUG string spec = filterAndPayloadSpec.Substring(startIdx, endIdx - startIdx); #endif Next = next; _eventSource = eventSource; string listenerNameFilter = null; // Means WildCard. string eventNameFilter = null; // Means WildCard. string activityName = null; var startTransformIdx = startIdx; var endEventNameIdx = endIdx; var colonIdx = filterAndPayloadSpec.IndexOf(':', startIdx, endIdx - startIdx); if (0 <= colonIdx) { endEventNameIdx = colonIdx; startTransformIdx = colonIdx + 1; } // Parse the Source/Event name into listenerNameFilter and eventNameFilter var slashIdx = filterAndPayloadSpec.IndexOf('/', startIdx, endEventNameIdx - startIdx); if (0 <= slashIdx) { listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, slashIdx - startIdx); var atIdx = filterAndPayloadSpec.IndexOf('@', slashIdx + 1, endEventNameIdx - slashIdx - 1); if (0 <= atIdx) { activityName = filterAndPayloadSpec.Substring(atIdx + 1, endEventNameIdx - atIdx - 1); eventNameFilter = filterAndPayloadSpec.Substring(slashIdx + 1, atIdx - slashIdx - 1); } else { eventNameFilter = filterAndPayloadSpec.Substring(slashIdx + 1, endEventNameIdx - slashIdx - 1); } } else if (startIdx < endEventNameIdx) { listenerNameFilter = filterAndPayloadSpec.Substring(startIdx, endEventNameIdx - startIdx); } _eventSource.Message("DiagnosticSource: Enabling '" + (listenerNameFilter ?? "*") + "/" + (eventNameFilter ?? "*") + "'"); // If the transform spec begins with a - it means you don't want implicit transforms. if (startTransformIdx < endIdx && filterAndPayloadSpec[startTransformIdx] == '-') { _eventSource.Message("DiagnosticSource: suppressing implicit transforms."); _noImplicitTransforms = true; startTransformIdx++; } // Parse all the explicit transforms, if present if (startTransformIdx < endIdx) { for (;;) { int specStartIdx = startTransformIdx; int semiColonIdx = filterAndPayloadSpec.LastIndexOf(';', endIdx - 1, endIdx - startTransformIdx); if (0 <= semiColonIdx) specStartIdx = semiColonIdx + 1; // Ignore empty specifications. if (specStartIdx < endIdx) { if (_eventSource.IsEnabled(EventLevel.Informational, Keywords.Messages)) _eventSource.Message("DiagnosticSource: Parsing Explicit Transform '" + filterAndPayloadSpec.Substring(specStartIdx, endIdx - specStartIdx) + "'"); _explicitTransforms = new TransformSpec(filterAndPayloadSpec, specStartIdx, endIdx, _explicitTransforms); } if (startTransformIdx == specStartIdx) break; endIdx = semiColonIdx; } } Action<string, string, IEnumerable<KeyValuePair<string, string>>> writeEvent = null; if (activityName != null && activityName.Contains("Activity")) { MethodInfo writeEventMethodInfo = typeof(DiagnosticSourceEventSource).GetTypeInfo().GetDeclaredMethod(activityName); if (writeEventMethodInfo != null) { // This looks up the activityName (which needs to be a name of an event on DiagnosticSourceEventSource // like Activity1Start and returns that method). This allows us to have a number of them and this code // just works. try { writeEvent = (Action<string, string, IEnumerable<KeyValuePair<string, string>>>) writeEventMethodInfo.CreateDelegate(typeof(Action<string, string, IEnumerable<KeyValuePair<string, string>>>), _eventSource); } catch (Exception) { } } if (writeEvent == null) _eventSource.Message("DiagnosticSource: Could not find Event to log Activity " + activityName); } if (writeEvent == null) { #if !NO_EVENTSOURCE_COMPLEX_TYPE_SUPPORT writeEvent = _eventSource.Event; #else writeEvent = delegate (string sourceName, string eventName, IEnumerable<KeyValuePair<string, string>> arguments) { _eventSource.EventJson(sourceName, eventName, ToJson(arguments)); }; #endif } // Set up a subscription that watches for the given Diagnostic Sources and events which will call back // to the EventSource. _diagnosticsListenersSubscription = DiagnosticListener.AllListeners.Subscribe(new CallbackObserver<DiagnosticListener>(delegate (DiagnosticListener newListener) { if (listenerNameFilter == null || listenerNameFilter == newListener.Name) { _eventSource.NewDiagnosticListener(newListener.Name); Predicate<string> eventNameFilterPredicate = null; if (eventNameFilter != null) eventNameFilterPredicate = (string eventName) => eventNameFilter == eventName; var subscription = newListener.Subscribe(new CallbackObserver<KeyValuePair<string, object>>(delegate (KeyValuePair<string, object> evnt) { // The filter given to the DiagnosticSource may not work if users don't is 'IsEnabled' as expected. // Thus we look for any events that may have snuck through and filter them out before forwarding. if (eventNameFilter != null && eventNameFilter != evnt.Key) return; var outputArgs = this.Morph(evnt.Value); var eventName = evnt.Key; writeEvent(newListener.Name, eventName, outputArgs); }), eventNameFilterPredicate); _liveSubscriptions = new Subscriptions(subscription, _liveSubscriptions); } })); } private void Dispose() { if (_diagnosticsListenersSubscription != null) { _diagnosticsListenersSubscription.Dispose(); _diagnosticsListenersSubscription = null; } if (_liveSubscriptions != null) { var subscr = _liveSubscriptions; _liveSubscriptions = null; while (subscr != null) { subscr.Subscription.Dispose(); subscr = subscr.Next; } } } public List<KeyValuePair<string, string>> Morph(object args) { // Transform the args into a bag of key-value strings. var outputArgs = new List<KeyValuePair<string, string>>(); if (args != null) { if (!_noImplicitTransforms) { // given the type, fetch the implicit transforms for that type and put it in the implicitTransforms variable. Type argType = args.GetType(); TransformSpec implicitTransforms; // First check the one-element cache _firstImplicitTransformsEntry ImplicitTransformEntry cacheEntry = _firstImplicitTransformsEntry; if (cacheEntry != null && cacheEntry.Type == argType) { implicitTransforms = cacheEntry.Transforms; // Yeah we hit the cache. } else if (cacheEntry == null) { // _firstImplicitTransformsEntry is empty, we should fill it. // Note that it is OK that two threads may race and both call MakeImplicitTransforms on their own // (that is we don't expect exactly once initialization of _firstImplicitTransformsEntry) implicitTransforms = MakeImplicitTransforms(argType); Interlocked.CompareExchange(ref _firstImplicitTransformsEntry, new ImplicitTransformEntry() { Type = argType, Transforms = implicitTransforms }, null); } else { // This should only happen when you are wildcarding your events (reasonably rare). // In that case you will probably need many types // Note currently we don't limit the cache size, but it is limited by the number of // distinct types of objects passed to DiagnosticSource.Write. if (_implicitTransformsTable == null) { Interlocked.CompareExchange(ref _implicitTransformsTable, new ConcurrentDictionary<Type, TransformSpec>(1, 8), null); } implicitTransforms = _implicitTransformsTable.GetOrAdd(argType, type => MakeImplicitTransforms(type)); } // implicitTransformas now fetched from cache or constructed, use it to Fetch all the implicit fields. if (implicitTransforms != null) { for (TransformSpec serializableArg = implicitTransforms; serializableArg != null; serializableArg = serializableArg.Next) outputArgs.Add(serializableArg.Morph(args)); } } if (_explicitTransforms != null) { for (var explicitTransform = _explicitTransforms; explicitTransform != null; explicitTransform = explicitTransform.Next) { var keyValue = explicitTransform.Morph(args); if (keyValue.Value != null) outputArgs.Add(keyValue); } } } return outputArgs; } public FilterAndTransform Next; #region private // Given a type generate all the the implicit transforms for type (that is for every field // generate the spec that fetches it). private static TransformSpec MakeImplicitTransforms(Type type) { TransformSpec newSerializableArgs = null; TypeInfo curTypeInfo = type.GetTypeInfo(); foreach (PropertyInfo property in curTypeInfo.DeclaredProperties) { Type propertyType = property.PropertyType; newSerializableArgs = new TransformSpec(property.Name, 0, property.Name.Length, newSerializableArgs); } return Reverse(newSerializableArgs); } // Reverses a linked list (of TransformSpecs) in place. private static TransformSpec Reverse(TransformSpec list) { TransformSpec ret = null; while (list != null) { var next = list.Next; list.Next = ret; ret = list; list = next; } return ret; } private IDisposable _diagnosticsListenersSubscription; // This is our subscription that listens for new Diagnostic source to appear. private Subscriptions _liveSubscriptions; // These are the subscriptions that we are currently forwarding to the EventSource. private bool _noImplicitTransforms; // Listener can say they don't want implicit transforms. private ImplicitTransformEntry _firstImplicitTransformsEntry; // The transform for _firstImplicitFieldsType private ConcurrentDictionary<Type, TransformSpec> _implicitTransformsTable; // If there is more than one object type for an implicit transform, they go here. private TransformSpec _explicitTransforms; // payload to include because the user explicitly indicated how to fetch the field. private DiagnosticSourceEventSource _eventSource; // Where the data is written to. #endregion } // This olds one the implicit transform for one type of object. // We remember this type-transform pair in the _firstImplicitTransformsEntry cache. internal class ImplicitTransformEntry { public Type Type; public TransformSpec Transforms; } /// <summary> /// Transform spec represents a string that describes how to extract a piece of data from /// the DiagnosticSource payload. An example string is OUTSTR=EVENT_VALUE.PROP1.PROP2.PROP3 /// It has a Next field so they can be chained together in a linked list. /// </summary> internal class TransformSpec { /// <summary> /// parse the strings 'spec' from startIdx to endIdx (points just beyond the last considered char) /// The syntax is ID1=ID2.ID3.ID4 .... Where ID1= is optional. /// </summary> public TransformSpec(string transformSpec, int startIdx, int endIdx, TransformSpec next = null) { Debug.Assert(transformSpec != null && startIdx < endIdx); #if DEBUG string spec = transformSpec.Substring(startIdx, endIdx - startIdx); #endif Next = next; // Pick off the Var= int equalsIdx = transformSpec.IndexOf('=', startIdx, endIdx - startIdx); if (0 <= equalsIdx) { _outputName = transformSpec.Substring(startIdx, equalsIdx - startIdx); startIdx = equalsIdx + 1; } // Working from back to front, create a PropertySpec for each .ID in the string. while (startIdx < endIdx) { int dotIdx = transformSpec.LastIndexOf('.', endIdx - 1, endIdx - startIdx); int idIdx = startIdx; if (0 <= dotIdx) idIdx = dotIdx + 1; string propertName = transformSpec.Substring(idIdx, endIdx - idIdx); _fetches = new PropertySpec(propertName, _fetches); // If the user did not explicitly set a name, it is the last one (first to be processed from the end). if (_outputName == null) _outputName = propertName; endIdx = dotIdx; // This works even when LastIndexOf return -1. } } /// <summary> /// Given the DiagnosticSourcePayload 'obj', compute a key-value pair from it. For example /// if the spec is OUTSTR=EVENT_VALUE.PROP1.PROP2.PROP3 and the ultimate value of PROP3 is /// 10 then the return key value pair is KeyValuePair("OUTSTR","10") /// </summary> public KeyValuePair<string, string> Morph(object obj) { for (PropertySpec cur = _fetches; cur != null; cur = cur.Next) { if (obj != null) obj = cur.Fetch(obj); } return new KeyValuePair<string, string>(_outputName, obj?.ToString()); } /// <summary> /// A public field that can be used to form a linked list. /// </summary> public TransformSpec Next; #region private /// <summary> /// A PropertySpec represents information needed to fetch a property from /// and efficiently. Thus it represents a '.PROP' in a TransformSpec /// (and a transformSpec has a list of these). /// </summary> internal class PropertySpec { /// <summary> /// Make a new PropertySpec for a property named 'propertyName'. /// For convenience you can set he 'next' field to form a linked /// list of PropertySpecs. /// </summary> public PropertySpec(string propertyName, PropertySpec next = null) { Next = next; _propertyName = propertyName; } /// <summary> /// Given an object fetch the property that this PropertySpec represents. /// </summary> public object Fetch(object obj) { Type objType = obj.GetType(); PropertyFetch fetch = _fetchForExpectedType; if (fetch == null || fetch.Type != objType) { _fetchForExpectedType = fetch = PropertyFetch.FetcherForProperty( objType, objType.GetTypeInfo().GetDeclaredProperty(_propertyName)); } return fetch.Fetch(obj); } /// <summary> /// A public field that can be used to form a linked list. /// </summary> public PropertySpec Next; #region private /// <summary> /// PropertyFetch is a helper class. It takes a PropertyInfo and then knows how /// to efficiently fetch that property from a .NET object (See Fetch method). /// It hides some slightly complex generic code. /// </summary> private class PropertyFetch { protected PropertyFetch(Type type) { Debug.Assert(type != null); Type = type; } internal Type Type { get; } /// <summary> /// Create a property fetcher from a .NET Reflection PropertyInfo class that /// represents a property of a particular type. /// </summary> public static PropertyFetch FetcherForProperty(Type type, PropertyInfo propertyInfo) { if (propertyInfo == null) return new PropertyFetch(type); // returns null on any fetch. var typedPropertyFetcher = typeof(TypedFetchProperty<,>); var instantiatedTypedPropertyFetcher = typedPropertyFetcher.GetTypeInfo().MakeGenericType( propertyInfo.DeclaringType, propertyInfo.PropertyType); return (PropertyFetch)Activator.CreateInstance(instantiatedTypedPropertyFetcher, type, propertyInfo); } /// <summary> /// Given an object, fetch the property that this propertyFech represents. /// </summary> public virtual object Fetch(object obj) { return null; } #region private private sealed class TypedFetchProperty<TObject, TProperty> : PropertyFetch { public TypedFetchProperty(Type type, PropertyInfo property) : base(type) { _propertyFetch = (Func<TObject, TProperty>)property.GetMethod.CreateDelegate(typeof(Func<TObject, TProperty>)); } public override object Fetch(object obj) { return _propertyFetch((TObject)obj); } private readonly Func<TObject, TProperty> _propertyFetch; } #endregion } private string _propertyName; private volatile PropertyFetch _fetchForExpectedType; #endregion } private string _outputName; private PropertySpec _fetches; #endregion } /// <summary> /// CallbackObserver is an adapter class that creates an observer (which you can pass /// to IObservable.Subscribe), and calls the given callback every time the 'next' /// operation on the IObserver happens. /// </summary> /// <typeparam name="T"></typeparam> internal class CallbackObserver<T> : IObserver<T> { public CallbackObserver(Action<T> callback) { _callback = callback; } #region private public void OnCompleted() { } public void OnError(Exception error) { } public void OnNext(T value) { _callback(value); } private Action<T> _callback; #endregion } // A linked list of IObservable subscriptions (which are IDisposable). // We use this to keep track of the DiagnosticSource subscriptions. // We use this linked list for thread atomicity internal class Subscriptions { public Subscriptions(IDisposable subscription, Subscriptions next) { Subscription = subscription; Next = next; } public IDisposable Subscription; public Subscriptions Next; } #endregion private FilterAndTransform _specs; // Transformation specifications that indicate which sources/events are forwarded. #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.AddImport; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Packaging; using Microsoft.CodeAnalysis.SymbolSearch; using Moq; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.AddUsing { using FixProviderData = Tuple<IPackageInstallerService, ISymbolSearchService>; public partial class AddUsingTests { const string NugetOrgSource = "nuget.org"; public class NuGet : AddUsingTests { private static readonly ImmutableArray<PackageSource> NugetPackageSources = ImmutableArray.Create(new PackageSource(NugetOrgSource, "http://nuget.org/")); protected override async Task<TestWorkspace> CreateWorkspaceFromFileAsync(string definition, ParseOptions parseOptions, CompilationOptions compilationOptions) { var workspace = await base.CreateWorkspaceFromFileAsync(definition, parseOptions, compilationOptions); workspace.Options = workspace.Options .WithChangedOption(SymbolSearchOptions.SuggestForTypesInNuGetPackages, LanguageNames.CSharp, true) .WithChangedOption(SymbolSearchOptions.SuggestForTypesInReferenceAssemblies, LanguageNames.CSharp, true); return workspace; } internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer( Workspace workspace, object fixProviderData) { var data = (FixProviderData)fixProviderData; return Tuple.Create<DiagnosticAnalyzer, CodeFixProvider>( null, new CSharpAddImportCodeFixProvider(data.Item1, data.Item2)); } protected override IList<CodeAction> MassageActions(IList<CodeAction> actions) { return FlattenActions(actions); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public async Task TestSearchPackageSingleName() { // Make a loose mock for the installer service. We don't care what this test // calls on it. var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose); installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true); installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources); installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(true); var packageServiceMock = new Mock<ISymbolSearchService>(); packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync( NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>())) .Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); await TestAsync( @"class C { [|NuGetType|] n; }", @"using NuGetNamespace; class C { NuGetType n; }", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public async Task TestSearchPackageMultipleNames() { // Make a loose mock for the installer service. We don't care what this test // calls on it. var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose); installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true); installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources); installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", It.IsAny<string>(), It.IsAny<CancellationToken>())) .Returns(true); var packageServiceMock = new Mock<ISymbolSearchService>(); packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync( NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>())) .Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); await TestAsync( @"class C { [|NuGetType|] n; }", @"using NS1.NS2; class C { NuGetType n; }", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public async Task TestMissingIfPackageAlreadyInstalled() { // Make a loose mock for the installer service. We don't care what this test // calls on it. var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose); installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true); installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources); installerServiceMock.Setup(s => s.IsInstalled(It.IsAny<Workspace>(), It.IsAny<ProjectId>(), "NuGetPackage")) .Returns(true); var packageServiceMock = new Mock<ISymbolSearchService>(); packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync( NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>())) .Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); await TestMissingAsync( @"class C { [|NuGetType|] n; }", fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public async Task TestOptionsOffered() { // Make a loose mock for the installer service. We don't care what this test // calls on it. var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose); installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true); installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources); installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage")) .Returns(ImmutableArray.Create("1.0", "2.0")); var packageServiceMock = new Mock<ISymbolSearchService>(); packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync( NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>())) .Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NS1", "NS2"))); var data = new FixProviderData(installerServiceMock.Object, packageServiceMock.Object); await TestSmartTagTextAsync( @"class C { [|NuGetType|] n; }", "Use local version '1.0'", index: 0, fixProviderData: data); await TestSmartTagTextAsync( @"class C { [|NuGetType|] n; }", "Use local version '2.0'", index: 1, fixProviderData: data); await TestSmartTagTextAsync( @"class C { [|NuGetType|] n; }", "Find and install latest version", index: 2, fixProviderData: data); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public async Task TestInstallGetsCalledNoVersion() { var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose); installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true); installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources); installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", /*versionOpt*/ null, It.IsAny<CancellationToken>())) .Returns(true); var packageServiceMock = new Mock<ISymbolSearchService>(); packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync( NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>())) .Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); await TestAsync( @"class C { [|NuGetType|] n; }", @"using NuGetNamespace; class C { NuGetType n; }", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object)); installerServiceMock.Verify(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public async Task TestInstallGetsCalledWithVersion() { var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose); installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true); installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources); installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage")) .Returns(ImmutableArray.Create("1.0")); installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", "1.0", It.IsAny<CancellationToken>())) .Returns(true); var packageServiceMock = new Mock<ISymbolSearchService>(); packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>())) .Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); await TestAsync( @"class C { [|NuGetType|] n; }", @"using NuGetNamespace; class C { NuGetType n; }", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object)); installerServiceMock.Verify(); } [WorkItem(14516, "https://github.com/dotnet/roslyn/pull/14516")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)] public async Task TestFailedInstallRollsBackFile() { var installerServiceMock = new Mock<IPackageInstallerService>(MockBehavior.Loose); installerServiceMock.SetupGet(i => i.IsEnabled).Returns(true); installerServiceMock.SetupGet(i => i.PackageSources).Returns(NugetPackageSources); installerServiceMock.Setup(s => s.GetInstalledVersions("NuGetPackage")) .Returns(ImmutableArray.Create("1.0")); installerServiceMock.Setup(s => s.TryInstallPackage(It.IsAny<Workspace>(), It.IsAny<DocumentId>(), It.IsAny<string>(), "NuGetPackage", "1.0", It.IsAny<CancellationToken>())) .Returns(false); var packageServiceMock = new Mock<ISymbolSearchService>(); packageServiceMock.Setup(s => s.FindPackagesWithTypeAsync(NugetOrgSource, "NuGetType", 0, It.IsAny<CancellationToken>())) .Returns(CreateSearchResult("NuGetPackage", "NuGetType", CreateNameParts("NuGetNamespace"))); await TestAsync( @"class C { [|NuGetType|] n; }", @"class C { NuGetType n; }", systemSpecialCase: false, fixProviderData: new FixProviderData(installerServiceMock.Object, packageServiceMock.Object)); installerServiceMock.Verify(); } private Task<ImmutableArray<PackageWithTypeResult>> CreateSearchResult( string packageName, string typeName, IReadOnlyList<string> containingNamespaceNames) { return CreateSearchResult(new PackageWithTypeResult( packageName: packageName, typeName: typeName, version: null, rank: 0, containingNamespaceNames: containingNamespaceNames)); } private Task<ImmutableArray<PackageWithTypeResult>> CreateSearchResult(params PackageWithTypeResult[] results) => Task.FromResult(ImmutableArray.Create(results)); private IReadOnlyList<string> CreateNameParts(params string[] parts) => parts; } } }
// 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: Some floating-point math operations ** ** ===========================================================*/ namespace System { //This class contains only static members and doesn't require serialization. using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public static class Math { private static double doubleRoundLimit = 1e16d; private const int maxRoundingDigits = 15; // This table is required for the Round function which can specify the number of digits to round to private static double[] roundPower10Double = new double[] { 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 }; public const double PI = 3.14159265358979323846; public const double E = 2.7182818284590452354; [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Acos(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Asin(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Atan(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Atan2(double y,double x); public static Decimal Ceiling(Decimal d) { return Decimal.Ceiling(d); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Ceiling(double a); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Cos (double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Cosh(double value); public static Decimal Floor(Decimal d) { return Decimal.Floor(d); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Floor(double d); [System.Security.SecuritySafeCritical] // auto-generated private static unsafe double InternalRound(double value, int digits, MidpointRounding mode) { if (Abs(value) < doubleRoundLimit) { Double power10 = roundPower10Double[digits]; value *= power10; if (mode == MidpointRounding.AwayFromZero) { double fraction = SplitFractionDouble(&value); if (Abs(fraction) >= 0.5d) { value += Sign(fraction); } } else { // On X86 this can be inlined to just a few instructions value = Round(value); } value /= power10; } return value; } [System.Security.SecuritySafeCritical] // auto-generated private unsafe static double InternalTruncate(double d) { SplitFractionDouble(&d); return d; } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sin(double a); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Tan(double a); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sinh(double value); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Tanh(double value); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Round(double a); public static double Round(double value, int digits) { if ((digits < 0) || (digits > maxRoundingDigits)) throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); Contract.EndContractBlock(); return InternalRound(value, digits, MidpointRounding.ToEven); } public static double Round(double value, MidpointRounding mode) { return Round(value, 0, mode); } public static double Round(double value, int digits, MidpointRounding mode) { if ((digits < 0) || (digits > maxRoundingDigits)) throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, "MidpointRounding"), "mode"); } Contract.EndContractBlock(); return InternalRound(value, digits, mode); } public static Decimal Round(Decimal d) { return Decimal.Round(d,0); } public static Decimal Round(Decimal d, int decimals) { return Decimal.Round(d,decimals); } public static Decimal Round(Decimal d, MidpointRounding mode) { return Decimal.Round(d, 0, mode); } public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) { return Decimal.Round(d, decimals, mode); } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern double SplitFractionDouble(double* value); public static Decimal Truncate(Decimal d) { return Decimal.Truncate(d); } public static double Truncate(double d) { return InternalTruncate(d); } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sqrt(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Log (double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Log10(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Exp(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Pow(double x, double y); public static double IEEERemainder(double x, double y) { if (Double.IsNaN(x)) { return x; // IEEE 754-2008: NaN payload must be preserved } if (Double.IsNaN(y)) { return y; // IEEE 754-2008: NaN payload must be preserved } double regularMod = x % y; if (Double.IsNaN(regularMod)) { return Double.NaN; } if (regularMod == 0) { if (Double.IsNegative(x)) { return Double.NegativeZero; } } double alternativeResult; alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x)); if (Math.Abs(alternativeResult) == Math.Abs(regularMod)) { double divisionResult = x/y; double roundedResult = Math.Round(divisionResult); if (Math.Abs(roundedResult) > Math.Abs(divisionResult)) { return alternativeResult; } else { return regularMod; } } if (Math.Abs(alternativeResult) < Math.Abs(regularMod)) { return alternativeResult; } else { return regularMod; } } /*================================Abs========================================= **Returns the absolute value of it's argument. ============================================================================*/ [CLSCompliant(false)] public static sbyte Abs(sbyte value) { if (value >= 0) return value; else return AbsHelper(value); } private static sbyte AbsHelper(sbyte value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == SByte.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return ((sbyte)(-value)); } public static short Abs(short value) { if (value >= 0) return value; else return AbsHelper(value); } private static short AbsHelper(short value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int16.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return (short) -value; } public static int Abs(int value) { if (value >= 0) return value; else return AbsHelper(value); } private static int AbsHelper(int value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int32.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return -value; } public static long Abs(long value) { if (value >= 0) return value; else return AbsHelper(value); } private static long AbsHelper(long value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int64.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return -value; } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static float Abs(float value); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static double Abs(double value); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; public static Decimal Abs(Decimal value) { return Decimal.Abs(value); } /*================================MAX========================================= **Returns the larger of val1 and val2 ============================================================================*/ [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static sbyte Max(sbyte val1, sbyte val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static byte Max(byte val1, byte val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static short Max(short val1, short val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ushort Max(ushort val1, ushort val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static int Max(int val1, int val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static uint Max(uint val1, uint val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static long Max(long val1, long val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ulong Max(ulong val1, ulong val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Max(float val1, float val2) { if (val1 > val2) return val1; if (Single.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static double Max(double val1, double val2) { if (val1 > val2) return val1; if (Double.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static Decimal Max(Decimal val1, Decimal val2) { return Decimal.Max(val1,val2); } /*================================MIN========================================= **Returns the smaller of val1 and val2. ============================================================================*/ [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static sbyte Min(sbyte val1, sbyte val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static byte Min(byte val1, byte val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static short Min(short val1, short val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ushort Min(ushort val1, ushort val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static int Min(int val1, int val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static uint Min(uint val1, uint val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static long Min(long val1, long val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ulong Min(ulong val1, ulong val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Min(float val1, float val2) { if (val1 < val2) return val1; if (Single.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static double Min(double val1, double val2) { if (val1 < val2) return val1; if (Double.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static Decimal Min(Decimal val1, Decimal val2) { return Decimal.Min(val1,val2); } /*=====================================Log====================================== ** ==============================================================================*/ public static double Log(double a, double newBase) { if (Double.IsNaN(a)) { return a; // IEEE 754-2008: NaN payload must be preserved } if (Double.IsNaN(newBase)) { return newBase; // IEEE 754-2008: NaN payload must be preserved } if (newBase == 1) return Double.NaN; if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase))) return Double.NaN; return (Log(a)/Log(newBase)); } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. [CLSCompliant(false)] public static int Sign(sbyte value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. public static int Sign(short value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. public static int Sign(int value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static int Sign(long value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static int Sign (float value) { if (value < 0) return -1; else if (value > 0) return 1; else if (value == 0) return 0; throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN")); } public static int Sign(double value) { if (value < 0) return -1; else if (value > 0) return 1; else if (value == 0) return 0; throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN")); } public static int Sign(Decimal value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static long BigMul(int a, int b) { return ((long)a) * b; } public static int DivRem(int a, int b, out int result) { result = a%b; return a/b; } public static long DivRem(long a, long b, out long result) { result = a%b; return a/b; } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * 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. * - Neither the name of the openmetaverse.co 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; namespace OpenMetaverse { /// <summary> /// Identifier code for primitive types /// </summary> public enum PCode : byte { /// <summary>None</summary> None = 0, /// <summary>A Primitive</summary> Prim = 9, /// <summary>A Avatar</summary> Avatar = 47, /// <summary>Linden grass</summary> Grass = 95, /// <summary>Linden tree</summary> NewTree = 111, /// <summary>A primitive that acts as the source for a particle stream</summary> ParticleSystem = 143, /// <summary>A Linden tree</summary> Tree = 255 } /// <summary> /// Primary parameters for primitives such as Physics Enabled or Phantom /// </summary> [Flags] public enum PrimFlags : uint { /// <summary>Deprecated</summary> None = 0, /// <summary>Whether physics are enabled for this object</summary> Physics = 0x00000001, /// <summary></summary> CreateSelected = 0x00000002, /// <summary></summary> ObjectModify = 0x00000004, /// <summary></summary> ObjectCopy = 0x00000008, /// <summary></summary> ObjectAnyOwner = 0x00000010, /// <summary></summary> ObjectYouOwner = 0x00000020, /// <summary></summary> Scripted = 0x00000040, /// <summary>Whether this object contains an active touch script</summary> Touch = 0x00000080, /// <summary></summary> ObjectMove = 0x00000100, /// <summary>Whether this object can receive payments</summary> Money = 0x00000200, /// <summary>Whether this object is phantom (no collisions)</summary> Phantom = 0x00000400, /// <summary></summary> InventoryEmpty = 0x00000800, /// <summary></summary> JointHinge = 0x00001000, /// <summary></summary> JointP2P = 0x00002000, /// <summary></summary> JointLP2P = 0x00004000, /// <summary>Deprecated</summary> JointWheel = 0x00008000, /// <summary></summary> AllowInventoryDrop = 0x00010000, /// <summary></summary> ObjectTransfer = 0x00020000, /// <summary></summary> ObjectGroupOwned = 0x00040000, /// <summary>Deprecated</summary> ObjectYouOfficer = 0x00080000, /// <summary></summary> CameraDecoupled = 0x00100000, /// <summary></summary> AnimSource = 0x00200000, /// <summary></summary> CameraSource = 0x00400000, /// <summary></summary> CastShadows = 0x00800000, /// <summary>Server flag, will not be sent to clients. Specifies that /// the object is destroyed when it touches a simulator edge</summary> DieAtEdge = 0x01000000, /// <summary>Server flag, will not be sent to clients. Specifies that /// the object will be returned to the owner's inventory when it /// touches a simulator edge</summary> ReturnAtEdge = 0x02000000, /// <summary>Server flag, will not be sent to clients.</summary> Sandbox = 0x04000000, /// <summary>Server flag, will not be sent to client. Specifies that /// the object is hovering/flying</summary> Flying = 0x08000000, /// <summary></summary> ObjectOwnerModify = 0x10000000, /// <summary></summary> TemporaryOnRez = 0x20000000, /// <summary></summary> Temporary = 0x40000000, /// <summary></summary> ZlibCompressed = 0x80000000 } /// <summary> /// Sound flags for sounds attached to primitives /// </summary> [Flags] public enum SoundFlags : byte { /// <summary></summary> None = 0, /// <summary></summary> Loop = 0x01, /// <summary></summary> SyncMaster = 0x02, /// <summary></summary> SyncSlave = 0x04, /// <summary></summary> SyncPending = 0x08, /// <summary></summary> Queue = 0x10, /// <summary></summary> Stop = 0x20 } public enum ProfileCurve : byte { Circle = 0x00, Square = 0x01, IsoTriangle = 0x02, EqualTriangle = 0x03, RightTriangle = 0x04, HalfCircle = 0x05 } public enum HoleType : byte { Same = 0x00, Circle = 0x10, Square = 0x20, Triangle = 0x30 } public enum PathCurve : byte { Line = 0x10, Circle = 0x20, Circle2 = 0x30, Test = 0x40, Flexible = 0x80 } /// <summary> /// Material type for a primitive /// </summary> public enum Material : byte { /// <summary></summary> Stone = 0, /// <summary></summary> Metal, /// <summary></summary> Glass, /// <summary></summary> Wood, /// <summary></summary> Flesh, /// <summary></summary> Plastic, /// <summary></summary> Rubber, /// <summary></summary> Light } /// <summary> /// Used in a helper function to roughly determine prim shape /// </summary> public enum PrimType { Unknown, Box, Cylinder, Prism, Sphere, Torus, Tube, Ring, Sculpt, Mesh } /// <summary> /// Extra parameters for primitives, these flags are for features that have /// been added after the original ObjectFlags that has all eight bits /// reserved already /// </summary> [Flags] public enum ExtraParamType : ushort { /// <summary>Whether this object has flexible parameters</summary> Flexible = 0x10, /// <summary>Whether this object has light parameters</summary> Light = 0x20, /// <summary>Whether this object is a sculpted prim</summary> Sculpt = 0x30, /// <summary>Whether this object is a light image map</summary> LightImage = 0x40, /// <summary>Whether this object is a mesh</summary> Mesh = 0x60, } /// <summary> /// /// </summary> public enum JointType : byte { /// <summary></summary> Invalid = 0, /// <summary></summary> Hinge = 1, /// <summary></summary> Point = 2, // <summary></summary> //[Obsolete] //LPoint = 3, //[Obsolete] //Wheel = 4 } /// <summary> /// /// </summary> public enum SculptType : byte { /// <summary></summary> None = 0, /// <summary></summary> Sphere = 1, /// <summary></summary> Torus = 2, /// <summary></summary> Plane = 3, /// <summary></summary> Cylinder = 4, /// <summary></summary> Mesh = 5, /// <summary></summary> Invert = 64, /// <summary></summary> Mirror = 128 } /// <summary> /// /// </summary> public enum FaceType : ushort { /// <summary></summary> PathBegin = 0x1 << 0, /// <summary></summary> PathEnd = 0x1 << 1, /// <summary></summary> InnerSide = 0x1 << 2, /// <summary></summary> ProfileBegin = 0x1 << 3, /// <summary></summary> ProfileEnd = 0x1 << 4, /// <summary></summary> OuterSide0 = 0x1 << 5, /// <summary></summary> OuterSide1 = 0x1 << 6, /// <summary></summary> OuterSide2 = 0x1 << 7, /// <summary></summary> OuterSide3 = 0x1 << 8 } /// <summary> /// /// </summary> public enum ObjectCategory { /// <summary></summary> Invalid = -1, /// <summary></summary> None = 0, /// <summary></summary> Owner, /// <summary></summary> Group, /// <summary></summary> Other, /// <summary></summary> Selected, /// <summary></summary> Temporary } /// <summary> /// Attachment points for objects on avatar bodies /// </summary> /// <remarks> /// Both InventoryObject and InventoryAttachment types can be attached ///</remarks> public enum AttachmentPoint : byte { /// <summary>Right hand if object was not previously attached</summary> [EnumInfo(Text = "Default")] Default = 0, /// <summary>Chest</summary> [EnumInfo(Text = "Chest")] Chest = 1, /// <summary>Skull</summary> [EnumInfo(Text = "Head")] Skull, /// <summary>Left shoulder</summary> [EnumInfo(Text = "Left Shoulder")] LeftShoulder, /// <summary>Right shoulder</summary> [EnumInfo(Text = "Right Shoulder")] RightShoulder, /// <summary>Left hand</summary> [EnumInfo(Text = "Left Hand")] LeftHand, /// <summary>Right hand</summary> [EnumInfo(Text = "Right Hand")] RightHand, /// <summary>Left foot</summary> [EnumInfo(Text = "Left Foot")] LeftFoot, /// <summary>Right foot</summary> [EnumInfo(Text = "Right Foot")] RightFoot, /// <summary>Spine</summary> [EnumInfo(Text = "Back")] Spine, /// <summary>Pelvis</summary> [EnumInfo(Text = "Pelvis")] Pelvis, /// <summary>Mouth</summary> [EnumInfo(Text = "Mouth")] Mouth, /// <summary>Chin</summary> [EnumInfo(Text = "Chin")] Chin, /// <summary>Left ear</summary> [EnumInfo(Text = "Left Ear")] LeftEar, /// <summary>Right ear</summary> [EnumInfo(Text = "Right Ear")] RightEar, /// <summary>Left eyeball</summary> [EnumInfo(Text = "Left Eye")] LeftEyeball, /// <summary>Right eyeball</summary> [EnumInfo(Text = "Right Eye")] RightEyeball, /// <summary>Nose</summary> [EnumInfo(Text = "Nose")] Nose, /// <summary>Right upper arm</summary> [EnumInfo(Text = "Right Upper Arm")] RightUpperArm, /// <summary>Right forearm</summary> [EnumInfo(Text = "Right Lower Arm")] RightForearm, /// <summary>Left upper arm</summary> [EnumInfo(Text = "Left Upper Arm")] LeftUpperArm, /// <summary>Left forearm</summary> [EnumInfo(Text = "Left Lower Arm")] LeftForearm, /// <summary>Right hip</summary> [EnumInfo(Text = "Right Hip")] RightHip, /// <summary>Right upper leg</summary> [EnumInfo(Text = "Right Upper Leg")] RightUpperLeg, /// <summary>Right lower leg</summary> [EnumInfo(Text = "Right Lower Leg")] RightLowerLeg, /// <summary>Left hip</summary> [EnumInfo(Text = "Left Hip")] LeftHip, /// <summary>Left upper leg</summary> [EnumInfo(Text = "Left Upper Leg")] LeftUpperLeg, /// <summary>Left lower leg</summary> [EnumInfo(Text = "Left Lower Leg")] LeftLowerLeg, /// <summary>Stomach</summary> [EnumInfo(Text = "Belly")] Stomach, /// <summary>Left pectoral</summary> [EnumInfo(Text = "Left Pec")] LeftPec, /// <summary>Right pectoral</summary> [EnumInfo(Text = "Right Pec")] RightPec, /// <summary>HUD Center position 2</summary> [EnumInfo(Text = "HUD Center 2")] HUDCenter2, /// <summary>HUD Top-right</summary> [EnumInfo(Text = "HUD Top Right")] HUDTopRight, /// <summary>HUD Top</summary> [EnumInfo(Text = "HUD Top Center")] HUDTop, /// <summary>HUD Top-left</summary> [EnumInfo(Text = "HUD Top Left")] HUDTopLeft, /// <summary>HUD Center</summary> [EnumInfo(Text = "HUD Center 1")] HUDCenter, /// <summary>HUD Bottom-left</summary> [EnumInfo(Text = "HUD Bottom Left")] HUDBottomLeft, /// <summary>HUD Bottom</summary> [EnumInfo(Text = "HUD Bottom")] HUDBottom, /// <summary>HUD Bottom-right</summary> [EnumInfo(Text = "HUD Bottom Right")] HUDBottomRight, /// <summary>Neck</summary> [EnumInfo(Text = "Neck")] Neck, /// <summary>Avatar Center</summary> [EnumInfo(Text = "Avatar Center")] Root, } /// <summary> /// Tree foliage types /// </summary> public enum Tree : byte { /// <summary>Pine1 tree</summary> Pine1 = 0, /// <summary>Oak tree</summary> Oak, /// <summary>Tropical Bush1</summary> TropicalBush1, /// <summary>Palm1 tree</summary> Palm1, /// <summary>Dogwood tree</summary> Dogwood, /// <summary>Tropical Bush2</summary> TropicalBush2, /// <summary>Palm2 tree</summary> Palm2, /// <summary>Cypress1 tree</summary> Cypress1, /// <summary>Cypress2 tree</summary> Cypress2, /// <summary>Pine2 tree</summary> Pine2, /// <summary>Plumeria</summary> Plumeria, /// <summary>Winter pinetree1</summary> WinterPine1, /// <summary>Winter Aspen tree</summary> WinterAspen, /// <summary>Winter pinetree2</summary> WinterPine2, /// <summary>Eucalyptus tree</summary> Eucalyptus, /// <summary>Fern</summary> Fern, /// <summary>Eelgrass</summary> Eelgrass, /// <summary>Sea Sword</summary> SeaSword, /// <summary>Kelp1 plant</summary> Kelp1, /// <summary>Beach grass</summary> BeachGrass1, /// <summary>Kelp2 plant</summary> Kelp2 } /// <summary> /// Grass foliage types /// </summary> public enum Grass : byte { /// <summary></summary> Grass0 = 0, /// <summary></summary> Grass1, /// <summary></summary> Grass2, /// <summary></summary> Grass3, /// <summary></summary> Grass4, /// <summary></summary> Undergrowth1 } /// <summary> /// Action associated with clicking on an object /// </summary> public enum ClickAction : byte { /// <summary>Touch object</summary> Touch = 0, /// <summary>Sit on object</summary> Sit = 1, /// <summary>Purchase object or contents</summary> Buy = 2, /// <summary>Pay the object</summary> Pay = 3, /// <summary>Open task inventory</summary> OpenTask = 4, /// <summary>Play parcel media</summary> PlayMedia = 5, /// <summary>Open parcel media</summary> OpenMedia = 6 } /// <summary> /// Type of physics representation used for this prim in the simulator /// </summary> public enum PhysicsShapeType : byte { /// <summary>Use prim physics form this object</summary> Prim = 0, /// <summary>No physics, prim doesn't collide</summary> None, /// <summary>Use convex hull represantion of this prim</summary> ConvexHull } }
/* * 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; using System.Collections.Generic; using System.Data; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using Mono.Data.SqliteClient; namespace OpenSim.Data.SQLiteLegacy { public class SQLiteAuthenticationData : SQLiteFramework, IAuthenticationData { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private string m_Realm; private List<string> m_ColumnNames; private int m_LastExpire; private string m_connectionString; protected static SqliteConnection m_Connection; private static bool m_initialized = false; public SQLiteAuthenticationData(string connectionString, string realm) : base(connectionString) { m_Realm = realm; m_connectionString = connectionString; if (!m_initialized) { m_Connection = new SqliteConnection(connectionString); m_Connection.Open(); using (SqliteConnection dbcon = (SqliteConnection)((ICloneable)m_Connection).Clone()) { dbcon.Open(); Migration m = new Migration(dbcon, GetType().Assembly, "AuthStore"); m.Update(); dbcon.Close(); } m_initialized = true; } } public AuthenticationData Get(UUID principalID) { AuthenticationData ret = new AuthenticationData(); ret.Data = new Dictionary<string, object>(); SqliteCommand cmd = new SqliteCommand("select * from `" + m_Realm + "` where UUID = :PrincipalID"); cmd.Parameters.Add(new SqliteParameter(":PrincipalID", principalID.ToString())); IDataReader result = ExecuteReader(cmd, m_Connection); try { if (result.Read()) { ret.PrincipalID = principalID; if (m_ColumnNames == null) { m_ColumnNames = new List<string>(); DataTable schemaTable = result.GetSchemaTable(); foreach (DataRow row in schemaTable.Rows) m_ColumnNames.Add(row["ColumnName"].ToString()); } foreach (string s in m_ColumnNames) { if (s == "UUID") continue; ret.Data[s] = result[s].ToString(); } return ret; } else { return null; } } catch { } finally { CloseCommand(cmd); } return null; } public bool Store(AuthenticationData data) { if (data.Data.ContainsKey("UUID")) data.Data.Remove("UUID"); string[] fields = new List<string>(data.Data.Keys).ToArray(); string[] values = new string[data.Data.Count]; int i = 0; foreach (object o in data.Data.Values) values[i++] = o.ToString(); SqliteCommand cmd = new SqliteCommand(); if (Get(data.PrincipalID) != null) { string update = "update `" + m_Realm + "` set "; bool first = true; foreach (string field in fields) { if (!first) update += ", "; update += "`" + field + "` = :" + field; cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); first = false; } update += " where UUID = :UUID"; cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); cmd.CommandText = update; try { if (ExecuteNonQuery(cmd, m_Connection) < 1) { CloseCommand(cmd); return false; } } catch (Exception e) { m_log.Error("[SQLITE]: Exception storing authentication data", e); CloseCommand(cmd); return false; } } else { string insert = "insert into `" + m_Realm + "` (`UUID`, `" + String.Join("`, `", fields) + "`) values (:UUID, :" + String.Join(", :", fields) + ")"; cmd.Parameters.Add(new SqliteParameter(":UUID", data.PrincipalID.ToString())); foreach (string field in fields) cmd.Parameters.Add(new SqliteParameter(":" + field, data.Data[field])); cmd.CommandText = insert; try { if (ExecuteNonQuery(cmd, m_Connection) < 1) { CloseCommand(cmd); return false; } } catch (Exception e) { Console.WriteLine(e.ToString()); CloseCommand(cmd); return false; } } CloseCommand(cmd); return true; } public bool SetDataItem(UUID principalID, string item, string value) { SqliteCommand cmd = new SqliteCommand("update `" + m_Realm + "` set `" + item + "` = " + value + " where UUID = '" + principalID.ToString() + "'"); if (ExecuteNonQuery(cmd, m_Connection) > 0) return true; return false; } public bool SetToken(UUID principalID, string token, int lifetime) { if (System.Environment.TickCount - m_LastExpire > 30000) DoExpire(); SqliteCommand cmd = new SqliteCommand("insert into tokens (UUID, token, validity) values ('" + principalID.ToString() + "', '" + token + "', datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes'))"); if (ExecuteNonQuery(cmd, m_Connection) > 0) { cmd.Dispose(); return true; } cmd.Dispose(); return false; } public bool CheckToken(UUID principalID, string token, int lifetime) { if (System.Environment.TickCount - m_LastExpire > 30000) DoExpire(); SqliteCommand cmd = new SqliteCommand("update tokens set validity = datetime('now', 'localtime', '+" + lifetime.ToString() + " minutes') where UUID = '" + principalID.ToString() + "' and token = '" + token + "' and validity > datetime('now', 'localtime')"); if (ExecuteNonQuery(cmd, m_Connection) > 0) { cmd.Dispose(); return true; } cmd.Dispose(); return false; } private void DoExpire() { SqliteCommand cmd = new SqliteCommand("delete from tokens where validity < datetime('now', 'localtime')"); ExecuteNonQuery(cmd, m_Connection); cmd.Dispose(); m_LastExpire = System.Environment.TickCount; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Net; using System.Security.Cryptography.X509Certificates; using System.ComponentModel; using System.Runtime.InteropServices; using System.Collections; using System.Text; using System.Diagnostics; using System.Security.Authentication; using System.Runtime.CompilerServices; using System.Security.Permissions; namespace System.DirectoryServices.Protocols { public delegate LdapConnection QueryForConnectionCallback(LdapConnection primaryConnection, LdapConnection referralFromConnection, string newDistinguishedName, LdapDirectoryIdentifier identifier, NetworkCredential credential, long currentUserToken); public delegate bool NotifyOfNewConnectionCallback(LdapConnection primaryConnection, LdapConnection referralFromConnection, string newDistinguishedName, LdapDirectoryIdentifier identifier, LdapConnection newConnection, NetworkCredential credential, long currentUserToken, int errorCodeFromBind); public delegate void DereferenceConnectionCallback(LdapConnection primaryConnection, LdapConnection connectionToDereference); public delegate X509Certificate QueryClientCertificateCallback(LdapConnection connection, byte[][] trustedCAs); public delegate bool VerifyServerCertificateCallback(LdapConnection connection, X509Certificate certificate); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int QUERYFORCONNECTIONInternal(IntPtr Connection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref IntPtr ConnectionToUse); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool NOTIFYOFNEWCONNECTIONInternal(IntPtr Connection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, IntPtr NewConnection, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUser, int ErrorCodeFromBind); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int DEREFERENCECONNECTIONInternal(IntPtr Connection, IntPtr ConnectionToDereference); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate bool VERIFYSERVERCERT(IntPtr Connection, IntPtr pServerCert); [Flags] public enum LocatorFlags : long { None = 0, ForceRediscovery = 0x00000001, DirectoryServicesRequired = 0x00000010, DirectoryServicesPreferred = 0x00000020, GCRequired = 0x00000040, PdcRequired = 0x00000080, IPRequired = 0x00000200, KdcRequired = 0x00000400, TimeServerRequired = 0x00000800, WriteableRequired = 0x00001000, GoodTimeServerPreferred = 0x00002000, AvoidSelf = 0x00004000, OnlyLdapNeeded = 0x00008000, IsFlatName = 0x00010000, IsDnsName = 0x00020000, ReturnDnsName = 0x40000000, ReturnFlatName = 0x80000000, } public enum SecurityProtocol { Pct1Server = 0x1, Pct1Client = 0x2, Ssl2Server = 0x4, Ssl2Client = 0x8, Ssl3Server = 0x10, Ssl3Client = 0x20, Tls1Server = 0x40, Tls1Client = 0x80 } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] public class SecurityPackageContextConnectionInformation { private SecurityProtocol _securityProtocol; private CipherAlgorithmType _identifier; private int _strength; private HashAlgorithmType _hashAlgorithm; private int _hashStrength; private int _keyExchangeAlgorithm; private int _exchangeStrength; internal SecurityPackageContextConnectionInformation() { } public SecurityProtocol Protocol => _securityProtocol; public CipherAlgorithmType AlgorithmIdentifier => _identifier; public int CipherStrength => _strength; public HashAlgorithmType Hash => _hashAlgorithm; public int HashStrength => _hashStrength; public int KeyExchangeAlgorithm => _keyExchangeAlgorithm; public int ExchangeStrength => _exchangeStrength; } public sealed class ReferralCallback { public ReferralCallback() { } public QueryForConnectionCallback QueryForConnection { get; set; } public NotifyOfNewConnectionCallback NotifyNewConnection { get; set; } public DereferenceConnectionCallback DereferenceConnection { get; set; } } internal struct SecurityHandle { public IntPtr Lower; public IntPtr Upper; } public class LdapSessionOptions { private LdapConnection _connection = null; private ReferralCallback _callbackRoutine = new ReferralCallback(); internal QueryClientCertificateCallback _clientCertificateDelegate = null; private VerifyServerCertificateCallback _serverCertificateDelegate = null; private QUERYFORCONNECTIONInternal _queryDelegate = null; private NOTIFYOFNEWCONNECTIONInternal _notifiyDelegate = null; private DEREFERENCECONNECTIONInternal _dereferenceDelegate = null; private VERIFYSERVERCERT _serverCertificateRoutine = null; internal LdapSessionOptions(LdapConnection connection) { _connection = connection; _queryDelegate = new QUERYFORCONNECTIONInternal(ProcessQueryConnection); _notifiyDelegate = new NOTIFYOFNEWCONNECTIONInternal(ProcessNotifyConnection); _dereferenceDelegate = new DEREFERENCECONNECTIONInternal(ProcessDereferenceConnection); _serverCertificateRoutine = new VERIFYSERVERCERT(ProcessServerCertificate); } public ReferralChasingOptions ReferralChasing { get { int result = GetIntValueHelper(LdapOption.LDAP_OPT_REFERRALS); return result == 1 ? ReferralChasingOptions.All : (ReferralChasingOptions)result; } set { if (((value) & (~ReferralChasingOptions.All)) != 0) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ReferralChasingOptions)); } SetIntValueHelper(LdapOption.LDAP_OPT_REFERRALS, (int)value); } } public bool SecureSocketLayer { get { int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_SSL); return outValue == 1; } set { int temp = value ? 1 : 0; SetIntValueHelper(LdapOption.LDAP_OPT_SSL, temp); } } public int ReferralHopLimit { get => GetIntValueHelper(LdapOption.LDAP_OPT_REFERRAL_HOP_LIMIT); set { if (value < 0) { throw new ArgumentException(SR.ValidValue, nameof(value)); } SetIntValueHelper(LdapOption.LDAP_OPT_REFERRAL_HOP_LIMIT, value); } } public int ProtocolVersion { get => GetIntValueHelper(LdapOption.LDAP_OPT_VERSION); set => SetIntValueHelper(LdapOption.LDAP_OPT_VERSION, value); } public string HostName { get => GetStringValueHelper(LdapOption.LDAP_OPT_HOST_NAME, false); set => SetStringValueHelper(LdapOption.LDAP_OPT_HOST_NAME, value); } public string DomainName { get => GetStringValueHelper(LdapOption.LDAP_OPT_DNSDOMAIN_NAME, true); set => SetStringValueHelper(LdapOption.LDAP_OPT_DNSDOMAIN_NAME, value); } public LocatorFlags LocatorFlag { get { int result = GetIntValueHelper(LdapOption.LDAP_OPT_GETDSNAME_FLAGS); return (LocatorFlags)result; } set { // We don't do validation to the dirsync flag here as underneath API does not check for it and we don't want to put // unnecessary limitation on it. SetIntValueHelper(LdapOption.LDAP_OPT_GETDSNAME_FLAGS, (int)value); } } public bool HostReachable { get { int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_HOST_REACHABLE); return outValue == 1; } } public TimeSpan PingKeepAliveTimeout { get { int result = GetIntValueHelper(LdapOption.LDAP_OPT_PING_KEEP_ALIVE); return new TimeSpan(result * TimeSpan.TicksPerSecond); } set { if (value < TimeSpan.Zero) { throw new ArgumentException(SR.NoNegativeTime, nameof(value)); } // Prevent integer overflow. if (value.TotalSeconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } int seconds = (int)(value.Ticks / TimeSpan.TicksPerSecond); SetIntValueHelper(LdapOption.LDAP_OPT_PING_KEEP_ALIVE, seconds); } } public int PingLimit { get => GetIntValueHelper(LdapOption.LDAP_OPT_PING_LIMIT); set { if (value < 0) { throw new ArgumentException(SR.ValidValue, nameof(value)); } SetIntValueHelper(LdapOption.LDAP_OPT_PING_LIMIT, value); } } public TimeSpan PingWaitTimeout { get { int result = GetIntValueHelper(LdapOption.LDAP_OPT_PING_WAIT_TIME); return new TimeSpan(result * TimeSpan.TicksPerMillisecond); } set { if (value < TimeSpan.Zero) { throw new ArgumentException(SR.NoNegativeTime, nameof(value)); } // Prevent integer overflow. if (value.TotalMilliseconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } int milliseconds = (int)(value.Ticks / TimeSpan.TicksPerMillisecond); SetIntValueHelper(LdapOption.LDAP_OPT_PING_WAIT_TIME, milliseconds); } } public bool AutoReconnect { get { int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_AUTO_RECONNECT); return outValue == 1; } set { int temp = value ? 1 : 0; SetIntValueHelper(LdapOption.LDAP_OPT_AUTO_RECONNECT, temp); } } public int SspiFlag { get => GetIntValueHelper(LdapOption.LDAP_OPT_SSPI_FLAGS); set => SetIntValueHelper(LdapOption.LDAP_OPT_SSPI_FLAGS, value); } public SecurityPackageContextConnectionInformation SslInformation { get { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } var secInfo = new SecurityPackageContextConnectionInformation(); int error = Wldap32.ldap_get_option_secInfo(_connection._ldapHandle, LdapOption.LDAP_OPT_SSL_INFO, secInfo); ErrorChecking.CheckAndSetLdapError(error); return secInfo; } } public object SecurityContext { get { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } var tempHandle = new SecurityHandle(); int error = Wldap32.ldap_get_option_sechandle(_connection._ldapHandle, LdapOption.LDAP_OPT_SECURITY_CONTEXT, ref tempHandle); ErrorChecking.CheckAndSetLdapError(error); return tempHandle; } } public bool Signing { get { int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_SIGN); return outValue == 1; } set { int temp = value ? 1 : 0; SetIntValueHelper(LdapOption.LDAP_OPT_SIGN, temp); } } public bool Sealing { get { int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_ENCRYPT); return outValue == 1; } set { int temp = value ? 1 : 0; SetIntValueHelper(LdapOption.LDAP_OPT_ENCRYPT, temp); } } public string SaslMethod { get => GetStringValueHelper(LdapOption.LDAP_OPT_SASL_METHOD, true); set => SetStringValueHelper(LdapOption.LDAP_OPT_SASL_METHOD, value); } public bool RootDseCache { get { int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_ROOTDSE_CACHE); return outValue == 1; } set { int temp = value ? 1 : 0; SetIntValueHelper(LdapOption.LDAP_OPT_ROOTDSE_CACHE, temp); } } public bool TcpKeepAlive { get { int outValue = GetIntValueHelper(LdapOption.LDAP_OPT_TCP_KEEPALIVE); return outValue == 1; } set { int temp = value ? 1 : 0; SetIntValueHelper(LdapOption.LDAP_OPT_TCP_KEEPALIVE, temp); } } public TimeSpan SendTimeout { get { int result = GetIntValueHelper(LdapOption.LDAP_OPT_SEND_TIMEOUT); return new TimeSpan(result * TimeSpan.TicksPerSecond); } set { if (value < TimeSpan.Zero) { throw new ArgumentException(SR.NoNegativeTime, nameof(value)); } // Prevent integer overflow. if (value.TotalSeconds > int.MaxValue) { throw new ArgumentException(SR.TimespanExceedMax, nameof(value)); } int seconds = (int)(value.Ticks / TimeSpan.TicksPerSecond); SetIntValueHelper(LdapOption.LDAP_OPT_SEND_TIMEOUT, seconds); } } public ReferralCallback ReferralCallback { get { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } return _callbackRoutine; } set { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } var tempCallback = new ReferralCallback(); if (value != null) { tempCallback.QueryForConnection = value.QueryForConnection; tempCallback.NotifyNewConnection = value.NotifyNewConnection; tempCallback.DereferenceConnection = value.DereferenceConnection; } else { tempCallback.QueryForConnection = null; tempCallback.NotifyNewConnection = null; tempCallback.DereferenceConnection = null; } ProcessCallBackRoutine(tempCallback); _callbackRoutine = value; } } public QueryClientCertificateCallback QueryClientCertificate { get { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } return _clientCertificateDelegate; } set { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } if (value != null) { int certError = Wldap32.ldap_set_option_clientcert(_connection._ldapHandle, LdapOption.LDAP_OPT_CLIENT_CERTIFICATE, _connection._clientCertificateRoutine); if (certError != (int)ResultCode.Success) { if (Utility.IsLdapError((LdapError)certError)) { string certerrorMessage = LdapErrorMappings.MapResultCode(certError); throw new LdapException(certError, certerrorMessage); } else { throw new LdapException(certError); } } // A certificate callback is specified so automatic bind is disabled. _connection.AutoBind = false; } _clientCertificateDelegate = value; } } public VerifyServerCertificateCallback VerifyServerCertificate { get { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } return _serverCertificateDelegate; } set { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } if (value != null) { int error = Wldap32.ldap_set_option_servercert(_connection._ldapHandle, LdapOption.LDAP_OPT_SERVER_CERTIFICATE, _serverCertificateRoutine); ErrorChecking.CheckAndSetLdapError(error); } _serverCertificateDelegate = value; } } internal string ServerErrorMessage => GetStringValueHelper(LdapOption.LDAP_OPT_SERVER_ERROR, true); internal DereferenceAlias DerefAlias { get => (DereferenceAlias)GetIntValueHelper(LdapOption.LDAP_OPT_DEREF); set => SetIntValueHelper(LdapOption.LDAP_OPT_DEREF, (int)value); } internal bool FQDN { set { // set the value to true SetIntValueHelper(LdapOption.LDAP_OPT_AREC_EXCLUSIVE, 1); } } public void FastConcurrentBind() { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } // Bump up the protocol version ProtocolVersion = 3; // Do the fast concurrent bind. int inValue = 1; int error = Wldap32.ldap_set_option_int(_connection._ldapHandle, LdapOption.LDAP_OPT_FAST_CONCURRENT_BIND, ref inValue); ErrorChecking.CheckAndSetLdapError(error); } public unsafe void StartTransportLayerSecurity(DirectoryControlCollection controls) { IntPtr serverControlArray = IntPtr.Zero; LdapControl[] managedServerControls = null; IntPtr clientControlArray = IntPtr.Zero; LdapControl[] managedClientControls = null; IntPtr ldapResult = IntPtr.Zero; IntPtr referral = IntPtr.Zero; int serverError = 0; Uri[] responseReferral = null; if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } try { IntPtr tempPtr = IntPtr.Zero; // build server control managedServerControls = _connection.BuildControlArray(controls, true); int structSize = Marshal.SizeOf(typeof(LdapControl)); if (managedServerControls != null) { serverControlArray = Utility.AllocHGlobalIntPtrArray(managedServerControls.Length + 1); for (int i = 0; i < managedServerControls.Length; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(managedServerControls[i], controlPtr, false); tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)serverControlArray + IntPtr.Size * managedServerControls.Length); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } // Build client control. managedClientControls = _connection.BuildControlArray(controls, false); if (managedClientControls != null) { clientControlArray = Utility.AllocHGlobalIntPtrArray(managedClientControls.Length + 1); for (int i = 0; i < managedClientControls.Length; i++) { IntPtr controlPtr = Marshal.AllocHGlobal(structSize); Marshal.StructureToPtr(managedClientControls[i], controlPtr, false); tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * i); Marshal.WriteIntPtr(tempPtr, controlPtr); } tempPtr = (IntPtr)((long)clientControlArray + IntPtr.Size * managedClientControls.Length); Marshal.WriteIntPtr(tempPtr, IntPtr.Zero); } int error = Wldap32.ldap_start_tls(_connection._ldapHandle, ref serverError, ref ldapResult, serverControlArray, clientControlArray); if (ldapResult != IntPtr.Zero) { // Parse the referral. int resultError = Wldap32.ldap_parse_result_referral(_connection._ldapHandle, ldapResult, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref referral, IntPtr.Zero, 0 /* not free it */); if (resultError == 0 && referral != IntPtr.Zero) { char** referralPtr = (char**)referral; char* singleReferral = referralPtr[0]; int i = 0; ArrayList referralList = new ArrayList(); while (singleReferral != null) { string s = Marshal.PtrToStringUni((IntPtr)singleReferral); referralList.Add(s); i++; singleReferral = referralPtr[i]; } // Free heap memory. if (referral != IntPtr.Zero) { Wldap32.ldap_value_free(referral); referral = IntPtr.Zero; } if (referralList.Count > 0) { responseReferral = new Uri[referralList.Count]; for (int j = 0; j < referralList.Count; j++) { responseReferral[j] = new Uri((string)referralList[j]); } } } } if (error != (int)ResultCode.Success) { if (Utility.IsResultCode((ResultCode)error)) { // If the server failed request for whatever reason, the ldap_start_tls returns LDAP_OTHER // and the ServerReturnValue will contain the error code from the server. if (error == (int)ResultCode.Other) { error = serverError; } string errorMessage = OperationErrorMappings.MapResultCode(error); ExtendedResponse response = new ExtendedResponse(null, null, (ResultCode)error, errorMessage, responseReferral); response.ResponseName = "1.3.6.1.4.1.1466.20037"; throw new TlsOperationException(response); } else if (Utility.IsLdapError((LdapError)error)) { string errorMessage = LdapErrorMappings.MapResultCode(error); throw new LdapException(error, errorMessage); } } } finally { if (serverControlArray != IntPtr.Zero) { // Release the memory from the heap. for (int i = 0; i < managedServerControls.Length; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(serverControlArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(serverControlArray); } if (managedServerControls != null) { for (int i = 0; i < managedServerControls.Length; i++) { if (managedServerControls[i].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(managedServerControls[i].ldctl_oid); } if (managedServerControls[i].ldctl_value != null) { if (managedServerControls[i].ldctl_value.bv_val != IntPtr.Zero) { Marshal.FreeHGlobal(managedServerControls[i].ldctl_value.bv_val); } } } } if (clientControlArray != IntPtr.Zero) { // Release the memor from the heap. for (int i = 0; i < managedClientControls.Length; i++) { IntPtr tempPtr = Marshal.ReadIntPtr(clientControlArray, IntPtr.Size * i); if (tempPtr != IntPtr.Zero) { Marshal.FreeHGlobal(tempPtr); } } Marshal.FreeHGlobal(clientControlArray); } if (managedClientControls != null) { for (int i = 0; i < managedClientControls.Length; i++) { if (managedClientControls[i].ldctl_oid != IntPtr.Zero) { Marshal.FreeHGlobal(managedClientControls[i].ldctl_oid); } if (managedClientControls[i].ldctl_value != null) { if (managedClientControls[i].ldctl_value.bv_val != IntPtr.Zero) Marshal.FreeHGlobal(managedClientControls[i].ldctl_value.bv_val); } } } if (referral != IntPtr.Zero) { Wldap32.ldap_value_free(referral); } } } public void StopTransportLayerSecurity() { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } byte result = Wldap32.ldap_stop_tls(_connection._ldapHandle); if (result == 0) { throw new TlsOperationException(null, SR.TLSStopFailure); } } private int GetIntValueHelper(LdapOption option) { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } int outValue = 0; int error = Wldap32.ldap_get_option_int(_connection._ldapHandle, option, ref outValue); ErrorChecking.CheckAndSetLdapError(error); return outValue; } private void SetIntValueHelper(LdapOption option, int value) { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } int temp = value; int error = Wldap32.ldap_set_option_int(_connection._ldapHandle, option, ref temp); ErrorChecking.CheckAndSetLdapError(error); } private string GetStringValueHelper(LdapOption option, bool releasePtr) { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } IntPtr outValue = new IntPtr(0); int error = Wldap32.ldap_get_option_ptr(_connection._ldapHandle, option, ref outValue); ErrorChecking.CheckAndSetLdapError(error); string stringValue = null; if (outValue != IntPtr.Zero) { stringValue = Marshal.PtrToStringUni(outValue); } if (releasePtr) { Wldap32.ldap_memfree(outValue); } return stringValue; } private void SetStringValueHelper(LdapOption option, string value) { if (_connection._disposed) { throw new ObjectDisposedException(GetType().Name); } IntPtr inValue = IntPtr.Zero; if (value != null) { inValue = Marshal.StringToHGlobalUni(value); } try { int error = Wldap32.ldap_set_option_ptr(_connection._ldapHandle, option, ref inValue); ErrorChecking.CheckAndSetLdapError(error); } finally { if (inValue != IntPtr.Zero) { Marshal.FreeHGlobal(inValue); } } } private void ProcessCallBackRoutine(ReferralCallback tempCallback) { LdapReferralCallback value = new LdapReferralCallback() { sizeofcallback = Marshal.SizeOf(typeof(LdapReferralCallback)), query = tempCallback.QueryForConnection == null ? null : _queryDelegate, notify = tempCallback.NotifyNewConnection == null ? null : _notifiyDelegate, dereference = tempCallback.DereferenceConnection == null ? null : _dereferenceDelegate }; int error = Wldap32.ldap_set_option_referral(_connection._ldapHandle, LdapOption.LDAP_OPT_REFERRAL_CALLBACK, ref value); ErrorChecking.CheckAndSetLdapError(error); } private int ProcessQueryConnection(IntPtr PrimaryConnection, IntPtr ReferralFromConnection, IntPtr NewDNPtr, string HostName, int PortNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid CurrentUserToken, ref IntPtr ConnectionToUse) { ConnectionToUse = IntPtr.Zero; string NewDN = null; // The user must have registered callback function. Debug.Assert(_callbackRoutine.QueryForConnection != null); // The user registers the QUERYFORCONNECTION callback. if (_callbackRoutine.QueryForConnection != null) { if (NewDNPtr != IntPtr.Zero) { NewDN = Marshal.PtrToStringUni(NewDNPtr); } var target = new StringBuilder(); target.Append(HostName); target.Append(":"); target.Append(PortNumber); var identifier = new LdapDirectoryIdentifier(target.ToString()); NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity); LdapConnection tempReferralConnection = null; // If ReferralFromConnection handle is valid. if (ReferralFromConnection != IntPtr.Zero) { lock (LdapConnection.s_objectLock) { // Make sure first whether we have saved it in the handle table before WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[ReferralFromConnection]); if (reference != null && reference.IsAlive) { // Save this before and object has not been garbage collected yet. tempReferralConnection = (LdapConnection)reference.Target; } else { if (reference != null) { // Connection has been garbage collected, we need to remove this one. LdapConnection.s_handleTable.Remove(ReferralFromConnection); } // We don't have it yet, construct a new one. tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ReferralFromConnection); // Save it to the handle table. LdapConnection.s_handleTable.Add(ReferralFromConnection, new WeakReference(tempReferralConnection)); } } } long tokenValue = (uint)CurrentUserToken.LowPart + (((long)CurrentUserToken.HighPart) << 32); LdapConnection con = _callbackRoutine.QueryForConnection(_connection, tempReferralConnection, NewDN, identifier, cred, tokenValue); if (con != null && con._ldapHandle != null && !con._ldapHandle.IsInvalid) { bool success = AddLdapHandleRef(con); if (success) { ConnectionToUse = con._ldapHandle.DangerousGetHandle(); } } return 0; } // The user does not take ownership of the connection. return 1; } private bool ProcessNotifyConnection(IntPtr primaryConnection, IntPtr referralFromConnection, IntPtr newDNPtr, string hostName, IntPtr newConnection, int portNumber, SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentity, Luid currentUser, int errorCodeFromBind) { if (newConnection != IntPtr.Zero && _callbackRoutine.NotifyNewConnection != null) { string newDN = null; if (newDNPtr != IntPtr.Zero) { newDN = Marshal.PtrToStringUni(newDNPtr); } var target = new StringBuilder(); target.Append(hostName); target.Append(":"); target.Append(portNumber); var identifier = new LdapDirectoryIdentifier(target.ToString()); NetworkCredential cred = ProcessSecAuthIdentity(SecAuthIdentity); LdapConnection tempNewConnection = null; LdapConnection tempReferralConnection = null; lock (LdapConnection.s_objectLock) { // Check whether the referralFromConnection handle is valid. if (referralFromConnection != IntPtr.Zero) { // Check whether we have save it in the handle table before. WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[referralFromConnection]); if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target)._ldapHandle) { // Save this before and object has not been garbage collected yet. tempReferralConnection = (LdapConnection)reference.Target; } else { // Connection has been garbage collected, we need to remove this one. if (reference != null) { LdapConnection.s_handleTable.Remove(referralFromConnection); } // We don't have it yet, construct a new one. tempReferralConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, referralFromConnection); // Save it to the handle table. LdapConnection.s_handleTable.Add(referralFromConnection, new WeakReference(tempReferralConnection)); } } if (newConnection != IntPtr.Zero) { // Check whether we have save it in the handle table before. WeakReference reference = (WeakReference)(LdapConnection.s_handleTable[newConnection]); if (reference != null && reference.IsAlive && null != ((LdapConnection)reference.Target)._ldapHandle) { // Save this before and object has not been garbage collected yet. tempNewConnection = (LdapConnection)reference.Target; } else { // Connection has been garbage collected, we need to remove this one. if (reference != null) { LdapConnection.s_handleTable.Remove(newConnection); } // We don't have it yet, construct a new one. tempNewConnection = new LdapConnection(identifier, cred, _connection.AuthType, newConnection); // Save it to the handle table. LdapConnection.s_handleTable.Add(newConnection, new WeakReference(tempNewConnection)); } } } long tokenValue = (uint)currentUser.LowPart + (((long)currentUser.HighPart) << 32); bool value = _callbackRoutine.NotifyNewConnection(_connection, tempReferralConnection, newDN, identifier, tempNewConnection, cred, tokenValue, errorCodeFromBind); if (value) { value = AddLdapHandleRef(tempNewConnection); if (value) { tempNewConnection.NeedDispose = true; } } return value; } return false; } private int ProcessDereferenceConnection(IntPtr PrimaryConnection, IntPtr ConnectionToDereference) { if (ConnectionToDereference != IntPtr.Zero && _callbackRoutine.DereferenceConnection != null) { LdapConnection dereferenceConnection = null; WeakReference reference = null; // in most cases it should be in our table lock (LdapConnection.s_objectLock) { reference = (WeakReference)(LdapConnection.s_handleTable[ConnectionToDereference]); } // not been added to the table before or it is garbage collected, we need to construct it if (reference == null || !reference.IsAlive) { dereferenceConnection = new LdapConnection(((LdapDirectoryIdentifier)(_connection.Directory)), _connection.GetCredential(), _connection.AuthType, ConnectionToDereference); } else { dereferenceConnection = (LdapConnection)reference.Target; ReleaseLdapHandleRef(dereferenceConnection); } _callbackRoutine.DereferenceConnection(_connection, dereferenceConnection); // there is no need to remove the connection object from the handle table, as it will be removed automatically when // connection object is disposed. } return 1; } private NetworkCredential ProcessSecAuthIdentity(SEC_WINNT_AUTH_IDENTITY_EX SecAuthIdentit) { if (SecAuthIdentit == null) { return new NetworkCredential(); } string user = SecAuthIdentit.user; string domain = SecAuthIdentit.domain; string password = SecAuthIdentit.password; return new NetworkCredential(user, password, domain); } private bool ProcessServerCertificate(IntPtr connection, IntPtr serverCert) { // If callback is not specified by user, it means the server certificate is accepted. bool value = true; if (_serverCertificateDelegate != null) { IntPtr certPtr = IntPtr.Zero; X509Certificate certificate = null; try { Debug.Assert(serverCert != IntPtr.Zero); certPtr = Marshal.ReadIntPtr(serverCert); certificate = new X509Certificate(certPtr); } finally { Wldap32.CertFreeCRLContext(certPtr); } value = _serverCertificateDelegate(_connection, certificate); } return value; } [PermissionSet(SecurityAction.Assert, Unrestricted = true)] private static bool AddLdapHandleRef(LdapConnection ldapConnection) { bool success = false; if (ldapConnection != null && ldapConnection._ldapHandle != null && !ldapConnection._ldapHandle.IsInvalid) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { ldapConnection._ldapHandle.DangerousAddRef(ref success); } } return success; } [PermissionSet(SecurityAction.Assert, Unrestricted = true)] private static void ReleaseLdapHandleRef(LdapConnection ldapConnection) { if (ldapConnection != null && ldapConnection._ldapHandle != null && !ldapConnection._ldapHandle.IsInvalid) { RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { ldapConnection._ldapHandle.DangerousRelease(); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.ServiceModel { public partial class DnsEndpointIdentity : System.ServiceModel.EndpointIdentity { public DnsEndpointIdentity(string dnsName) { } } public abstract partial class MessageSecurityVersion { internal MessageSecurityVersion() { } public abstract System.ServiceModel.Security.BasicSecurityProfileVersion BasicSecurityProfileVersion { get; } public System.ServiceModel.Security.SecureConversationVersion SecureConversationVersion { get { return default; } } public abstract System.ServiceModel.Security.SecurityPolicyVersion SecurityPolicyVersion { get; } public System.ServiceModel.Security.SecurityVersion SecurityVersion { get { return default; } } public System.ServiceModel.Security.TrustVersion TrustVersion { get { return default; } } public static System.ServiceModel.MessageSecurityVersion WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10 { get { return default; } } public static System.ServiceModel.MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11 { get { return default; } } public static System.ServiceModel.MessageSecurityVersion WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10 { get { return default; } } public static System.ServiceModel.MessageSecurityVersion WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10 { get { return default; } } } public partial class SpnEndpointIdentity : System.ServiceModel.EndpointIdentity { public SpnEndpointIdentity(string spnName) { } public static System.TimeSpan SpnLookupTime { get { return default; } set { } } } public partial class UpnEndpointIdentity : System.ServiceModel.EndpointIdentity { public UpnEndpointIdentity(string upnName) { } } public partial class X509CertificateEndpointIdentity : System.ServiceModel.EndpointIdentity { public X509CertificateEndpointIdentity(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) { } public System.Security.Cryptography.X509Certificates.X509Certificate2Collection Certificates { get; } } } namespace System.ServiceModel.Channels { public partial interface ISecurityCapabilities { System.Net.Security.ProtectionLevel SupportedRequestProtectionLevel { get; } System.Net.Security.ProtectionLevel SupportedResponseProtectionLevel { get; } bool SupportsClientAuthentication { get; } bool SupportsClientWindowsIdentity { get; } bool SupportsServerAuthentication { get; } } public sealed partial class LocalClientSecuritySettings { public LocalClientSecuritySettings() { } public bool DetectReplays { get { return default; } set { } } public System.TimeSpan MaxClockSkew { get { return default; } set { } } public System.TimeSpan ReplayWindow { get { return default; } set { } } public System.TimeSpan TimestampValidityDuration { get { return default; } set { } } public System.ServiceModel.Channels.LocalClientSecuritySettings Clone() { return default; } } public abstract partial class SecurityBindingElement : System.ServiceModel.Channels.BindingElement { internal SecurityBindingElement() { } public System.ServiceModel.Security.Tokens.SupportingTokenParameters EndpointSupportingTokenParameters { get { return default; } } public bool IncludeTimestamp { get { return default; } set { } } public System.ServiceModel.Security.SecurityAlgorithmSuite DefaultAlgorithmSuite { get { return default; } set { } } public System.ServiceModel.Channels.LocalClientSecuritySettings LocalClientSettings { get { return default; } } public System.ServiceModel.MessageSecurityVersion MessageSecurityVersion { get { return default; } set { } } public System.ServiceModel.Channels.SecurityHeaderLayout SecurityHeaderLayout { get { return default; } set { } } public override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } protected abstract System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactoryCore<TChannel>(System.ServiceModel.Channels.BindingContext context); public override bool CanBuildChannelFactory<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } public static System.ServiceModel.Channels.SecurityBindingElement CreateSecureConversationBindingElement(System.ServiceModel.Channels.SecurityBindingElement bootstrapSecurity) { return default; } public static System.ServiceModel.Channels.TransportSecurityBindingElement CreateUserNameOverTransportBindingElement() { return default; } public static TransportSecurityBindingElement CreateIssuedTokenOverTransportBindingElement(System.ServiceModel.Security.Tokens.IssuedSecurityTokenParameters issuedTokenParameters) { return default; } public override T GetProperty<T>(System.ServiceModel.Channels.BindingContext context) { return default; } public override string ToString() { return default; } public System.ServiceModel.Security.SecurityKeyEntropyMode KeyEntropyMode { get { return default;} set { } } } public enum SecurityHeaderLayout { Lax = 1, Strict = 0, } public sealed partial class TransportSecurityBindingElement : System.ServiceModel.Channels.SecurityBindingElement { public TransportSecurityBindingElement() { } protected override System.ServiceModel.Channels.IChannelFactory<TChannel> BuildChannelFactoryCore<TChannel>(System.ServiceModel.Channels.BindingContext context) { return default; } public override System.ServiceModel.Channels.BindingElement Clone() { return default; } public override T GetProperty<T>(System.ServiceModel.Channels.BindingContext context) { return default; } } } namespace System.ServiceModel.Security { public enum SecurityKeyEntropyMode { ClientEntropy, ServerEntropy, CombinedEntropy } public abstract partial class BasicSecurityProfileVersion { internal BasicSecurityProfileVersion() { } public static System.ServiceModel.Security.BasicSecurityProfileVersion BasicSecurityProfile10 { get { return default; } } } public abstract partial class SecureConversationVersion { internal SecureConversationVersion() { } public static System.ServiceModel.Security.SecureConversationVersion Default { get { return default; } } public System.Xml.XmlDictionaryString Namespace { get { return default; } } public System.Xml.XmlDictionaryString Prefix { get { return default; } } public static System.ServiceModel.Security.SecureConversationVersion WSSecureConversationFeb2005 { get { return default; } } public static System.ServiceModel.Security.SecureConversationVersion WSSecureConversation13 { get { return default; } } } public abstract partial class SecurityAlgorithmSuite { static public SecurityAlgorithmSuite TripleDes { get { return default; } } protected SecurityAlgorithmSuite() { } public abstract string DefaultCanonicalizationAlgorithm { get; } public abstract string DefaultDigestAlgorithm { get; } public abstract string DefaultEncryptionAlgorithm { get; } public abstract int DefaultEncryptionKeyDerivationLength { get; } public abstract string DefaultSymmetricKeyWrapAlgorithm { get; } public abstract string DefaultAsymmetricKeyWrapAlgorithm { get; } public abstract string DefaultSymmetricSignatureAlgorithm { get; } public abstract string DefaultAsymmetricSignatureAlgorithm { get; } public abstract int DefaultSignatureKeyDerivationLength { get; } public abstract int DefaultSymmetricKeyLength { get; } } public abstract partial class SecurityPolicyVersion { internal SecurityPolicyVersion() { } public string Namespace { get { return default; } } public string Prefix { get { return default; } } public static System.ServiceModel.Security.SecurityPolicyVersion WSSecurityPolicy11 { get { return default; } } public static System.ServiceModel.Security.SecurityPolicyVersion WSSecurityPolicy12 { get { return default; } } } public abstract partial class SecurityVersion { internal SecurityVersion() { } public static System.ServiceModel.Security.SecurityVersion WSSecurity10 { get { return default; } } public static System.ServiceModel.Security.SecurityVersion WSSecurity11 { get { return default; } } } public abstract partial class TrustVersion { internal TrustVersion() { } public static System.ServiceModel.Security.TrustVersion Default { get { return default; } } public System.Xml.XmlDictionaryString Namespace { get { return default; } } public System.Xml.XmlDictionaryString Prefix { get { return default; } } public static System.ServiceModel.Security.TrustVersion WSTrustFeb2005 { get { return default; } } public static System.ServiceModel.Security.TrustVersion WSTrust13 { get { return default; } } } } namespace System.ServiceModel.Security.Tokens { public partial class BinarySecretSecurityToken : System.IdentityModel.Tokens.SecurityToken { public BinarySecretSecurityToken(string id, byte[] key) { } public BinarySecretSecurityToken(byte[] key) { } protected BinarySecretSecurityToken(string id, int keySizeInBits, bool allowCrypto) { } protected BinarySecretSecurityToken(string id, byte[] key, bool allowCrypto) { } public override string Id { get { return default; } } public override DateTime ValidFrom { get { return default; } } public override DateTime ValidTo { get { return default; } } public int KeySize { get { return default; } } public override System.Collections.ObjectModel.ReadOnlyCollection<System.IdentityModel.Tokens.SecurityKey> SecurityKeys { get { return default; } } public byte[] GetKeyBytes() { return default; } } public class IssuedSecurityTokenParameters : System.ServiceModel.Security.Tokens.SecurityTokenParameters { protected IssuedSecurityTokenParameters(IssuedSecurityTokenParameters other) { } public IssuedSecurityTokenParameters() { } protected override SecurityTokenParameters CloneCore() { return default; } public MessageSecurityVersion DefaultMessageSecurityVersion { get { return default; } set { } } public EndpointAddress IssuerAddress { get { return default; } set { } } public Channels.Binding IssuerBinding { get { return default; } set { } } public System.IdentityModel.Tokens.SecurityKeyType KeyType { get { return default; } set { } } public string TokenType { get { return default; } set { } } } public partial class SecureConversationSecurityTokenParameters : System.ServiceModel.Security.Tokens.SecurityTokenParameters { public SecureConversationSecurityTokenParameters() { } public SecureConversationSecurityTokenParameters(System.ServiceModel.Channels.SecurityBindingElement bootstrapSecurityBindingElement) { } public System.ServiceModel.Channels.SecurityBindingElement BootstrapSecurityBindingElement { get { return default; } set { } } protected override SecurityTokenParameters CloneCore() { return default; } public bool RequireCancellation { get { return default; } set { } } } public abstract partial class SecurityTokenParameters { internal SecurityTokenParameters() { } protected abstract SecurityTokenParameters CloneCore(); public bool RequireDerivedKeys { get { return default; } set { } } public System.ServiceModel.Security.Tokens.SecurityTokenParameters Clone() { return default; } } public abstract partial class ServiceModelSecurityTokenRequirement : System.IdentityModel.Selectors.SecurityTokenRequirement { protected ServiceModelSecurityTokenRequirement() { } static public string ChannelParametersCollectionProperty { get { return default; } } } public partial class SupportingTokenParameters { public SupportingTokenParameters() { } public System.Collections.ObjectModel.Collection<System.ServiceModel.Security.Tokens.SecurityTokenParameters> Endorsing { get { return default; } } public System.Collections.ObjectModel.Collection<System.ServiceModel.Security.Tokens.SecurityTokenParameters> SignedEncrypted { get { return default; } } public System.ServiceModel.Security.Tokens.SupportingTokenParameters Clone() { return default; } public System.Collections.ObjectModel.Collection<System.ServiceModel.Security.Tokens.SecurityTokenParameters> Signed { get { return default; } } } public partial class UserNameSecurityTokenParameters : System.ServiceModel.Security.Tokens.SecurityTokenParameters { public UserNameSecurityTokenParameters() { } protected override SecurityTokenParameters CloneCore() { return default; } } } namespace System.IdentityModel.Policy { public partial interface IAuthorizationPolicy {} } namespace System.IdentityModel.Tokens { public partial class GenericXmlSecurityToken : System.IdentityModel.Tokens.SecurityToken { public GenericXmlSecurityToken(System.Xml.XmlElement tokenXml, System.IdentityModel.Tokens.SecurityToken proofToken, DateTime effectiveTime, DateTime expirationTime, SecurityKeyIdentifierClause internalTokenReference, SecurityKeyIdentifierClause externalTokenReference, System.Collections.ObjectModel.ReadOnlyCollection<System.IdentityModel.Policy.IAuthorizationPolicy> authorizationPolicies) {} public override string Id { get; } public override DateTime ValidFrom { get; } public override DateTime ValidTo { get; } public override System.Collections.ObjectModel.ReadOnlyCollection<System.IdentityModel.Tokens.SecurityKey> SecurityKeys { get; } } public enum SecurityKeyType { SymmetricKey, AsymmetricKey, BearerKey } public partial class GenericXmlSecurityKeyIdentifierClause : SecurityKeyIdentifierClause { public GenericXmlSecurityKeyIdentifierClause(System.Xml.XmlElement referenceXml) : this(referenceXml, null, 0) { } public GenericXmlSecurityKeyIdentifierClause(System.Xml.XmlElement referenceXml, byte[] derivationNonce, int derivationLength) : base(null, derivationNonce, derivationLength) { } public System.Xml.XmlElement ReferenceXml { get { return default; } } public override bool Matches(SecurityKeyIdentifierClause keyIdentifierClause){ return default; } } }
// 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; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { /// <summary> /// CA1711: Identifiers should not have incorrect suffix /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldNotHaveIncorrectSuffixAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1711"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTypeNoAlternate = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageTypeNoAlternate), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberNewerVersion = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageMemberNewerVersion), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTypeNewerVersion = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageTypeNewerVersion), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberWithAlternate = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageMemberWithAlternate), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); internal static DiagnosticDescriptor TypeNoAlternateRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageTypeNoAlternate, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor MemberNewerVersionRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageMemberNewerVersion, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor TypeNewerVersionRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageTypeNewerVersion, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); internal static DiagnosticDescriptor MemberWithAlternateRule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessageMemberWithAlternate, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create( TypeNoAlternateRule, MemberNewerVersionRule, TypeNewerVersionRule, MemberWithAlternateRule); internal const string AttributeSuffix = "Attribute"; internal const string CollectionSuffix = "Collection"; internal const string DictionarySuffix = "Dictionary"; internal const string EventArgsSuffix = "EventArgs"; internal const string EventHandlerSuffix = "EventHandler"; internal const string ExSuffix = "Ex"; internal const string ExceptionSuffix = "Exception"; internal const string NewSuffix = "New"; internal const string PermissionSuffix = "Permission"; internal const string StreamSuffix = "Stream"; internal const string DelegateSuffix = "Delegate"; internal const string EnumSuffix = "Enum"; internal const string ImplSuffix = "Impl"; internal const string CoreSuffix = "Core"; internal const string QueueSuffix = "Queue"; internal const string StackSuffix = "Stack"; internal const string FlagSuffix = "Flag"; internal const string FlagsSuffix = "Flags"; // Dictionary that maps from a type name suffix to the set of base types from which // a type with that suffix is permitted to derive. private static readonly ImmutableDictionary<string, ImmutableArray<string>> s_suffixToBaseTypeNamesDictionary = ImmutableDictionary.CreateRange( new Dictionary<string, ImmutableArray<string>> { [AttributeSuffix] = ImmutableArray.CreateRange(new[] { "System.Attribute" }), [CollectionSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.IEnumerable" }), [DictionarySuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.IDictionary", "System.Collections.Generic.IDictionary`2", "System.Collections.Generic.IReadOnlyDictionary`2" }), [EventArgsSuffix] = ImmutableArray.CreateRange(new[] { "System.EventArgs" }), [ExceptionSuffix] = ImmutableArray.CreateRange(new[] { "System.Exception" }), [PermissionSuffix] = ImmutableArray.CreateRange(new[] { "System.Security.IPermission" }), [StreamSuffix] = ImmutableArray.CreateRange(new[] { "System.IO.Stream" }), [QueueSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.Queue", "System.Collections.Generic.Queue`1" }), [StackSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.Stack", "System.Collections.Generic.Stack`1" }) }); // Dictionary from type name suffix to an array containing the only types that are // allowed to have that suffix. private static readonly ImmutableDictionary<string, ImmutableArray<string>> s_suffixToAllowedTypesDictionary = ImmutableDictionary.CreateRange( new Dictionary<string, ImmutableArray<string>> { [DelegateSuffix] = ImmutableArray.CreateRange(new[] { "System.Delegate", "System.MulticastDelegate" }), [EventHandlerSuffix] = ImmutableArray.CreateRange(new[] { "System.EventHandler" }), [EnumSuffix] = ImmutableArray.CreateRange(new[] { "System.Enum" }) }); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); // Analyze type names. context.RegisterCompilationStartAction( compilationStartAnalysisContext => { var suffixToBaseTypeDictionaryBuilder = ImmutableDictionary.CreateBuilder<string, ImmutableArray<INamedTypeSymbol>>(); foreach (string suffix in s_suffixToBaseTypeNamesDictionary.Keys) { ImmutableArray<string> typeNames = s_suffixToBaseTypeNamesDictionary[suffix]; ImmutableArray<INamedTypeSymbol> namedTypeSymbolArray = ImmutableArray.CreateRange( typeNames.Select(typeName => compilationStartAnalysisContext.Compilation.GetOrCreateTypeByMetadataName(typeName)?.OriginalDefinition).WhereNotNull()); suffixToBaseTypeDictionaryBuilder.Add(suffix, namedTypeSymbolArray); } var suffixToBaseTypeDictionary = suffixToBaseTypeDictionaryBuilder.ToImmutableDictionary(); compilationStartAnalysisContext.RegisterSymbolAction( (SymbolAnalysisContext symbolAnalysisContext) => { var namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; // Note all the descriptors/rules for this analyzer have the same ID and category and hence // will always have identical configured visibility. if (!symbolAnalysisContext.Options.MatchesConfiguredVisibility(TypeNoAlternateRule, namedTypeSymbol, symbolAnalysisContext.Compilation, symbolAnalysisContext.CancellationToken)) { return; } var allowedSuffixes = symbolAnalysisContext.Options.GetStringOptionValue(EditorConfigOptionNames.AllowedSuffixes, TypeNoAlternateRule, namedTypeSymbol.Locations[0].SourceTree, symbolAnalysisContext.Compilation, symbolAnalysisContext.CancellationToken) .Split('|') .ToImmutableHashSet(); string name = namedTypeSymbol.Name; Compilation compilation = symbolAnalysisContext.Compilation; foreach (string suffix in s_suffixToBaseTypeNamesDictionary.Keys) { if (IsNotChildOfAnyButHasSuffix(namedTypeSymbol, suffixToBaseTypeDictionary[suffix], suffix, allowedSuffixes)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNoAlternateRule, name, suffix)); return; } } foreach (string suffix in s_suffixToAllowedTypesDictionary.Keys) { if (IsInvalidSuffix(name, suffix, allowedSuffixes) && !s_suffixToAllowedTypesDictionary[suffix].Contains(name)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNoAlternateRule, name, suffix)); return; } } if (IsInvalidSuffix(name, ImplSuffix, allowedSuffixes)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(MemberWithAlternateRule, ImplSuffix, name, CoreSuffix)); return; } // FxCop performed the length check for "Ex", but not for any of the other // suffixes, because alone among the suffixes, "Ex" is the only one that // isn't itself a known type or a language keyword. if (IsInvalidSuffix(name, ExSuffix, allowedSuffixes) && name.Length > ExSuffix.Length) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNewerVersionRule, ExSuffix, name)); return; } if (IsInvalidSuffix(name, NewSuffix, allowedSuffixes)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNewerVersionRule, NewSuffix, name)); return; } if (namedTypeSymbol.TypeKind == TypeKind.Enum) { if (IsInvalidSuffix(name, FlagSuffix, allowedSuffixes)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNoAlternateRule, name, FlagSuffix)); return; } if (IsInvalidSuffix(name, FlagsSuffix, allowedSuffixes)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNoAlternateRule, name, FlagsSuffix)); return; } } }, SymbolKind.NamedType); }); // Analyze method names. context.RegisterSymbolAction( (SymbolAnalysisContext context) => { var memberSymbol = context.Symbol; // Note all the descriptors/rules for this analyzer have the same ID and category and hence // will always have identical configured visibility. if (!context.Options.MatchesConfiguredVisibility(TypeNoAlternateRule, memberSymbol, context.Compilation, context.CancellationToken)) { return; } if (memberSymbol.IsOverride || memberSymbol.IsImplementationOfAnyInterfaceMember()) { return; } // If this is a method, and it's actually the getter or setter of a property, // then don't complain. We'll complain about the property itself. if (memberSymbol is IMethodSymbol methodSymbol && methodSymbol.IsPropertyAccessor()) { return; } string name = memberSymbol.Name; var allowedSuffixes = context.Options.GetStringOptionValue(EditorConfigOptionNames.AllowedSuffixes, TypeNoAlternateRule, memberSymbol.Locations[0].SourceTree, context.Compilation, context.CancellationToken) .Split('|') .ToImmutableHashSet(); if (IsInvalidSuffix(name, ExSuffix, allowedSuffixes)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberNewerVersionRule, ExSuffix, name)); return; } // We only fire on member suffix "New" if the type already defines // another member minus the suffix, e.g., we only fire on "MemberNew" if // "Member" already exists. For some reason FxCop did not apply the // same logic to the "Ex" suffix, and we follow FxCop's implementation. if (IsInvalidSuffix(name, NewSuffix, allowedSuffixes)) { string nameWithoutSuffix = name.WithoutSuffix(NewSuffix); INamedTypeSymbol containingType = memberSymbol.ContainingType; if (MemberNameExistsInHierarchy(nameWithoutSuffix, containingType, memberSymbol.Kind)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberNewerVersionRule, NewSuffix, name)); return; } } if (IsInvalidSuffix(name, ImplSuffix, allowedSuffixes)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberWithAlternateRule, ImplSuffix, name, CoreSuffix)); } }, SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property); } private static bool MemberNameExistsInHierarchy(string memberName, INamedTypeSymbol containingType, SymbolKind kind) { for (INamedTypeSymbol baseType = containingType; baseType != null; baseType = baseType.BaseType) { if (baseType.GetMembers(memberName).Any(member => member.Kind == kind)) { return true; } } return false; } private static bool IsNotChildOfAnyButHasSuffix(INamedTypeSymbol namedTypeSymbol, ImmutableArray<INamedTypeSymbol> parentTypes, string suffix, ImmutableHashSet<string> allowedSuffixes) { if (parentTypes.IsEmpty) { // Bail out if we cannot find any well-known types with the suffix in the compilation. return false; } return IsInvalidSuffix(namedTypeSymbol.Name, suffix, allowedSuffixes) && !parentTypes.Any(parentType => namedTypeSymbol.DerivesFromOrImplementsAnyConstructionOf(parentType)); } private static bool IsInvalidSuffix(string name, string suffix, ImmutableHashSet<string> allowedSuffixes) => !allowedSuffixes.Contains(suffix) && name.HasSuffix(suffix); } }
using DotNet.HighStock.Attributes; using DotNet.HighStock.Enums; using DotNet.HighStock.Helpers; using System; using System.Drawing; namespace DotNet.HighStock.Options { /// <summary> /// <p>The Y axis or value axis. Normally this is the vertical axis, though if the chart is inverted this is the horizontal axis. In case of multiple axes, the yAxis node is an array of configuration objects.</p> <p>See <a class='internal' href='#axis.object'>the Axis object</a> for programmatic access to the axis.</p> /// </summary> public class YAxis { /// <summary> /// Whether to allow decimals in this axis' ticks. When counting integers, like persons or hits on a web page, decimals must be avoided in the axis tick labels. /// Default: true /// </summary> public bool? AllowDecimals { get; set; } /// <summary> /// When using an alternate grid color, a band is painted across the plot area between every other grid line. /// </summary> public Color? AlternateGridColor { get; set; } /// <summary> /// <p>If categories are present for the xAxis, names are used instead of numbers for that axis. Since Highstock 3.0, categories can also be extracted by giving each point a <a href='#series.data'>name</a> and setting axis <a href='#xAxis.type'>type</a> to <code>'category'</code>.</p><p>Example:<pre>categories: ['Apples', 'Bananas', 'Oranges']</pre> Defaults to <code>null</code></p> /// </summary> public string[] Categories { get; set; } /// <summary> /// The highest allowed value for automatically computed axis extremes. /// </summary> public Number? Ceiling { get; set; } /// <summary> /// For a datetime axis, the scale will automatically adjust to the appropriate unit. This member gives the default string representations used for each unit. For an overview of the replacement codes, see dateFormat. Defaults to:<pre>{ millisecond: '%H:%M:%S.%L', second: '%H:%M:%S', minute: '%H:%M', hour: '%H:%M', day: '%e. %b', week: '%e. %b', month: '%b \'%y', year: '%Y'}</pre> /// </summary> public DateTimeLabel DateTimeLabelFormats { get; set; } /// <summary> /// Whether to force the axis to end on a tick. Use this option with the <code>maxPadding</code> option to control the axis end. /// Default: true /// </summary> public bool? EndOnTick { get; set; } public YAxisEvents Events { get; set; } /// <summary> /// The lowest allowed value for automatically computed axis extremes. /// Default: null /// </summary> public Number? Floor { get; set; } /// <summary> /// Color of the grid lines extending the ticks across the plot area. /// Default: #C0C0C0 /// </summary> public Color? GridLineColor { get; set; } /// <summary> /// The dash or dot style of the grid lines. For possible values, see <a href='http://jsfiddle.net/gh/get/jquery/1.7.2/highslide-software/highstock.com/tree/master/samples/highstock/plotoptions/series-dashstyle-all/'>this demonstration</a>. /// Default: Solid /// </summary> public DashStyles? GridLineDashStyle { get; set; } /// <summary> /// Polar charts only. Whether the grid lines should draw as a polygon with straight lines between categories, or as circles. Can be either <code>circle</code> or <code>polygon</code>. /// Default: null /// </summary> public string GridLineInterpolation { get; set; } /// <summary> /// The width of the grid lines extending the ticks across the plot area. /// Default: 1 /// </summary> public Number? GridLineWidth { get; set; } /// <summary> /// The Z index of the grid lines. /// Default: 1 /// </summary> public Number? GridZIndex { get; set; } /// <summary> /// An id for the axis. This can be used after render time to get a pointer to the axis object through <code>chart.get()</code>. /// </summary> public string Id { get; set; } public YAxisLabels Labels { get; set; } /// <summary> /// The color of the line marking the axis itself. /// Default: #C0D0E0 /// </summary> public Color? LineColor { get; set; } /// <summary> /// The width of the line marking the axis itself. /// Default: 0 /// </summary> public Number? LineWidth { get; set; } /// <summary> /// Index of another axis that this axis is linked to. When an axis is linked to a master axis, it will take the same extremes as the master, but as assigned by min or max or by setExtremes. It can be used to show additional info, or to ease reading the chart by duplicating the scales. /// </summary> public Number? LinkedTo { get; set; } /// <summary> /// The maximum value of the axis. If <code>null</code>, the max value is automatically calculated. If the <code>endOnTick</code> option is true, the <code>max</code> value might be rounded up. The actual maximum value is also influenced by <a class='internal' href='#chart'>chart.alignTicks</a>. /// </summary> public Number? Max { get; set; } /// <summary> /// Solid gauge only. Unless <a href='#yAxis.stops'>stops</a> are set, the color to represent the maximum value of the Y axis. /// Default: #102D4C /// </summary> public Color? MaxColor { get; set; } /// <summary> /// Padding of the max value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the highest data value to appear on the edge of the plot area. /// Default: 0.05 /// </summary> public Number? MaxPadding { get; set; } [Obsolete("Deprecated. Renamed to <code>minRange</code> as of Highstock 2.2.")] public Number? MaxZoom { get; set; } /// <summary> /// The minimum value of the axis. If <code>null</code> the min value is automatically calculated. If the <code>startOnTick</code> option is true, the <code>min</code> value might be rounded down. /// </summary> public Number? Min { get; set; } /// <summary> /// Solid gauge only. Unless <a href='#yAxis.stops'>stops</a> are set, the color to represent the minimum value of the Y axis. /// Default: #EFEFFF /// </summary> public Color? MinColor { get; set; } /// <summary> /// Padding of the min value relative to the length of the axis. A padding of 0.05 will make a 100px axis 5px longer. This is useful when you don't want the lowest data value to appear on the edge of the plot area. /// Default: 0.05 /// </summary> public Number? MinPadding { get; set; } /// <summary> /// <p>The minimum range to display on this axis. The entire axis will not be allowed to span over a smaller interval than this. For example, for a datetime axis the main unit is milliseconds. If minRange is set to 3600000, you can't zoom in more than to one hour.</p> <p>The default minRange for the x axis is five times the smallest interval between any of the data points.</p> <p>On a logarithmic axis, the unit for the minimum range is the power. So a minRange of 1 means that the axis can be zoomed to 10-100, 100-1000, 1000-10000 etc.</p> /// </summary> public Number? MinRange { get; set; } /// <summary> /// The minimum tick interval allowed in axis values. For example on zooming in on an axis with daily data, this can be used to prevent the axis from showing hours. /// </summary> public Number? MinTickInterval { get; set; } /// <summary> /// Color of the minor, secondary grid lines. /// Default: #E0E0E0 /// </summary> public Color? MinorGridLineColor { get; set; } /// <summary> /// The dash or dot style of the minor grid lines. For possible values, see <a href='http://jsfiddle.net/gh/get/jquery/1.7.1/highslide-software/highstock.com/tree/master/samples/highstock/plotoptions/series-dashstyle-all/'>this demonstration</a>. /// Default: Solid /// </summary> public DashStyles? MinorGridLineDashStyle { get; set; } /// <summary> /// Width of the minor, secondary grid lines. /// Default: 1 /// </summary> public Number? MinorGridLineWidth { get; set; } /// <summary> /// Color for the minor tick marks. /// Default: #A0A0A0 /// </summary> public Color? MinorTickColor { get; set; } /// <summary> /// <p>Tick interval in scale units for the minor ticks. On a linear axis, if <code>'auto'</code>, the minor tick interval is calculated as a fifth of the tickInterval. If <code>null</code>, minor ticks are not shown.</p> <p>On logarithmic axes, the unit is the power of the value. For example, setting the minorTickInterval to 1 puts one tick on each of 0.1, 1, 10, 100 etc. Setting the minorTickInterval to 0.1 produces 9 ticks between 1 and 10, 10 and 100 etc. A minorTickInterval of 'auto' on a log axis results in a best guess, attempting to enter approximately 5 minor ticks between each major tick.</p><p>On axes using <a href='#xAxis.categories'>categories</a>, minor ticks are not supported.</p> /// </summary> public Number? MinorTickInterval { get; set; } /// <summary> /// The pixel length of the minor tick marks. /// Default: 2 /// </summary> public Number? MinorTickLength { get; set; } /// <summary> /// The position of the minor tick marks relative to the axis line. Can be one of <code>inside</code> and <code>outside</code>. /// Default: outside /// </summary> public TickPositions? MinorTickPosition { get; set; } /// <summary> /// The pixel width of the minor tick mark. /// Default: 0 /// </summary> public Number? MinorTickWidth { get; set; } /// <summary> /// The distance in pixels from the plot area to the axis line. A positive offset moves the axis with it's line, labels and ticks away from the plot area. This is typically used when two or more axes are displayed on the same side of the plot. /// Default: 0 /// </summary> public Number? Offset { get; set; } /// <summary> /// Whether to display the axis on the opposite side of the normal. The normal is on the left side for vertical axes and bottom for horizontal, so the opposite sides will be right and top respectively. This is typically used with dual or multiple axes. /// Default: false /// </summary> public bool? Opposite { get; set; } public YAxisPlotBands[] PlotBands { get; set; } public YAxisPlotLines[] PlotLines { get; set; } /// <summary> /// Whether to reverse the axis so that the highest number is closest to the origin. If the chart is inverted, the x axis is reversed by default. /// Default: false /// </summary> public bool? Reversed { get; set; } /// <summary> /// If <code>true</code>, the first series in a stack will be drawn on top in a positive, non-reversed Y axis. If <code>false</code>, the first series is in the base of the stack. /// Default: true /// </summary> public bool? ReversedStacks { get; set; } /// <summary> /// Whether to show the axis line and title when the axis has no data. /// Default: true /// </summary> public bool? ShowEmpty { get; set; } /// <summary> /// Whether to show the first tick label. /// Default: true /// </summary> public bool? ShowFirstLabel { get; set; } /// <summary> /// Whether to show the last tick label. /// Default: true /// </summary> public bool? ShowLastLabel { get; set; } /// <summary> /// The stack labels show the total value for each bar in a stacked column or bar chart. The label will be placed on top of positive columns and below negative columns. In case of an inverted column chart or a bar chart the label is placed to the right of positive bars and to the left of negative bars. /// </summary> public YAxisStackLabels StackLabels { get; set; } /// <summary> /// For datetime axes, this decides where to put the tick between weeks. 0 = Sunday, 1 = Monday. /// Default: 1 /// </summary> public WeekDays? StartOfWeek { get; set; } /// <summary> /// Whether to force the axis to start on a tick. Use this option with the <code>maxPadding</code> option to control the axis start. /// Default: true /// </summary> public bool? StartOnTick { get; set; } /// <summary> /// <p>Solid gauge series only. Color stops for the solid gauge. Use this in cases where a linear gradient between a <code>minColor</code> and <code>maxColor</code> is not sufficient. The stops is an array of tuples, where the first item is a float between 0 and 1 assigning the relative position in the gradient, and the second item is the color.</p><p>For solid gauges, the Y axis also inherits the concept of <a href='http://api.highstock.com/highmaps#colorAxis.dataClasses'>data classes</a> from the Highmaps color axis.</p> /// </summary> [JsonFormatter(addPropertyName: false, useCurlyBracketsForObject: false)] public Gradient Stops { get; set; } /// <summary> /// Color for the main tick marks. /// Default: #C0D0E0 /// </summary> public Color? TickColor { get; set; } /// <summary> /// <p>The interval of the tick marks in axis units. When <code>null</code>, the tick interval is computed to approximately follow the <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> on linear and datetime axes. On categorized axes, a <code>null</code> tickInterval will default to 1, one category. Note that datetime axes are based on milliseconds, so for example an interval of one day is expressed as <code>24 * 3600 * 1000</code>.</p> <p>On logarithmic axes, the tickInterval is based on powers, so a tickInterval of 1 means one tick on each of 0.1, 1, 10, 100 etc. A tickInterval of 2 means a tick of 0.1, 10, 1000 etc. A tickInterval of 0.2 puts a tick on 0.1, 0.2, 0.4, 0.6, 0.8, 1, 2, 4, 6, 8, 10, 20, 40 etc.</p> /// </summary> public Number? TickInterval { get; set; } /// <summary> /// The pixel length of the main tick marks. /// Default: 10 /// </summary> public Number? TickLength { get; set; } /// <summary> /// If tickInterval is <code>null</code> this option sets the approximate pixel interval of the tick marks. Not applicable to categorized axis. Defaults to <code>72</code> for the Y axis and <code>100</code> forthe X axis. /// </summary> public Number? TickPixelInterval { get; set; } /// <summary> /// The position of the major tick marks relative to the axis line. Can be one of <code>inside</code> and <code>outside</code>. /// Default: outside /// </summary> public TickPositions? TickPosition { get; set; } /// <summary> /// A callback function returning array defining where the ticks are laid out on the axis. This overrides the default behaviour of <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> and <a href='#xAxis.tickInterval'>tickInterval</a>. /// </summary> [JsonFormatter("{0}")] public string TickPositioner { get; set; } /// <summary> /// An array defining where the ticks are laid out on the axis. This overrides the default behaviour of <a href='#xAxis.tickPixelInterval'>tickPixelInterval</a> and <a href='#xAxis.tickInterval'>tickInterval</a>. /// </summary> public Number?[] TickPositions { get; set; } /// <summary> /// The pixel width of the major tick marks. /// Default: 0 /// </summary> public Number? TickWidth { get; set; } /// <summary> /// For categorized axes only. If 'on' the tick mark is placed in the center of the category, if 'between' the tick mark is placed between categories. /// Default: between /// </summary> public Placement? TickmarkPlacement { get; set; } public YAxisTitle Title { get; set; } /// <summary> /// The type of axis. Can be one of <code>'linear'</code>, <code>'logarithmic'</code>, <code>'datetime'</code> or <code>'category'</code>. In a datetime axis, the numbers are given in milliseconds, and tick marks are placed on appropriate values like full hours or days. In a category axis, the <a href='#series.data'>point names</a> of the chart's series are used for categories, if not a <a href='#xAxis.categories'>categories</a> array is defined. /// Default: linear /// </summary> public AxisTypes? Type { get; set; } /// <summary> /// The height of the Y axis. If it's a number, it is interpreted as pixels. Since Highstock 2: If it's a percentage string, it is interpreted as percentages of the total plot height. /// Default: null /// </summary> public string Height { get; set; } /// <summary> /// The top position of the Y axis. If it's a number, it is interpreted as pixel position relative to the chart. Since Highstock 2: If it's a percentage string, it is interpreted as percentages of the plot height, offset from plot area top. /// Default: null /// </summary> public string Top { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing.Printing { /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind"]/*' /> /// <devdoc> /// <para> /// Specifies the standard paper sizes. /// </para> /// </devdoc> [Serializable] public enum PaperKind { /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Custom"]/*' /> /// <devdoc> /// <para> /// The paper size is defined by the user. /// </para> /// </devdoc> Custom = 0, // I got this information from two places: MSDN's writeup of DEVMODE // (http://msdn.microsoft.com/library/psdk/gdi/prntspol_8nle.htm), // and the raw C++ header file (wingdi.h). Beyond that, your guess // is as good as mine as to what these members mean. /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Letter"]/*' /> /// <devdoc> /// <para> /// Letter paper (8.5 in. /// by 11 in.). /// </para> /// </devdoc> Letter = SafeNativeMethods.DMPAPER_LETTER, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Legal"]/*' /> /// <devdoc> /// <para> /// Legal paper (8.5 in. /// by 14 /// in.). /// </para> /// </devdoc> Legal = SafeNativeMethods.DMPAPER_LEGAL, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A4"]/*' /> /// <devdoc> /// <para> /// A4 paper (210 /// mm by 297 /// mm). /// </para> /// </devdoc> A4 = SafeNativeMethods.DMPAPER_A4, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.CSheet"]/*' /> /// <devdoc> /// C paper (17 in. by 22 in.). /// </devdoc> CSheet = SafeNativeMethods.DMPAPER_CSHEET, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.DSheet"]/*' /> /// <devdoc> /// <para> /// D paper (22 /// in. by 34 in.). /// </para> /// </devdoc> DSheet = SafeNativeMethods.DMPAPER_DSHEET, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.ESheet"]/*' /> /// <devdoc> /// <para> /// E paper (34 /// in. by 44 in.). /// </para> /// </devdoc> ESheet = SafeNativeMethods.DMPAPER_ESHEET, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.LetterSmall"]/*' /> /// <devdoc> /// <para> /// Letter small paper (8.5 in. by 11 in.). /// </para> /// </devdoc> LetterSmall = SafeNativeMethods.DMPAPER_LETTERSMALL, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Tabloid"]/*' /> /// <devdoc> /// <para> /// Tabloid paper (11 /// in. by 17 in.). /// </para> /// </devdoc> Tabloid = SafeNativeMethods.DMPAPER_TABLOID, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Ledger"]/*' /> /// <devdoc> /// <para> /// Ledger paper (17 /// in. by 11 in.). /// </para> /// </devdoc> Ledger = SafeNativeMethods.DMPAPER_LEDGER, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Statement"]/*' /> /// <devdoc> /// <para> /// Statement paper (5.5 /// in. by 8.5 in.). /// </para> /// </devdoc> Statement = SafeNativeMethods.DMPAPER_STATEMENT, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Executive"]/*' /> /// <devdoc> /// <para> /// Executive paper (7.25 /// in. by 10.5 /// in.). /// </para> /// </devdoc> Executive = SafeNativeMethods.DMPAPER_EXECUTIVE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A3"]/*' /> /// <devdoc> /// <para> /// A3 paper /// (297 mm by 420 mm). /// </para> /// </devdoc> A3 = SafeNativeMethods.DMPAPER_A3, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A4Small"]/*' /> /// <devdoc> /// <para> /// A4 small paper /// (210 mm by 297 mm). /// </para> /// </devdoc> A4Small = SafeNativeMethods.DMPAPER_A4SMALL, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A5"]/*' /> /// <devdoc> /// <para> /// A5 paper (148 /// mm by 210 /// mm). /// </para> /// </devdoc> A5 = SafeNativeMethods.DMPAPER_A5, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B4"]/*' /> /// <devdoc> /// <para> /// B4 paper (250 mm by 353 mm). /// </para> /// </devdoc> B4 = SafeNativeMethods.DMPAPER_B4, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B5"]/*' /> /// <devdoc> /// <para> /// B5 paper (176 /// mm by 250 mm). /// </para> /// </devdoc> B5 = SafeNativeMethods.DMPAPER_B5, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Folio"]/*' /> /// <devdoc> /// <para> /// Folio paper (8.5 /// in. by 13 in.). /// </para> /// </devdoc> Folio = SafeNativeMethods.DMPAPER_FOLIO, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Quarto"]/*' /> /// <devdoc> /// <para> /// Quarto paper (215 /// mm by 275 mm). /// </para> /// </devdoc> Quarto = SafeNativeMethods.DMPAPER_QUARTO, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Standard10x14"]/*' /> /// <devdoc> /// <para> /// 10-by-14-inch paper. /// /// </para> /// </devdoc> Standard10x14 = SafeNativeMethods.DMPAPER_10X14, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Standard11x17"]/*' /> /// <devdoc> /// <para> /// 11-by-17-inch paper. /// /// </para> /// </devdoc> Standard11x17 = SafeNativeMethods.DMPAPER_11X17, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Note"]/*' /> /// <devdoc> /// <para> /// Note paper (8.5 in. /// by 11 in.). /// </para> /// </devdoc> Note = SafeNativeMethods.DMPAPER_NOTE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Number9Envelope"]/*' /> /// <devdoc> /// <para> /// #9 envelope (3.875 /// in. by 8.875 in.). /// </para> /// </devdoc> Number9Envelope = SafeNativeMethods.DMPAPER_ENV_9, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Number10Envelope"]/*' /> /// <devdoc> /// <para> /// #10 envelope /// (4.125 in. by 9.5 in.). /// </para> /// </devdoc> Number10Envelope = SafeNativeMethods.DMPAPER_ENV_10, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Number11Envelope"]/*' /> /// <devdoc> /// <para> /// #11 envelope (4.5 /// in. by 10.375 in.). /// </para> /// </devdoc> Number11Envelope = SafeNativeMethods.DMPAPER_ENV_11, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Number12Envelope"]/*' /> /// <devdoc> /// <para> /// #12 envelope (4.75 /// in. by 11 in.). /// </para> /// </devdoc> Number12Envelope = SafeNativeMethods.DMPAPER_ENV_12, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Number14Envelope"]/*' /> /// <devdoc> /// <para> /// #14 envelope (5 in. by 11.5 in.). /// </para> /// </devdoc> Number14Envelope = SafeNativeMethods.DMPAPER_ENV_14, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.DLEnvelope"]/*' /> /// <devdoc> /// <para> /// DL envelope /// (110 mm by 220 mm). /// </para> /// </devdoc> DLEnvelope = SafeNativeMethods.DMPAPER_ENV_DL, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.C5Envelope"]/*' /> /// <devdoc> /// <para> /// C5 envelope /// (162 mm by 229 mm). /// </para> /// </devdoc> C5Envelope = SafeNativeMethods.DMPAPER_ENV_C5, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.C3Envelope"]/*' /> /// <devdoc> /// C3 envelope (324 mm by 458 mm). /// </devdoc> C3Envelope = SafeNativeMethods.DMPAPER_ENV_C3, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.C4Envelope"]/*' /> /// <devdoc> /// <para> /// C4 envelope (229 /// mm by 324 mm). /// </para> /// </devdoc> C4Envelope = SafeNativeMethods.DMPAPER_ENV_C4, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.C6Envelope"]/*' /> /// <devdoc> /// C6 envelope (114 mm by 162 mm). /// </devdoc> C6Envelope = SafeNativeMethods.DMPAPER_ENV_C6, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.C65Envelope"]/*' /> /// <devdoc> /// <para> /// C65 envelope (114 /// mm by 229 mm). /// </para> /// </devdoc> C65Envelope = SafeNativeMethods.DMPAPER_ENV_C65, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B4Envelope"]/*' /> /// <devdoc> /// <para> /// B4 envelope (250 mm by 353 mm). /// </para> /// </devdoc> B4Envelope = SafeNativeMethods.DMPAPER_ENV_B4, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B5Envelope"]/*' /> /// <devdoc> /// <para> /// B5 envelope (176 /// mm by 250 mm). /// </para> /// </devdoc> B5Envelope = SafeNativeMethods.DMPAPER_ENV_B5, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B6Envelope"]/*' /> /// <devdoc> /// <para> /// B6 envelope (176 /// mm by 125 mm). /// </para> /// </devdoc> B6Envelope = SafeNativeMethods.DMPAPER_ENV_B6, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.ItalyEnvelope"]/*' /> /// <devdoc> /// <para> /// Italy envelope (110 mm by 230 mm). /// </para> /// </devdoc> ItalyEnvelope = SafeNativeMethods.DMPAPER_ENV_ITALY, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.MonarchEnvelope"]/*' /> /// <devdoc> /// <para> /// Monarch envelope (3.875 /// in. by 7.5 in.). /// </para> /// </devdoc> MonarchEnvelope = SafeNativeMethods.DMPAPER_ENV_MONARCH, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PersonalEnvelope"]/*' /> /// <devdoc> /// <para> /// 6 3/4 envelope /// (3.625 in. by 6.5 in.). /// </para> /// </devdoc> PersonalEnvelope = SafeNativeMethods.DMPAPER_ENV_PERSONAL, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.USStandardFanfold"]/*' /> /// <devdoc> /// <para> /// US standard /// fanfold (14.875 in. by 11 in.). /// </para> /// </devdoc> USStandardFanfold = SafeNativeMethods.DMPAPER_FANFOLD_US, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.GermanStandardFanfold"]/*' /> /// <devdoc> /// <para> /// German standard fanfold /// (8.5 in. by 12 in.). /// </para> /// </devdoc> GermanStandardFanfold = SafeNativeMethods.DMPAPER_FANFOLD_STD_GERMAN, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.GermanLegalFanfold"]/*' /> /// <devdoc> /// <para> /// German legal fanfold /// (8.5 in. by 13 in.). /// </para> /// </devdoc> GermanLegalFanfold = SafeNativeMethods.DMPAPER_FANFOLD_LGL_GERMAN, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.IsoB4"]/*' /> /// <devdoc> /// <para> /// ISO B4 (250 mm by 353 mm). /// </para> /// </devdoc> IsoB4 = SafeNativeMethods.DMPAPER_ISO_B4, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapanesePostcard"]/*' /> /// <devdoc> /// <para> /// Japanese postcard (100 mm by 148 mm). /// </para> /// </devdoc> JapanesePostcard = SafeNativeMethods.DMPAPER_JAPANESE_POSTCARD, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Standard9x11"]/*' /> /// <devdoc> /// <para> /// 9-by-11-inch /// paper. /// /// </para> /// </devdoc> Standard9x11 = SafeNativeMethods.DMPAPER_9X11, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Standard10x11"]/*' /> /// <devdoc> /// <para> /// 10-by-11-inch paper. /// /// </para> /// </devdoc> Standard10x11 = SafeNativeMethods.DMPAPER_10X11, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Standard15x11"]/*' /> /// <devdoc> /// <para> /// 15-by-11-inch paper. /// /// </para> /// </devdoc> Standard15x11 = SafeNativeMethods.DMPAPER_15X11, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.InviteEnvelope"]/*' /> /// <devdoc> /// <para> /// Invite envelope (220 /// mm by 220 mm). /// </para> /// </devdoc> InviteEnvelope = SafeNativeMethods.DMPAPER_ENV_INVITE, //= SafeNativeMethods.DMPAPER_RESERVED_48, //= SafeNativeMethods.DMPAPER_RESERVED_49, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.LetterExtra"]/*' /> /// <devdoc> /// <para> /// Letter extra paper /// (9.275 in. by /// 12 in.). This value is specific to the PostScript driver and is used only /// by Linotronic printers in order to conserve paper. /// </para> /// </devdoc> LetterExtra = SafeNativeMethods.DMPAPER_LETTER_EXTRA, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.LegalExtra"]/*' /> /// <devdoc> /// <para> /// Legal extra /// paper (9.275 in. /// by 15 in.). This value is specific to the PostScript driver, and is used /// only by Linotronic printers in order to conserve paper. /// </para> /// </devdoc> LegalExtra = SafeNativeMethods.DMPAPER_LEGAL_EXTRA, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.TabloidExtra"]/*' /> /// <devdoc> /// <para> /// Tabloid extra paper /// (11.69 in. by 18 in.). This /// value is specific to the PostScript driver and is used only by Linotronic printers in order to conserve paper. /// </para> /// </devdoc> TabloidExtra = SafeNativeMethods.DMPAPER_TABLOID_EXTRA, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A4Extra"]/*' /> /// <devdoc> /// <para> /// A4 extra /// paper /// (236 mm by 322 mm). This value is specific to the PostScript driver and is used only /// by Linotronic printers to help save paper. /// </para> /// </devdoc> A4Extra = SafeNativeMethods.DMPAPER_A4_EXTRA, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.LetterTransverse"]/*' /> /// <devdoc> /// <para> /// Letter transverse paper /// (8.275 in. by 11 in.). /// </para> /// </devdoc> LetterTransverse = SafeNativeMethods.DMPAPER_LETTER_TRANSVERSE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A4Transverse"]/*' /> /// <devdoc> /// <para> /// A4 transverse paper /// (210 mm by 297 mm). /// </para> /// </devdoc> A4Transverse = SafeNativeMethods.DMPAPER_A4_TRANSVERSE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.LetterExtraTransverse"]/*' /> /// <devdoc> /// <para> /// Letter extra transverse /// paper (9.275 in. by 12 /// in.). /// </para> /// </devdoc> LetterExtraTransverse = SafeNativeMethods.DMPAPER_LETTER_EXTRA_TRANSVERSE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.APlus"]/*' /> /// <devdoc> /// <para> /// SuperA/SuperA/A4 paper (227 /// mm by 356 mm). /// </para> /// </devdoc> APlus = SafeNativeMethods.DMPAPER_A_PLUS, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.BPlus"]/*' /> /// <devdoc> /// <para> /// SuperB/SuperB/A3 paper (305 /// mm by 487 mm). /// </para> /// </devdoc> BPlus = SafeNativeMethods.DMPAPER_B_PLUS, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.LetterPlus"]/*' /> /// <devdoc> /// <para> /// Letter plus paper /// (8.5 in. by 12.69 in.). /// </para> /// </devdoc> LetterPlus = SafeNativeMethods.DMPAPER_LETTER_PLUS, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A4Plus"]/*' /> /// <devdoc> /// <para> /// A4 plus paper /// (210 mm by 330 mm). /// </para> /// </devdoc> A4Plus = SafeNativeMethods.DMPAPER_A4_PLUS, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A5Transverse"]/*' /> /// <devdoc> /// <para> /// A5 transverse paper /// (148 mm by 210 /// mm). /// </para> /// </devdoc> A5Transverse = SafeNativeMethods.DMPAPER_A5_TRANSVERSE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B5Transverse"]/*' /> /// <devdoc> /// <para> /// JIS B5 transverse /// paper (182 mm by 257 mm). /// </para> /// </devdoc> B5Transverse = SafeNativeMethods.DMPAPER_B5_TRANSVERSE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A3Extra"]/*' /> /// <devdoc> /// <para> /// A3 extra paper /// (322 mm by 445 mm). /// </para> /// </devdoc> A3Extra = SafeNativeMethods.DMPAPER_A3_EXTRA, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A5Extra"]/*' /> /// <devdoc> /// <para> /// A5 extra paper /// (174 mm by 235 mm). /// </para> /// </devdoc> A5Extra = SafeNativeMethods.DMPAPER_A5_EXTRA, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B5Extra"]/*' /> /// <devdoc> /// <para> /// ISO B5 extra /// paper (201 mm by 276 mm). /// </para> /// </devdoc> B5Extra = SafeNativeMethods.DMPAPER_B5_EXTRA, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A2"]/*' /> /// <devdoc> /// <para> /// A2 paper /// (420 /// mm by 594 mm). /// </para> /// </devdoc> A2 = SafeNativeMethods.DMPAPER_A2, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A3Transverse"]/*' /> /// <devdoc> /// <para> /// A3 transverse paper /// (297 mm by 420 mm). /// </para> /// </devdoc> A3Transverse = SafeNativeMethods.DMPAPER_A3_TRANSVERSE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A3ExtraTransverse"]/*' /> /// <devdoc> /// <para> /// A3 extra transverse /// paper (322 mm by 445 mm). /// </para> /// </devdoc> A3ExtraTransverse = SafeNativeMethods.DMPAPER_A3_EXTRA_TRANSVERSE, /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseDoublePostcard"]/*' /> /// <devdoc> /// <para> /// Japanese double postcard /// (200 mm by 148 /// mm). Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseDoublePostcard = SafeNativeMethods.DMPAPER_DBL_JAPANESE_POSTCARD, /* Japanese Double Postcard 200 x 148 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A6"]/*' /> /// <devdoc> /// <para> /// A6 paper (105 /// mm by 148 mm). Requires /// Windows 98, /// Windows /// NT 4.0, or later. /// </para> /// </devdoc> A6 = SafeNativeMethods.DMPAPER_A6, /* A6 105 x 148 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeKakuNumber2"]/*' /> /// <devdoc> /// <para> /// Japanese Kaku #2 envelope. Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeKakuNumber2 = SafeNativeMethods.DMPAPER_JENV_KAKU2, /* Japanese Envelope Kaku #2 */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeKakuNumber3"]/*' /> /// <devdoc> /// <para> /// Japanese Kaku #3 envelope. Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeKakuNumber3 = SafeNativeMethods.DMPAPER_JENV_KAKU3, /* Japanese Envelope Kaku #3 */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeChouNumber3"]/*' /> /// <devdoc> /// <para> /// Japanese Chou #3 envelope. Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeChouNumber3 = SafeNativeMethods.DMPAPER_JENV_CHOU3, /* Japanese Envelope Chou #3 */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeChouNumber4"]/*' /> /// <devdoc> /// <para> /// Japanese Chou #4 envelope. Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeChouNumber4 = SafeNativeMethods.DMPAPER_JENV_CHOU4, /* Japanese Envelope Chou #4 */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.LetterRotated"]/*' /> /// <devdoc> /// <para> /// Letter rotated paper (11 /// in. by /// 8.5 in.). /// </para> /// </devdoc> LetterRotated = SafeNativeMethods.DMPAPER_LETTER_ROTATED, /* Letter Rotated 11 x 8 1/2 11 in */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A3Rotated"]/*' /> /// <devdoc> /// <para> /// A3 /// rotated paper (420mm by 297 mm). /// </para> /// </devdoc> A3Rotated = SafeNativeMethods.DMPAPER_A3_ROTATED, /* A3 Rotated 420 x 297 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A4Rotated"]/*' /> /// <devdoc> /// <para> /// A4 rotated paper /// (297 mm by 210 mm). /// Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> A4Rotated = SafeNativeMethods.DMPAPER_A4_ROTATED, /* A4 Rotated 297 x 210 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A5Rotated"]/*' /> /// <devdoc> /// <para> /// A5 rotated paper /// (210 mm by 148 mm). /// Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> A5Rotated = SafeNativeMethods.DMPAPER_A5_ROTATED, /* A5 Rotated 210 x 148 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B4JisRotated"]/*' /> /// <devdoc> /// <para> /// JIS B4 rotated /// paper (364 mm by 257 /// mm). Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> B4JisRotated = SafeNativeMethods.DMPAPER_B4_JIS_ROTATED, /* B4 (JIS) Rotated 364 x 257 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B5JisRotated"]/*' /> /// <devdoc> /// <para> /// JIS B5 rotated /// paper (257 mm by 182 /// mm). Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> B5JisRotated = SafeNativeMethods.DMPAPER_B5_JIS_ROTATED, /* B5 (JIS) Rotated 257 x 182 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapanesePostcardRotated"]/*' /> /// <devdoc> /// <para> /// Japanese rotated postcard /// (148 mm by 100 /// mm). Requires Windows /// 98, /// Windows NT 4.0, or later. /// </para> /// </devdoc> JapanesePostcardRotated = SafeNativeMethods.DMPAPER_JAPANESE_POSTCARD_ROTATED, /* Japanese Postcard Rotated 148 x 100 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseDoublePostcardRotated"]/*' /> /// <devdoc> /// <para> /// Japanese rotated double /// postcard (148 mm by /// 200 mm). Requires /// Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseDoublePostcardRotated = SafeNativeMethods.DMPAPER_DBL_JAPANESE_POSTCARD_ROTATED, /* Double Japanese Postcard Rotated 148 x 200 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.A6Rotated"]/*' /> /// <devdoc> /// <para> /// A6 /// rotated paper /// (148 mm by 105 mm). /// Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> A6Rotated = SafeNativeMethods.DMPAPER_A6_ROTATED, /* A6 Rotated 148 x 105 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeKakuNumber2Rotated"]/*' /> /// <devdoc> /// <para> /// Japanese rotated Kaku #2 envelope. Requires /// Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeKakuNumber2Rotated = SafeNativeMethods.DMPAPER_JENV_KAKU2_ROTATED, /* Japanese Envelope Kaku #2 Rotated */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeKakuNumber3Rotated"]/*' /> /// <devdoc> /// <para> /// Japanese rotated Kaku #3 envelope. Requires /// Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeKakuNumber3Rotated = SafeNativeMethods.DMPAPER_JENV_KAKU3_ROTATED, /* Japanese Envelope Kaku #3 Rotated */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeChouNumber3Rotated"]/*' /> /// <devdoc> /// <para> /// Japanese rotated Chou #3 envelope. Requires /// Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeChouNumber3Rotated = SafeNativeMethods.DMPAPER_JENV_CHOU3_ROTATED, /* Japanese Envelope Chou #3 Rotated */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeChouNumber4Rotated"]/*' /> /// <devdoc> /// <para> /// Japanese rotated Chou #4 envelope. Requires /// Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeChouNumber4Rotated = SafeNativeMethods.DMPAPER_JENV_CHOU4_ROTATED, /* Japanese Envelope Chou #4 Rotated */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B6Jis"]/*' /> /// <devdoc> /// <para> /// JIS B6 paper /// (128 mm by 182 mm). /// Requires Windows 98, /// Windows NT 4.0, or later. /// </para> /// </devdoc> B6Jis = SafeNativeMethods.DMPAPER_B6_JIS, /* B6 (JIS) 128 x 182 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.B6JisRotated"]/*' /> /// <devdoc> /// <para> /// JIS B6 /// rotated paper (182 mm by 128 /// mm). Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> B6JisRotated = SafeNativeMethods.DMPAPER_B6_JIS_ROTATED, /* B6 (JIS) Rotated 182 x 128 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Standard12x11"]/*' /> /// <devdoc> /// <para> /// 12-by-11-inch paper. Requires Windows 98, /// Windows /// NT 4.0, or later. /// </para> /// </devdoc> Standard12x11 = SafeNativeMethods.DMPAPER_12X11, /* 12 x 11 in */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeYouNumber4"]/*' /> /// <devdoc> /// <para> /// Japanese You #4 envelope. Requires Windows /// 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeYouNumber4 = SafeNativeMethods.DMPAPER_JENV_YOU4, /* Japanese Envelope You #4 */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.JapaneseEnvelopeYouNumber4Rotated"]/*' /> /// <devdoc> /// <para> /// Japanese You #4 rotated envelope. Requires /// Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> JapaneseEnvelopeYouNumber4Rotated = SafeNativeMethods.DMPAPER_JENV_YOU4_ROTATED, /* Japanese Envelope You #4 Rotated*/ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Prc16K"]/*' /> /// <devdoc> /// <para> /// PRC 16K paper (146 mm /// by 215 /// mm). Requires Windows /// 98, Windows NT 4.0, /// or later. /// </para> /// </devdoc> Prc16K = SafeNativeMethods.DMPAPER_P16K, /* PRC 16K 146 x 215 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Prc32K"]/*' /> /// <devdoc> /// <para> /// PRC 32K paper (97 mm /// by 151 /// mm). Requires Windows 98, Windows /// NT 4.0, or later. /// </para> /// </devdoc> Prc32K = SafeNativeMethods.DMPAPER_P32K, /* PRC 32K 97 x 151 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Prc32KBig"]/*' /> /// <devdoc> /// <para> /// PRC 32K big paper (97 /// mm by /// 151 mm). Requires Windows 98, Windows /// NT 4.0, or later. /// </para> /// </devdoc> Prc32KBig = SafeNativeMethods.DMPAPER_P32KBIG, /* PRC 32K(Big) 97 x 151 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber1"]/*' /> /// <devdoc> /// <para> /// PRC #1 envelope (102 mm /// by 165 /// mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber1 = SafeNativeMethods.DMPAPER_PENV_1, /* PRC Envelope #1 102 x 165 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber2"]/*' /> /// <devdoc> /// <para> /// PRC #2 envelope (102 mm /// by 176 /// mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber2 = SafeNativeMethods.DMPAPER_PENV_2, /* PRC Envelope #2 102 x 176 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber3"]/*' /> /// <devdoc> /// <para> /// PRC #3 envelope (125 mm /// by 176 /// mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber3 = SafeNativeMethods.DMPAPER_PENV_3, /* PRC Envelope #3 125 x 176 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber4"]/*' /> /// <devdoc> /// <para> /// PRC #4 envelope (110 mm /// by 208 /// mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber4 = SafeNativeMethods.DMPAPER_PENV_4, /* PRC Envelope #4 110 x 208 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber5"]/*' /> /// <devdoc> /// <para> /// PRC #5 envelope (110 mm by 220 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber5 = SafeNativeMethods.DMPAPER_PENV_5, /* PRC Envelope #5 110 x 220 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber6"]/*' /> /// <devdoc> /// <para> /// PRC #6 envelope (120 mm by 230 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber6 = SafeNativeMethods.DMPAPER_PENV_6, /* PRC Envelope #6 120 x 230 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber7"]/*' /> /// <devdoc> /// <para> /// PRC #7 envelope (160 mm /// by 230 /// mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber7 = SafeNativeMethods.DMPAPER_PENV_7, /* PRC Envelope #7 160 x 230 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber8"]/*' /> /// <devdoc> /// <para> /// PRC #8 envelope (120 mm /// by 309 /// mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber8 = SafeNativeMethods.DMPAPER_PENV_8, /* PRC Envelope #8 120 x 309 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber9"]/*' /> /// <devdoc> /// <para> /// PRC #9 envelope (229 mm by 324 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber9 = SafeNativeMethods.DMPAPER_PENV_9, /* PRC Envelope #9 229 x 324 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber10"]/*' /> /// <devdoc> /// <para> /// PRC #10 envelope (324 mm /// by 458 /// mm). Requires Windows 98, Windows NT 4.0, or /// later. /// </para> /// </devdoc> PrcEnvelopeNumber10 = SafeNativeMethods.DMPAPER_PENV_10, /* PRC Envelope #10 324 x 458 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Prc16KRotated"]/*' /> /// <devdoc> /// <para> /// PRC 16K rotated paper (146 mm by 215 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> Prc16KRotated = SafeNativeMethods.DMPAPER_P16K_ROTATED, /* PRC 16K Rotated */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Prc32KRotated"]/*' /> /// <devdoc> /// <para> /// PRC 32K rotated paper (97 mm by 151 /// mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> Prc32KRotated = SafeNativeMethods.DMPAPER_P32K_ROTATED, /* PRC 32K Rotated */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.Prc32KBigRotated"]/*' /> /// <devdoc> /// <para> /// PRC 32K big rotated paper (97 mm by 151 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> Prc32KBigRotated = SafeNativeMethods.DMPAPER_P32KBIG_ROTATED, /* PRC 32K(Big) Rotated */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber1Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #1 rotated envelope (165 mm by 102 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber1Rotated = SafeNativeMethods.DMPAPER_PENV_1_ROTATED, /* PRC Envelope #1 Rotated 165 x 102 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber2Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #2 rotated envelope /// (176 mm by /// 102 mm). Requires Windows 98, Windows NT 4.0, or /// later. /// </para> /// </devdoc> PrcEnvelopeNumber2Rotated = SafeNativeMethods.DMPAPER_PENV_2_ROTATED, /* PRC Envelope #2 Rotated 176 x 102 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber3Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #3 rotated envelope /// (176 mm by /// 125 mm). Requires Windows 98, Windows NT 4.0, or /// later. /// </para> /// </devdoc> PrcEnvelopeNumber3Rotated = SafeNativeMethods.DMPAPER_PENV_3_ROTATED, /* PRC Envelope #3 Rotated 176 x 125 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber4Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #4 rotated envelope (208 mm by 110 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber4Rotated = SafeNativeMethods.DMPAPER_PENV_4_ROTATED, /* PRC Envelope #4 Rotated 208 x 110 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber5Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #5 rotated envelope (220 mm by 110 mm). Requires Windows 98, Windows NT 4.0, or /// later. /// </para> /// </devdoc> PrcEnvelopeNumber5Rotated = SafeNativeMethods.DMPAPER_PENV_5_ROTATED, /* PRC Envelope #5 Rotated 220 x 110 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber6Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #6 rotated envelope (230 mm by 120 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber6Rotated = SafeNativeMethods.DMPAPER_PENV_6_ROTATED, /* PRC Envelope #6 Rotated 230 x 120 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber7Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #7 rotated envelope (230 mm by 160 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber7Rotated = SafeNativeMethods.DMPAPER_PENV_7_ROTATED, /* PRC Envelope #7 Rotated 230 x 160 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber8Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #8 rotated /// envelope (309 mm /// by 120 /// mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber8Rotated = SafeNativeMethods.DMPAPER_PENV_8_ROTATED, /* PRC Envelope #8 Rotated 309 x 120 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber9Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #9 rotated envelope (324 mm by 229 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber9Rotated = SafeNativeMethods.DMPAPER_PENV_9_ROTATED, /* PRC Envelope #9 Rotated 324 x 229 mm */ /// <include file='doc\PaperKinds.uex' path='docs/doc[@for="PaperKind.PrcEnvelopeNumber10Rotated"]/*' /> /// <devdoc> /// <para> /// PRC #10 rotated envelope (458 mm by 324 mm). Requires Windows 98, Windows NT 4.0, or later. /// </para> /// </devdoc> PrcEnvelopeNumber10Rotated = SafeNativeMethods.DMPAPER_PENV_10_ROTATED, /* PRC Envelope #10 Rotated 458 x 324 mm */ // Other useful values: SafeNativeMethods.DMPAPER_LAST, SafeNativeMethods.DMPAPER_USER } }
#region License /* * WebSocketServiceManager.cs * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Threading; using WebSocketSharp.Net; namespace WebSocketSharp.Server { /// <summary> /// Provides the management function for the WebSocket services. /// </summary> /// <remarks> /// This class manages the WebSocket services provided by /// the <see cref="WebSocketServer"/> or <see cref="HttpServer"/>. /// </remarks> public class WebSocketServiceManager { #region Private Fields private volatile bool _clean; private Dictionary<string, WebSocketServiceHost> _hosts; private Logger _log; private volatile ServerState _state; private object _sync; private TimeSpan _waitTime; #endregion #region Internal Constructors internal WebSocketServiceManager (Logger log) { _log = log; _clean = true; _hosts = new Dictionary<string, WebSocketServiceHost> (); _state = ServerState.Ready; _sync = ((ICollection) _hosts).SyncRoot; _waitTime = TimeSpan.FromSeconds (1); } #endregion #region Public Properties /// <summary> /// Gets the number of the WebSocket services. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of the services. /// </value> public int Count { get { lock (_sync) return _hosts.Count; } } /// <summary> /// Gets the host instances for the WebSocket services. /// </summary> /// <value> /// <para> /// An <c>IEnumerable&lt;WebSocketServiceHost&gt;</c> instance. /// </para> /// <para> /// It provides an enumerator which supports the iteration over /// the collection of the host instances. /// </para> /// </value> public IEnumerable<WebSocketServiceHost> Hosts { get { lock (_sync) return _hosts.Values.ToList (); } } /// <summary> /// Gets the host instance for a WebSocket service with /// the specified <paramref name="path"/>. /// </summary> /// <remarks> /// <paramref name="path"/> is converted to a URL-decoded string and /// / is trimmed from the end of the converted string if any. /// </remarks> /// <value> /// <para> /// A <see cref="WebSocketServiceHost"/> instance or /// <see langword="null"/> if not found. /// </para> /// <para> /// That host instance provides the function to access /// the information in the service. /// </para> /// </value> /// <param name="path"> /// A <see cref="string"/> that represents an absolute path to /// the service to find. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// </exception> public WebSocketServiceHost this[string path] { get { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } WebSocketServiceHost host; InternalTryGetServiceHost (path, out host); return host; } } /// <summary> /// Gets or sets a value indicating whether the inactive sessions in /// the WebSocket services are cleaned up periodically. /// </summary> /// <remarks> /// The set operation does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <value> /// <c>true</c> if the inactive sessions are cleaned up every 60 seconds; /// otherwise, <c>false</c>. /// </value> public bool KeepClean { get { return _clean; } set { string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } foreach (var host in _hosts.Values) host.KeepClean = value; _clean = value; } } } /// <summary> /// Gets the paths for the WebSocket services. /// </summary> /// <value> /// <para> /// An <c>IEnumerable&lt;string&gt;</c> instance. /// </para> /// <para> /// It provides an enumerator which supports the iteration over /// the collection of the paths. /// </para> /// </value> public IEnumerable<string> Paths { get { lock (_sync) return _hosts.Keys.ToList (); } } /// <summary> /// Gets the total number of the sessions in the WebSocket services. /// </summary> /// <value> /// An <see cref="int"/> that represents the total number of /// the sessions in the services. /// </value> [Obsolete ("This property will be removed.")] public int SessionCount { get { var cnt = 0; foreach (var host in Hosts) { if (_state != ServerState.Start) break; cnt += host.Sessions.Count; } return cnt; } } /// <summary> /// Gets or sets the time to wait for the response to the WebSocket Ping or /// Close. /// </summary> /// <remarks> /// The set operation does nothing if the server has already started or /// it is shutting down. /// </remarks> /// <value> /// A <see cref="TimeSpan"/> to wait for the response. /// </value> /// <exception cref="ArgumentOutOfRangeException"> /// The value specified for a set operation is zero or less. /// </exception> public TimeSpan WaitTime { get { return _waitTime; } set { if (value <= TimeSpan.Zero) throw new ArgumentOutOfRangeException ("value", "Zero or less."); string msg; if (!canSet (out msg)) { _log.Warn (msg); return; } lock (_sync) { if (!canSet (out msg)) { _log.Warn (msg); return; } foreach (var host in _hosts.Values) host.WaitTime = value; _waitTime = value; } } } #endregion #region Private Methods private void broadcast (Opcode opcode, byte[] data, Action completed) { var cache = new Dictionary<CompressionMethod, byte[]> (); try { foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } host.Sessions.Broadcast (opcode, data, cache); } if (completed != null) completed (); } catch (Exception ex) { _log.Error (ex.Message); _log.Debug (ex.ToString ()); } finally { cache.Clear (); } } private void broadcast (Opcode opcode, Stream stream, Action completed) { var cache = new Dictionary<CompressionMethod, Stream> (); try { foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } host.Sessions.Broadcast (opcode, stream, cache); } if (completed != null) completed (); } catch (Exception ex) { _log.Error (ex.Message); _log.Debug (ex.ToString ()); } finally { foreach (var cached in cache.Values) cached.Dispose (); cache.Clear (); } } private void broadcastAsync (Opcode opcode, byte[] data, Action completed) { ThreadPool.QueueUserWorkItem ( state => broadcast (opcode, data, completed) ); } private void broadcastAsync (Opcode opcode, Stream stream, Action completed) { ThreadPool.QueueUserWorkItem ( state => broadcast (opcode, stream, completed) ); } private Dictionary<string, Dictionary<string, bool>> broadping ( byte[] frameAsBytes, TimeSpan timeout ) { var ret = new Dictionary<string, Dictionary<string, bool>> (); foreach (var host in Hosts) { if (_state != ServerState.Start) { _log.Error ("The server is shutting down."); break; } var res = host.Sessions.Broadping (frameAsBytes, timeout); ret.Add (host.Path, res); } return ret; } private bool canSet (out string message) { message = null; if (_state == ServerState.Start) { message = "The server has already started."; return false; } if (_state == ServerState.ShuttingDown) { message = "The server is shutting down."; return false; } return true; } #endregion #region Internal Methods internal void Add<TBehavior> (string path, Func<TBehavior> creator) where TBehavior : WebSocketBehavior { path = HttpUtility.UrlDecode (path).TrimSlashFromEnd (); lock (_sync) { WebSocketServiceHost host; if (_hosts.TryGetValue (path, out host)) throw new ArgumentException ("Already in use.", "path"); host = new WebSocketServiceHost<TBehavior> ( path, creator, null, _log ); if (!_clean) host.KeepClean = false; if (_waitTime != host.WaitTime) host.WaitTime = _waitTime; if (_state == ServerState.Start) host.Start (); _hosts.Add (path, host); } } internal bool InternalTryGetServiceHost ( string path, out WebSocketServiceHost host ) { path = HttpUtility.UrlDecode (path).TrimSlashFromEnd (); lock (_sync) return _hosts.TryGetValue (path, out host); } internal void Start () { lock (_sync) { foreach (var host in _hosts.Values) host.Start (); _state = ServerState.Start; } } internal void Stop (ushort code, string reason) { lock (_sync) { _state = ServerState.ShuttingDown; foreach (var host in _hosts.Values) host.Stop (code, reason); _state = ServerState.Stop; } } #endregion #region Public Methods /// <summary> /// Adds a WebSocket service with the specified behavior, /// <paramref name="path"/>, and <paramref name="initializer"/>. /// </summary> /// <remarks> /// <paramref name="path"/> is converted to a URL-decoded string and /// / is trimmed from the end of the converted string if any. /// </remarks> /// <param name="path"> /// A <see cref="string"/> that represents an absolute path to /// the service to add. /// </param> /// <param name="initializer"> /// <para> /// An <c>Action&lt;TBehavior&gt;</c> delegate or /// <see langword="null"/> if not needed. /// </para> /// <para> /// That delegate invokes the method called for initializing /// a new session instance for the service. /// </para> /// </param> /// <typeparam name="TBehavior"> /// The type of the behavior for the service. It must inherit /// the <see cref="WebSocketBehavior"/> class and it must have /// a public parameterless constructor. /// </typeparam> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is already in use. /// </para> /// </exception> public void AddService<TBehavior> ( string path, Action<TBehavior> initializer ) where TBehavior : WebSocketBehavior, new () { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } path = HttpUtility.UrlDecode (path).TrimSlashFromEnd (); lock (_sync) { WebSocketServiceHost host; if (_hosts.TryGetValue (path, out host)) throw new ArgumentException ("Already in use.", "path"); host = new WebSocketServiceHost<TBehavior> ( path, () => new TBehavior (), initializer, _log ); if (!_clean) host.KeepClean = false; if (_waitTime != host.WaitTime) host.WaitTime = _waitTime; if (_state == ServerState.Start) host.Start (); _hosts.Add (path, host); } } /// <summary> /// Sends <paramref name="data"/> to every client in the WebSocket services. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> [Obsolete ("This method will be removed.")] public void Broadcast (byte[] data) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); if (data.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, null); else broadcast (Opcode.Binary, new MemoryStream (data), null); } /// <summary> /// Sends <paramref name="data"/> to every client in the WebSocket services. /// </summary> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="data"/> could not be UTF-8-encoded. /// </exception> [Obsolete ("This method will be removed.")] public void Broadcast (string data) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); byte[] bytes; if (!data.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "data"); } if (bytes.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Text, bytes, null); else broadcast (Opcode.Text, new MemoryStream (bytes), null); } /// <summary> /// Sends <paramref name="data"/> asynchronously to every client in /// the WebSocket services. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="completed"> /// <para> /// An <see cref="Action"/> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> [Obsolete ("This method will be removed.")] public void BroadcastAsync (byte[] data, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); if (data.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, data, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (data), completed); } /// <summary> /// Sends <paramref name="data"/> asynchronously to every client in /// the WebSocket services. /// </summary> /// <remarks> /// This method does not wait for the send to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="completed"> /// <para> /// An <see cref="Action"/> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="data"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="data"/> could not be UTF-8-encoded. /// </exception> [Obsolete ("This method will be removed.")] public void BroadcastAsync (string data, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (data == null) throw new ArgumentNullException ("data"); byte[] bytes; if (!data.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "data"); } if (bytes.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Text, bytes, completed); else broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed); } /// <summary> /// Sends the data from <paramref name="stream"/> asynchronously to /// every client in the WebSocket services. /// </summary> /// <remarks> /// <para> /// The data is sent as the binary data. /// </para> /// <para> /// This method does not wait for the send to be complete. /// </para> /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> instance from which to read the data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that specifies the number of bytes to send. /// </param> /// <param name="completed"> /// <para> /// An <see cref="Action"/> delegate or <see langword="null"/> /// if not needed. /// </para> /// <para> /// The delegate invokes the method called when the send is complete. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="stream"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="stream"/> cannot be read. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="length"/> is less than 1. /// </para> /// <para> /// -or- /// </para> /// <para> /// No data could be read from <paramref name="stream"/>. /// </para> /// </exception> [Obsolete ("This method will be removed.")] public void BroadcastAsync (Stream stream, int length, Action completed) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (stream == null) throw new ArgumentNullException ("stream"); if (!stream.CanRead) { var msg = "It cannot be read."; throw new ArgumentException (msg, "stream"); } if (length < 1) { var msg = "Less than 1."; throw new ArgumentException (msg, "length"); } var bytes = stream.ReadBytes (length); var len = bytes.Length; if (len == 0) { var msg = "No data could be read from it."; throw new ArgumentException (msg, "stream"); } if (len < length) { _log.Warn ( String.Format ( "Only {0} byte(s) of data could be read from the stream.", len ) ); } if (len <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, bytes, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (bytes), completed); } /// <summary> /// Sends a ping to every client in the WebSocket services. /// </summary> /// <returns> /// <para> /// A <c>Dictionary&lt;string, Dictionary&lt;string, bool&gt;&gt;</c>. /// </para> /// <para> /// It represents a collection of pairs of a service path and another /// collection of pairs of a session ID and a value indicating whether /// a pong has been received from the client within a time. /// </para> /// </returns> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> [Obsolete ("This method will be removed.")] public Dictionary<string, Dictionary<string, bool>> Broadping () { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } return broadping (WebSocketFrame.EmptyPingBytes, _waitTime); } /// <summary> /// Sends a ping with <paramref name="message"/> to every client in /// the WebSocket services. /// </summary> /// <returns> /// <para> /// A <c>Dictionary&lt;string, Dictionary&lt;string, bool&gt;&gt;</c>. /// </para> /// <para> /// It represents a collection of pairs of a service path and another /// collection of pairs of a session ID and a value indicating whether /// a pong has been received from the client within a time. /// </para> /// </returns> /// <param name="message"> /// <para> /// A <see cref="string"/> that represents the message to send. /// </para> /// <para> /// The size must be 125 bytes or less in UTF-8. /// </para> /// </param> /// <exception cref="InvalidOperationException"> /// The current state of the manager is not Start. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="message"/> could not be UTF-8-encoded. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// The size of <paramref name="message"/> is greater than 125 bytes. /// </exception> [Obsolete ("This method will be removed.")] public Dictionary<string, Dictionary<string, bool>> Broadping (string message) { if (_state != ServerState.Start) { var msg = "The current state of the manager is not Start."; throw new InvalidOperationException (msg); } if (message.IsNullOrEmpty ()) return broadping (WebSocketFrame.EmptyPingBytes, _waitTime); byte[] bytes; if (!message.TryGetUTF8EncodedBytes (out bytes)) { var msg = "It could not be UTF-8-encoded."; throw new ArgumentException (msg, "message"); } if (bytes.Length > 125) { var msg = "Its size is greater than 125 bytes."; throw new ArgumentOutOfRangeException ("message", msg); } var frame = WebSocketFrame.CreatePingFrame (bytes, false); return broadping (frame.ToArray (), _waitTime); } /// <summary> /// Removes all WebSocket services managed by the manager. /// </summary> /// <remarks> /// A service is stopped with close status 1001 (going away) /// if it has already started. /// </remarks> public void Clear () { List<WebSocketServiceHost> hosts = null; lock (_sync) { hosts = _hosts.Values.ToList (); _hosts.Clear (); } foreach (var host in hosts) { if (host.State == ServerState.Start) host.Stop (1001, String.Empty); } } /// <summary> /// Removes a WebSocket service with the specified <paramref name="path"/>. /// </summary> /// <remarks> /// <para> /// <paramref name="path"/> is converted to a URL-decoded string and /// / is trimmed from the end of the converted string if any. /// </para> /// <para> /// The service is stopped with close status 1001 (going away) /// if it has already started. /// </para> /// </remarks> /// <returns> /// <c>true</c> if the service is successfully found and removed; /// otherwise, <c>false</c>. /// </returns> /// <param name="path"> /// A <see cref="string"/> that represents an absolute path to /// the service to remove. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// </exception> public bool RemoveService (string path) { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } path = HttpUtility.UrlDecode (path).TrimSlashFromEnd (); WebSocketServiceHost host; lock (_sync) { if (!_hosts.TryGetValue (path, out host)) return false; _hosts.Remove (path); } if (host.State == ServerState.Start) host.Stop (1001, String.Empty); return true; } /// <summary> /// Tries to get the host instance for a WebSocket service with /// the specified <paramref name="path"/>. /// </summary> /// <remarks> /// <paramref name="path"/> is converted to a URL-decoded string and /// / is trimmed from the end of the converted string if any. /// </remarks> /// <returns> /// <c>true</c> if the service is successfully found; /// otherwise, <c>false</c>. /// </returns> /// <param name="path"> /// A <see cref="string"/> that represents an absolute path to /// the service to find. /// </param> /// <param name="host"> /// <para> /// When this method returns, a <see cref="WebSocketServiceHost"/> /// instance or <see langword="null"/> if not found. /// </para> /// <para> /// That host instance provides the function to access /// the information in the service. /// </para> /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="path"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <para> /// <paramref name="path"/> is empty. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> is not an absolute path. /// </para> /// <para> /// -or- /// </para> /// <para> /// <paramref name="path"/> includes either or both /// query and fragment components. /// </para> /// </exception> public bool TryGetServiceHost (string path, out WebSocketServiceHost host) { if (path == null) throw new ArgumentNullException ("path"); if (path.Length == 0) throw new ArgumentException ("An empty string.", "path"); if (path[0] != '/') throw new ArgumentException ("Not an absolute path.", "path"); if (path.IndexOfAny (new[] { '?', '#' }) > -1) { var msg = "It includes either or both query and fragment components."; throw new ArgumentException (msg, "path"); } return InternalTryGetServiceHost (path, out host); } #endregion } }
// // Copyright (c) 2004-2016 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. // using System.Runtime.CompilerServices; namespace NLog.UnitTests { using System; using NLog.Common; using System.IO; using System.Text; using NLog.Layouts; using NLog.Config; using NLog.Targets; using Xunit; #if SILVERLIGHT using System.Xml.Linq; #else using System.Xml; using System.IO.Compression; using System.Security.Permissions; #if NET3_5 || NET4_0 || NET4_5 using Ionic.Zip; #endif #endif public abstract class NLogTestBase { protected NLogTestBase() { //reset before every test if (LogManager.Configuration != null) { //flush all events if needed. LogManager.Configuration.Close(); } LogManager.Configuration = null; InternalLogger.Reset(); LogManager.ThrowExceptions = false; } protected void AssertDebugCounter(string targetName, int val) { Assert.Equal(val, GetDebugTarget(targetName).Counter); } protected void AssertDebugLastMessage(string targetName, string msg) { Assert.Equal(msg, GetDebugLastMessage(targetName)); } protected void AssertDebugLastMessageContains(string targetName, string msg) { string debugLastMessage = GetDebugLastMessage(targetName); Assert.True(debugLastMessage.Contains(msg), string.Format("Expected to find '{0}' in last message value on '{1}', but found '{2}'", msg, targetName, debugLastMessage)); } protected string GetDebugLastMessage(string targetName) { return GetDebugLastMessage(targetName, LogManager.Configuration); } protected string GetDebugLastMessage(string targetName, LoggingConfiguration configuration) { return GetDebugTarget(targetName, configuration).LastMessage; } public NLog.Targets.DebugTarget GetDebugTarget(string targetName) { return GetDebugTarget(targetName, LogManager.Configuration); } protected NLog.Targets.DebugTarget GetDebugTarget(string targetName, LoggingConfiguration configuration) { var debugTarget = (NLog.Targets.DebugTarget)configuration.FindTargetByName(targetName); Assert.NotNull(debugTarget); return debugTarget; } protected void AssertFileContentsStartsWith(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); Assert.True(encodedBuf.Length <= fi.Length); byte[] buf = new byte[encodedBuf.Length]; using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } protected void AssertFileContentsEndsWith(string fileName, string contents, Encoding encoding) { if (!File.Exists(fileName)) Assert.True(false, "File '" + fileName + "' doesn't exist."); string fileText = File.ReadAllText(fileName, encoding); Assert.True(fileText.Length >= contents.Length); Assert.Equal(contents, fileText.Substring(fileText.Length - contents.Length)); } protected class CustomFileCompressor : IFileCompressor { public void CompressFile(string fileName, string archiveFileName) { #if NET3_5 || NET4_0 || NET4_5 using (ZipFile zip = new ZipFile()) { zip.AddFile(fileName); zip.Save(archiveFileName); } #endif } } #if NET3_5 || NET4_0 protected void AssertZipFileContents(string fileName, string contents, Encoding encoding) { if (!File.Exists(fileName)) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); using (var zip = new ZipFile(fileName)) { Assert.Equal(1, zip.Count); Assert.Equal(encodedBuf.Length, zip[0].UncompressedSize); byte[] buf = new byte[zip[0].UncompressedSize]; using (var fs = zip[0].OpenReader()) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } } #elif NET4_5 protected void AssertZipFileContents(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var zip = new ZipArchive(stream, ZipArchiveMode.Read)) { Assert.Equal(1, zip.Entries.Count); Assert.Equal(encodedBuf.Length, zip.Entries[0].Length); byte[] buf = new byte[(int)zip.Entries[0].Length]; using (var fs = zip.Entries[0].Open()) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } } #else protected void AssertZipFileContents(string fileName, string contents, Encoding encoding) { Assert.True(false); } #endif protected void AssertFileContents(string fileName, string contents, Encoding encoding) { FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); byte[] encodedBuf = encoding.GetBytes(contents); Assert.Equal(encodedBuf.Length, fi.Length); byte[] buf = new byte[(int)fi.Length]; using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { fs.Read(buf, 0, buf.Length); } for (int i = 0; i < buf.Length; ++i) { Assert.Equal(encodedBuf[i], buf[i]); } } protected void AssertFileContains(string fileName, string contentToCheck, Encoding encoding) { if (contentToCheck.Contains(Environment.NewLine)) Assert.True(false, "Please use only single line string to check."); FileInfo fi = new FileInfo(fileName); if (!fi.Exists) Assert.True(false, "File '" + fileName + "' doesn't exist."); using (TextReader fs = new StreamReader(fileName, encoding)) { string line; while ((line = fs.ReadLine()) != null) { if (line.Contains(contentToCheck)) return; } } Assert.True(false, "File doesn't contains '" + contentToCheck + "'"); } protected string StringRepeat(int times, string s) { StringBuilder sb = new StringBuilder(s.Length * times); for (int i = 0; i < times; ++i) sb.Append(s); return sb.ToString(); } /// <summary> /// Render layout <paramref name="layout"/> with dummy <see cref="LogEventInfo" />and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, string expected) { var logEventInfo = LogEventInfo.Create(LogLevel.Info, "loggername", "message"); AssertLayoutRendererOutput(layout, logEventInfo, expected); } /// <summary> /// Render layout <paramref name="layout"/> with <paramref name="logEventInfo"/> and compare result with <paramref name="expected"/>. /// </summary> protected static void AssertLayoutRendererOutput(Layout layout, LogEventInfo logEventInfo, string expected) { layout.Initialize(null); string actual = layout.Render(logEventInfo); layout.Close(); Assert.Equal(expected, actual); } #if MONO || NET4_5 /// <summary> /// Get line number of previous line. /// </summary> protected int GetPrevLineNumber([CallerLineNumber] int callingFileLineNumber = 0) { return callingFileLineNumber - 1; } #else /// <summary> /// Get line number of previous line. /// </summary> protected int GetPrevLineNumber() { //fixed value set with #line 100000 return 100001; } #endif protected XmlLoggingConfiguration CreateConfigurationFromString(string configXml) { #if SILVERLIGHT XElement element = XElement.Parse(configXml); return new XmlLoggingConfiguration(element.CreateReader(), null); #else XmlDocument doc = new XmlDocument(); doc.LoadXml(configXml); return new XmlLoggingConfiguration(doc.DocumentElement, Environment.CurrentDirectory); #endif } protected string RunAndCaptureInternalLog(SyncAction action, LogLevel internalLogLevel) { var stringWriter = new StringWriter(); InternalLogger.LogWriter = stringWriter; InternalLogger.LogLevel = LogLevel.Trace; InternalLogger.IncludeTimestamp = false; action(); return stringWriter.ToString(); } public delegate void SyncAction(); public class InternalLoggerScope : IDisposable { private readonly LogLevel globalThreshold; private readonly bool throwExceptions; private readonly bool? throwConfigExceptions; public InternalLoggerScope() { this.globalThreshold = LogManager.GlobalThreshold; this.throwExceptions = LogManager.ThrowExceptions; this.throwConfigExceptions = LogManager.ThrowConfigExceptions; } public void Dispose() { if (File.Exists(InternalLogger.LogFile)) File.Delete(InternalLogger.LogFile); InternalLogger.Reset(); //restore logmanager LogManager.GlobalThreshold = this.globalThreshold; LogManager.ThrowExceptions = this.throwExceptions; LogManager.ThrowConfigExceptions = this.throwConfigExceptions; } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Threading; using ServiceStack.Text.Common; using ServiceStack.Text.Jsv; using ServiceStack.Text.Reflection; namespace ServiceStack.Text { public class CsvSerializer { private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false); private static Dictionary<Type, WriteObjectDelegate> WriteFnCache = new Dictionary<Type, WriteObjectDelegate>(); internal static WriteObjectDelegate GetWriteFn(Type type) { try { WriteObjectDelegate writeFn; if (WriteFnCache.TryGetValue(type, out writeFn)) return writeFn; var genericType = typeof(CsvSerializer<>).MakeGenericType(type); var mi = genericType.GetMethod("WriteFn", BindingFlags.Public | BindingFlags.Static); var writeFactoryFn = (Func<WriteObjectDelegate>)Delegate.CreateDelegate( typeof(Func<WriteObjectDelegate>), mi); writeFn = writeFactoryFn(); Dictionary<Type, WriteObjectDelegate> snapshot, newCache; do { snapshot = WriteFnCache; newCache = new Dictionary<Type, WriteObjectDelegate>(WriteFnCache); newCache[type] = writeFn; } while (!ReferenceEquals( Interlocked.CompareExchange(ref WriteFnCache, newCache, snapshot), snapshot)); return writeFn; } catch (Exception ex) { Tracer.Instance.WriteError(ex); throw; } } public static string SerializeToCsv<T>(IEnumerable<T> records) { var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { writer.WriteCsv(records); return sb.ToString(); } } public static string SerializeToString<T>(T value) { if (value == null) return null; if (typeof(T) == typeof(string)) return value as string; var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { CsvSerializer<T>.WriteObject(writer, value); } return sb.ToString(); } public static void SerializeToWriter<T>(T value, TextWriter writer) { if (value == null) return; if (typeof(T) == typeof(string)) { writer.Write(value); return; } CsvSerializer<T>.WriteObject(writer, value); } public static void SerializeToStream<T>(T value, Stream stream) { if (value == null) return; var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); CsvSerializer<T>.WriteObject(writer, value); writer.Flush(); } public static void SerializeToStream(object obj, Stream stream) { if (obj == null) return; var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); var writeFn = GetWriteFn(obj.GetType()); writeFn(writer, obj); writer.Flush(); } public static T DeserializeFromStream<T>(Stream stream) { throw new NotImplementedException(); } public static object DeserializeFromStream(Type type, Stream stream) { throw new NotImplementedException(); } public static void WriteLateBoundObject(TextWriter writer, object value) { if (value == null) return; var writeFn = GetWriteFn(value.GetType()); writeFn(writer, value); } } internal static class CsvSerializer<T> { private static readonly WriteObjectDelegate CacheFn; public static WriteObjectDelegate WriteFn() { return CacheFn; } private const string IgnoreResponseStatus = "ResponseStatus"; private static Func<object, object> valueGetter = null; private static WriteObjectDelegate writeElementFn = null; private static WriteObjectDelegate GetWriteFn() { PropertyInfo firstCandidate = null; Type bestCandidateEnumerableType = null; PropertyInfo bestCandidate = null; if (typeof(T).IsValueType) { return JsvWriter<T>.WriteObject; } //If type is an enumerable property itself write that bestCandidateEnumerableType = typeof(T).GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>)); if (bestCandidateEnumerableType != null) { var elementType = bestCandidateEnumerableType.GetGenericArguments()[0]; writeElementFn = CreateWriteFn(elementType); return WriteEnumerableType; } //Look for best candidate property if DTO if (typeof(T).IsDto() || typeof(T).HasAttr<CsvAttribute>()) { var properties = TypeConfig<T>.Properties; foreach (var propertyInfo in properties) { if (propertyInfo.Name == IgnoreResponseStatus) continue; if (propertyInfo.PropertyType == typeof(string) || propertyInfo.PropertyType.IsValueType || propertyInfo.PropertyType == typeof(byte[])) continue; if (firstCandidate == null) { firstCandidate = propertyInfo; } var enumProperty = propertyInfo.PropertyType .GetTypeWithGenericTypeDefinitionOf(typeof(IEnumerable<>)); if (enumProperty != null) { bestCandidateEnumerableType = enumProperty; bestCandidate = propertyInfo; break; } } } //If is not DTO or no candidates exist, write self var noCandidatesExist = bestCandidate == null && firstCandidate == null; if (noCandidatesExist) { return WriteSelf; } //If is DTO and has an enumerable property serialize that if (bestCandidateEnumerableType != null) { valueGetter = bestCandidate.GetValueGetter(typeof(T)); var elementType = bestCandidateEnumerableType.GetGenericArguments()[0]; writeElementFn = CreateWriteFn(elementType); return WriteEnumerableProperty; } //If is DTO and has non-enumerable, reference type property serialize that valueGetter = firstCandidate.GetValueGetter(typeof(T)); writeElementFn = CreateWriteRowFn(firstCandidate.PropertyType); return WriteNonEnumerableType; } private static WriteObjectDelegate CreateWriteFn(Type elementType) { return CreateCsvWriterFn(elementType, "WriteObject"); } private static WriteObjectDelegate CreateWriteRowFn(Type elementType) { return CreateCsvWriterFn(elementType, "WriteObjectRow"); } private static WriteObjectDelegate CreateCsvWriterFn(Type elementType, string methodName) { var genericType = typeof(CsvWriter<>).MakeGenericType(elementType); var mi = genericType.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public); var writeFn = (WriteObjectDelegate)Delegate.CreateDelegate(typeof(WriteObjectDelegate), mi); return writeFn; } public static void WriteEnumerableType(TextWriter writer, object obj) { writeElementFn(writer, obj); } public static void WriteSelf(TextWriter writer, object obj) { CsvWriter<T>.WriteRow(writer, (T)obj); } public static void WriteEnumerableProperty(TextWriter writer, object obj) { if (obj == null) return; //AOT var enumerableProperty = valueGetter(obj); writeElementFn(writer, enumerableProperty); } public static void WriteNonEnumerableType(TextWriter writer, object obj) { var nonEnumerableType = valueGetter(obj); writeElementFn(writer, nonEnumerableType); } static CsvSerializer() { if (typeof(T) == typeof(object)) { CacheFn = CsvSerializer.WriteLateBoundObject; } else { CacheFn = GetWriteFn(); } } public static void WriteObject(TextWriter writer, object value) { CacheFn(writer, value); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Xunit; namespace System.IO.Tests { public class Directory_GetFileSystemEntries_str : FileSystemTest { #region Utilities public static string[] WindowsInvalidUnixValid = new string[] { " ", " ", "\n", ">", "<", "\t" }; protected virtual bool TestFiles { get { return true; } } // True if the virtual GetEntries mmethod returns files protected virtual bool TestDirectories { get { return true; } } // True if the virtual GetEntries mmethod returns Directories public virtual string[] GetEntries(string dirName) { return Directory.GetFileSystemEntries(dirName); } #endregion #region UniversalTests [Fact] public void NullFileName() { Assert.Throws<ArgumentNullException>(() => GetEntries(null)); } [Fact] public void EmptyFileName() { Assert.Throws<ArgumentException>(() => GetEntries(string.Empty)); } [Fact] public void InvalidFileNames() { Assert.Throws<DirectoryNotFoundException>(() => GetEntries("DoesNotExist")); Assert.Throws<ArgumentException>(() => GetEntries("\0")); } [Fact] public void EmptyDirectory() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Assert.Empty(GetEntries(testDir.FullName)); } [Fact] public void GetEntriesThenDelete() { string testDirPath = GetTestFilePath(); DirectoryInfo testDirInfo = new DirectoryInfo(testDirPath); testDirInfo.Create(); string testDir1 = GetTestFileName(); string testDir2 = GetTestFileName(); string testFile1 = GetTestFileName(); string testFile2 = GetTestFileName(); string testFile3 = GetTestFileName(); string testFile4 = GetTestFileName(); string testFile5 = GetTestFileName(); testDirInfo.CreateSubdirectory(testDir1); testDirInfo.CreateSubdirectory(testDir2); using (File.Create(Path.Combine(testDirPath, testFile1))) using (File.Create(Path.Combine(testDirPath, testFile2))) using (File.Create(Path.Combine(testDirPath, testFile3))) { string[] results; using (File.Create(Path.Combine(testDirPath, testFile4))) using (File.Create(Path.Combine(testDirPath, testFile5))) { results = GetEntries(testDirPath); Assert.NotNull(results); Assert.NotEmpty(results); if (TestFiles) { Assert.Contains(Path.Combine(testDirPath, testFile1), results); Assert.Contains(Path.Combine(testDirPath, testFile2), results); Assert.Contains(Path.Combine(testDirPath, testFile3), results); Assert.Contains(Path.Combine(testDirPath, testFile4), results); Assert.Contains(Path.Combine(testDirPath, testFile5), results); } if (TestDirectories) { Assert.Contains(Path.Combine(testDirPath, testDir1), results); Assert.Contains(Path.Combine(testDirPath, testDir2), results); } } File.Delete(Path.Combine(testDirPath, testFile4)); File.Delete(Path.Combine(testDirPath, testFile5)); FailSafeDirectoryOperations.DeleteDirectory(testDir1, true); results = GetEntries(testDirPath); Assert.NotNull(results); Assert.NotEmpty(results); if (TestFiles) { Assert.Contains(Path.Combine(testDirPath, testFile1), results); Assert.Contains(Path.Combine(testDirPath, testFile2), results); Assert.Contains(Path.Combine(testDirPath, testFile3), results); } if (TestDirectories) { Assert.Contains(Path.Combine(testDirPath, testDir2), results); } } } [Fact] public virtual void IgnoreSubDirectoryFiles() { string subDir = GetTestFileName(); Directory.CreateDirectory(Path.Combine(TestDirectory, subDir)); string testFile = Path.Combine(TestDirectory, GetTestFileName()); string testFileInSub = Path.Combine(TestDirectory, subDir, GetTestFileName()); string testDir = Path.Combine(TestDirectory, GetTestFileName()); string testDirInSub = Path.Combine(TestDirectory, subDir, GetTestFileName()); Directory.CreateDirectory(testDir); Directory.CreateDirectory(testDirInSub); using (File.Create(testFile)) using (File.Create(testFileInSub)) { string[] results = GetEntries(TestDirectory); if (TestFiles) Assert.Contains(testFile, results); if (TestDirectories) Assert.Contains(testDir, results); Assert.DoesNotContain(testFileInSub, results); Assert.DoesNotContain(testDirInSub, results); } } [Theory, MemberData(nameof(TrailingCharacters))] public void MissingFile_ThrowsDirectoryNotFound(char trailingChar) { string path = GetTestFilePath() + trailingChar; Assert.Throws<DirectoryNotFoundException>(() => GetEntries(path)); } [Theory, MemberData(nameof(TrailingCharacters))] public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar) { string path = Path.Combine(GetTestFilePath(), "file" + trailingChar); Assert.Throws<DirectoryNotFoundException>(() => GetEntries(path)); } [Fact] public void TrailingSlashes() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); Directory.CreateDirectory(Path.Combine(testDir.FullName, GetTestFileName())); using (File.Create(Path.Combine(testDir.FullName, GetTestFileName()))) { string[] strArr = GetEntries(testDir.FullName + new string(Path.DirectorySeparatorChar, 5)); Assert.NotNull(strArr); Assert.NotEmpty(strArr); } } #endregion #region PlatformSpecific [Fact] public void InvalidPath() { foreach (char invalid in Path.GetInvalidFileNameChars()) { if (invalid == '/' || invalid == '\\') { Assert.Throws<DirectoryNotFoundException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } else if (invalid == ':') { if (FileSystemDebugInfo.IsCurrentDriveNTFS()) Assert.Throws<NotSupportedException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } else { Assert.Throws<ArgumentException>(() => GetEntries(Path.Combine(TestDirectory, string.Format("te{0}st", invalid.ToString())))); } } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Windows-only Invalid chars in path public void WindowsInvalidCharsPath() { Assert.All(WindowsInvalidUnixValid, invalid => Assert.Throws<ArgumentException>(() => GetEntries(invalid))); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Unix-only valid chars in file path public void UnixValidCharsFilePath() { if (TestFiles) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); foreach (string valid in WindowsInvalidUnixValid) File.Create(Path.Combine(testDir.FullName, valid)).Dispose(); string[] results = GetEntries(testDir.FullName); Assert.All(WindowsInvalidUnixValid, valid => Assert.Contains(Path.Combine(testDir.FullName, valid), results)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Windows-only invalid chars in directory path public void UnixValidCharsDirectoryPath() { if (TestDirectories) { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); foreach (string valid in WindowsInvalidUnixValid) testDir.CreateSubdirectory(valid); string[] results = GetEntries(testDir.FullName); Assert.All(WindowsInvalidUnixValid, valid => Assert.Contains(Path.Combine(testDir.FullName, valid), results)); } } #endregion } public sealed class Directory_GetEntries_CurrentDirectory : RemoteExecutorTestBase { [Fact] public void CurrentDirectory() { string testDir = GetTestFilePath(); Directory.CreateDirectory(testDir); File.WriteAllText(Path.Combine(testDir, GetTestFileName()), "cat"); Directory.CreateDirectory(Path.Combine(testDir, GetTestFileName())); RemoteInvoke((testDirectory) => { Directory.SetCurrentDirectory(testDirectory); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.GetFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateFileSystemEntries(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateDirectories(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory())); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*")); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.AllDirectories)); Assert.NotEmpty(Directory.EnumerateFiles(Directory.GetCurrentDirectory(), "*", SearchOption.TopDirectoryOnly)); return SuccessExitCode; }, $"\"{testDir}\"").Dispose(); } } }
// --------------------------------------------------------------------------- // <copyright file="TableDefinition.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- // --------------------------------------------------------------------- // <summary> // </summary> // --------------------------------------------------------------------- namespace Microsoft.Database.Isam { using Microsoft.Isam.Esent.Interop; /// <summary> /// A Table Definition contains the schema for a single table. It can be /// used to explore the schema for an existing table, modify the schema /// for an existing table, and to create the definition for a new table. /// </summary> public partial class TableDefinition { /// <summary> /// The database /// </summary> private IsamDatabase database = null; /// <summary> /// The name /// </summary> private string name = null; /// <summary> /// The table type /// </summary> private TableType tableType = TableType.None; /// <summary> /// The column collection /// </summary> private ColumnCollection columnCollection = null; /// <summary> /// The index collection /// </summary> private IndexCollection indexCollection = null; /// <summary> /// Initializes a new instance of the <see cref="TableDefinition"/> class. /// For use when defining a new table. /// </summary> /// <param name="name">the name of the table to be defined</param> public TableDefinition(string name) { this.name = name; this.tableType = TableType.Base; this.columnCollection = new ColumnCollection(); this.indexCollection = new IndexCollection(); } /// <summary> /// Initializes a new instance of the <see cref="TableDefinition" /> class. /// For use when defining a new table. /// </summary> /// <param name="name">the name of the table to be defined</param> /// <param name="tableType">Type of the table.</param> public TableDefinition(string name, TableType tableType) { this.name = name; this.tableType = tableType; this.columnCollection = new ColumnCollection(); this.indexCollection = new IndexCollection(); } /// <summary> /// Initializes a new instance of the <see cref="TableDefinition"/> class. /// </summary> internal TableDefinition() { } /// <summary> /// Gets the name of the table. /// </summary> /// <value> /// The name. /// </value> public string Name { get { return this.name; } } /// <summary> /// Gets the type of the table. /// </summary> public TableType Type { get { return this.tableType; } } /// <summary> /// Gets a collection containing the table's columns. /// </summary> public ColumnCollection Columns { get { return this.columnCollection; } } /// <summary> /// Gets a collection containing the tables indices. /// </summary> public IndexCollection Indices { get { return this.indexCollection; } } /// <summary> /// Gets the session. /// </summary> /// <value> /// The session. /// </value> internal IsamSession IsamSession { get { return this.database.IsamSession; } } /// <summary> /// Gets the database. /// </summary> /// <value> /// The database. /// </value> internal IsamDatabase Database { get { return this.database; } } /// <summary> /// Creates a single column with the specified definition in the table /// underlying this table definition /// </summary> /// <param name="columnDefinition">The column definition.</param> /// <returns>The <see cref="Columnid"/> object corresponding to the /// newly-added column.</returns> /// <remarks> /// It is currently not possible to add an AutoIncrement column to a /// table that is being used by a Cursor. All such Cursors must be /// disposed before the column can be successfully added. /// </remarks> public Columnid AddColumn(ColumnDefinition columnDefinition) { lock (this.database.IsamSession) { using (IsamTransaction trx = new IsamTransaction(this.database.IsamSession)) { OpenTableGrbit grbit = OpenTableGrbit.None; // if we are trying to add an auto-inc column then we must // be able to open the table for exclusive access. if we can't // then we will not be able to add the column if ((columnDefinition.Flags & ColumnFlags.AutoIncrement) != 0) { grbit = grbit | OpenTableGrbit.DenyRead; } // open the table with the appropriate access JET_TABLEID tableid; Api.JetOpenTable(this.database.IsamSession.Sesid, this.database.Dbid, this.name, null, 0, grbit, out tableid); // add the new column to the table JET_COLUMNDEF columndef = new JET_COLUMNDEF(); columndef.coltyp = DatabaseCommon.ColtypFromColumnDefinition(columnDefinition); columndef.cp = JET_CP.Unicode; columndef.cbMax = columnDefinition.MaxLength; columndef.grbit = Converter.ColumndefGrbitFromColumnFlags(columnDefinition.Flags); byte[] defaultValueBytes = Converter.BytesFromObject( columndef.coltyp, false /* ASCII */, columnDefinition.DefaultValue); int defaultValueBytesLength = (defaultValueBytes == null) ? 0 : defaultValueBytes.Length; JET_COLUMNID jetColumnid; Api.JetAddColumn( this.database.IsamSession.Sesid, tableid, columnDefinition.Name, columndef, defaultValueBytes, defaultValueBytesLength, out jetColumnid); // commit our change Api.JetCloseTable(this.database.IsamSession.Sesid, tableid); trx.Commit(); DatabaseCommon.SchemaUpdateID++; // return the columnid for the new column return new Columnid( columnDefinition.Name, jetColumnid, columndef.coltyp, columndef.cp == JET_CP.ASCII); } } } /// <summary> /// Deletes a single column from the table underlying this table /// definition /// </summary> /// <param name="columnName">Name of the column.</param> /// <remarks> /// It is not possible to delete a column that is currently referenced /// by an index over this table. /// </remarks> public void DropColumn(string columnName) { lock (this.database.IsamSession) { using (IsamTransaction trx = new IsamTransaction(this.database.IsamSession)) { // open the table JET_TABLEID tableid; Api.JetOpenTable( this.database.IsamSession.Sesid, this.database.Dbid, this.name, null, 0, OpenTableGrbit.None, out tableid); // delete the column from the table Api.JetDeleteColumn(this.database.IsamSession.Sesid, tableid, columnName); // commit our change Api.JetCloseTable(this.database.IsamSession.Sesid, tableid); trx.Commit(); DatabaseCommon.SchemaUpdateID++; } } } /// <summary> /// Creates a single index with the specified definition in the table /// underlying this table definition /// </summary> /// <param name="indexDefinition">The index definition.</param> public void CreateIndex(IndexDefinition indexDefinition) { lock (this.database.IsamSession) { using (IsamTransaction trx = new IsamTransaction(this.database.IsamSession)) { // open the table JET_TABLEID tableid; Api.JetOpenTable( this.database.IsamSession.Sesid, this.database.Dbid, this.name, null, 0, OpenTableGrbit.None, out tableid); // add the new index to the table JET_INDEXCREATE[] indexcreates = new JET_INDEXCREATE[1] { new JET_INDEXCREATE() }; indexcreates[0].szIndexName = indexDefinition.Name; indexcreates[0].szKey = DatabaseCommon.IndexKeyFromIndexDefinition(indexDefinition); indexcreates[0].cbKey = indexcreates[0].szKey.Length; indexcreates[0].grbit = DatabaseCommon.GrbitFromIndexDefinition(indexDefinition); indexcreates[0].ulDensity = indexDefinition.Density; indexcreates[0].pidxUnicode = new JET_UNICODEINDEX(); indexcreates[0].pidxUnicode.lcid = indexDefinition.CultureInfo.LCID; indexcreates[0].pidxUnicode.dwMapFlags = Converter.MapFlagsFromUnicodeIndexFlags(Converter.UnicodeFlagsFromCompareOptions(indexDefinition.CompareOptions)); indexcreates[0].rgconditionalcolumn = DatabaseCommon.ConditionalColumnsFromIndexDefinition(indexDefinition); indexcreates[0].cConditionalColumn = indexcreates[0].rgconditionalcolumn.Length; indexcreates[0].cbKeyMost = indexDefinition.MaxKeyLength; Api.JetCreateIndex2(this.database.IsamSession.Sesid, tableid, indexcreates, indexcreates.Length); // commit our change Api.JetCloseTable(this.database.IsamSession.Sesid, tableid); trx.Commit(); DatabaseCommon.SchemaUpdateID++; } } } /// <summary> /// Deletes a single index from the table underlying this table /// </summary> /// <param name="name">The name.</param> /// <remarks> /// It is currently not possible to delete an index that is being used /// by a Cursor as its CurrentIndex. All such Cursors must either be /// disposed or set to a different index before the index can be /// successfully deleted. /// </remarks> public void DropIndex(string name) { lock (this.database.IsamSession) { using (IsamTransaction trx = new IsamTransaction(this.database.IsamSession)) { // open the table JET_TABLEID tableid; Api.JetOpenTable( this.database.IsamSession.Sesid, this.database.Dbid, this.name, null, 0, OpenTableGrbit.None, out tableid); // delete the index from the table Api.JetDeleteIndex(this.database.IsamSession.Sesid, tableid, name); // commit our change Api.JetCloseTable(this.database.IsamSession.Sesid, tableid); trx.Commit(); DatabaseCommon.SchemaUpdateID++; } } } /// <summary> /// Loads the specified table specified in the <see cref="JET_OBJECTLIST"/> object. /// </summary> /// <param name="database">The database.</param> /// <param name="objectList">The object list.</param> /// <returns>A <see cref="TableDefinition"/> corresponding to the table specified in <paramref name="objectList"/>.</returns> internal static TableDefinition Load(IsamDatabase database, JET_OBJECTLIST objectList) { lock (database.IsamSession) { // save the database TableDefinition tableDefinition = new TableDefinition(); tableDefinition.database = database; // load info for the table tableDefinition.name = Api.RetrieveColumnAsString( database.IsamSession.Sesid, objectList.tableid, objectList.columnidobjectname); // create our column and index collections tableDefinition.columnCollection = new ColumnCollection(database, tableDefinition.name); tableDefinition.indexCollection = new IndexCollection(database, tableDefinition.name); return tableDefinition; } } /// <summary> /// Loads the specified table specified in the <see cref="JET_OBJECTINFO"/> object. /// </summary> /// <param name="database">The database.</param> /// <param name="tableName">Name of the table.</param> /// <param name="objectInfo">The object information.</param> /// <returns>A <see cref="TableDefinition"/> corresponding to the table specified in <paramref name="objectInfo"/>.</returns> internal static TableDefinition Load(IsamDatabase database, string tableName, JET_OBJECTINFO objectInfo) { lock (database.IsamSession) { // save the database TableDefinition tableDefinition = new TableDefinition(); tableDefinition.database = database; // load info for the table tableDefinition.name = tableName; // create our column and index collections tableDefinition.columnCollection = new ColumnCollection(database, tableDefinition.name); tableDefinition.indexCollection = new IndexCollection(database, tableDefinition.name); return tableDefinition; } } } }
// // ValaTextEditorExtension.cs // // Authors: // Levi Bard <taktaktaktaktaktaktaktaktaktak@gmail.com> // // Copyright (C) 2008 Levi Bard // Based on CBinding by Marcos David Marin Amador <MarcosMarin@gmail.com> // // This source code is licenced under The 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.IO; using System.Text; using System.Linq; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Threading; using MonoDevelop.Ide; using MonoDevelop.Ide.Gui; using MonoDevelop.Ide.Gui.Content; using MonoDevelop.Ide.CodeCompletion; using MonoDevelop.Core; using MonoDevelop.Components; using Gtk; using MonoDevelop.ValaBinding.Parser; using Mono.TextEditor; using Xwt; using MonoDevelop.Ide.TypeSystem; namespace MonoDevelop.ValaBinding { public class ValaTextEditorExtension : CompletionTextEditorExtension, IPathedDocument { // Allowed chars to be next to an identifier private static char[] allowedChars = new char[] { ' ', '\t', '\r', '\n', ':', '=', '*', '+', '-', '/', '%', ',', '&', '|', '^', '{', '}', '[', ']', '(', ')', '\n', '!', '?', '<', '>' }; private static char[] operators = new char[] { '=', '+', '-', ',', '&', '|', '^', '[', '!', '?', '<', '>', ':' }; private ProjectInformation Parser { get { ValaProject project = Document.Project as ValaProject; return (null == project) ? null : ProjectInformationManager.Instance.Get(project); } }// Parser protected Mono.TextEditor.TextEditorData textEditorData { get; set; } public override bool KeyPress(Gdk.Key key, char keyChar, Gdk.ModifierType modifier) { string lineText = Editor.GetLineText(Editor.Caret.Line); // smart formatting strategy if (Document.Editor.Options.IndentStyle == IndentStyle.Smart || Document.Editor.Options.IndentStyle == IndentStyle.Virtual) { if (key == Gdk.Key.Return) { if (lineText.TrimEnd().EndsWith("{")) { Editor.InsertAtCaret("\n" + Document.Editor.Options.IndentationString + Editor.Document.GetLineIndent(Editor.Caret.Line)); return false; } } // TODO: The '}' is invisible before next key press /*else if (keyChar == '}' && AllWhiteSpace(lineText) && lineText.StartsWith(Document.Editor.Options.IndentationString)) { if (lineText.Length > 0) lineText = lineText.Substring(Document.Editor.Options.IndentationString.Length); var lineSegment = Editor.Document.GetLine(Editor.Caret.Line); Editor.Replace(lineSegment.Offset, lineSegment.Length, lineText + "}"); return false; }*/ } return base.KeyPress(key, keyChar, modifier); } /// <summary> /// Expression to match instance construction/initialization /// </summary> private static Regex initializationRegex = new Regex(@"(((?<typename>\w[\w\d\.<>]*)\s+)?(?<variable>\w[\w\d]*)\s*=\s*)?new\s*(?<constructor>\w[\w\d\.<>]*)?", RegexOptions.Compiled); public override ICompletionDataList HandleCodeCompletion(CodeCompletionContext completionContext, char completionChar, ref int triggerWordLength) { string lineText = null; ProjectInformation parser = Parser; var loc = Editor.Document.OffsetToLocation(completionContext.TriggerOffset); int line = loc.Line, column = loc.Column; switch (completionChar) { case '.': // foo.[complete] lineText = Editor.GetLineText(line); if (column > lineText.Length) { column = lineText.Length; } lineText = lineText.Substring(0, column - 1); string itemName = GetTrailingSymbol(lineText); if (string.IsNullOrEmpty(itemName)) return null; return GetMembersOfItem(itemName, line, column); case '\t': case ' ': lineText = Editor.GetLineText(line); if (0 == lineText.Length) { return null; } if (column > lineText.Length) { column = lineText.Length; } lineText = lineText.Substring(0, column - 1).Trim(); if (lineText.EndsWith("new")) { return CompleteConstructor(lineText, line, column); } else if (lineText.EndsWith("is")) { ValaCompletionDataList list = new ValaCompletionDataList(); ThreadPool.QueueUserWorkItem(delegate { parser.GetTypesVisibleFrom(Document.FileName, line, column, list); }); return list; } else if (0 < lineText.Length) { char lastNonWS = lineText[lineText.Length - 1]; if (0 <= Array.IndexOf(operators, lastNonWS) || (1 == lineText.Length && 0 > Array.IndexOf(allowedChars, lastNonWS))) { return GlobalComplete(completionContext); } } break; default: if (0 <= Array.IndexOf(operators, completionChar)) { return GlobalComplete(completionContext); } break; } return null; } static string GetTrailingSymbol(string text) { // remove the trailing '.' if (text.EndsWith(".", StringComparison.Ordinal)) text = text.Substring(0, text.Length - 1); int nameStart = text.LastIndexOfAny(allowedChars); return text.Substring(nameStart + 1).Trim(); } /// <summary> /// Perform constructor-specific completion /// </summary> private ValaCompletionDataList CompleteConstructor(string lineText, int line, int column) { ProjectInformation parser = Parser; Match match = initializationRegex.Match(lineText); ValaCompletionDataList list = new ValaCompletionDataList(); ThreadPool.QueueUserWorkItem(delegate { if (match.Success) { // variable initialization if (match.Groups["typename"].Success || "var" != match.Groups["typename"].Value) { // simultaneous declaration and initialization parser.GetConstructorsForType(match.Groups["typename"].Value, Document.FileName, line, column, list); } else if (match.Groups["variable"].Success) { // initialization of previously declared variable parser.GetConstructorsForExpression(match.Groups["variable"].Value, Document.FileName, line, column, list); } if (0 == list.Count) { // Fallback to known types parser.GetTypesVisibleFrom(Document.FileName, line, column, list); } } }); return list; }// CompleteConstructor public override ICompletionDataList CodeCompletionCommand( CodeCompletionContext completionContext) { if (null == (Document.Project as ValaProject)) { return null; } int pos = completionContext.TriggerOffset; int triggerWordLength = completionContext.TriggerWordLength; ICompletionDataList list = HandleCodeCompletion(completionContext, Editor.GetCharAt(pos), ref triggerWordLength); if (null == list) { list = GlobalComplete(completionContext); } return list; } /// <summary> /// Get the members of a symbol /// </summary> private ValaCompletionDataList GetMembersOfItem(string itemFullName, int line, int column) { ProjectInformation info = Parser; if (null == info) { return null; } ValaCompletionDataList list = new ValaCompletionDataList(); ThreadPool.QueueUserWorkItem(delegate { info.Complete(itemFullName, Document.FileName, line, column, list); }); return list; } /// <summary> /// Complete all symbols visible from a given location /// </summary> private ValaCompletionDataList GlobalComplete(CodeCompletionContext context) { ProjectInformation info = Parser; if (null == info) { return null; } ValaCompletionDataList list = new ValaCompletionDataList(); var loc = Editor.Document.OffsetToLocation(context.TriggerOffset); ThreadPool.QueueUserWorkItem(delegate { info.GetSymbolsVisibleFrom(Document.FileName, loc.Line + 1, loc.Column + 1, list); }); return list; } public override MonoDevelop.Ide.CodeCompletion.ParameterDataProvider HandleParameterCompletion( CodeCompletionContext completionContext, char completionChar) { if (completionChar != '(') return null; ProjectInformation info = Parser; if (null == info) { return null; } int position = Editor.Document.GetLine(Editor.Caret.Line).Offset; string lineText = Editor.GetTextBetween(position, Editor.Caret.Offset - 1).TrimEnd(); string functionName = string.Empty; Match match = initializationRegex.Match(lineText); if (match.Success && match.Groups["constructor"].Success) { string[] tokens = match.Groups["constructor"].Value.Split('.'); string overload = tokens[tokens.Length - 1]; string typename = (match.Groups["typename"].Success ? match.Groups["typename"].Value : null); int index = 0; if (1 == tokens.Length || null == typename) { // Ideally if typename is null and token length is longer than 1, // we have an expression like: var w = new x.y.z(); and // we would check whether z is the type or if y.z is an overload for type y typename = overload; } else if ("var".Equals(typename, StringComparison.Ordinal)) { typename = match.Groups["constructor"].Value; } else { // Foo.Bar bar = new Foo.Bar.blah( ... for (string[] typeTokens = typename.Split('.'); index < typeTokens.Length && index < tokens.Length; ++index) { if (!typeTokens[index].Equals(tokens[index], StringComparison.Ordinal)) { break; } } List<string> overloadTokens = new List<string>(); for (int i = index; i < tokens.Length; ++i) { overloadTokens.Add(tokens[i]); } overload = string.Join(".", overloadTokens.ToArray()); } // HACK: Generics if (0 < (index = overload.IndexOf("<", StringComparison.Ordinal))) { overload = overload.Substring(0, index); } if (0 < (index = typename.IndexOf("<", StringComparison.Ordinal))) { typename = typename.Substring(0, index); } // Console.WriteLine ("Constructor: type {0}, overload {1}", typename, overload); return new ParameterDataProvider(Document, info, typename, overload); } int nameStart = lineText.LastIndexOfAny(allowedChars) + 1; functionName = lineText.Substring(nameStart).Trim(); return (string.IsNullOrEmpty(functionName) ? null : new ParameterDataProvider(Document, info, functionName)); } private bool AllWhiteSpace(string lineText) { foreach (char c in lineText) if (!char.IsWhiteSpace(c)) return false; return true; } #region IPathedDocument implementation public event EventHandler<DocumentPathChangedEventArgs> PathChanged; public Gtk.Widget CreatePathWidget(int index) { PathEntry[] path = CurrentPath; if (null == path || 0 > index || path.Length <= index) { return null; } object tag = path[index].Tag; DropDownBoxListWindow.IListDataProvider provider = null; if (tag is ParsedDocument) { provider = new CompilationUnitDataProvider(Document); } else { provider = new DataProvider(Document, tag, GetAmbience()); } DropDownBoxListWindow window = new DropDownBoxListWindow(provider); window.SelectItem(tag); return window; } public PathEntry[] CurrentPath { get; private set; } protected virtual void OnPathChanged(DocumentPathChangedEventArgs args) { if (null != PathChanged) { PathChanged(this, args); } } #endregion // Yoinked from C# binding void UpdatePath(object sender, DocumentLocationEventArgs e) { // TODO: /*var unit = Document.CompilationUnit; if (unit == null) return; var loc = textEditorData.Caret.Location; IType type = unit.GetTypeAt(loc.Line, loc.Column); List<PathEntry> result = new List<PathEntry>(); Ambience amb = GetAmbience(); IMember member = null; INode node = (INode)unit; if (type != null && type.ClassType != ClassType.Delegate) { member = type.GetMemberAt(loc.Line, loc.Column); } if (null != member) { node = member; } else if (null != type) { node = type; } while (node != null) { PathEntry entry; if (node is ICompilationUnit) { if (!Document.ParsedDocument.UserRegions.Any()) break; FoldingRegion reg = Document.ParsedDocument.UserRegions.Where(r => r.Region.Contains(loc.Line, loc.Column)).LastOrDefault(); if (reg == null) { entry = new PathEntry(GettextCatalog.GetString("No region")); } else { entry = new PathEntry(CompilationUnitDataProvider.Pixbuf, reg.Name); } entry.Position = EntryPosition.Right; } else { entry = new PathEntry(ImageService.GetPixbuf(((IMember)node).StockIcon, IconSize.Menu), amb.GetString((IMember)node, OutputFlags.IncludeGenerics | OutputFlags.IncludeParameters | OutputFlags.ReformatDelegates)); } entry.Tag = node; result.Insert(0, entry); node = node.Parent; } PathEntry noSelection = null; if (type == null) { noSelection = new PathEntry(GettextCatalog.GetString("No selection")) { Tag = new CustomNode(Document.CompilationUnit) }; } else if (member == null && type.ClassType != ClassType.Delegate) noSelection = new PathEntry(GettextCatalog.GetString("No selection")) { Tag = new CustomNode(type) }; if (noSelection != null) { result.Add(noSelection); } var prev = CurrentPath; CurrentPath = result.ToArray(); OnPathChanged(new DocumentPathChangedEventArgs(prev));*/ } public override void Initialize() { base.Initialize(); textEditorData = Document.Editor; UpdatePath(null, null); textEditorData.Caret.PositionChanged += UpdatePath; Document.DocumentParsed += delegate { UpdatePath(null, null); }; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using System.Runtime; #if OUYA using Ouya.Console.Api; #endif namespace Monocle { public enum GameTags { Player = 0, Corpse, Solid, Actor, Arrow, JumpPad, Target, Chain, PlayerCollider, PlayerCollectible, ExplosionCollider, Orb, Enemy, Climbable, Brambles, Dummy, LightSource, PlayerOnlySolid, NotArrowsSolid, Ice, Hat, Granite }; public class Engine : Game { public const float FRAME_RATE = 60f; static private readonly TimeSpan SixtyDelta = TimeSpan.FromSeconds(1.0 / FRAME_RATE); private const float FULL_DELTA = 1f / 60f; private const float CLAMP_ADD = FULL_DELTA * .25f; static public Engine Instance { get; private set; } static internal int TagAmount = Enum.GetNames(typeof(GameTags)).Length; static public float TimeMult { get; private set; } static public float LastTimeMult { get; private set; } static public float DeltaTime { get; private set; } static public float ActualDeltaTime { get; private set; } static public float TimeRate = 1f; #if OUYA static public OuyaFacade OuyaFacade; #endif public GraphicsDeviceManager Graphics { get; private set; } public Screen Screen { get; private set; } private Scene scene; private Scene nextScene; private string windowTitle; #if DEBUG #if DESKTOP public Commands Commands { get; private set; } #elif OUYA public string FrameRateDisplay { get; private set; } #endif private TimeSpan counterElapsed = TimeSpan.Zero; private int counterFrames = 0; #endif public Engine(int width, int height, float scale, string windowTitle) { this.windowTitle = windowTitle; Instance = this; Graphics = new GraphicsDeviceManager(this); Content.RootDirectory = Calc.LOADPATH + "Content"; IsMouseVisible = false; Screen = new Screen(this, width, height, scale); #if DESKTOP IsFixedTimeStep = false; #elif OUYA IsFixedTimeStep = false; #endif TargetElapsedTime = TimeSpan.FromSeconds(1.0 / FRAME_RATE); //GCSettings.LatencyMode = GCLatencyMode.LowLatency; } protected override void Initialize() { base.Initialize(); #if DEBUG #if DESKTOP Commands = new Commands(); #elif OUYA FrameRateDisplay = ""; #endif #endif Music.Initialize(); Input.Initialize(); Screen.Initialize(); Monocle.Draw.Init(GraphicsDevice); Graphics.DeviceReset += OnGraphicsReset; #if DESKTOP Window.Title = windowTitle; #endif } private void OnGraphicsReset(object sender, EventArgs e) { if (scene != null) scene.HandleGraphicsReset(); if (nextScene != null) nextScene.HandleGraphicsReset(); } protected override void Update(GameTime gameTime) { //Calculate delta time stuff LastTimeMult = TimeMult; ActualDeltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds * TimeRate; if (IsFixedTimeStep) { TimeMult = (60f / FRAME_RATE) * TimeRate; DeltaTime = (1f / FRAME_RATE) * TimeRate; } else { DeltaTime = MathHelper.Clamp( ActualDeltaTime, FULL_DELTA * TimeRate - CLAMP_ADD, FULL_DELTA * TimeRate + CLAMP_ADD ); TimeMult = DeltaTime / FULL_DELTA; } #if DEBUG && DESKTOP if (Commands.Open) Input.UpdateNoKeyboard(); else Input.Update(); #else Input.Update(); #endif Music.Update(); if (scene != null && scene.Active) scene.Update(); #if DEBUG && DESKTOP if (Commands.Open) Commands.UpdateOpen(); else Commands.UpdateClosed(); #endif if (scene != nextScene) { if (scene != null) scene.End(); scene = nextScene; OnSceneTransition(); if (scene != null) scene.Begin(); } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.SetRenderTarget(Screen.RenderTarget); GraphicsDevice.Clear(Screen.ClearColor); if (scene != null) scene.Render(); //if (scene != null) // scene.PostRender(); GraphicsDevice.SetRenderTarget(null); GraphicsDevice.Clear(Color.Black); Screen.Render(); //if (scene != null) // scene.PostScreen(); base.Draw(gameTime); #if DEBUG #if DESKTOP //Debug console if (Commands.Open) Commands.Render(); //Frame counter counterFrames++; counterElapsed += gameTime.ElapsedGameTime; if (counterElapsed > TimeSpan.FromSeconds(1)) { Window.Title = windowTitle + " " + counterFrames.ToString() + " fps - " + (GC.GetTotalMemory(true) / 1048576f).ToString("F") + " MB"; counterFrames = 0; counterElapsed -= TimeSpan.FromSeconds(1); } #elif OUYA //Frame counter counterFrames++; counterElapsed += gameTime.ElapsedGameTime; if (counterElapsed > TimeSpan.FromSeconds(1)) { FrameRateDisplay = counterFrames.ToString() + " fps"; counterFrames = 0; counterElapsed -= TimeSpan.FromSeconds(1); } if (FrameRateDisplay != "") { Monocle.Draw.SpriteBatch.Begin(); Monocle.Draw.TextJustify(Monocle.Draw.DefaultFont, FrameRateDisplay, new Vector2(4, 4), Color.White, Vector2.Zero); Monocle.Draw.SpriteBatch.End(); } #endif #endif } public Scene Scene { get { return scene; } set { nextScene = value; } } protected virtual void OnSceneTransition() { GC.Collect(); GC.WaitForPendingFinalizers(); } protected override void OnExiting(object sender, EventArgs args) { Audio.Stop(); Music.Stop(); base.OnExiting(sender, args); } } }
// 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.Text; using System.Reflection; using System.Collections.Generic; using Internal.Metadata.NativeFormat; using Internal.Runtime.Augments; using Internal.Runtime.TypeLoader; using Internal.Reflection.Core.Execution; using Internal.Reflection.Execution.PayForPlayExperience; using Internal.Reflection.Extensions.NonPortable; using Debug = System.Diagnostics.Debug; namespace Internal.Reflection.Execution { //========================================================================================================================== // This class provides various services down to System.Private.CoreLib. (Though we forward most or all of them directly up to Reflection.Core.) //========================================================================================================================== internal sealed class ReflectionExecutionDomainCallbacksImplementation : ReflectionExecutionDomainCallbacks { public ReflectionExecutionDomainCallbacksImplementation(ExecutionDomain executionDomain, ExecutionEnvironmentImplementation executionEnvironment) { _executionDomain = executionDomain; _executionEnvironment = executionEnvironment; } /// <summary> /// Register a module for reflection support - locate the reflection metadata blob in the module /// and register its metadata reader in an internal map. Manipulation of the internal map /// is not thread safe with respect to reflection runtime. /// </summary> /// <param name="moduleHandle">Module handle to register</param> public sealed override void RegisterModule(IntPtr moduleHandle) { ModuleList.Instance.RegisterModule(moduleHandle); } public sealed override Object ActivatorCreateInstance(Type type, Object[] args) { if (type == null) throw new ArgumentNullException("type"); if (args == null) args = new Object[] { }; TypeInfo typeInfo = type.GetTypeInfo(); // All value types have an implied default constructor that has no representation in metadata. if (args.Length == 0 && typeInfo.IsValueType) return RuntimeAugments.NewObject(type.TypeHandle); LowLevelList<MethodBase> candidates = new LowLevelList<MethodBase>(); foreach (ConstructorInfo constructor in typeInfo.DeclaredConstructors) { if (constructor.IsStatic) continue; if (!constructor.IsPublic) continue; // Project N does not support varargs - if it ever does, we'll probably have port over more desktop policy for this code... if (0 != (constructor.CallingConvention & CallingConventions.VarArgs)) throw new PlatformNotSupportedException(SR.PlatformNotSupported_VarArgs); // The default binder rules allow omitting optional parameters but Activator.CreateInstance() doesn't. Thus, if the # of arguments doesn't match // the # of parameters, do the pre-verification that the desktop does and ensure that the method has a "params" argument and that the argument count // isn't shorter by more than one. ParameterInfo[] parameters = constructor.GetParameters(); if (args.Length != parameters.Length) { if (args.Length < parameters.Length - 1) continue; if (parameters.Length == 0) continue; ParameterInfo finalParameter = parameters[parameters.Length - 1]; if (!finalParameter.ParameterType.IsArray) continue; bool hasParamArray = false; foreach (CustomAttributeData cad in finalParameter.CustomAttributes) { if (cad.AttributeType.Equals(typeof(ParamArrayAttribute))) { hasParamArray = true; break; } } if (!hasParamArray) continue; } candidates.Add(constructor); } if (candidates.Count == 0) throw new MissingMethodException(SR.Format(SR.MissingConstructor_Name, type)); MethodBase[] candidatesArray = candidates.ToArray(); Binder binder = Type._GetDefaultBinder(); object ignore; BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance; ConstructorInfo match = (ConstructorInfo)binder.BindToMethod(bindingAttr, candidatesArray, ref args, null, null, null, out ignore); Object newObject = match.Invoke(args); return newObject; } public sealed override Type GetType(String typeName, bool throwOnError, bool ignoreCase) { return _executionDomain.GetType(typeName, throwOnError, ignoreCase, ReflectionExecution.DefaultAssemblyNamesForGetType); } public sealed override bool IsReflectionBlocked(RuntimeTypeHandle typeHandle) { return _executionEnvironment.IsReflectionBlocked(typeHandle); } public sealed override bool TryGetMetadataNameForRuntimeTypeHandle(RuntimeTypeHandle rtth, out string name) { return _executionEnvironment.TryGetMetadataNameForRuntimeTypeHandle(rtth, out name); } //======================================================================================= // This group of methods jointly service the Type.GetTypeFromHandle() path. The caller // is responsible for analyzing the RuntimeTypeHandle to figure out which flavor to call. //======================================================================================= public sealed override Type GetNamedTypeForHandle(RuntimeTypeHandle typeHandle, bool isGenericTypeDefinition) { return _executionDomain.GetNamedTypeForHandle(typeHandle, isGenericTypeDefinition); } public sealed override Type GetArrayTypeForHandle(RuntimeTypeHandle typeHandle) { return _executionDomain.GetArrayTypeForHandle(typeHandle); } public sealed override Type GetMdArrayTypeForHandle(RuntimeTypeHandle typeHandle, int rank) { return _executionDomain.GetMdArrayTypeForHandle(typeHandle, rank); } public sealed override Type GetPointerTypeForHandle(RuntimeTypeHandle typeHandle) { return _executionDomain.GetPointerTypeForHandle(typeHandle); } public sealed override Type GetConstructedGenericTypeForHandle(RuntimeTypeHandle typeHandle) { return _executionDomain.GetConstructedGenericTypeForHandle(typeHandle); } //======================================================================================= // MissingMetadataException support. //======================================================================================= public sealed override Exception CreateMissingMetadataException(Type pertainant) { return _executionDomain.CreateMissingMetadataException(pertainant); } public sealed override EnumInfo GetEnumInfoIfAvailable(Type enumType) { // Handle the weird case of an enum type nested under a generic type that makes the // enum itself generic. if (enumType.IsConstructedGenericType) { enumType = enumType.GetGenericTypeDefinition(); } MetadataReader reader; TypeDefinitionHandle typeDefinitionHandle; if (!ReflectionExecution.ExecutionEnvironment.TryGetMetadataForNamedType(enumType.TypeHandle, out reader, out typeDefinitionHandle)) return null; return new EnumInfoImplementation(enumType, reader, typeDefinitionHandle); } // This is called from the ToString() helper of a RuntimeType that does not have full metadata. // This helper makes a "best effort" to give the caller something better than "EETypePtr nnnnnnnnn". public sealed override String GetBetterDiagnosticInfoIfAvailable(RuntimeTypeHandle runtimeTypeHandle) { return Type.GetTypeFromHandle(runtimeTypeHandle).ToDisplayStringIfAvailable(null); } public sealed override String GetMethodNameFromStartAddressIfAvailable(IntPtr methodStartAddress) { RuntimeTypeHandle declaringTypeHandle = default(RuntimeTypeHandle); MethodHandle methodHandle; RuntimeTypeHandle[] genericMethodTypeArgumentHandles; if (!ReflectionExecution.ExecutionEnvironment.TryGetMethodForOriginalLdFtnResult(methodStartAddress, ref declaringTypeHandle, out methodHandle, out genericMethodTypeArgumentHandles)) { return null; } MethodBase methodBase = ReflectionCoreExecution.ExecutionDomain.GetMethod( declaringTypeHandle, methodHandle, genericMethodTypeArgumentHandles); if (methodBase == null || string.IsNullOrEmpty(methodBase.Name)) return null; // get type name string typeName = string.Empty; Type declaringType = Type.GetTypeFromHandle(declaringTypeHandle); if (declaringType != null) typeName = declaringType.ToDisplayStringIfAvailable(null); if (string.IsNullOrEmpty(typeName)) typeName = "<unknown>"; StringBuilder fullMethodName = new StringBuilder(); fullMethodName.Append(typeName); fullMethodName.Append('.'); fullMethodName.Append(methodBase.Name); fullMethodName.Append('('); // get parameter list ParameterInfo[] paramArr = methodBase.GetParameters(); for (int i = 0; i < paramArr.Length; ++i) { if (i != 0) fullMethodName.Append(", "); ParameterInfo param = paramArr[i]; string paramTypeName = string.Empty; if (param.ParameterType != null) paramTypeName = param.ParameterType.ToDisplayStringIfAvailable(null); if (string.IsNullOrEmpty(paramTypeName)) paramTypeName = "<unknown>"; else { // remove namespace from param type-name int idxSeparator = paramTypeName.IndexOf("."); if (idxSeparator >= 0) paramTypeName = paramTypeName.Remove(0, idxSeparator + 1); } string paramName = param.Name; if (string.IsNullOrEmpty(paramName)) paramName = "<unknown>"; fullMethodName.Append(paramTypeName); fullMethodName.Append(' '); fullMethodName.Append(paramName); } fullMethodName.Append(')'); return fullMethodName.ToString(); } public sealed override bool TryGetGenericVirtualTargetForTypeAndSlot(RuntimeTypeHandle targetHandle, ref RuntimeTypeHandle declaringType, RuntimeTypeHandle[] genericArguments, ref string methodName, ref IntPtr methodSignature, out IntPtr methodPointer, out IntPtr dictionaryPointer, out bool slotUpdated) { return _executionEnvironment.TryGetGenericVirtualTargetForTypeAndSlot(targetHandle, ref declaringType, genericArguments, ref methodName, ref methodSignature, out methodPointer, out dictionaryPointer, out slotUpdated); } private String GetTypeFullNameFromTypeRef(TypeReferenceHandle typeReferenceHandle, MetadataReader reader) { String s = ""; TypeReference typeReference = typeReferenceHandle.GetTypeReference(reader); s = typeReference.TypeName.GetString(reader); Handle parentHandle = typeReference.ParentNamespaceOrType; HandleType parentHandleType = parentHandle.HandleType; if (parentHandleType == HandleType.TypeReference) { String containingTypeName = GetTypeFullNameFromTypeRef(parentHandle.ToTypeReferenceHandle(reader), reader); s = containingTypeName + "+" + s; } else if (parentHandleType == HandleType.NamespaceReference) { NamespaceReferenceHandle namespaceReferenceHandle = parentHandle.ToNamespaceReferenceHandle(reader); for (;;) { NamespaceReference namespaceReference = namespaceReferenceHandle.GetNamespaceReference(reader); String namespacePart = namespaceReference.Name.GetStringOrNull(reader); if (namespacePart == null) break; // Reached the root namespace. s = namespacePart + "." + s; if (namespaceReference.ParentScopeOrNamespace.HandleType != HandleType.NamespaceReference) break; // Should have reached the root namespace first but this helper is for ToString() - better to // return partial information than crash. namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(reader); } } else { // If we got here, the metadata is illegal but this helper is for ToString() - better to // return something partial than throw. } return s; } public override IntPtr TryGetDefaultConstructorForType(RuntimeTypeHandle runtimeTypeHandle) { return TypeLoaderEnvironment.Instance.TryGetDefaultConstructorForType(runtimeTypeHandle); } public override IntPtr TryGetDefaultConstructorForTypeUsingLocator(object canonEquivalentEntryLocator) { return TypeLoaderEnvironment.Instance.TryGetDefaultConstructorForTypeUsingLocator(canonEquivalentEntryLocator); } public sealed override IntPtr TryGetStaticClassConstructionContext(RuntimeTypeHandle runtimeTypeHandle) { return _executionEnvironment.TryGetStaticClassConstructionContext(runtimeTypeHandle); } /// <summary> /// Compares FieldInfos, sorting by name. /// </summary> private class FieldInfoNameComparer : IComparer<FieldInfo> { private static FieldInfoNameComparer s_instance = new FieldInfoNameComparer(); public static FieldInfoNameComparer Instance { get { return s_instance; } } public int Compare(FieldInfo x, FieldInfo y) { return x.Name.CompareTo(y.Name); } } /// <summary> /// Reflection-based implementation of ValueType.GetHashCode. Matches the implementation created by the ValueTypeTransform. /// </summary> /// <param name="valueType">Boxed value type</param> /// <returns>Hash code for the value type</returns> public sealed override int ValueTypeGetHashCodeUsingReflection(object valueType) { // The algorithm is to use the hash of the first non-null instance field sorted by name. List<FieldInfo> sortedFilteredFields = new List<FieldInfo>(); foreach (FieldInfo field in valueType.GetType().GetTypeInfo().DeclaredFields) { if (field.IsStatic) { continue; } sortedFilteredFields.Add(field); } sortedFilteredFields.Sort(FieldInfoNameComparer.Instance); foreach (FieldInfo field in sortedFilteredFields) { object fieldValue = field.GetValue(valueType); if (fieldValue != null) { return fieldValue.GetHashCode(); } } // Fallback path if no non-null instance field. The desktop hashes the GetType() object, but this seems like a lot of effort // for a corner case - let's wait and see if we really need that. return 1; } /// <summary> /// Reflection-based implementation of ValueType.Equals. Matches the implementation created by the ValueTypeTransform. /// </summary> /// <param name="left">Boxed 'this' value type</param> /// <param name="right">Boxed 'that' value type</param> /// <returns>True if all nonstatic fields of the objects are equal</returns> public sealed override bool ValueTypeEqualsUsingReflection(object left, object right) { if (right == null) { return false; } if (left.GetType() != right.GetType()) { return false; } foreach (FieldInfo field in left.GetType().GetTypeInfo().DeclaredFields) { if (field.IsStatic) { continue; } object leftField = field.GetValue(left); object rightField = field.GetValue(right); if (leftField == null) { if (rightField != null) { return false; } } else if (!leftField.Equals(rightField)) { return false; } } return true; } /// <summary> /// Retrieves the default value for a parameter of a method. /// </summary> /// <param name="defaultParametersContext">The default parameters context used to invoke the method, /// this should identify the method in question. This is passed to the RuntimeAugments.CallDynamicInvokeMethod.</param> /// <param name="thType">The type of the parameter to retrieve.</param> /// <param name="argIndex">The index of the parameter on the method to retrieve.</param> /// <param name="defaultValue">The default value of the parameter if available.</param> /// <returns>true if the default parameter value is available, otherwise false.</returns> public sealed override bool TryGetDefaultParameterValue(object defaultParametersContext, RuntimeTypeHandle thType, int argIndex, out object defaultValue) { defaultValue = null; MethodBase methodInfo = defaultParametersContext as MethodBase; if (methodInfo == null) { return false; } ParameterInfo parameterInfo = methodInfo.GetParameters()[argIndex]; if (!parameterInfo.HasDefaultValue) { // If the parameter is optional, with no default value and we're asked for its default value, // it means the caller specified Missing.Value as the value for the parameter. In this case the behavior // is defined as passing in the Missing.Value, regardless of the parameter type. // If Missing.Value is convertible to the parameter type, it will just work, otherwise we will fail // due to type mismatch. if (parameterInfo.IsOptional) { defaultValue = Missing.Value; return true; } return false; } defaultValue = parameterInfo.DefaultValue; return true; } public sealed override RuntimeTypeHandle GetTypeHandleIfAvailable(Type type) { return _executionDomain.GetTypeHandleIfAvailable(type); } public sealed override bool SupportsReflection(Type type) { return _executionDomain.SupportsReflection(type); } public sealed override MethodInfo GetDelegateMethod(Delegate del) { return DelegateMethodInfoRetriever.GetDelegateMethodInfo(del); } private ExecutionDomain _executionDomain; private ExecutionEnvironmentImplementation _executionEnvironment; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Runtime.InteropServices; namespace System.IO { public partial class FileSystemWatcher { /// <summary>Starts a new watch operation if one is not currently running.</summary> private void StartRaisingEvents() { // If we already have a cancellation object, we're already running. if (_cancellation != null) { return; } // Open an inotify file descriptor. Ideally this would be a constrained execution region, but we don't have access to // PrepareConstrainedRegions. We still use a finally block to house the code that opens the handle and stores it in // hopes of making it as non-interruptable as possible. Ideally the SafeFileHandle would be allocated before the block, // but SetHandle is protected and SafeFileHandle is sealed, so we're stuck doing the allocation here. SafeFileHandle handle; try { } finally { int fd; Interop.CheckIo(fd = Interop.libc.inotify_init()); handle = new SafeFileHandle((IntPtr)fd, ownsHandle: true); } try { // Create the cancellation object that will be used by this FileSystemWatcher to cancel the new watch operation CancellationTokenSource cancellation = new CancellationTokenSource(); // Start running. All state associated with the watch operation is stored in a separate object; this is done // to avoid race conditions that could result if the users quickly starts/stops/starts/stops/etc. causing multiple // active operations to all be outstanding at the same time. new RunningInstance( this, handle, _directory, IncludeSubdirectories, TranslateFilters(NotifyFilter), cancellation.Token); // Now that we've started running successfully, store the cancellation object and mark the instance // as running. We wait to store the cancellation token so that if there was a failure, StartRaisingEvents // may be called to try again without first having to call StopRaisingEvents. _cancellation = cancellation; _enabled = true; } catch { // If we fail to actually start the watching even though we've opened the // inotify handle, close the inotify handle proactively rather than waiting for it // to be finalized. handle.Dispose(); throw; } } /// <summary>Cancels the currently running watch operation if there is one.</summary> private void StopRaisingEvents() { // If there's an active cancellation token, cancel and release it. // The cancellation token and the processing task respond to cancellation // to handle all other cleanup. var cts = _cancellation; if (cts != null) { _enabled = false; _cancellation = null; cts.Cancel(); } } /// <summary>Called when FileSystemWatcher is finalized.</summary> private void FinalizeDispose() { // The RunningInstance remains rooted and holds open the SafeFileHandle until it's explicitly // torn down. FileSystemWatcher.Dispose will call StopRaisingEvents, but not on finalization; // thus we need to explicitly call it here. StopRaisingEvents(); } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// Cancellation for the currently running watch operation. /// This is non-null if an operation has been started and null if stopped. /// </summary> private CancellationTokenSource _cancellation; /// <summary> /// Maps the FileSystemWatcher's NotifyFilters enumeration to the /// corresponding Interop.libc.NotifyEvents values. /// </summary> /// <param name="filters">The filters provided the by user.</param> /// <returns>The corresponding NotifyEvents values to use with inotify.</returns> private static Interop.libc.NotifyEvents TranslateFilters(NotifyFilters filters) { Interop.libc.NotifyEvents result = 0; // We always include a few special inotify watch values that configure // the watch's behavior. result |= Interop.libc.NotifyEvents.IN_ONLYDIR | // we only allow watches on directories Interop.libc.NotifyEvents.IN_EXCL_UNLINK; // we want to stop monitoring unlinked files // For the Created and Deleted events, we need to always // register for the created/deleted inotify events, regardless // of the supplied filters values. We explicitly don't include IN_DELETE_SELF. // The Windows implementation doesn't include notifications for the root directory, // and having this for subdirectories results in duplicate notifications, one from // the parent and one from self. result |= Interop.libc.NotifyEvents.IN_CREATE | Interop.libc.NotifyEvents.IN_DELETE; // For the Changed event, which inotify events we subscribe to // are based on the NotifyFilters supplied. const NotifyFilters filtersForAccess = NotifyFilters.LastAccess; const NotifyFilters filtersForModify = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; const NotifyFilters filtersForAttrib = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size; if ((filters & filtersForAccess) != 0) { result |= Interop.libc.NotifyEvents.IN_ACCESS; } if ((filters & filtersForModify) != 0) { result |= Interop.libc.NotifyEvents.IN_MODIFY; } if ((filters & filtersForAttrib) != 0) { result |= Interop.libc.NotifyEvents.IN_ATTRIB; } // For the Rename event, we'll register for the corresponding move inotify events if the // caller's NotifyFilters asks for notications related to names. const NotifyFilters filtersForMoved = NotifyFilters.FileName | NotifyFilters.DirectoryName; if ((filters & filtersForMoved) != 0) { result |= Interop.libc.NotifyEvents.IN_MOVED_FROM | Interop.libc.NotifyEvents.IN_MOVED_TO; } return result; } /// <summary> /// State and processing associatd with an active watch operation. This state is kept separate from FileSystemWatcher to avoid /// race conditions when a user starts/stops/starts/stops/etc. in quick succession, resulting in the potential for multiple /// active operations. It also helps with avoiding rooted cycles and enabling proper finalization. /// </summary> private sealed class RunningInstance { /// <summary> /// The size of the native struct inotify_event. 4 32-bit integer values, the last of which is a length /// that indicates how many bytes follow to form the string name. /// </summary> const int c_INotifyEventSize = 16; /// <summary> /// Weak reference to the associated watcher. A weak reference is used so that the FileSystemWatcher may be collected and finalized, /// causing an active operation to be torn down. With a strong reference, a blocking read on the inotify handle will keep alive this /// instance which will keep alive the FileSystemWatcher which will not be finalizable and thus which will never signal to the blocking /// read to wake up in the event that the user neglects to stop raising events. /// </summary> private readonly WeakReference<FileSystemWatcher> _weakWatcher; /// <summary> /// The path for the primary watched directory. /// </summary> private readonly string _directoryPath; /// <summary> /// The inotify handle / file descriptor /// </summary> private readonly SafeFileHandle _inotifyHandle; /// <summary> /// Buffer used to store raw bytes read from the inotify handle. /// </summary> private readonly byte[] _buffer; /// <summary> /// The number of bytes read into the _buffer. /// </summary> private int _bufferAvailable; /// <summary> /// The next position in _buffer from which an event should be read. /// </summary> private int _bufferPos; /// <summary> /// Filters to use when adding a watch on directories. /// </summary> private readonly Interop.libc.NotifyEvents _notifyFilters; /// <summary> /// Whether to monitor subdirectories. Unlike Win32, inotify does not implicitly monitor subdirectories; /// watches must be explicitly added for those subdirectories. /// </summary> private readonly bool _includeSubdirectories; /// <summary> /// Token to monitor for cancellation requests, upon which processing is stopped and all /// state is cleaned up. /// </summary> private readonly CancellationToken _cancellationToken; /// <summary> /// Mapping from watch descriptor (as returned by inotify_add_watch) to state for /// the associated directory being watched. Events from inotify include only relative /// names, so the watch descriptor in an event must be used to look up the associated /// directory path in order to conver the relative filename into a full path. /// </summary> private readonly Dictionary<int, WatchedDirectory> _wdToPathMap = new Dictionary<int, WatchedDirectory>(); /// <summary> /// Maximum length of a name returned from inotify event. /// </summary> private const int NAME_MAX = 255; // from limits.h /// <summary>Initializes the instance with all state necessary to operate a watch.</summary> internal RunningInstance( FileSystemWatcher watcher, SafeFileHandle inotifyHandle, string directoryPath, bool includeSubdirectories, Interop.libc.NotifyEvents notifyFilters, CancellationToken cancellationToken) { Debug.Assert(watcher != null); Debug.Assert(inotifyHandle != null && !inotifyHandle.IsInvalid && !inotifyHandle.IsClosed); Debug.Assert(directoryPath != null); _weakWatcher = new WeakReference<FileSystemWatcher>(watcher); _inotifyHandle = inotifyHandle; _directoryPath = directoryPath; _buffer = watcher.AllocateBuffer(); Debug.Assert(_buffer != null && _buffer.Length > (c_INotifyEventSize + NAME_MAX + 1)); _includeSubdirectories = includeSubdirectories; _notifyFilters = notifyFilters; _cancellationToken = cancellationToken; FileSystemWatcher.CaseSensitive = true; // Add a watch for this starting directory. We keep track of the watch descriptor => directory information // mapping in a dictionary; this is needed in order to be able to determine the containing directory // for all notifications so that we can reconstruct the full path. AddDirectoryWatchUnlocked(null, directoryPath); // Schedule a task to read from the inotify queue and process the events. Task.Factory.StartNew(obj => ((RunningInstance)obj).ProcessEvents(), this, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); // PERF: As needed, we can look into making this use async I/O rather than burning // a thread that blocks in the read syscall. } /// <summary>Object to use for synchronizing access to state when necessary.</summary> private object SyncObj { get { return _wdToPathMap; } } /// <summary>Adds a watch on a directory to the existing inotify handle.</summary> /// <param name="parent">The parent directory entry.</param> /// <param name="directoryName">The new directory path to monitor, relative to the root.</param> private void AddDirectoryWatch(WatchedDirectory parent, string directoryName) { lock (SyncObj) { // The read syscall on the file descriptor will block until either close is called or until // all previously added watches are removed. We don't want to rely on close, as a) that could // lead to race conditions where we inadvertently read from a recycled file descriptor, and b) // the SafeFileHandle that wraps the file descriptor can't be disposed (thus closing // the underlying file descriptor and allowing read to wake up) while there's an active ref count // against the handle, so we'd deadlock if we relied on that approach. Instead, we want to follow // the approach of removing all watches when we're done, which means we also don't want to // add any new watches once the count hits zero. if (parent == null || _wdToPathMap.Count > 0) { Debug.Assert(parent != null || _wdToPathMap.Count == 0); AddDirectoryWatchUnlocked(parent, directoryName); } } } /// <summary>Adds a watch on a directory to the existing inotify handle.</summary> /// <param name="parent">The parent directory entry.</param> /// <param name="directoryName">The new directory path to monitor, relative to the root.</param> private WatchedDirectory AddDirectoryWatchUnlocked(WatchedDirectory parent, string directoryName) { string fullPath = parent != null ? parent.GetPath(false, directoryName) : directoryName; // Add a watch for the full path. If the path is already being watched, this will return // the existing descriptor. This works even in the case of a rename. int wd = (int)SysCall(fd => Interop.libc.inotify_add_watch(fd, fullPath, (uint)_notifyFilters)); // Then store the path information into our map. WatchedDirectory directoryEntry; bool isNewDirectory = false; if (_wdToPathMap.TryGetValue(wd, out directoryEntry)) { // The watch descriptor was already in the map. Hard links on directories // aren't possible, and symlinks aren't annotated as IN_ISDIR, // so this is a rename. (In extremely remote cases, this could be // a recycled watch descriptor if many, many events were lost // such that our dictionary got very inconsistent with the state // of the world, but there's little that can be done about that.) if (directoryEntry.Parent != parent) { if (directoryEntry.Parent != null) { directoryEntry.Parent.Children.Remove (directoryEntry); } directoryEntry.Parent = parent; if (parent != null) { parent.InitializedChildren.Add (directoryEntry); } } directoryEntry.Name = directoryName; } else { // The watch descriptor wasn't in the map. This is a creation. directoryEntry = new WatchedDirectory { Parent = parent, WatchDescriptor = wd, Name = directoryName }; if (parent != null) { parent.InitializedChildren.Add (directoryEntry); } _wdToPathMap.Add(wd, directoryEntry); isNewDirectory = true; } // Since inotify doesn't handle nesting implicitly, explicitly // add a watch for each child directory if the developer has // asked for subdirectories to be included. if (isNewDirectory && _includeSubdirectories) { // This method is recursive. If we expect to see hierarchies // so deep that it would cause us to overflow the stack, we could // consider using an explicit stack object rather than recursion. // This is unlikely, however, given typical directory names // and max path limits. foreach (string subDir in Directory.EnumerateDirectories(fullPath)) { AddDirectoryWatchUnlocked(directoryEntry, System.IO.Path.GetFileName(subDir)); // AddDirectoryWatchUnlocked will add the new directory to // this.Children, so we don't have to / shouldn't also do it here. } } return directoryEntry; } /// <summary>Removes the watched directory from our state, and optionally removes the inotify watch itself.</summary> /// <param name="directoryEntry">The directory entry to remove.</param> /// <param name="removeInotify">true to remove the inotify watch; otherwise, false. The default is true.</param> private void RemoveWatchedDirectory(WatchedDirectory directoryEntry, bool removeInotify = true) { Debug.Assert (_includeSubdirectories); lock (SyncObj) { if (directoryEntry.Parent != null) { directoryEntry.Parent.Children.Remove (directoryEntry); } RemoveWatchedDirectoryUnlocked (directoryEntry, removeInotify); } } /// <summary>Removes the watched directory from our state, and optionally removes the inotify watch itself.</summary> /// <param name="directoryEntry">The directory entry to remove.</param> /// <param name="removeInotify">true to remove the inotify watch; otherwise, false. The default is true.</param> private void RemoveWatchedDirectoryUnlocked(WatchedDirectory directoryEntry, bool removeInotify) { // If the directory has children, recursively remove them (see comments on recursion in AddDirectoryWatch). if (directoryEntry.Children != null) { foreach (WatchedDirectory child in directoryEntry.Children) { RemoveWatchedDirectoryUnlocked (child, removeInotify); } directoryEntry.Children = null; } // Then remove the directory itself. _wdToPathMap.Remove(directoryEntry.WatchDescriptor); // And if the caller has requested, remove the associated inotify watch. if (removeInotify) { SysCall(fd => { // Remove the inotify watch. This could fail if our state has become inconsistent // with the state of the world (e.g. due to lost events). So we don't want failures // to throw exceptions, but we do assert to detect coding problems during debugging. long result = Interop.libc.inotify_rm_watch(fd, directoryEntry.WatchDescriptor); Debug.Assert(result >= 0); return 0; }); } } /// <summary> /// Callback invoked when cancellation is requested. Removes all watches, /// which will cause the active processing loop to shutdown. /// </summary> private void CancellationCallback() { lock (SyncObj) { // Remove all watches (inotiy_rm_watch) and clear out the map. // No additional watches will be added after this point. SysCall(fd => { foreach (int wd in _wdToPathMap.Keys) { int result = Interop.libc.inotify_rm_watch(fd, wd); Debug.Assert(result >= 0); // ignore errors; they're non-fatal, but they also shouldn't happen } return 0; }); _wdToPathMap.Clear(); } } /// <summary> /// Main processing loop. This is currently implemented as a synchronous operation that continually /// reads events and processes them... in the future, this could be changed to use asynchronous processing /// if the impact of using a thread-per-FileSystemWatcher is too high. /// </summary> private void ProcessEvents() { // When cancellation is requested, clear out all watches. This should force any active or future reads // on the inotify handle to return 0 bytes read immediately, allowing us to wake up from the blocking call // and exit the processing loop and clean up. var ctr = _cancellationToken.Register(obj => ((RunningInstance)obj).CancellationCallback(), this); try { // Previous event information string previousEventName = null; WatchedDirectory previousEventParent = null; uint previousEventCookie = 0; // Process events as long as we're not canceled and there are more to read... NotifyEvent nextEvent; while (!_cancellationToken.IsCancellationRequested && TryReadEvent(out nextEvent)) { // Try to get the actual watcher from our weak reference. We maintain a weak reference most of the time // so as to avoid a rooted cycle that would prevent our processing loop from ever ending // if the watcher is dropped by the user without being disposed. If we can't get the watcher, // there's nothing more to do (we can't raise events), so bail. FileSystemWatcher watcher; if (!_weakWatcher.TryGetTarget(out watcher)) { break; } uint mask = nextEvent.mask; bool addWatch = false; string expandedName = null; WatchedDirectory associatedDirectoryEntry = null; if (nextEvent.wd != -1) // wd is -1 for events like IN_Q_OVERFLOW that aren't tied to a particular watch descriptor { // Look up the directory information for the supplied wd lock (SyncObj) { if (!_wdToPathMap.TryGetValue(nextEvent.wd, out associatedDirectoryEntry)) { // The watch descriptor could be missing from our dictionary if it was removed // due to cancellation, or if we already removed it and this is a related event // like IN_IGNORED. In any case, just ignore it... even if for some reason we // should have the value, there's little we can do about it at this point, // and there's no more processing of this event we can do without it. continue; } } expandedName = associatedDirectoryEntry.GetPath(true, nextEvent.name); } // Determine whether the affected object is a directory (rather than a file). // If it is, we may need to do special processing, such as adding a watch for new // directories if IncludeSubdirectories is enabled. Since we're only watching // directories, any IN_IGNORED event is also for a directory. bool isDir = (mask & (uint)(Interop.libc.NotifyEvents.IN_ISDIR | Interop.libc.NotifyEvents.IN_IGNORED)) != 0; // Renames come in the form of two events: IN_MOVED_FROM and IN_MOVED_TO. // In general, these should come as a sequence, one immediately after the other. // So, we delay raising an event for IN_MOVED_FROM until we see what comes next. if (previousEventName != null && ((mask & (uint)Interop.libc.NotifyEvents.IN_MOVED_TO) == 0 || previousEventCookie != nextEvent.cookie)) { // IN_MOVED_FROM without an immediately-following corresponding IN_MOVED_TO. // We have to assume that it was moved outside of our root watch path, which // should be considered a deletion to match Win32 behavior. // But since we explicitly added watches on directories, if it's a directory it'll // still be watched, so we need to explicitly remove the watch. if (previousEventParent != null && previousEventParent.Children != null) { // previousEventParent will be non-null iff the IN_MOVED_FROM // was for a directory, in which case previousEventParent is that directory's // parent and previousEventName is the name of the directory to be removed. foreach (WatchedDirectory child in previousEventParent.Children) { if (child.Name == previousEventName) { RemoveWatchedDirectory(child); break; } } } // Then fire the deletion event, even though the event was IN_MOVED_FROM. watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, previousEventName); previousEventName = null; previousEventParent = null; previousEventCookie = 0; } const Interop.libc.NotifyEvents switchMask = Interop.libc.NotifyEvents.IN_Q_OVERFLOW | Interop.libc.NotifyEvents.IN_IGNORED | Interop.libc.NotifyEvents.IN_CREATE | Interop.libc.NotifyEvents.IN_DELETE | Interop.libc.NotifyEvents.IN_ACCESS | Interop.libc.NotifyEvents.IN_MODIFY | Interop.libc.NotifyEvents.IN_ATTRIB | Interop.libc.NotifyEvents.IN_MOVED_FROM | Interop.libc.NotifyEvents.IN_MOVED_TO; switch ((Interop.libc.NotifyEvents)(mask & (uint)switchMask)) { case Interop.libc.NotifyEvents.IN_Q_OVERFLOW: watcher.NotifyInternalBufferOverflowEvent(); break; case Interop.libc.NotifyEvents.IN_CREATE: watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, expandedName); addWatch = true; break; case Interop.libc.NotifyEvents.IN_IGNORED: // We're getting an IN_IGNORED because a directory watch was removed. // and we're getting this far in our code because we still have an entry for it // in our dictionary. So we want to clean up the relevant state, but not clean // attempt to call back to inotify to remove the watches. RemoveWatchedDirectory(associatedDirectoryEntry, removeInotify:false); break; case Interop.libc.NotifyEvents.IN_DELETE: watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Deleted, expandedName); // We don't explicitly RemoveWatchedDirectory here, as that'll be handled // by IN_IGNORED processing if this is a directory. break; case Interop.libc.NotifyEvents.IN_ACCESS: case Interop.libc.NotifyEvents.IN_MODIFY: case Interop.libc.NotifyEvents.IN_ATTRIB: watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Changed, expandedName); break; case Interop.libc.NotifyEvents.IN_MOVED_FROM: previousEventName = expandedName; previousEventParent = isDir ? associatedDirectoryEntry : null; previousEventCookie = nextEvent.cookie; break; case Interop.libc.NotifyEvents.IN_MOVED_TO: if (previousEventName != null) { // If the previous name from IN_MOVED_FROM is non-null, then this is a rename. watcher.NotifyRenameEventArgs(WatcherChangeTypes.Renamed, expandedName, previousEventName); } else { // If it is null, then we didn't get an IN_MOVED_FROM (or we got it a long time // ago and treated it as a deletion), in which case this is considered a creation. watcher.NotifyFileSystemEventArgs(WatcherChangeTypes.Created, expandedName); } previousEventName = null; previousEventParent = null; previousEventCookie = 0; addWatch = true; // for either rename or creation, we need to update our state break; } // If the event signaled that there's a new subdirectory and if we're monitoring subdirectories, // add a watch for it. if (addWatch && isDir && _includeSubdirectories) { AddDirectoryWatch(associatedDirectoryEntry, nextEvent.name); } // Drop our strong reference to the watcher now that we're potentially going to block again for another read watcher = null; } } catch (Exception exc) { FileSystemWatcher watcher; if (_weakWatcher.TryGetTarget(out watcher)) { watcher.OnError(new ErrorEventArgs(exc)); } } finally { ctr.Dispose(); _inotifyHandle.Dispose(); } } /// <summary>Read events from the inotify handle into the supplied array.</summary> /// <param name="events">The array into which events should be read.</param> /// <returns>The number of events read and stored into the array.</returns> private bool TryReadEvent(out NotifyEvent notifyEvent) { Debug.Assert(_buffer != null); Debug.Assert(_bufferAvailable >= 0 && _bufferAvailable <= _buffer.Length); Debug.Assert(_bufferPos >= 0 && _bufferPos <= _bufferAvailable); // Read more data into our buffer if we need it if (_bufferAvailable == 0 || _bufferPos == _bufferAvailable) { // Read from the handle. This will block until either data is available // or all watches have been removed, in which case zero bytes are read. unsafe { try { _bufferAvailable = (int)SysCall(fd => { long result; fixed (byte* buf = _buffer) { result = (long)Interop.libc.read(fd, buf, (IntPtr)_buffer.Length); } Debug.Assert(result <= _buffer.Length); return result; }); } catch (ArgumentException) { _bufferAvailable = 0; Debug.Fail("Buffer provided to read was too small"); } Debug.Assert(_bufferAvailable >= 0); } if (_bufferAvailable == 0) { notifyEvent = default(NotifyEvent); return false; } Debug.Assert(_bufferAvailable >= c_INotifyEventSize); _bufferPos = 0; } // Parse each event: // struct inotify_event { // int wd; // uint32_t mask; // uint32_t cookie; // uint32_t len; // char name[]; // length determined by len; at least 1 for required null termination // }; Debug.Assert(_bufferPos + c_INotifyEventSize <= _bufferAvailable); NotifyEvent readEvent; readEvent.wd = BitConverter.ToInt32(_buffer, _bufferPos); readEvent.mask = BitConverter.ToUInt32(_buffer, _bufferPos + 4); // +4 to get past wd readEvent.cookie = BitConverter.ToUInt32(_buffer, _bufferPos + 8); // +8 to get past wd, mask int nameLength = (int)BitConverter.ToUInt32(_buffer, _bufferPos + 12); // +12 to get past wd, mask, cookie readEvent.name = ReadName(_bufferPos + c_INotifyEventSize, nameLength); // +16 to get past wd, mask, cookie, len _bufferPos += c_INotifyEventSize + nameLength; notifyEvent = readEvent; return true; } /// <summary> /// Reads a UTF8 string from _buffer starting at the specified position and up to /// the specified length. Null termination is trimmed off (the length may include /// many null bytes, not just one, or it may include none). /// </summary> /// <param name="position"></param> /// <param name="nameLength"></param> /// <returns></returns> private string ReadName(int position, int nameLength) { Debug.Assert(position > 0); Debug.Assert(nameLength >= 0 && (position + nameLength) <= _buffer.Length); int lengthWithoutNullTerm = nameLength; for (int i = 0; i < nameLength; i++) { if (_buffer[position + i] == '\0') { lengthWithoutNullTerm = i; break; } } Debug.Assert(lengthWithoutNullTerm <= nameLength); // should be null terminated or empty return lengthWithoutNullTerm > 0 ? Encoding.UTF8.GetString(_buffer, position, lengthWithoutNullTerm) : string.Empty; } /// <summary> /// Helper for making system calls that involve the stream's file descriptor. /// System calls are expected to return greather than or equal to zero on success, /// and less than zero on failure. In the case of failure, errno is expected to /// be set to the relevant error code. /// </summary> /// <param name="handle">The SafeFileHandle that wraps the file descriptor to use with the system call.</param> /// <param name="sysCall">A delegate that invokes the system call. It's passed the associated file descriptor and should return the result.</param> /// <returns>The return value of the system call.</returns> private long SysCall(Func<int, long> sysCall) { bool gotRefOnHandle = false; try { // Get the file descriptor from the handle. We increment the ref count to help // ensure it's not closed out from under us. _inotifyHandle.DangerousAddRef(ref gotRefOnHandle); Debug.Assert(gotRefOnHandle); int fd = (int)_inotifyHandle.DangerousGetHandle(); Debug.Assert(fd >= 0); long result; while (Interop.CheckIo(result = sysCall(fd), isDirectory: true)) ; return result; } finally { if (gotRefOnHandle) { _inotifyHandle.DangerousRelease(); } else { throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); } } } /// <summary>An event read and translated from the inotify handle.</summary> /// <remarks> /// Unlike it's native counterpart, this struct stores a string name rather than /// an integer length and a char[]. It is not directly marshalable. /// </remarks> private struct NotifyEvent { internal int wd; internal uint mask; internal uint cookie; internal string name; } /// <summary>State associated with a watched directory.</summary> private sealed class WatchedDirectory { /// <summary>A StringBuilder cached on the current thread to avoid allocations when possible.</summary> [ThreadStatic] private static StringBuilder t_builder; /// <summary>The parent directory.</summary> internal WatchedDirectory Parent; /// <summary>The watch descriptor associated with this directory.</summary> internal int WatchDescriptor; /// <summary>The filename of this directory.</summary> internal string Name; /// <summary>Child directories of this directory for which we added explicit watches.</summary> internal List<WatchedDirectory> Children; /// <summary>Child directories of this directory for which we added explicit watches. This is the same as Children, but ensured to be initialized as non-null.</summary> internal List<WatchedDirectory> InitializedChildren { get { if (Children == null) { Children = new List<WatchedDirectory> (); } return Children; } } // PERF: Work is being done here proportionate to depth of watch directories. // If this becomes a bottleneck, we'll need to come up with another mechanism // for obtaining and keeping paths up to date, for example storing the full path // in each WatchedDirectory node and recursively updating all children on a move, // which we can do given that we store all children. For now we're not doing that // because it's not a clear win: either you update all children recursively when // a directory moves / is added, or you compute each name when an event occurs. // The former is better if there are going to be lots of events causing lots // of traversals to compute names, and the latter is better for big directory // structures that incur fewer file events. /// <summary>Gets the path of this directory.</summary> /// <param name="relativeToRoot">Whether to get a path relative to the root directory being watched, or a full path.</param> /// <param name="additionalName">An additional name to include in the path, relative to this directory.</param> /// <returns>The computed path.</returns> internal string GetPath(bool relativeToRoot, string additionalName = null) { // Use our cached builder StringBuilder builder = t_builder; if (builder == null) { t_builder = builder = new StringBuilder(); } builder.Clear(); // Write the directory's path. Then if an additional filename was supplied, append it Write(builder, relativeToRoot); if (additionalName != null) { AppendSeparatorIfNeeded(builder); builder.Append(additionalName); } return builder.ToString(); } /// <summary>Write's this directory's path to the builder.</summary> /// <param name="builder">The builder to which to write.</param> /// <param name="relativeToRoot"> /// true if the path should be relative to the root directory being watched. /// false if the path should be a full file system path, including that of /// the root directory being watched. /// </param> private void Write(StringBuilder builder, bool relativeToRoot) { // This method is recursive. If we expect to see hierarchies // so deep that it would cause us to overflow the stack, we could // consider using an explicit stack object rather than recursion. // This is unlikely, however, given typical directory names // and max path limits. // First append the parent's path if (Parent != null) { Parent.Write(builder, relativeToRoot); AppendSeparatorIfNeeded(builder); } // Then append ours. In the case of the root directory // being watched, we only append its name if the caller // has asked for a full path. if (Parent != null || !relativeToRoot) { builder.Append(Name); } } /// <summary>Adds a directory path separator to the end of the builder if one isn't there.</summary> /// <param name="builder">The builder.</param> private static void AppendSeparatorIfNeeded(StringBuilder builder) { if (builder.Length > 0) { char c = builder[builder.Length - 1]; if (c != System.IO.Path.DirectorySeparatorChar && c != System.IO.Path.AltDirectorySeparatorChar) { builder.Append(System.IO.Path.DirectorySeparatorChar); } } } } } } }
/* * 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 Apache.Ignite.Core.Impl.Portable { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using Apache.Ignite.Core.Impl.Common; /** * <summary>Collection info helper.</summary> */ internal class PortableCollectionInfo { /** Flag: none. */ private const byte FlagNone = 0; /** Flag: generic dictionary. */ private const byte FlagGenericDictionary = 1; /** Flag: generic collection. */ private const byte FlagGenericCollection = 2; /** Flag: dictionary. */ private const byte FlagDictionary = 3; /** Flag: collection. */ private const byte FlagCollection = 4; /** Cache "none" value. */ private static readonly PortableCollectionInfo None = new PortableCollectionInfo(FlagNone, null, null, null); /** Cache "dictionary" value. */ private static readonly PortableCollectionInfo Dictionary = new PortableCollectionInfo(FlagDictionary, PortableSystemHandlers.WriteHndDictionary, null, null); /** Cache "collection" value. */ private static readonly PortableCollectionInfo Collection = new PortableCollectionInfo(FlagCollection, PortableSystemHandlers.WriteHndCollection, null, null); /** Cached infos. */ private static readonly IDictionary<Type, PortableCollectionInfo> Infos = new ConcurrentDictionary<Type, PortableCollectionInfo>(64, 32); /** * <summary>Get collection info for type.</summary> * <param name="type">Type.</param> * <returns>Collection info.</returns> */ public static PortableCollectionInfo Info(Type type) { PortableCollectionInfo info; if (!Infos.TryGetValue(type, out info)) { info = Info0(type); Infos[type] = info; } return info; } /** * <summary>Internal routine to get collection info for type.</summary> * <param name="type">Type.</param> * <returns>Collection info.</returns> */ private static PortableCollectionInfo Info0(Type type) { if (type.IsGenericType) { if (type.GetGenericTypeDefinition() == PortableUtils.TypGenericDictionary) { MethodInfo writeMthd = PortableUtils.MtdhWriteGenericDictionary.MakeGenericMethod(type.GetGenericArguments()); MethodInfo readMthd = PortableUtils.MtdhReadGenericDictionary.MakeGenericMethod(type.GetGenericArguments()); return new PortableCollectionInfo(FlagGenericDictionary, PortableSystemHandlers.WriteHndGenericDictionary, writeMthd, readMthd); } Type genTyp = type.GetInterface(PortableUtils.TypGenericDictionary.FullName); if (genTyp != null) { MethodInfo writeMthd = PortableUtils.MtdhWriteGenericDictionary.MakeGenericMethod(genTyp.GetGenericArguments()); MethodInfo readMthd = PortableUtils.MtdhReadGenericDictionary.MakeGenericMethod(genTyp.GetGenericArguments()); return new PortableCollectionInfo(FlagGenericDictionary, PortableSystemHandlers.WriteHndGenericDictionary, writeMthd, readMthd); } if (type.GetGenericTypeDefinition() == PortableUtils.TypGenericCollection) { MethodInfo writeMthd = PortableUtils.MtdhWriteGenericCollection.MakeGenericMethod(type.GetGenericArguments()); MethodInfo readMthd = PortableUtils.MtdhReadGenericCollection.MakeGenericMethod(type.GetGenericArguments()); return new PortableCollectionInfo(FlagGenericCollection, PortableSystemHandlers.WriteHndGenericCollection, writeMthd, readMthd); } genTyp = type.GetInterface(PortableUtils.TypGenericCollection.FullName); if (genTyp != null) { MethodInfo writeMthd = PortableUtils.MtdhWriteGenericCollection.MakeGenericMethod(genTyp.GetGenericArguments()); MethodInfo readMthd = PortableUtils.MtdhReadGenericCollection.MakeGenericMethod(genTyp.GetGenericArguments()); return new PortableCollectionInfo(FlagGenericCollection, PortableSystemHandlers.WriteHndGenericCollection, writeMthd, readMthd); } } if (type == PortableUtils.TypDictionary || type.GetInterface(PortableUtils.TypDictionary.FullName) != null) return Dictionary; if (type == PortableUtils.TypCollection || type.GetInterface(PortableUtils.TypCollection.FullName) != null) return Collection; return None; } /** Flag. */ private readonly byte _flag; /** Write handler. */ private readonly PortableSystemWriteDelegate _writeHnd; /** Generic write func. */ private readonly Action<object, PortableWriterImpl> _writeFunc; /** Generic read func. */ private readonly Func<PortableReaderImpl, object, object> _readFunc; /** * <summary>Constructor.</summary> * <param name="flag0">Flag.</param> * <param name="writeHnd0">Write handler.</param> * <param name="writeMthd0">Generic write method.</param> * <param name="readMthd0">Generic read method.</param> */ private PortableCollectionInfo(byte flag0, PortableSystemWriteDelegate writeHnd0, MethodInfo writeMthd0, MethodInfo readMthd0) { _flag = flag0; _writeHnd = writeHnd0; if (writeMthd0 != null) _writeFunc = DelegateConverter.CompileFunc<Action<object, PortableWriterImpl>>(null, writeMthd0, null, new[] {true, false, false}); if (readMthd0 != null) _readFunc = DelegateConverter.CompileFunc<Func<PortableReaderImpl, object, object>>(null, readMthd0, null, new[] {false, true, false}); } /** * <summary>Generic dictionary flag.</summary> */ public bool IsGenericDictionary { get { return _flag == FlagGenericDictionary; } } /** * <summary>Generic collection flag.</summary> */ public bool IsGenericCollection { get { return _flag == FlagGenericCollection; } } /** * <summary>Dictionary flag.</summary> */ public bool IsDictionary { get { return _flag == FlagDictionary; } } /** * <summary>Collection flag.</summary> */ public bool IsCollection { get { return _flag == FlagCollection; } } /** * <summary>Whether at least one flag is set..</summary> */ public bool IsAny { get { return _flag != FlagNone; } } /** * <summary>Write handler.</summary> */ public PortableSystemWriteDelegate WriteHandler { get { return _writeHnd; } } /// <summary> /// Reads the generic collection. /// </summary> public object ReadGeneric(PortableReaderImpl reader) { Debug.Assert(reader != null); Debug.Assert(_readFunc != null); return _readFunc(reader, null); } /// <summary> /// Writes the generic collection. /// </summary> public void WriteGeneric(PortableWriterImpl writer, object value) { Debug.Assert(writer != null); Debug.Assert(_writeFunc != null); _writeFunc(value, writer); } } }
// Copyright 2020 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 CommandLine; using Google.Ads.GoogleAds.Lib; using Google.Ads.GoogleAds.V10.Common; using Google.Ads.GoogleAds.V10.Errors; using Google.Ads.GoogleAds.V10.Resources; using Google.Ads.GoogleAds.V10.Services; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using static Google.Ads.GoogleAds.V10.Enums.AdGroupCriterionStatusEnum.Types; using static Google.Ads.GoogleAds.V10.Enums.KeywordMatchTypeEnum.Types; using static Google.Ads.GoogleAds.V10.Errors.QuotaErrorEnum.Types; namespace Google.Ads.GoogleAds.Examples.V10 { /// <summary> /// This code example demonstrates how to handle RateExceededError in an application. /// This code example runs 5 threads in parallel, each thread attempting to validate /// 100 keywords in a single request. While spanning 5 parallel threads is unlikely to /// trigger a rate exceeded error, substantially increasing the number of threads may /// have that effect. Note that this example is for illustrative purposes only, and you /// shouldn't intentionally try to trigger a rate exceed error in your application. /// </summary> public class HandleRateExceededError : ExampleBase { /// <summary> /// Command line options for running the <see cref="HandleRateExceededError"/> example. /// </summary> public class Options : OptionsBase { /// <summary> /// The customer ID for which the call is made. /// </summary> [Option("customerId", Required = true, HelpText = "The customer ID for which the call is made.")] public long CustomerId { get; set; } /// <summary> /// ID of the ad group to which keywords are added. /// </summary> [Option("adGroupId", Required = true, HelpText = "ID of the ad group to which keywords are added.")] public long AdGroupId { get; set; } } /// <summary> /// Main method, to run this code example as a standalone application. /// </summary> /// <param name="args">The command line arguments.</param> public static void Main(string[] args) { Options options = new Options(); CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult( delegate (Options o) { options = o; return 0; }, delegate (IEnumerable<Error> errors) { // The customer ID for which the call is made. options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE"); // ID of the ad group to which keywords are added. options.AdGroupId = long.Parse("INSERT_AD_GROUP_ID_HERE"); return 0; }); HandleRateExceededError codeExample = new HandleRateExceededError(); Console.WriteLine(codeExample.Description); codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.AdGroupId); } // Number of threads to use in the code example. private const int NUM_THREADS = 5; // Number of keywords to be validated in each API call. private const int NUM_KEYWORDS = 5000; /// <summary> /// Returns a description about the code example. /// </summary> public override string Description => "This code example demonstrates how to handle RateExceededError in an application. " + "This code example runs 5 threads in parallel, each thread attempting to validate " + "100 keywords in a single request. While spanning 5 parallel threads is unlikely to " + "trigger a rate exceeded error, substantially increasing the number of threads may " + "have that effect. Note that this example is for illustrative purposes only, and you " + "shouldn't intentionally try to trigger a rate exceed error in your application."; /// <summary> /// Runs the code example. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The customer ID for which the call is made.</param> /// <param name="adGroupId">ID of the ad group to which keywords are added.</param> public void Run(GoogleAdsClient client, long customerId, long adGroupId) { List<Task> tasks = new List<Task>(); for (int i = 0; i < NUM_THREADS; i++) { Task t = CreateKeyword(client, i, customerId, adGroupId); tasks.Add(t); } Task.WaitAll(tasks.ToArray()); } /// <summary> /// Displays the result from the mutate operation. /// </summary> /// <param name="client">The Google Ads client.</param> /// <param name="customerId">The Google Ads customer ID for which the call is made.</param> /// <param name="adGroupId">The ad group to which keywords are added.</param> /// <param name="threadIndex">The thread ID.</param> private async Task CreateKeyword(GoogleAdsClient client, int threadIndex, long customerId, long adGroupId) { await Task.Run(() => { // Get the AdGroupCriterionServiceClient. AdGroupCriterionServiceClient adGroupCriterionService = client.GetService(Services.V10.AdGroupCriterionService); List<AdGroupCriterionOperation> operations = new List<AdGroupCriterionOperation>(); for (int i = 0; i < NUM_KEYWORDS; i++) { AdGroupCriterion criterion = new AdGroupCriterion() { Keyword = new KeywordInfo() { Text = $"mars cruise thread {threadIndex} seed {i}", MatchType = KeywordMatchType.Exact }, AdGroup = ResourceNames.AdGroup(customerId, adGroupId), Status = AdGroupCriterionStatus.Paused }; // Creates the operation. operations.Add(new AdGroupCriterionOperation() { Create = criterion }); } int retryCount = 0; int retrySeconds = 30; const int NUM_RETRIES = 3; while (retryCount < NUM_RETRIES) { try { // Makes the validateOnly mutate request. MutateAdGroupCriteriaResponse response = adGroupCriterionService.MutateAdGroupCriteria( new MutateAdGroupCriteriaRequest() { CustomerId = customerId.ToString(), Operations = { operations }, PartialFailure = false, ValidateOnly = true }); Console.WriteLine($"[{threadIndex}] Validated {operations.Count} " + $"ad group criteria:"); break; } catch (GoogleAdsException e) { // Checks if any of the errors are QuotaError.RESOURCE_EXHAUSTED or // QuotaError.RESOURCE_TEMPORARILY_EXHAUSTED. // Note: The code assumes that the developer token is approved for // Standard Access. if (e.Failure != null) { bool isRateExceededError = false; e.Failure.Errors .Where(err => err.ErrorCode.QuotaError == QuotaError.ResourceExhausted || err.ErrorCode.QuotaError == QuotaError.ResourceTemporarilyExhausted) .ToList() .ForEach(delegate (GoogleAdsError err) { Console.Error.WriteLine($"[{threadIndex}] Received rate " + $"exceeded error. Message says, \"{err.Message}\"."); isRateExceededError = true; } ); if (isRateExceededError) { Console.Error.WriteLine( $"[{threadIndex}] Will retry after {retrySeconds} seconds."); Thread.Sleep(retrySeconds * 1000); retryCount++; // Uses an exponential backoff policy to avoid polling too // aggressively. retrySeconds *= 2; } } else { Console.WriteLine("Failure:"); Console.WriteLine($"Message: {e.Message}"); Console.WriteLine($"Failure: {e.Failure}"); Console.WriteLine($"Request ID: {e.RequestId}"); break; } } finally { if (retryCount == NUM_RETRIES) { throw new Exception($"[{ threadIndex }] Could not recover after " + $"making {retryCount} attempts."); } } } }); } } }
using System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Text; namespace ShellTools.CommandLine { /// <summary> /// Parser for command line arguments. /// /// The parser specification is infered from the instance fields of the object /// specified as the destination of the parse. /// Valid argument types are: int, uint, string, bool, enums /// Also argument types of Array of the above types are also valid. /// /// Error checking options can be controlled by adding a ArgumentAttribute /// to the instance fields of the destination object. /// /// At most one field may be marked with the DefaultArgumentAttribute /// indicating that arguments without a '-' or '/' prefix will be parsed as that argument. /// /// If not specified then the parser will infer default options for parsing each /// instance field. The default long name of the argument is the field name. The /// default short name is the first character of the long name. Long names and explicitly /// specified short names must be unique. Default short names will be used provided that /// the default short name does not conflict with a long name or an explicitly /// specified short name. /// /// Arguments which are array types are collection arguments. Collection /// arguments can be specified multiple times. /// </summary> public sealed class Parser { /// <summary> /// The System Defined new line string. /// </summary> public const string NewLine = "\r\n"; /// <summary> /// Don't ever call this. /// </summary> private Parser() { } /// <summary> /// Parses Command Line Arguments. Displays usage message to Console.Out /// if /?, /help or invalid arguments are encounterd. /// Errors are output on Console.Error. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="arguments"> The actual arguments. </param> /// <param name="destination"> The resulting parsed arguments. </param> /// <returns> true if no errors were detected. </returns> public static bool ParseArgumentsWithUsage(string [] arguments, object destination) { if (Parser.ParseHelp(arguments) || !Parser.ParseArguments(arguments, destination)) { // error encountered in arguments. Display usage message Console.Write(Parser.ArgumentsUsage(destination.GetType())); return false; } return true; } /// <summary> /// Parses Command Line Arguments. /// Errors are output on Console.Error. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="arguments"> The actual arguments. </param> /// <param name="destination"> The resulting parsed arguments. </param> /// <returns> true if no errors were detected. </returns> public static bool ParseArguments(string [] arguments, object destination) { return Parser.ParseArguments(arguments, destination, new ErrorReporter(Console.Error.WriteLine)); } /// <summary> /// Parses Command Line Arguments. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="arguments"> The actual arguments. </param> /// <param name="destination"> The resulting parsed arguments. </param> /// <param name="reporter"> The destination for parse errors. </param> /// <returns> true if no errors were detected. </returns> public static bool ParseArguments(string[] arguments, object destination, ErrorReporter reporter) { Parser parser = new Parser(destination.GetType(), reporter); return parser.Parse(arguments, destination); } private static void NullErrorReporter(string message) { } private class HelpArgument { [Argument(ArgumentType.AtMostOnce, ShortName="?")] public bool help = false; } /// <summary> /// Checks if a set of arguments asks for help. /// </summary> /// <param name="args"> Args to check for help. </param> /// <returns> Returns true if args contains /? or /help. </returns> public static bool ParseHelp(string[] args) { Parser helpParser = new Parser(typeof(HelpArgument), new ErrorReporter(NullErrorReporter)); HelpArgument helpArgument = new HelpArgument(); helpParser.Parse(args, helpArgument); return helpArgument.help; } /// <summary> /// Returns a Usage string for command line argument parsing. /// Use ArgumentAttributes to control parsing behaviour. /// Formats the output to the width of the current console window. /// </summary> /// <param name="argumentType"> The type of the arguments to display usage for. </param> /// <returns> Printable string containing a user friendly description of command line arguments. </returns> public static string ArgumentsUsage(Type argumentType) { int screenWidth = Parser.GetConsoleWindowWidth(); if (screenWidth == 0) screenWidth = 80; return ArgumentsUsage(argumentType, screenWidth); } /// <summary> /// Returns a Usage string for command line argument parsing. /// Use ArgumentAttributes to control parsing behaviour. /// </summary> /// <param name="argumentType"> The type of the arguments to display usage for. </param> /// <param name="columns"> The number of columns to format the output to. </param> /// <returns> Printable string containing a user friendly description of command line arguments. </returns> public static string ArgumentsUsage(Type argumentType, int columns) { return (new Parser(argumentType, null)).GetUsageString(columns); } private const int STD_OUTPUT_HANDLE = -11; private struct COORD { internal Int16 x; internal Int16 y; } private struct SMALL_RECT { internal Int16 Left; internal Int16 Top; internal Int16 Right; internal Int16 Bottom; } private struct CONSOLE_SCREEN_BUFFER_INFO { internal COORD dwSize; internal COORD dwCursorPosition; internal Int16 wAttributes; internal SMALL_RECT srWindow; internal COORD dwMaximumWindowSize; } [DllImport("kernel32.dll", EntryPoint="GetStdHandle", SetLastError=true, CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)] private static extern int GetStdHandle(int nStdHandle); [DllImport("kernel32.dll", EntryPoint="GetConsoleScreenBufferInfo", SetLastError=true, CharSet=CharSet.Auto, CallingConvention=CallingConvention.StdCall)] private static extern int GetConsoleScreenBufferInfo(int hConsoleOutput, ref CONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo); /// <summary> /// Returns the number of columns in the current console window /// </summary> /// <returns>Returns the number of columns in the current console window</returns> public static int GetConsoleWindowWidth() { int screenWidth; CONSOLE_SCREEN_BUFFER_INFO csbi = new CONSOLE_SCREEN_BUFFER_INFO(); int rc; rc = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), ref csbi); screenWidth = csbi.dwSize.x; return screenWidth; } /// <summary> /// Searches a StringBuilder for a character /// </summary> /// <param name="text"> The text to search. </param> /// <param name="value"> The character value to search for. </param> /// <param name="startIndex"> The index to stat searching at. </param> /// <returns> The index of the first occurence of value or -1 if it is not found. </returns> public static int IndexOf(StringBuilder text, char value, int startIndex) { for (int index = startIndex; index < text.Length; index++) { if (text[index] == value) return index; } return -1; } /// <summary> /// Searches a StringBuilder for a character in reverse /// </summary> /// <param name="text"> The text to search. </param> /// <param name="value"> The character to search for. </param> /// <param name="startIndex"> The index to start the search at. </param> /// <returns>The index of the last occurence of value in text or -1 if it is not found. </returns> public static int LastIndexOf(StringBuilder text, char value, int startIndex) { for (int index = Math.Min(startIndex, text.Length - 1); index >= 0; index --) { if (text[index] == value) return index; } return -1; } private const int spaceBeforeParam = 2; /// <summary> /// Creates a new command line argument parser. /// </summary> /// <param name="argumentSpecification"> The type of object to parse. </param> /// <param name="reporter"> The destination for parse errors. </param> public Parser(Type argumentSpecification, ErrorReporter reporter) { this.reporter = reporter; this.arguments = new ArrayList(); this.argumentMap = new Hashtable(); foreach (FieldInfo field in argumentSpecification.GetFields()) { if (!field.IsStatic && !field.IsInitOnly && !field.IsLiteral) { ArgumentAttribute attribute = GetAttribute(field); if (attribute is DefaultArgumentAttribute) { Debug.Assert(this.defaultArgument == null); this.defaultArgument = new Argument(attribute, field, reporter); } else { this.arguments.Add(new Argument(attribute, field, reporter)); } } } // add explicit names to map foreach (Argument argument in this.arguments) { Debug.Assert(!argumentMap.ContainsKey(argument.LongName)); this.argumentMap[argument.LongName] = argument; if (argument.ExplicitShortName) { if (argument.ShortName != null && argument.ShortName.Length > 0) { Debug.Assert(!argumentMap.ContainsKey(argument.ShortName)); this.argumentMap[argument.ShortName] = argument; } else { argument.ClearShortName(); } } } // add implicit names which don't collide to map foreach (Argument argument in this.arguments) { if (!argument.ExplicitShortName) { if (argument.ShortName != null && argument.ShortName.Length > 0 && !argumentMap.ContainsKey(argument.ShortName)) this.argumentMap[argument.ShortName] = argument; else argument.ClearShortName(); } } } private static ArgumentAttribute GetAttribute(FieldInfo field) { object[] attributes = field.GetCustomAttributes(typeof(ArgumentAttribute), false); if (attributes.Length == 1) return (ArgumentAttribute) attributes[0]; Debug.Assert(attributes.Length == 0); return null; } private void ReportUnrecognizedArgument(string argument) { this.reporter(string.Format("Unrecognized command line argument '{0}'", argument)); } /// <summary> /// Parses an argument list into an object /// </summary> /// <param name="args"></param> /// <param name="destination"></param> /// <returns> true if an error occurred </returns> private bool ParseArgumentList(string[] args, object destination) { bool hadError = false; if (args != null) { foreach (string argument in args) { if (argument.Length > 0) { switch (argument[0]) { case '-': case '/': int endIndex = argument.IndexOfAny(new char[] {':', '+', '-'}, 1); string option = argument.Substring(1, endIndex == -1 ? argument.Length - 1 : endIndex - 1); string optionArgument; if (option.Length + 1 == argument.Length) { optionArgument = null; } else if (argument.Length > 1 + option.Length && argument[1 + option.Length] == ':') { optionArgument = argument.Substring(option.Length + 2); } else { optionArgument = argument.Substring(option.Length + 1); } Argument arg = (Argument) this.argumentMap[option]; if (arg == null) { ReportUnrecognizedArgument(argument); hadError = true; } else { hadError |= !arg.SetValue(optionArgument, destination); } break; case '@': string[] nestedArguments; hadError |= LexFileArguments(argument.Substring(1), out nestedArguments); hadError |= ParseArgumentList(nestedArguments, destination); break; default: if (this.defaultArgument != null) { hadError |= !this.defaultArgument.SetValue(argument, destination); } else { ReportUnrecognizedArgument(argument); hadError = true; } break; } } } } return hadError; } /// <summary> /// Parses an argument list. /// </summary> /// <param name="args"> The arguments to parse. </param> /// <param name="destination"> The destination of the parsed arguments. </param> /// <returns> true if no parse errors were encountered. </returns> public bool Parse(string[] args, object destination) { bool hadError = ParseArgumentList(args, destination); // check for missing required arguments foreach (Argument arg in this.arguments) { hadError |= arg.Finish(destination); } if (this.defaultArgument != null) { hadError |= this.defaultArgument.Finish(destination); } return !hadError; } private struct ArgumentHelpStrings { public ArgumentHelpStrings(string syntax, string help) { this.syntax = syntax; this.help = help; } public string syntax; public string help; } /// <summary> /// A user firendly usage string describing the command line argument syntax. /// </summary> public string GetUsageString(int screenWidth) { ArgumentHelpStrings[] strings = GetAllHelpStrings(); int maxParamLen = 0; foreach (ArgumentHelpStrings helpString in strings) { maxParamLen = Math.Max(maxParamLen, helpString.syntax.Length); } const int minimumNumberOfCharsForHelpText = 10; const int minimumHelpTextColumn = 5; const int minimumScreenWidth = minimumHelpTextColumn + minimumNumberOfCharsForHelpText; int helpTextColumn; int idealMinimumHelpTextColumn = maxParamLen + spaceBeforeParam; screenWidth = Math.Max(screenWidth, minimumScreenWidth); if (screenWidth < (idealMinimumHelpTextColumn + minimumNumberOfCharsForHelpText)) helpTextColumn = minimumHelpTextColumn; else helpTextColumn = idealMinimumHelpTextColumn; const string newLine = "\n"; StringBuilder builder = new StringBuilder(); foreach (ArgumentHelpStrings helpStrings in strings) { // add syntax string int syntaxLength = helpStrings.syntax.Length; builder.Append(helpStrings.syntax); // start help text on new line if syntax string is too long int currentColumn = syntaxLength; if (syntaxLength >= helpTextColumn) { builder.Append(newLine); currentColumn = 0; } // add help text broken on spaces int charsPerLine = screenWidth - helpTextColumn; int index = 0; while (index < helpStrings.help.Length) { // tab to start column builder.Append(' ', helpTextColumn - currentColumn); currentColumn = helpTextColumn; // find number of chars to display on this line int endIndex = index + charsPerLine; if (endIndex >= helpStrings.help.Length) { // rest of text fits on this line endIndex = helpStrings.help.Length; } else { endIndex = helpStrings.help.LastIndexOf(' ', endIndex - 1, Math.Min(endIndex - index, charsPerLine)); if (endIndex <= index) { // no spaces on this line, append full set of chars endIndex = index + charsPerLine; } } // add chars builder.Append(helpStrings.help, index, endIndex - index); index = endIndex; // do new line AddNewLine(newLine, builder, ref currentColumn); // don't start a new line with spaces while (index < helpStrings.help.Length && helpStrings.help[index] == ' ') index ++; } // add newline if there's no help text if (helpStrings.help.Length == 0) { builder.Append(newLine); } } return builder.ToString(); } private static void AddNewLine(string newLine, StringBuilder builder, ref int currentColumn) { builder.Append(newLine); currentColumn = 0; } private ArgumentHelpStrings[] GetAllHelpStrings() { ArgumentHelpStrings[] strings = new ArgumentHelpStrings[NumberOfParametersToDisplay()-1]; int index = 0; if (this.defaultArgument != null) strings[index++] = GetHelpStrings(this.defaultArgument); foreach (Argument arg in this.arguments) { strings[index] = GetHelpStrings(arg); index++; } //strings[index++] = new ArgumentHelpStrings("@<file>", "Read response file for more options"); return strings; } private static ArgumentHelpStrings GetHelpStrings(Argument arg) { return new ArgumentHelpStrings(arg.SyntaxHelp, arg.FullHelpText); } private int NumberOfParametersToDisplay() { int numberOfParameters = this.arguments.Count + 1; if (HasDefaultArgument) numberOfParameters += 1; return numberOfParameters; } /// <summary> /// Does this parser have a default argument. /// </summary> /// <value> Does this parser have a default argument. </value> public bool HasDefaultArgument { get { return this.defaultArgument != null; } } private bool LexFileArguments(string fileName, out string[] arguments) { string args = null; try { using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { args = (new StreamReader(file)).ReadToEnd(); } } catch (Exception e) { this.reporter(string.Format("Error: Can't open command line argument file '{0}' : '{1}'", fileName, e.Message)); arguments = null; return false; } bool hadError = false; ArrayList argArray = new ArrayList(); StringBuilder currentArg = new StringBuilder(); bool inQuotes = false; int index = 0; // while (index < args.Length) try { while (true) { // skip whitespace while (char.IsWhiteSpace(args[index])) { index += 1; } // # - comment to end of line if (args[index] == '#') { index += 1; while (args[index] != '\n') { index += 1; } continue; } // do one argument do { if (args[index] == '\\') { int cSlashes = 1; index += 1; while (index == args.Length && args[index] == '\\') { cSlashes += 1; } if (index == args.Length || args[index] != '"') { currentArg.Append('\\', cSlashes); } else { currentArg.Append('\\', (cSlashes >> 1)); if (0 != (cSlashes & 1)) { currentArg.Append('"'); } else { inQuotes = !inQuotes; } } } else if (args[index] == '"') { inQuotes = !inQuotes; index += 1; } else { currentArg.Append(args[index]); index += 1; } } while (!char.IsWhiteSpace(args[index]) || inQuotes); argArray.Add(currentArg.ToString()); currentArg.Length = 0; } } catch (IndexOutOfRangeException) { // got EOF if (inQuotes) { this.reporter(string.Format("Error: Unbalanced '\"' in command line argument file '{0}'", fileName)); hadError = true; } else if (currentArg.Length > 0) { // valid argument can be terminated by EOF argArray.Add(currentArg.ToString()); } } arguments = (string[]) argArray.ToArray(typeof (string)); return hadError; } private static string LongName(ArgumentAttribute attribute, FieldInfo field) { return (attribute == null || attribute.DefaultLongName) ? field.Name : attribute.LongName; } private static string ShortName(ArgumentAttribute attribute, FieldInfo field) { if (attribute is DefaultArgumentAttribute) return null; if (!ExplicitShortName(attribute)) return LongName(attribute, field).Substring(0,1); return attribute.ShortName; } private static string HelpText(ArgumentAttribute attribute, FieldInfo field) { if (attribute == null) return null; else return attribute.HelpText; } private static bool HasHelpText(ArgumentAttribute attribute) { return (attribute != null && attribute.HasHelpText); } private static bool ExplicitShortName(ArgumentAttribute attribute) { return (attribute != null && !attribute.DefaultShortName); } private static object DefaultValue(ArgumentAttribute attribute, FieldInfo field) { return (attribute == null || !attribute.HasDefaultValue) ? null : attribute.DefaultValue; } private static Type ElementType(FieldInfo field) { if (IsCollectionType(field.FieldType)) return field.FieldType.GetElementType(); else return null; } private static ArgumentType Flags(ArgumentAttribute attribute, FieldInfo field) { if (attribute != null) return attribute.Type; else if (IsCollectionType(field.FieldType)) return ArgumentType.MultipleUnique; else return ArgumentType.AtMostOnce; } private static bool IsCollectionType(Type type) { return type.IsArray; } private static bool IsValidElementType(Type type) { return type != null && ( type == typeof(int) || type == typeof(uint) || type == typeof(string) || type == typeof(bool) || type.IsEnum); } private class Argument { public Argument(ArgumentAttribute attribute, FieldInfo field, ErrorReporter reporter) { this.longName = Parser.LongName(attribute, field); this.explicitShortName = Parser.ExplicitShortName(attribute); this.shortName = Parser.ShortName(attribute, field); this.hasHelpText = Parser.HasHelpText(attribute); this.helpText = Parser.HelpText(attribute, field); this.defaultValue = Parser.DefaultValue(attribute, field); this.elementType = ElementType(field); this.flags = Flags(attribute, field); this.field = field; this.seenValue = false; this.reporter = reporter; this.isDefault = attribute != null && attribute is DefaultArgumentAttribute; if (IsCollection) { this.collectionValues = new ArrayList(); } Debug.Assert(this.longName != null && this.longName != ""); Debug.Assert(!this.isDefault || !this.ExplicitShortName); Debug.Assert(!IsCollection || AllowMultiple, "Collection arguments must have allow multiple"); Debug.Assert(!Unique || IsCollection, "Unique only applicable to collection arguments"); Debug.Assert(IsValidElementType(Type) || IsCollectionType(Type)); Debug.Assert((IsCollection && IsValidElementType(elementType)) || (!IsCollection && elementType == null)); Debug.Assert(!(this.IsRequired && this.HasDefaultValue), "Required arguments cannot have default value"); Debug.Assert(!this.HasDefaultValue || (this.defaultValue.GetType() == field.FieldType), "Type of default value must match field type"); } public bool Finish(object destination) { if (!this.SeenValue && this.HasDefaultValue) { this.field.SetValue(destination, this.DefaultValue); } if (this.IsCollection) { this.field.SetValue(destination, this.collectionValues.ToArray(this.elementType)); } return ReportMissingRequiredArgument(); } private bool ReportMissingRequiredArgument() { if (this.IsRequired && !this.SeenValue) { if (this.IsDefault) reporter(string.Format("Missing required argument '<{0}>'.", this.LongName)); else reporter(string.Format("Missing required argument '/{0}'.", this.LongName)); return true; } return false; } private void ReportDuplicateArgumentValue(string value) { this.reporter(string.Format("Duplicate '{0}' argument '{1}'", this.LongName, value)); } public bool SetValue(string value, object destination) { if (SeenValue && !AllowMultiple) { this.reporter(string.Format("Duplicate '{0}' argument", this.LongName)); return false; } this.seenValue = true; object newValue; if (!ParseValue(this.ValueType, value, out newValue)) return false; if (this.IsCollection) { if (this.Unique && this.collectionValues.Contains(newValue)) { ReportDuplicateArgumentValue(value); return false; } else { this.collectionValues.Add(newValue); } } else { this.field.SetValue(destination, newValue); } return true; } public Type ValueType { get { return this.IsCollection ? this.elementType : this.Type; } } private void ReportBadArgumentValue(string value) { this.reporter(string.Format("'{0}' is not a valid value for the '{1}' command line option", value, this.LongName)); } private bool ParseValue(Type type, string stringData, out object value) { // null is only valid for bool variables // empty string is never valid if ((stringData != null || type == typeof(bool)) && (stringData == null || stringData.Length > 0)) { try { if (type == typeof(string)) { value = stringData; return true; } else if (type == typeof(bool)) { if (stringData == null || stringData == "+") { value = true; return true; } else if (stringData == "-") { value = false; return true; } } else if (type == typeof(int)) { value = int.Parse(stringData); return true; } else if (type == typeof(uint)) { value = int.Parse(stringData); return true; } else { Debug.Assert(type.IsEnum); value = Enum.Parse(type, stringData, true); return true; } } catch { // catch parse errors } } ReportBadArgumentValue(stringData); value = null; return false; } private void AppendValue(StringBuilder builder, object value) { if (value is string || value is int || value is uint || value.GetType().IsEnum) { builder.Append(value.ToString()); } else if (value is bool) { builder.Append((bool) value ? "+" : "-"); } else { bool first = true; foreach (object o in (Array) value) { if (!first) { builder.Append(", "); } AppendValue(builder, o); first = false; } } } public string LongName { get { return this.longName; } } public bool ExplicitShortName { get { return this.explicitShortName; } } public string ShortName { get { return this.shortName; } } public bool HasShortName { get { return this.shortName != null; } } public void ClearShortName() { this.shortName = null; } public bool HasHelpText { get { return this.hasHelpText; } } public string HelpText { get { return this.helpText; } } public object DefaultValue { get { return this.defaultValue; } } public bool HasDefaultValue { get { return null != this.defaultValue; } } public string FullHelpText { get { StringBuilder builder = new StringBuilder(); if (this.HasHelpText) { builder.Append(this.HelpText); } if (this.HasDefaultValue) { if (builder.Length > 0) builder.Append(" "); builder.Append("Default value:'"); AppendValue(builder, this.DefaultValue); builder.Append('\''); } if (this.HasShortName) { if (builder.Length > 0) builder.Append(" "); builder.Append("(short form /"); builder.Append(this.ShortName); builder.Append(")"); } return builder.ToString(); } } public string SyntaxHelp { get { StringBuilder builder = new StringBuilder(); if (this.IsDefault) { builder.Append("<"); builder.Append(this.LongName); builder.Append(">"); } else { builder.Append("/"); builder.Append(this.LongName); Type valueType = this.ValueType; if (valueType == typeof(int)) { builder.Append(":<int>"); } else if (valueType == typeof(uint)) { builder.Append(":<uint>"); } else if (valueType == typeof(bool)) { builder.Append("[+|-]"); } else if (valueType == typeof(string)) { builder.Append(":<string>"); } else { Debug.Assert(valueType.IsEnum); builder.Append(":{"); bool first = true; foreach (FieldInfo field in valueType.GetFields()) { if (field.IsStatic) { if (first) first = false; else builder.Append('|'); builder.Append(field.Name); } } builder.Append('}'); } } return builder.ToString(); } } public bool IsRequired { get { return 0 != (this.flags & ArgumentType.Required); } } public bool SeenValue { get { return this.seenValue; } } public bool AllowMultiple { get { return 0 != (this.flags & ArgumentType.Multiple); } } public bool Unique { get { return 0 != (this.flags & ArgumentType.Unique); } } public Type Type { get { return field.FieldType; } } public bool IsCollection { get { return IsCollectionType(Type); } } public bool IsDefault { get { return this.isDefault; } } private string longName; private string shortName; private string helpText; private bool hasHelpText; private bool explicitShortName; private object defaultValue; private bool seenValue; private FieldInfo field; private Type elementType; private ArgumentType flags; private ArrayList collectionValues; private ErrorReporter reporter; private bool isDefault; } private ArrayList arguments; private Hashtable argumentMap; private Argument defaultArgument; private ErrorReporter reporter; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace _2016MT45WebApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
//------------------------------------------------------------------------------ // <copyright file="BaseDataBoundControl.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.Collections; using System.ComponentModel; using System.Web.Util; /// <summary> /// A BaseDataBoundControl is bound to a data source and generates its /// user interface (or child control hierarchy typically), by enumerating /// the items in the data source it is bound to. /// BaseDataBoundControl is an abstract base class that defines the common /// characteristics of all controls that use a list as a data source, such as /// DataGrid, DataBoundTable, ListBox etc. It encapsulates the logic /// of how a data-bound control binds to collections or DataControl instances. /// </summary> [ Designer("System.Web.UI.Design.WebControls.BaseDataBoundControlDesigner, " + AssemblyRef.SystemDesign), DefaultProperty("DataSourceID") ] public abstract class BaseDataBoundControl : WebControl { private static readonly object EventDataBound = new object(); private object _dataSource; private bool _requiresDataBinding; private bool _inited; private bool _preRendered; private bool _requiresBindToNull; private bool _throwOnDataPropertyChange; /// <summary> /// The data source to bind to. This allows a BaseDataBoundControl to bind /// to arbitrary lists of data items. /// </summary> [ Bindable(true), DefaultValue(null), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Themeable(false), WebCategory("Data"), WebSysDescription(SR.BaseDataBoundControl_DataSource), ] public virtual object DataSource { get { return _dataSource; } set { if (value != null) { ValidateDataSource(value); } _dataSource = value; OnDataPropertyChanged(); } } /// <summary> /// The ID of the DataControl that this control should use to retrieve /// its data source. When the control is bound to a DataControl, it /// can retrieve a data source instance on-demand, and thereby attempt /// to work in auto-DataBind mode. /// </summary> [ DefaultValue(""), Themeable(false), WebCategory("Data"), WebSysDescription(SR.BaseDataBoundControl_DataSourceID) ] public virtual string DataSourceID { get { object o = ViewState["DataSourceID"]; if (o != null) { return (string)o; } return String.Empty; } set { if (String.IsNullOrEmpty(value) && !String.IsNullOrEmpty(DataSourceID)) { _requiresBindToNull = true; } ViewState["DataSourceID"] = value; OnDataPropertyChanged(); } } protected bool Initialized { get { return _inited; } } /// <summary> /// Returns true if the DataBoundControl uses Select/Update/Delete/Insert Methods for databinding. /// Implementation on BaseDataBoundControl returns false. /// Override in child classes which support the above two properties. /// </summary> protected virtual bool IsUsingModelBinders { get { return false; } } /// <summary> /// This returns true only if the DataBoundControl is using a DataSourceID. /// Use the IsDataBindingAutomatic property to determine if the data bound control's data binding is /// automatic. The data binding is automatic if the control is using a DataSourceID or if control /// uses Select/Update/Delete/Insert Methods for data binding. /// </summary> protected bool IsBoundUsingDataSourceID { get { return (DataSourceID.Length > 0); } } /// <summary> /// This property is used by FormView/GridView/DetailsView/ListView in the following scenarios. /// 1. Perform an auto data bind (Listen to OnDataSourceViewChanged event and set RequiresDataBinding to true) /// 2. Calling the data source view operations /// 3. Raising exceptions when there is no DataSourceId (i.e., a DataSource is in use) and an event for Data Operation is not handled /// 4. Raising the ModeChanged events for DataControls /// This property is true if the control is bound using a DataSourceId or when the control participates in Model Binding. /// </summary> protected internal bool IsDataBindingAutomatic { get { return IsBoundUsingDataSourceID || IsUsingModelBinders; } } public override bool SupportsDisabledAttribute { get { return RenderingCompatibility < VersionUtil.Framework40; } } protected bool RequiresDataBinding { get { return _requiresDataBinding; } set { // if we have to play catch-up here because we've already PreRendered, call EnsureDataBound if (value && _preRendered && IsDataBindingAutomatic && Page != null && !Page.IsCallback) { _requiresDataBinding = true; EnsureDataBound(); } else { _requiresDataBinding = value; } } } [ WebCategory("Data"), WebSysDescription(SR.BaseDataBoundControl_OnDataBound) ] public event EventHandler DataBound { add { Events.AddHandler(EventDataBound, value); } remove { Events.RemoveHandler(EventDataBound, value); } } protected void ConfirmInitState() { _inited = true; // do this in OnLoad in case we were added to the page after Page.OnPreLoad } /// <summary> /// Overriden by BaseDataBoundControl to use its properties to determine the real /// data source that the control should bind to. It then clears the existing /// control hierarchy, and calls CreateChildControls to create a new control /// hierarchy based on the resolved data source. /// The implementation resolves various data source related properties to /// arrive at the appropriate IEnumerable implementation to use as the real /// data source. /// When resolving data sources, the DataSourceID takes highest precedence. /// If DataSourceID is not set, the value of the DataSource property is used. /// In this second alternative, DataMember is used to extract the appropriate /// list if the control has been handed an IListSource as a data source. /// /// Data bound controls should override PerformDataBinding instead /// of DataBind. If DataBind if overridden, the OnDataBinding and OnDataBound events will /// fire in the wrong order. However, for backwards compat on ListControl and AdRotator, we /// can't seal this method. It is sealed on all new BaseDataBoundControl-derived controls. /// </summary> public override void DataBind() { // Don't databind when the control is in the designer but not top-level if (DesignMode) { IDictionary designModeState = GetDesignModeState(); if (((designModeState == null) || (designModeState["EnableDesignTimeDataBinding"] == null)) && (Site == null)) { return; } } PerformSelect(); } protected virtual void EnsureDataBound() { try { _throwOnDataPropertyChange = true; if (RequiresDataBinding && (IsDataBindingAutomatic || _requiresBindToNull)) { DataBind(); _requiresBindToNull = false; } } finally { _throwOnDataPropertyChange = false; } } protected virtual void OnDataBound(EventArgs e) { EventHandler handler = Events[EventDataBound] as EventHandler; if (handler != null) { handler(this, e); } } /// <devdoc> /// This method is called when DataMember, DataSource, or DataSourceID is changed. /// </devdoc> protected virtual void OnDataPropertyChanged() { if (_throwOnDataPropertyChange) { throw new HttpException(SR.GetString(SR.DataBoundControl_InvalidDataPropertyChange, ID)); } if (_inited) { RequiresDataBinding = true; } } protected internal override void OnInit(EventArgs e) { base.OnInit(e); if (Page != null) { Page.PreLoad += new EventHandler(this.OnPagePreLoad); if (!IsViewStateEnabled && Page.IsPostBack) { RequiresDataBinding = true; } } } protected virtual void OnPagePreLoad(object sender, EventArgs e) { _inited = true; if (Page != null) { Page.PreLoad -= new EventHandler(this.OnPagePreLoad); } } protected internal override void OnPreRender(EventArgs e) { _preRendered = true; EnsureDataBound(); base.OnPreRender(e); } /// <summary> /// Override to control how the data is selected and the control is databound. /// </summary> protected abstract void PerformSelect(); protected abstract void ValidateDataSource(object dataSource); } }
// ReSharper disable All using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using Frapid.ApplicationState.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Frapid.WebsiteBuilder.DataAccess; using Frapid.WebsiteBuilder.Api.Fakes; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Xunit; namespace Frapid.WebsiteBuilder.Api.Tests { public class MenuTests { public static WebsiteMenuController Fixture() { WebsiteMenuController controller = new WebsiteMenuController(new MenuRepository()); return controller; } [Fact] [Conditional("Debug")] public void CountEntityColumns() { EntityView entityView = Fixture().GetEntityView(); Assert.Null(entityView.Columns); } [Fact] [Conditional("Debug")] public void Count() { long count = Fixture().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetAll() { int count = Fixture().GetAll().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Export() { int count = Fixture().Export().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void Get() { Frapid.WebsiteBuilder.Entities.Menu menu = Fixture().Get(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void First() { Frapid.WebsiteBuilder.Entities.Menu menu = Fixture().GetFirst(); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Previous() { Frapid.WebsiteBuilder.Entities.Menu menu = Fixture().GetPrevious(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Next() { Frapid.WebsiteBuilder.Entities.Menu menu = Fixture().GetNext(0); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void Last() { Frapid.WebsiteBuilder.Entities.Menu menu = Fixture().GetLast(); Assert.NotNull(menu); } [Fact] [Conditional("Debug")] public void GetMultiple() { IEnumerable<Frapid.WebsiteBuilder.Entities.Menu> menus = Fixture().Get(new int[] { }); Assert.NotNull(menus); } [Fact] [Conditional("Debug")] public void GetPaginatedResult() { int count = Fixture().GetPaginatedResult().Count(); Assert.Equal(1, count); count = Fixture().GetPaginatedResult(1).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountWhere() { long count = Fixture().CountWhere(new JArray()); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetWhere() { int count = Fixture().GetWhere(1, new JArray()).Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void CountFiltered() { long count = Fixture().CountFiltered(""); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetFiltered() { int count = Fixture().GetFiltered(1, "").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetDisplayFields() { int count = Fixture().GetDisplayFields().Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void GetCustomFields() { int count = Fixture().GetCustomFields().Count(); Assert.Equal(1, count); count = Fixture().GetCustomFields("").Count(); Assert.Equal(1, count); } [Fact] [Conditional("Debug")] public void AddOrEdit() { try { var form = new JArray { null, null }; Fixture().AddOrEdit(form); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Add() { try { Fixture().Add(null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void Edit() { try { Fixture().Edit(0, null); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode); } } [Fact] [Conditional("Debug")] public void BulkImport() { var collection = new JArray { null, null, null, null }; var actual = Fixture().BulkImport(collection); Assert.NotNull(actual); } [Fact] [Conditional("Debug")] public void Delete() { try { Fixture().Delete(0); } catch (HttpResponseException ex) { Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode); } } } }
//------------------------------------------------------------------------------ // <copyright file="TableCell.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.WebControls { using System; using System.ComponentModel; using System.Globalization; using System.Text; using System.Web; using System.Web.UI; using System.Web.Util; /// <devdoc> /// <para>Interacts with the parser to build a <see cref='System.Web.UI.WebControls.TableCell'/> control.</para> /// </devdoc> public class TableCellControlBuilder : ControlBuilder { /// <internalonly/> /// <devdoc> /// Specifies whether white space literals are allowed. /// </devdoc> public override bool AllowWhitespaceLiterals() { return false; } } /// <devdoc> /// <para>Encapsulates a cell within a table.</para> /// </devdoc> [ Bindable(false), ControlBuilderAttribute(typeof(TableCellControlBuilder)), DefaultProperty("Text"), ParseChildren(false), ToolboxItem(false) ] [Designer("System.Web.UI.Design.WebControls.PreviewControlDesigner, " + AssemblyRef.SystemDesign)] public class TableCell : WebControl { private bool _textSetByAddParsedSubObject = false; /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Web.UI.WebControls.TableCell'/> class. /// </para> /// </devdoc> public TableCell() : this(HtmlTextWriterTag.Td) { } /// <devdoc> /// </devdoc> internal TableCell(HtmlTextWriterTag tagKey) : base(tagKey) { PreventAutoID(); } /// <devdoc> /// <para> /// Contains a list of categories associated with the table header (read by screen readers). The categories can be any string values. The categories are rendered as a comma delimited list using the HTML axis attribute. /// </para> /// </devdoc> [ DefaultValue(null), TypeConverterAttribute(typeof(StringArrayConverter)), WebCategory("Accessibility"), WebSysDescription(SR.TableCell_AssociatedHeaderCellID) ] public virtual string[] AssociatedHeaderCellID { get { object x = ViewState["AssociatedHeaderCellID"]; return (x != null) ? (string[])((string[])x).Clone() : new string[0]; } set { if (value != null) { ViewState["AssociatedHeaderCellID"] = (string[])value.Clone(); } else { ViewState["AssociatedHeaderCellID"] = null; } } } /// <devdoc> /// <para>Gets or sets the number /// of columns this table cell stretches horizontally.</para> /// </devdoc> [ WebCategory("Appearance"), DefaultValue(0), WebSysDescription(SR.TableCell_ColumnSpan) ] public virtual int ColumnSpan { get { object o = ViewState["ColumnSpan"]; return((o == null) ? 0 : (int)o); } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } ViewState["ColumnSpan"] = value; } } /// <devdoc> /// <para>Gets or sets /// the horizontal alignment of the content within the cell.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(HorizontalAlign.NotSet), WebSysDescription(SR.TableItem_HorizontalAlign) ] public virtual HorizontalAlign HorizontalAlign { get { if (ControlStyleCreated == false) { return HorizontalAlign.NotSet; } return ((TableItemStyle)ControlStyle).HorizontalAlign; } set { ((TableItemStyle)ControlStyle).HorizontalAlign = value; } } public override bool SupportsDisabledAttribute { get { return RenderingCompatibility < VersionUtil.Framework40; } } /// <devdoc> /// <para>Gets or sets the /// number of rows this table cell stretches vertically.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(0), WebSysDescription(SR.TableCell_RowSpan) ] public virtual int RowSpan { get { object o = ViewState["RowSpan"]; return((o == null) ? 0 : (int)o); } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } ViewState["RowSpan"] = value; } } /// <devdoc> /// <para>Gets /// or sets the text contained in the cell.</para> /// </devdoc> [ Localizable(true), WebCategory("Appearance"), DefaultValue(""), PersistenceMode(PersistenceMode.InnerDefaultProperty), WebSysDescription(SR.TableCell_Text) ] public virtual string Text { get { object o = ViewState["Text"]; return((o == null) ? String.Empty : (string)o); } set { if (HasControls()) { Controls.Clear(); } ViewState["Text"] = value; } } /// <devdoc> /// <para>Gets or sets the vertical alignment of the content within the cell.</para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(VerticalAlign.NotSet), WebSysDescription(SR.TableItem_VerticalAlign) ] public virtual VerticalAlign VerticalAlign { get { if (ControlStyleCreated == false) { return VerticalAlign.NotSet; } return ((TableItemStyle)ControlStyle).VerticalAlign; } set { ((TableItemStyle)ControlStyle).VerticalAlign = value; } } /// <devdoc> /// <para> /// Gets or sets /// whether the cell content wraps within the cell. /// </para> /// </devdoc> [ WebCategory("Layout"), DefaultValue(true), WebSysDescription(SR.TableCell_Wrap) ] public virtual bool Wrap { get { if (ControlStyleCreated == false) { return true; } return ((TableItemStyle)ControlStyle).Wrap; } set { ((TableItemStyle)ControlStyle).Wrap = value; } } /// <internalonly/> /// <devdoc> /// <para>A protected method. Adds information about the column /// span and row span to the list of attributes to render.</para> /// </devdoc> protected override void AddAttributesToRender(HtmlTextWriter writer) { base.AddAttributesToRender(writer); int span = ColumnSpan; if (span > 0) writer.AddAttribute(HtmlTextWriterAttribute.Colspan, span.ToString(NumberFormatInfo.InvariantInfo)); span = RowSpan; if (span > 0) writer.AddAttribute(HtmlTextWriterAttribute.Rowspan, span.ToString(NumberFormatInfo.InvariantInfo)); string[] arr = AssociatedHeaderCellID; if (arr.Length > 0) { bool first = true; StringBuilder builder = new StringBuilder(); Control namingContainer = NamingContainer; foreach (string id in arr) { TableHeaderCell headerCell = namingContainer.FindControl(id) as TableHeaderCell; if (headerCell == null) { throw new HttpException(SR.GetString(SR.TableCell_AssociatedHeaderCellNotFound, id)); } if (first) { first = false; } else { // AssociatedHeaderCellID was seperated by "," instead of " ". (DevDiv Bugs 159670) builder.Append(" "); } builder.Append(headerCell.ClientID); } string val = builder.ToString(); if (!String.IsNullOrEmpty(val)) { writer.AddAttribute(HtmlTextWriterAttribute.Headers, val); } } } /// <devdoc> /// </devdoc> protected override void AddParsedSubObject(object obj) { if (HasControls()) { base.AddParsedSubObject(obj); } else { if (obj is LiteralControl) { // If we have multiple LiteralControls added here (as would happen if there were a code block // at design time) we don't want to overwrite Text with the last LiteralControl's Text. Just // concatenate their content. However, if Text was set by the property or was in ViewState, // we want to overwrite it. if (_textSetByAddParsedSubObject) { Text += ((LiteralControl)obj).Text; } else { Text = ((LiteralControl)obj).Text; } _textSetByAddParsedSubObject = true; } else { string currentText = Text; if (currentText.Length != 0) { Text = String.Empty; base.AddParsedSubObject(new LiteralControl(currentText)); } base.AddParsedSubObject(obj); } } } /// <internalonly/> /// <devdoc> /// <para>A protected /// method. Creates a table item control /// style.</para> /// </devdoc> protected override Style CreateControlStyle() { return new TableItemStyle(ViewState); } /// <internalonly/> /// <devdoc> /// <para>A protected method.</para> /// </devdoc> protected internal override void RenderContents(HtmlTextWriter writer) { // We can't use HasControls() here, because we may have a compiled render method (ASURT 94127) if (HasRenderingData()) { base.RenderContents(writer); } else { writer.Write(Text); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. #if !NET40 namespace ProductivityApiTests { using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.TestHelpers; using System.IO; using System.Linq; using System.Transactions; using SimpleModel; using Xunit; public class SimpleScenariosForLocalDb : FunctionalTestBase, IDisposable { #region Infrastructure/setup private readonly object _previousDataDirectory; public SimpleScenariosForLocalDb() { _previousDataDirectory = AppDomain.CurrentDomain.GetData("DataDirectory"); AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetTempPath()); MutableResolver.AddResolver<IDbConnectionFactory>(k => new LocalDbConnectionFactory("v11.0")); } [Fact] public void Scenario_Find() { using (var context = new SimpleLocalDbModelContext()) { var product = context.Products.Find(1); var category = context.Categories.Find("Foods"); // Scenario ends; simple validation of final state follows Assert.NotNull(product); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.NotNull(category); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State); Assert.Equal("Foods", product.CategoryId); Assert.Same(category, product.Category); Assert.True(category.Products.Contains(product)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } public void Dispose() { using (var context = new SimpleLocalDbModelContext()) { var product = new Product { Name = "Vegemite" }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.NotEqual(0, product.Id); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } try { // Ensure LocalDb databases are deleted after use so that LocalDb doesn't throw if // the temp location in which they are stored is later cleaned. using (var context = new SimpleLocalDbModelContext()) { context.Database.Delete(); } using (var context = new LocalDbLoginsContext()) { context.Database.Delete(); } using (var context = new ModelWithWideProperties()) { context.Database.Delete(); } Database.Delete("Scenario_CodeFirstWithModelBuilder"); Database.Delete("Scenario_Use_AppConfig_LocalDb_connection_string"); } finally { MutableResolver.ClearResolvers(); AppDomain.CurrentDomain.SetData("DataDirectory", _previousDataDirectory); } } #endregion #region Scenarios for SQL Server LocalDb using LocalDbConnectionFactory [Fact] [UseDefaultExecutionStrategy] public void SqlServer_Database_can_be_created_with_columns_that_explicitly_total_more_that_8060_bytes_and_data_longer_than_8060_can_be_inserted() { EnsureDatabaseInitialized(() => new ModelWithWideProperties()); using (new TransactionScope()) { using (var context = new ModelWithWideProperties()) { var entity = new EntityWithExplicitWideProperties { Property1 = new String('1', 1000), Property2 = new String('2', 1000), Property3 = new String('3', 1000), Property4 = new String('4', 1000), }; context.ExplicitlyWide.Add(entity); context.SaveChanges(); entity.Property1 = new String('A', 4000); entity.Property2 = new String('B', 4000); context.SaveChanges(); } } } [Fact] [UseDefaultExecutionStrategy] public void SqlServer_Database_can_be_created_with_columns_that_implicitly_total_more_that_8060_bytes_and_data_longer_than_8060_can_be_inserted() { EnsureDatabaseInitialized(() => new ModelWithWideProperties()); using (new TransactionScope()) { using (var context = new ModelWithWideProperties()) { var entity = new EntityWithImplicitWideProperties { Property1 = new String('1', 1000), Property2 = new String('2', 1000), Property3 = new String('3', 1000), Property4 = new String('4', 1000), }; context.ImplicitlyWide.Add(entity); context.SaveChanges(); entity.Property1 = new String('A', 4000); entity.Property2 = new String('B', 4000); context.SaveChanges(); } } } [Fact] public void Scenario_Insert() { EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new SimpleLocalDbModelContext()) { var product = new Product { Name = "Vegemite" }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.NotEqual(0, product.Id); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Update() { EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new SimpleLocalDbModelContext()) { var product = context.Products.Find(1); product.Name = "iSnack 2.0"; context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.Equal("iSnack 2.0", product.Name); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Query() { using (var context = new SimpleLocalDbModelContext()) { var products = context.Products.ToList(); // Scenario ends; simple validation of final state follows Assert.Equal(7, products.Count); Assert.True(products.TrueForAll(p => GetStateEntry(context, p).State == EntityState.Unchanged)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Relate_using_query() { EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new SimpleLocalDbModelContext()) { var category = context.Categories.Find("Foods"); var product = new Product { Name = "Bovril", Category = category }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.NotNull(product); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.NotNull(category); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State); Assert.Equal("Foods", product.CategoryId); Assert.Same(category, product.Category); Assert.True(category.Products.Contains(product)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Relate_using_FK() { EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new SimpleLocalDbModelContext()) { var product = new Product { Name = "Bovril", CategoryId = "Foods" }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.NotNull(product); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal("Foods", product.CategoryId); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_CodeFirst_with_ModelBuilder() { Database.Delete("Scenario_CodeFirstWithModelBuilder"); var builder = new DbModelBuilder(); builder.Entity<Product>(); builder.Entity<Category>(); var model = builder.Build(ProviderRegistry.Sql2008_ProviderInfo).Compile(); using (var context = new SimpleLocalDbModelContextWithNoData("Scenario_CodeFirstWithModelBuilder", model)) { InsertIntoCleanContext(context); } using (var context = new SimpleLocalDbModelContextWithNoData("Scenario_CodeFirstWithModelBuilder", model)) { ValidateFromCleanContext(context); } } private void ValidateFromCleanContext(SimpleLocalDbModelContextWithNoData context) { var product = context.Products.Find(1); var category = context.Categories.Find("Large Hadron Collider"); // Scenario ends; simple validation of final state follows Assert.NotNull(product); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.NotNull(category); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State); Assert.Equal("Large Hadron Collider", product.CategoryId); Assert.Same(category, product.Category); Assert.True(category.Products.Contains(product)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } private void InsertIntoCleanContext(SimpleLocalDbModelContextWithNoData context) { context.Categories.Add( new Category { Id = "Large Hadron Collider" }); context.Products.Add( new Product { Name = "Higgs Boson", CategoryId = "Large Hadron Collider" }); context.SaveChanges(); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } [Fact] public void Scenario_Using_two_databases() { EnsureDatabaseInitialized(() => new LocalDbLoginsContext()); EnsureDatabaseInitialized(() => new SimpleLocalDbModelContext()); using (var context = new LocalDbLoginsContext()) { var login = new Login { Id = Guid.NewGuid(), Username = "elmo" }; context.Logins.Add(login); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.Same(login, context.Logins.Find(login.Id)); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, login).State); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } using (var context = new SimpleLocalDbModelContext()) { var category = new Category { Id = "Books" }; var product = new Product { Name = "The Unbearable Lightness of Being", Category = category }; context.Products.Add(product); context.SaveChanges(); // Scenario ends; simple validation of final state follows Assert.Equal(EntityState.Unchanged, GetStateEntry(context, product).State); Assert.Equal(EntityState.Unchanged, GetStateEntry(context, category).State); Assert.Equal("Books", product.CategoryId); Assert.Same(category, product.Category); Assert.True(category.Products.Contains(product)); Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_Use_AppConfig_connection_string() { Database.Delete("Scenario_Use_AppConfig_LocalDb_connection_string"); using (var context = new SimpleLocalDbModelContextWithNoData("Scenario_Use_AppConfig_LocalDb_connection_string")) { Assert.Equal("Scenario_Use_AppConfig_LocalDb", context.Database.Connection.Database); InsertIntoCleanContext(context); } using (var context = new SimpleLocalDbModelContextWithNoData("Scenario_Use_AppConfig_LocalDb_connection_string")) { ValidateFromCleanContext(context); } } [Fact] public void Scenario_Include() { using (var context = new SimpleLocalDbModelContext()) { context.Configuration.LazyLoadingEnabled = false; var products = context.Products.Where(p => p != null).Include("Category").ToList(); foreach (var product in products) { Assert.NotNull(product.Category); } Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } [Fact] public void Scenario_IncludeWithLambda() { using (var context = new SimpleLocalDbModelContext()) { context.Configuration.LazyLoadingEnabled = false; var products = context.Products.Where(p => p != null).Include(p => p.Category).ToList(); foreach (var product in products) { Assert.NotNull(product.Category); } Assert.Equal(@"(localdb)\v11.0", context.Database.Connection.DataSource); } } #endregion } } #endif
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.Bluetooth.Msft.NativeMethods // // Copyright (c) 2003-2011 In The Hand Ltd, All rights reserved. // This source code is licensed under the MIT License using System; using System.Runtime.InteropServices; namespace InTheHand.Net.Bluetooth.Msft { static class NativeMethods { // WINDEF.H internal const int MAX_PATH = 260; #if NETCF private const string wsDll = "ws2.dll"; private const string btdrtDll = "btdrt.dll"; internal const string ceRegistryRoot = "\\SOFTWARE\\Microsoft\\Bluetooth\\"; #else private const string wsDll = "ws2_32.dll"; private const string irpropsDll = "Irprops.cpl"; private const string bthpropsDll = "bthprops.cpl"; #endif #if NETCF [DllImport("coredll.dll", SetLastError = true)] internal static extern int GetModuleFileName(IntPtr hModule, System.Text.StringBuilder lpFilename, int nSize); //CE 5.0 [DllImport(btdrtDll, SetLastError = false)] internal static extern int BthAcceptSCOConnections(int fAccept); [DllImport(btdrtDll, SetLastError=false)] internal static extern int BthAuthenticate(byte[] pbt); [DllImport(btdrtDll, SetLastError=false)] internal static extern int BthCancelInquiry(); [DllImport(btdrtDll, SetLastError=false)] internal static extern int BthClearInquiryFilter(); [DllImport(btdrtDll, SetLastError=false)] internal static extern int BthCloseConnection(ushort handle); [DllImport(btdrtDll, SetLastError=false)] internal static extern int BthCreateACLConnection(byte[] pbt, out ushort phandle); [DllImport(btdrtDll, SetLastError=false)] internal static extern int BthCreateSCOConnection(byte[] pbt, out ushort phandle); /* [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthEnterHoldMode(ref long pba, ushort hold_mode_max, ushort hold_mode_min, ref ushort pinterval); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthEnterParkMode(ref long pba, ushort beacon_max, ushort beacon_min, ref ushort pinterval); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthEnterSniffMode(ref long pba, ushort sniff_mode_max, ushort sniff_mode_min, ushort sniff_attempt, ushort sniff_timeout, ref ushort pinterval); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthExitParkMode(ref long pba); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthExitSniffMode(ref long pba); */ [DllImport(btdrtDll, SetLastError=false)] internal static extern int BthGetAddress(ushort handle, out long pba); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthGetBasebandConnections(int cConnections, byte[] pConnections, ref int pcConnectionsReturned); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthGetBasebandHandles(int cHandles, ref ushort pHandles, ref int pcHandlesReturned); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthGetCurrentMode(byte[] pba, ref byte pmode); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthGetHardwareStatus(ref HardwareStatus pistatus); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthGetLinkKey(byte[] pba, ref Guid key); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthGetPINRequest(byte[] pba); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthGetRemoteCOD(byte[] pbt, out uint pcod); //CE 5.0 [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthPairRequest(byte[] pba, int cPinLength, byte[] ppin); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthPerformInquiry(int LAP, byte length, byte num_responses, int cBuffer, ref int pcDiscoveredDevices, byte[] InquiryList); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadAuthenticationEnable(out byte pae); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadCOD(out uint pcod); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadLinkPolicySettings(byte[] pba, ref ushort plps); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadLocalAddr(byte[] pba); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadLocalVersion(out byte phci_version, out ushort phci_revision, out byte plmp_version, out ushort plmp_subversion, out ushort pmanufacturer, byte[] plmp_features); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadPageTimeout(out ushort ptimeout); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadRemoteVersion(byte[] pba, ref byte plmp_version, ref ushort plmp_subversion, ref ushort pmanufacturer, ref byte plmp_features); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadRemoteVersion(byte[] pba, out LmpVersion plmp_version, out ushort plmp_subversion, out Manufacturer pmanufacturer, out LmpFeatures plmp_features); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthReadScanEnableMask(out byte pmask); [DllImport(btdrtDll, SetLastError = true)] internal static extern int BthReadScanEnableMask(out WinCeScanMask pmask); //CE 6.0 [DllImport(btdrtDll, SetLastError = true)] internal static extern int BthReadRSSI(byte[] pbt, out sbyte pbRSSI); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthRefusePINRequest(byte[] pbt); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthRemoteNameQuery(byte[] pba, int cBuffer, out int pcRequired, byte[] szString); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthRevokeLinkKey(byte[] pba); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthRevokePIN(byte[] pba); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthSetEncryption(byte[] pba, int fOn); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthSetInquiryFilter(byte[] pba); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthSetLinkKey(byte[] pba, ref Guid key); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthSetPIN(byte[] pba, int cPinLength, byte[] ppin); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthSetSecurityUI(IntPtr hEvent, int dwStoreTimeout, int dwProcTimeout); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthTerminateIdleConnections(); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthWriteAuthenticationEnable(byte ae); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthWriteCOD(uint cod); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthWriteLinkPolicySettings(byte[] pba, ushort lps); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthWritePageTimeout(ushort timeout); [DllImport(btdrtDll, SetLastError=true)] internal static extern int BthWriteScanEnableMask(byte mask); [DllImport(btdrtDll, SetLastError = true)] internal static extern int BthWriteScanEnableMask(WinCeScanMask mask); //Utils [DllImport("BthUtil.dll", SetLastError=true)] internal static extern int BthSetMode(RadioMode dwMode); [DllImport("BthUtil.dll", SetLastError=true)] internal static extern int BthGetMode(out RadioMode dwMode); //msgqueue (for notifications) /* [DllImport("coredll.dll", SetLastError = true)] internal static extern IntPtr RequestBluetoothNotifications(BTE_CLASS dwClass, IntPtr hMsgQ); [DllImport("coredll.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool StopBluetoothNotifications(IntPtr h); internal enum BTE { CONNECTION = 100, DISCONNECTION = 101, ROLE_SWITCH = 102, MODE_CHANGE = 103, PAGE_TIMEOUT = 104, KEY_NOTIFY = 200, KEY_REVOKED = 201, LOCAL_NAME = 300, COD = 301, STACK_UP = 400, STACK_DOWN = 401, } [Flags()] internal enum BTE_CLASS { CONNECTIONS = 1, PAIRING = 2, DEVICE = 4, STACK = 8, } [DllImport("coredll.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseMsgQueue(IntPtr hMsgQ); [DllImport("coredll.dll", SetLastError = true)] internal static extern IntPtr CreateMsgQueue(string lpszName, ref MSGQUEUEOPTIONS lpOptions); [DllImport("coredll.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ReadMsgQueue(IntPtr hMsgQ, IntPtr lpBuffer, int cbBufferSize, out int lpNumberOfBytesRead, int dwTimeout, out int pdwFlags); [StructLayout(LayoutKind.Sequential)] internal struct MSGQUEUEOPTIONS { internal int dwSize; internal int dwFlags; internal int dwMaxMessages; internal int cbMaxMessage; [MarshalAs(UnmanagedType.Bool)] internal bool bReadAccess; } [StructLayout(LayoutKind.Sequential)] internal struct BTEVENT { internal BTE dwEventId; internal int dwReserved; [MarshalAs(UnmanagedType.ByValArray, SizeConst=64)] internal byte[] baEventData; } internal struct BT_CONNECT_EVENT { internal int dwSize; internal ushort hConnection; internal long bta; internal byte ucLinkType; internal byte ucEncryptMode; } */ #if V1 [DllImport("coredll.dll", SetLastError=true)] internal static extern int LocalFree(IntPtr ptr); #endif #endif //SetService [DllImport(wsDll, EntryPoint = "WSASetService", SetLastError = true)] internal static extern int WSASetService(ref WSAQUERYSET lpqsRegInfo, WSAESETSERVICEOP essoperation, int dwControlFlags); //LookupService [DllImport(wsDll, EntryPoint = "WSALookupServiceBegin", SetLastError = true)] internal static extern int WSALookupServiceBegin(byte[] pQuerySet, LookupFlags dwFlags, out IntPtr lphLookup); [DllImport(wsDll, EntryPoint = "WSALookupServiceBegin", SetLastError = true)] internal static extern int WSALookupServiceBegin(ref WSAQUERYSET pQuerySet, LookupFlags dwFlags, out IntPtr lphLookup); [DllImport(wsDll, EntryPoint = "WSALookupServiceNext", SetLastError = true)] internal static extern int WSALookupServiceNext(IntPtr hLookup, LookupFlags dwFlags, ref int lpdwBufferLength, byte[] pResults); [DllImport(wsDll, EntryPoint = "WSALookupServiceEnd", SetLastError = true)] internal static extern int WSALookupServiceEnd(IntPtr hLookup); #if WinXP internal enum BTH_ERROR { SUCCESS = (0x00), UNKNOWN_HCI_COMMAND = (0x01), NO_CONNECTION = (0x02), HARDWARE_FAILURE = (0x03), PAGE_TIMEOUT = (0x04), AUTHENTICATION_FAILURE = (0x05), KEY_MISSING = (0x06), MEMORY_FULL = (0x07), CONNECTION_TIMEOUT = (0x08), MAX_NUMBER_OF_CONNECTIONS = (0x09), MAX_NUMBER_OF_SCO_CONNECTIONS = (0x0a), ACL_CONNECTION_ALREADY_EXISTS = (0x0b), COMMAND_DISALLOWED = (0x0c), HOST_REJECTED_LIMITED_RESOURCES = (0x0d), HOST_REJECTED_SECURITY_REASONS = (0x0e), HOST_REJECTED_PERSONAL_DEVICE = (0x0f), HOST_TIMEOUT = (0x10), UNSUPPORTED_FEATURE_OR_PARAMETER = (0x11), INVALID_HCI_PARAMETER = (0x12), REMOTE_USER_ENDED_CONNECTION = (0x13), REMOTE_LOW_RESOURCES = (0x14), REMOTE_POWERING_OFF = (0x15), LOCAL_HOST_TERMINATED_CONNECTION = (0x16), REPEATED_ATTEMPTS = (0x17), PAIRING_NOT_ALLOWED = (0x18), UKNOWN_LMP_PDU = (0x19), UNSUPPORTED_REMOTE_FEATURE = (0x1a), SCO_OFFSET_REJECTED = (0x1b), SCO_INTERVAL_REJECTED = (0x1c), SCO_AIRMODE_REJECTED = (0x1d), INVALID_LMP_PARAMETERS = (0x1e), UNSPECIFIED_ERROR = (0x1f), UNSUPPORTED_LMP_PARM_VALUE = (0x20), ROLE_CHANGE_NOT_ALLOWED = (0x21), LMP_RESPONSE_TIMEOUT = (0x22), LMP_TRANSACTION_COLLISION = (0x23), LMP_PDU_NOT_ALLOWED = (0x24), ENCRYPTION_MODE_NOT_ACCEPTABLE = (0x25), UNIT_KEY_NOT_USED = (0x26), QOS_IS_NOT_SUPPORTED = (0x27), INSTANT_PASSED = (0x28), PAIRING_WITH_UNIT_KEY_NOT_SUPPORTED = (0x29), DIFFERENT_TRANSACTION_COLLISION = (0x2a), QOS_UNACCEPTABLE_PARAMETER = (0x2c), QOS_REJECTED = (0x2d), CHANNEL_CLASSIFICATION_NOT_SUPPORTED = (0x2e), INSUFFICIENT_SECURITY = (0x2f), PARAMETER_OUT_OF_MANDATORY_RANGE = (0x30), ROLE_SWITCH_PENDING = (0x32), RESERVED_SLOT_VIOLATION = (0x34), ROLE_SWITCH_FAILED = (0x35), EXTENDED_INQUIRY_RESPONSE_TOO_LARGE = (0x36), SECURE_SIMPLE_PAIRING_NOT_SUPPORTED_BY_HOST = (0x37), HOST_BUSY_PAIRING = (0x38), // Added in Windows 8 CONNECTION_REJECTED_DUE_TO_NO_SUITABLE_CHANNEL_FOUND = (0x39), CONTROLLER_BUSY = (0x3a), UNACCEPTABLE_CONNECTION_INTERVAL = (0x3b), DIRECTED_ADVERTISING_TIMEOUT = (0x3c), CONNECTION_TERMINATED_DUE_TO_MIC_FAILURE = (0x3d), CONNECTION_FAILED_TO_BE_ESTABLISHED = (0x3e), MAC_CONNECTION_FAILED = (0x3f), // UNSPECIFIED = (0xFF), } //for bluetooth events (Win32) // ... are now defined in BluetoothWin32Events.cs. internal const int BTH_MAX_NAME_SIZE = 248; internal const int BLUETOOTH_MAX_PASSKEY_SIZE = 16; //[DllImport(wsDll, EntryPoint = "WSAAddressToString", SetLastError = true)] //internal static extern int WSAAddressToString(byte[] lpsaAddress, int dwAddressLength, IntPtr lpProtocolInfo, System.Text.StringBuilder lpszAddressString, ref int lpdwAddressStringLength); //desktop methods /// <summary> /// The BluetoothAuthenticateDevice function sends an authentication request to a remote Bluetooth device. /// </summary> /// <param name="hwndParent">The window to parent the authentication wizard. /// If NULL, the wizard will be parented off the desktop.</param> /// <param name="hRadio">A valid local radio handle, or NULL. If NULL, authentication is attempted on all local radios; if any radio succeeds, the function call succeeds.</param> /// <param name="pbtdi">A structure of type BLUETOOTH_DEVICE_INFO that contains the record of the Bluetooth device to be authenticated.</param> /// <param name="pszPasskey">A Personal Identification Number (PIN) to be used for device authentication. If set to NULL, the user interface is displayed and and the user must follow the authentication process provided in the user interface. If pszPasskey is not NULL, no user interface is displayed. If the passkey is not NULL, it must be a NULL-terminated string. For more information, see the Remarks section.</param> /// <param name="ulPasskeyLength">The size, in characters, of pszPasskey. /// The size of pszPasskey must be less than or equal to BLUETOOTH_MAX_PASSKEY_SIZE.</param> /// <returns></returns> [DllImport(irpropsDll, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int BluetoothAuthenticateDevice(IntPtr hwndParent, IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pbtdi, string pszPasskey, int ulPasskeyLength); /// <summary> /// The BluetoothAuthenticateDeviceEx function sends an authentication request to a remote Bluetooth device. Additionally, this function allows for out-of-band data to be passed into the function call for the device being authenticated. /// Note This API is supported in Windows Vista SP2 and Windows 7. /// </summary> /// <param name="hwndParentIn">The window to parent the authentication wizard. /// If NULL, the wizard will be parented off the desktop.</param> /// <param name="hRadioIn">A valid local radio handle or NULL. /// If NULL, then all radios will be tried. If any of the radios succeed, then the call will succeed.</param> /// <param name="pbtdiInout">A pointer to a BLUETOOTH_DEVICE_INFO structure describing the device being authenticated.</param> /// <param name="pbtOobData">Pointer to device specific out-of-band data to be provided with this API call. /// If NULL, then UI is displayed to continue the authentication process. /// If not NULL, no UI is displayed.</param> /// <param name="authenticationRequirement">An AUTHENTICATION_REQUIREMENTS enumeration that specifies the protection required for authentication.</param> /// <returns></returns> [DllImport(bthpropsDll, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int BluetoothAuthenticateDeviceEx(IntPtr hwndParentIn, IntPtr hRadioIn, ref BLUETOOTH_DEVICE_INFO pbtdiInout, byte[] pbtOobData, BluetoothAuthenticationRequirements authenticationRequirement); // This method is deprecated and other stacks have no equivalent so do not implement //[DllImport(irpropsDll, SetLastError = true, CharSet = CharSet.Unicode)] //internal static extern int BluetoothAuthenticateMultipleDevices(IntPtr hwndParent, IntPtr hRadio, int cDevices, BLUETOOTH_DEVICE_INFO[] rgbtdi); [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothDisplayDeviceProperties(IntPtr hwndParent, ref BLUETOOTH_DEVICE_INFO pbtdi); [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothEnableDiscovery(WindowsRadioHandle hRadio, bool fEnabled); [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothEnableIncomingConnections(WindowsRadioHandle hRadio, bool fEnabled); [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothEnumerateInstalledServices(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pbtdi, ref int pcServices, byte[] pGuidServices); [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothSetServiceState(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pbtdi, ref Guid pGuidService, int dwServiceFlags); //Radio // (Tried to use WindowsRadioHandle instead of IntPtr for the second // param but got a missing method type exception.) [DllImport(irpropsDll, SetLastError = true)] internal static extern IntPtr BluetoothFindFirstRadio(ref BLUETOOTH_FIND_RADIO_PARAMS pbtfrp, out IntPtr phRadio); [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothFindNextRadio(IntPtr hFind, out IntPtr phRadio); [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothFindRadioClose(IntPtr hFind); [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothGetDeviceInfo(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pbtdi); [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothGetRadioInfo(WindowsRadioHandle hRadio, ref BLUETOOTH_RADIO_INFO pRadioInfo); [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothIsConnectable(WindowsRadioHandle hRadio); [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothIsDiscoverable(WindowsRadioHandle hRadio); [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothUpdateDeviceRecord(ref BLUETOOTH_DEVICE_INFO pbtdi); //XP SDP Parsing [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothSdpGetAttributeValue(byte[] pRecordStream, int cbRecordLength, ushort usAttributeId, IntPtr pAttributeData); [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothSdpGetContainerElementData(byte[] pContainerStream, uint cbContainerLength, ref IntPtr pElement, byte[] pData); [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothSdpGetElementData(byte[] pSdpStream, uint cbSpdStreamLength, byte[] pData); [DllImport(irpropsDll, SetLastError = true)] internal static extern int BluetoothSdpGetString(byte[] pRecordStream, uint cbRecordLength, /*PSDP_STRING_DATA_TYPE*/IntPtr pStringData, ushort usStringOffset, byte[] pszString, ref uint pcchStringLength); internal struct SDP_STRING_TYPE_DATA { internal ushort encoding; internal ushort mibeNum; internal ushort attributeID; void ShutUpCompiler() { encoding = 0; mibeNum = 0; attributeID = 0; } } [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothSdpEnumAttributes( IntPtr pSDPStream, int cbStreamSize, BluetoothEnumAttributesCallback pfnCallback, IntPtr pvParam); [return: MarshalAs(UnmanagedType.Bool)] internal delegate bool BluetoothEnumAttributesCallback( uint uAttribId, IntPtr pValueStream, int cbStreamSize, IntPtr pvParam); //Authentication functions [DllImport(irpropsDll, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern UInt32 BluetoothRegisterForAuthentication( ref BLUETOOTH_DEVICE_INFO pbtdi, out BluetoothAuthenticationRegistrationHandle phRegHandle, BluetoothAuthenticationCallback pfnCallback, IntPtr pvParam); //Requires Vista SP2 or later [DllImport(bthpropsDll, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern UInt32 BluetoothRegisterForAuthenticationEx( ref BLUETOOTH_DEVICE_INFO pbtdi, out BluetoothAuthenticationRegistrationHandle phRegHandle, BluetoothAuthenticationCallbackEx pfnCallback, IntPtr pvParam); [return: MarshalAs(UnmanagedType.Bool)] // Does this have any effect? internal delegate bool BluetoothAuthenticationCallback(IntPtr pvParam, ref BLUETOOTH_DEVICE_INFO bdi); [return: MarshalAs(UnmanagedType.Bool)] // Does this have any effect? internal delegate bool BluetoothAuthenticationCallbackEx(IntPtr pvParam, ref BLUETOOTH_AUTHENTICATION_CALLBACK_PARAMS pAuthCallbackParams); [DllImport(irpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [System.Security.SuppressUnmanagedCodeSecurity] // Since called from SafeHandle internal static extern bool BluetoothUnregisterAuthentication(IntPtr hRegHandle); [DllImport(bthpropsDll, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [System.Security.SuppressUnmanagedCodeSecurity] // Since called from SafeHandle internal static extern bool BluetoothUnregisterAuthenticationEx(IntPtr hRegHandle); [DllImport(irpropsDll, SetLastError = false, CharSet = CharSet.Unicode)] internal static extern Int32 BluetoothSendAuthenticationResponse(IntPtr hRadio, ref BLUETOOTH_DEVICE_INFO pbtdi, string pszPasskey); //[DllImport("bthprops.cpl", SetLastError = false, CharSet = CharSet.Unicode)] //internal static extern Int32 BluetoothSendAuthenticationResponseEx(IntPtr hRadio, ref BLUETOOTH_AUTHENTICATE_RESPONSE pauthResponse); [DllImport(bthpropsDll, SetLastError = false, CharSet = CharSet.Unicode)] internal static extern Int32 BluetoothSendAuthenticationResponseEx(IntPtr hRadio, ref BLUETOOTH_AUTHENTICATE_RESPONSE__PIN_INFO pauthResponse); [DllImport(bthpropsDll, SetLastError = false, CharSet = CharSet.Unicode)] internal static extern Int32 BluetoothSendAuthenticationResponseEx(IntPtr hRadio, ref BLUETOOTH_AUTHENTICATE_RESPONSE__OOB_DATA_INFO pauthResponse); [DllImport(bthpropsDll, SetLastError = false, CharSet = CharSet.Unicode)] internal static extern Int32 BluetoothSendAuthenticationResponseEx(IntPtr hRadio, ref BLUETOOTH_AUTHENTICATE_RESPONSE__NUMERIC_COMPARISON_PASSKEY_INFO pauthResponse); [DllImport(irpropsDll, SetLastError = true, CharSet = CharSet.Unicode)] internal static extern int BluetoothRemoveDevice(byte[] pAddress); // Code for setting radio name // devguid.h internal static readonly Guid GUID_DEVCLASS_BLUETOOTH = new Guid("{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}"); // SETUPAPI.H [Flags()] internal enum DIGCF { PRESENT = 0x00000002, // Return only devices that are currently present in a system. ALLCLASSES = 0x00000004, // Return a list of installed devices for all device setup classes or all device interface classes. PROFILE = 0x00000008, // Return only devices that are a part of the current hardware profile. } internal enum SPDRP { HARDWAREID = 0x00000001, // HardwareID (R/W) DRIVER = 0x00000009, // Driver (R/W) } [StructLayout(LayoutKind.Sequential)] internal struct SP_DEVINFO_DATA { internal int cbSize; // = (uint)Marshal.SizeOf(typeof(SP_DEVINFO_DATA)); internal Guid ClassGuid; internal UInt32 DevInst; internal IntPtr Reserved; } // ref Int64 -> p [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] internal static extern bool DeviceIoControl( IntPtr hDevice, uint dwIoControlCode, ref long InBuffer, int nInBufferSize, IntPtr OutBuffer, int nOutBufferSize, out int pBytesReturned, IntPtr lpOverlapped); // p -> byte[] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] internal static extern bool DeviceIoControl( IntPtr hDevice, uint dwIoControlCode, IntPtr InBuffer, int nInBufferSize, byte[] OutBuffer, int nOutBufferSize, out int pBytesReturned, IntPtr lpOverlapped); // p -> byte[] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool DeviceIoControl( WindowsRadioHandle hDevice, uint dwIoControlCode, IntPtr InBuffer, int nInBufferSize, byte[] OutBuffer, int nOutBufferSize, out int pBytesReturned, IntPtr lpOverlapped); // byte[]-> byte[] [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] internal static extern bool DeviceIoControl( IntPtr hDevice, uint dwIoControlCode, byte[] InBuffer, int nInBufferSize, byte[] OutBuffer, int nOutBufferSize, out int pBytesReturned, IntPtr lpOverlapped); // ref Int64 (btAddr) -> BTH_RADIO_INFO [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] internal static extern bool DeviceIoControl( IntPtr hDevice, uint dwIoControlCode, ref long InBuffer, int nInBufferSize, ref BTH_RADIO_INFO OutBuffer, int nOutBufferSize, out int pBytesReturned, IntPtr lpOverlapped); // From WinDDK inc\ddk\bthioctl.h internal static class MsftWin32BthIOCTL //: uint { // Every one fails with ERROR_NOT_SUPPORTED (50) on WindowsXP. // Most (should) work on Vista. // Most do work on Windows 7. // Kernel const uint IOCTL_INTERNAL_BTH_SUBMIT_BRB = 0x410003; const uint IOCTL_INTERNAL_BTHENUM_GET_ENUMINFO = 0x410007; const uint IOCTL_INTERNAL_BTHENUM_GET_DEVINFO = 0x41000b; // Other /// <summary> /// Input: none /// Output: BTH_LOCAL_RADIO_INFO /// </summary> internal const uint IOCTL_BTH_GET_LOCAL_INFO = 0x410000; /// <summary> /// Input: BTH_ADDR /// Output: BTH_RADIO_INFO /// </summary> internal const uint IOCTL_BTH_GET_RADIO_INFO = 0x410004; /// <summary> /// use this ioctl to get a list of cached discovered devices in the port driver. /// /// Input: None /// Output: BTH_DEVICE_INFO_LIST /// </summary> internal const uint IOCTL_BTH_GET_DEVICE_INFO = 0x410008; /// <summary> /// Input: BTH_ADDR /// Output: none /// </summary> internal const uint IOCTL_BTH_DISCONNECT_DEVICE = 0x41000c; // //#if (NTDDI_VERSION > NTDDI_VISTASP1 || \ // (NTDDI_VERSION == NTDDI_VISTASP1 && defined(VISTA_KB942567))) // //#ifdef FULL_EIR_SUPPORT // in WUR this funcitonality is disabled // // These five fail with ERROR_NOT_SUPPORTED (50) on Windows 7 /// <summary> /// Input: BTH_GET_DEVICE_RSSI /// Output: ULONG /// </summary> internal const uint IOCTL_BTH_GET_DEVICE_RSSI = 0x410014; /// <summary> /// Input: BTH_EIR_GET_RECORDS /// Output: UCHAR array, sequence of length + type + data fields triplets. /// </summary> internal const uint IOCTL_BTH_EIR_GET_RECORDS = 0x410040; /// <summary> /// Input: BTH_EIR_SUBMIT_RECORD /// Output HANDLE /// </summary> internal const uint IOCTL_BTH_EIR_SUBMIT_RECORD = 0x410044; /// <summary> /// Input: BTH_EIR_SUBMIT_RECORD /// Output None /// </summary> internal const uint IOCTL_BTH_EIR_UPDATE_RECORD = 0x410048; /// <summary> /// Input: HANDLE /// Output: None /// </summary> internal const uint IOCTL_BTH_EIR_REMOVE_RECORD = 0x41004c; //#endif // FULL_EIR_SUPPORT // /// <summary> /// Input: BTH_VENDOR_SPECIFIC_COMMAND /// Output: PVOID /// </summary> internal const uint IOCTL_BTH_HCI_VENDOR_COMMAND = 0x410050; //#endif // >= SP1+KB942567 // /// <summary> /// Input: BTH_SDP_CONNECT /// Output: BTH_SDP_CONNECT /// </summary> internal const uint IOCTL_BTH_SDP_CONNECT = 0x410200; /// <summary> /// Input: HANDLE_SDP /// Output: none /// </summary> internal const uint IOCTL_BTH_SDP_DISCONNECT = 0x410204; /// <summary> /// Input: BTH_SDP_SERVICE_SEARCH_REQUEST /// Output: ULONG * number of handles wanted /// </summary> internal const uint IOCTL_BTH_SDP_SERVICE_SEARCH = 0x410208; /// <summary> /// Input: BTH_SDP_ATTRIBUTE_SEARCH_REQUEST /// Output: BTH_SDP_STREAM_RESPONSE or bigger /// </summary> internal const uint IOCTL_BTH_SDP_ATTRIBUTE_SEARCH = 0x41020c; /// <summary> /// Input: BTH_SDP_SERVICE_ATTRIBUTE_SEARCH_REQUEST /// Output: BTH_SDP_STREAM_RESPONSE or bigger /// </summary> internal const uint IOCTL_BTH_SDP_SERVICE_ATTRIBUTE_SEARCH = 0x410210; /// <summary> /// Input: raw SDP stream (at least 2 bytes) /// Ouptut: HANDLE_SDP /// </summary> internal const uint IOCTL_BTH_SDP_SUBMIT_RECORD = 0x410214; /// <summary> /// Input: HANDLE_SDP /// Output: none /// </summary> internal const uint IOCTL_BTH_SDP_REMOVE_RECORD = 0x410218; /// <summary> /// Input: BTH_SDP_RECORD + raw SDP record /// Output: HANDLE_SDP /// </summary> internal const uint IOCTL_BTH_SDP_SUBMIT_RECORD_WITH_INFO = 0x41021c; } // The SetupDiGetClassDevs function returns a handle to a device information set that contains requested device information elements for a local machine. [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] internal static extern IntPtr SetupDiGetClassDevs( ref Guid classGuid, [MarshalAs(UnmanagedType.LPTStr)] string enumerator, IntPtr hwndParent, DIGCF flags); // The SetupDiEnumDeviceInfo function returns a SP_DEVINFO_DATA structure that specifies a device information element in a device information set. [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetupDiEnumDeviceInfo( IntPtr deviceInfoSet, uint memberIndex, ref SP_DEVINFO_DATA deviceInfoData); // The SetupDiDestroyDeviceInfoList function deletes a device information set and frees all associated memory. [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet); // The SetupDiGetDeviceInstanceId function retrieves the device instance ID that is associated with a device information element. [DllImport("setupapi.dll", SetLastError = true, CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetupDiGetDeviceInstanceId( IntPtr deviceInfoSet, ref SP_DEVINFO_DATA deviceInfoData, System.Text.StringBuilder deviceInstanceId, int deviceInstanceIdSize, out int requiredSize); //The BluetoothIsVersionAvailable function indicates if the installed Bluetooth binary set supports the requested version. //Requires Windows XP SP2 or later [DllImport(bthpropsDll, SetLastError = false)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool BluetoothIsVersionAvailable(byte MajorVersion, byte MinorVersion); #endif //-------- [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); } internal enum WSAESETSERVICEOP : int { /// <summary> /// Register the service. For SAP, this means sending out a periodic broadcast. /// This is an NOP for the DNS namespace. /// For persistent data stores, this means updating the address information. /// </summary> RNRSERVICE_REGISTER = 0, /// <summary> /// Remove the service from the registry. /// For SAP, this means stop sending out the periodic broadcast. /// This is an NOP for the DNS namespace. /// For persistent data stores this means deleting address information. /// </summary> RNRSERVICE_DEREGISTER, /// <summary> /// Delete the service from dynamic name and persistent spaces. /// For services represented by multiple CSADDR_INFO structures (using the SERVICE_MULTIPLE flag), only the specified address will be deleted, and this must match exactly the corresponding CSADDR_INFO structure that was specified when the service was registered /// </summary> RNRSERVICE_DELETE, } [Flags()] internal enum LookupFlags : uint { Containers = 0x0002, ReturnName = 0x0010, ReturnAddr = 0x0100, ReturnBlob = 0x0200, FlushCache = 0x1000, ResService = 0x8000, } [Flags()] internal enum WinCeScanMask : byte { None = 0, InquiryScan = 1, PageScan = 2, } }
using System; using System.Diagnostics.CodeAnalysis; using Shouldly; namespace NUnit.Framework.Constraints { /// <summary> /// The Numerics class contains common operations on numeric values. /// </summary> internal static class Numerics { /// <summary> /// Checks the type of the object, returning true if /// the object is a numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a numeric type</returns> public static bool IsNumericType([NotNullWhen(true)] object? obj) { return IsFloatingPointNumeric(obj) || IsFixedPointNumeric(obj); } /// <summary> /// Checks the type of the object, returning true if /// the object is a floating point numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a floating point numeric type</returns> public static bool IsFloatingPointNumeric([NotNullWhen(true)] object? obj) { if (null != obj) { if (obj is double) return true; if (obj is float) return true; } return false; } /// <summary> /// Checks the type of the object, returning true if /// the object is a fixed point numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a fixed point numeric type</returns> public static bool IsFixedPointNumeric([NotNullWhen(true)] object? obj) { if (null != obj) { if (obj is byte) return true; if (obj is sbyte) return true; if (obj is decimal) return true; if (obj is int) return true; if (obj is uint) return true; if (obj is long) return true; if (obj is ulong) return true; if (obj is short) return true; if (obj is ushort) return true; } return false; } /// <summary> /// Test two numeric values for equality, performing the usual numeric /// conversions and using a provided or default tolerance. If the tolerance /// provided is Empty, this method may set it to a default tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <param name="tolerance">A reference to the tolerance in effect</param> /// <returns>True if the values are equal</returns> public static bool AreEqual(object expected, object actual, ref Tolerance tolerance) { if (expected is double || actual is double) return AreEqual(Convert.ToDouble(expected), Convert.ToDouble(actual), ref tolerance); if (expected is float || actual is float) return AreEqual(Convert.ToSingle(expected), Convert.ToSingle(actual), ref tolerance); if (tolerance.Mode == ToleranceMode.Ulps) throw new InvalidOperationException("Ulps may only be specified for floating point arguments"); if (expected is decimal || actual is decimal) return AreEqual(Convert.ToDecimal(expected), Convert.ToDecimal(actual), tolerance); if (expected is ulong || actual is ulong) return AreEqual(Convert.ToUInt64(expected), Convert.ToUInt64(actual), tolerance); if (expected is long || actual is long) return AreEqual(Convert.ToInt64(expected), Convert.ToInt64(actual), tolerance); if (expected is uint || actual is uint) return AreEqual(Convert.ToUInt32(expected), Convert.ToUInt32(actual), tolerance); return AreEqual(Convert.ToInt32(expected), Convert.ToInt32(actual), tolerance); } private static bool AreEqual(double expected, double actual, ref Tolerance tolerance) { if (double.IsNaN(expected) && double.IsNaN(actual)) return true; // Handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. Also, handle // situation where no tolerance is used. if (double.IsInfinity(expected) || double.IsNaN(expected) || double.IsNaN(actual)) { return expected.Equals(actual); } if (tolerance.IsEmpty && ShouldlyConfiguration.DefaultFloatingPointTolerance > 0.0d) tolerance = new Tolerance(ShouldlyConfiguration.DefaultFloatingPointTolerance); switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value); case ToleranceMode.Percent: if (expected == 0.0) return expected.Equals(actual); var relativeError = Math.Abs((expected - actual)/expected); return relativeError <= Convert.ToDouble(tolerance.Value)/100.0; case ToleranceMode.Ulps: return FloatingPointNumerics.AreAlmostEqualUlps( expected, actual, Convert.ToInt64(tolerance.Value)); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(float expected, float actual, ref Tolerance tolerance) { if (float.IsNaN(expected) && float.IsNaN(actual)) return true; // handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. if (float.IsInfinity(expected) || float.IsNaN(expected) || float.IsNaN(actual)) { return expected.Equals(actual); } if (tolerance.IsEmpty && ShouldlyConfiguration.DefaultFloatingPointTolerance > 0.0d) tolerance = new Tolerance(ShouldlyConfiguration.DefaultFloatingPointTolerance); switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value); case ToleranceMode.Percent: if (expected == 0.0f) return expected.Equals(actual); var relativeError = Math.Abs((expected - actual)/expected); return relativeError <= Convert.ToSingle(tolerance.Value)/100.0f; case ToleranceMode.Ulps: return FloatingPointNumerics.AreAlmostEqualUlps( expected, actual, Convert.ToInt32(tolerance.Value)); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(decimal expected, decimal actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: var decimalTolerance = Convert.ToDecimal(tolerance.Value); if (decimalTolerance > 0m) return Math.Abs(expected - actual) <= decimalTolerance; return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0m) return expected.Equals(actual); var relativeError = Math.Abs( (double) (expected - actual)/(double) expected); return relativeError <= Convert.ToDouble(tolerance.Value)/100.0; default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(ulong expected, ulong actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: var ulongTolerance = Convert.ToUInt64(tolerance.Value); if (ulongTolerance > 0ul) { var diff = expected >= actual ? expected - actual : actual - expected; return diff <= ulongTolerance; } return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0ul) return expected.Equals(actual); // Can't do a simple Math.Abs() here since it's unsigned var difference = Math.Max(expected, actual) - Math.Min(expected, actual); var relativeError = Math.Abs(difference/(double) expected); return relativeError <= Convert.ToDouble(tolerance.Value)/100.0; default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(long expected, long actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: var longTolerance = Convert.ToInt64(tolerance.Value); if (longTolerance > 0L) return Math.Abs(expected - actual) <= longTolerance; return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0L) return expected.Equals(actual); var relativeError = Math.Abs( (expected - actual)/(double) expected); return relativeError <= Convert.ToDouble(tolerance.Value)/100.0; default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(uint expected, uint actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: var uintTolerance = Convert.ToUInt32(tolerance.Value); if (uintTolerance > 0) { var diff = expected >= actual ? expected - actual : actual - expected; return diff <= uintTolerance; } return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0u) return expected.Equals(actual); // Can't do a simple Math.Abs() here since it's unsigned var difference = Math.Max(expected, actual) - Math.Min(expected, actual); var relativeError = Math.Abs(difference/(double) expected); return relativeError <= Convert.ToDouble(tolerance.Value)/100.0; default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(int expected, int actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: var intTolerance = Convert.ToInt32(tolerance.Value); if (intTolerance > 0) return Math.Abs(expected - actual) <= intTolerance; return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0) return expected.Equals(actual); var relativeError = Math.Abs( (expected - actual)/(double) expected); return relativeError <= Convert.ToDouble(tolerance.Value)/100.0; default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } /// <summary> /// Compare two numeric values, performing the usual numeric conversions. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <returns>The relationship of the values to each other</returns> public static int Compare(object expected, object actual) { if (!IsNumericType(expected) || !IsNumericType(actual)) throw new ArgumentException("Both arguments must be numeric"); if (IsFloatingPointNumeric(expected) || IsFloatingPointNumeric(actual)) return Convert.ToDouble(expected).CompareTo(Convert.ToDouble(actual)); if (expected is decimal || actual is decimal) return Convert.ToDecimal(expected).CompareTo(Convert.ToDecimal(actual)); if (expected is ulong || actual is ulong) return Convert.ToUInt64(expected).CompareTo(Convert.ToUInt64(actual)); if (expected is long || actual is long) return Convert.ToInt64(expected).CompareTo(Convert.ToInt64(actual)); if (expected is uint || actual is uint) return Convert.ToUInt32(expected).CompareTo(Convert.ToUInt32(actual)); return Convert.ToInt32(expected).CompareTo(Convert.ToInt32(actual)); } } }
#region License /* * Copyright (C) 2002-2010 the original author or authors. * * 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. */ #endregion using System; using System.Collections.Generic; using System.Threading; namespace BitSharper.Threading.Locks { /// <author>Doug Lea</author> /// <author>Griffin Caprio (.NET)</author> /// <author>Kenneth Xu</author> [Serializable] internal class ConditionVariable : ICondition // BACKPORT_3_1 { private const string _notSupportedMessage = "Use FAIR version"; protected internal readonly IExclusiveLock _lock; /// <summary> /// Create a new <see cref="ConditionVariable"/> that relies on the given mutual /// exclusion lock. /// </summary> /// <param name="lock"> /// A non-reentrant mutual exclusion lock. /// </param> internal ConditionVariable(IExclusiveLock @lock) { _lock = @lock; } protected internal virtual IExclusiveLock Lock { get { return _lock; } } protected internal virtual int WaitQueueLength { get { throw new NotSupportedException(_notSupportedMessage); } } protected internal virtual ICollection<Thread> WaitingThreads { get { throw new NotSupportedException(_notSupportedMessage); } } protected internal virtual bool HasWaiters { get { throw new NotSupportedException(_notSupportedMessage); } } #region ICondition Members public virtual void AwaitUninterruptibly() { var holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } var wasInterrupted = false; try { lock (this) { for (var i = holdCount; i > 0; i--) _lock.Unlock(); try { Monitor.Wait(this); } catch (ThreadInterruptedException) { wasInterrupted = true; // may have masked the signal and there is no way // to tell; we must wake up spuriously. } } } finally { for (var i = holdCount; i > 0; i--) _lock.Lock(); if (wasInterrupted) { Thread.CurrentThread.Interrupt(); } } } public virtual void Await() { var holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } // This requires sleep(0) to implement in .Net, too expensive! // if (Thread.interrupted()) throw new InterruptedException(); try { lock (this) { for (var i = holdCount; i > 0; i--) _lock.Unlock(); try { Monitor.Wait(this); } catch (ThreadInterruptedException e) { Monitor.Pulse(this); throw e.PreserveStackTrace(); } } } finally { for (var i = holdCount; i > 0; i--) _lock.Lock(); } } public virtual bool Await(TimeSpan durationToWait) { var holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } // This requires sleep(0) to implement in .Net, too expensive! // if (Thread.interrupted()) throw new InterruptedException(); try { lock (this) { for (var i = holdCount; i > 0; i--) _lock.Unlock(); try { // .Net implementation is a little different than backport 3.1 // by taking advantage of the return value from Monitor.Wait. return (durationToWait.Ticks > 0) && Monitor.Wait(this, durationToWait); } catch (ThreadInterruptedException e) { Monitor.Pulse(this); throw e.PreserveStackTrace(); } } } finally { for (var i = holdCount; i > 0; i--) _lock.Lock(); } } public virtual bool AwaitUntil(DateTime deadline) { var holdCount = _lock.HoldCount; if (holdCount == 0) { throw new SynchronizationLockException(); } if ((deadline.Subtract(DateTime.UtcNow)).Ticks <= 0) return false; // This requires sleep(0) to implement in .Net, too expensive! // if (Thread.interrupted()) throw new InterruptedException(); try { lock (this) { for (var i = holdCount; i > 0; i--) _lock.Unlock(); try { // .Net has DateTime precision issue so we need to retry. TimeSpan durationToWait; while ((durationToWait = deadline.Subtract(DateTime.UtcNow)).Ticks > 0) { // .Net implementation is different than backport 3.1 // by taking advantage of the return value from Monitor.Wait. if (Monitor.Wait(this, durationToWait)) return true; } } catch (ThreadInterruptedException e) { Monitor.Pulse(this); throw e.PreserveStackTrace(); } } } finally { for (var i = holdCount; i > 0; i--) _lock.Lock(); } return false; } public virtual void Signal() { lock (this) { AssertOwnership(); Monitor.Pulse(this); } } public virtual void SignalAll() { lock (this) { AssertOwnership(); Monitor.PulseAll(this); } } #endregion protected void AssertOwnership() { if (!_lock.IsHeldByCurrentThread) { throw new SynchronizationLockException(); } } internal interface IExclusiveLock : ILock { bool IsHeldByCurrentThread { get; } int HoldCount { get; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Portions derived from React Native: // Copyright (c) 2015-present, Facebook, Inc. // Licensed under the MIT License. using ReactNative.Bridge; using ReactNative.Modules.Core; using ReactNative.Tracing; using System; using System.Collections.Generic; using System.Threading; #if WINDOWS_UWP using Windows.UI.Xaml.Media; #else using System.Windows.Media; #endif namespace ReactNative.UIManager.Events { /// <summary> /// Class responsible for dispatching UI events to JavaScript. The main /// purpose of this class is to act as an intermediary between UI code /// generating events and JavaScript, making sure we don't send more events /// than JavaScript can process. /// /// To use it, create a subclass of <see cref="Event"/> and call /// <see cref="DispatchEvent(Event)"/> whenever there is a UI event to /// dispatch. /// /// This class differs from the Android implementation of React as there is /// no analogy to the choreographer in UWP. Instead, there is a self-managed /// callback that coalesces events on the JavaScript thread. /// /// If JavaScript is taking a long time processing events, then the UI /// events generated on the dispatcher thread can be coalesced into fewer /// events so that, when the dispatch occurs, we do not overload JavaScript /// with a ton of events and cause it to get even farther behind. /// /// Ideally, this is unnecessary and JavaScript is fast enough to process /// all the events each frame, but this is a reasonable precautionary /// measure. /// </summary> /// <remarks> /// Event cookies are used to coalesce events. They are made up of the /// event type ID, view tag, and a custom coalescing key. /// /// Event Cookie Composition: /// VIEW_TAG_MASK = 0x00000000ffffffff /// EVENT_TYPE_ID_MASK = 0x0000ffff00000000 /// COALESCING_KEY_MASK = 0xffff000000000000 /// </remarks> public class EventDispatcher : ILifecycleEventListener { private static IComparer<Event> s_eventComparer = Comparer<Event>.Create((x, y) => { if (x == null && y == null) { return 0; } if (x == null) { return -1; } if (y == null) { return 1; } var value = x.Timestamp.CompareTo(y.Timestamp); if (value == 0) { return x.SortingKey.CompareTo(y.SortingKey); } return value; }); private readonly object _eventsStagingLock = new object(); private readonly object _eventsToDispatchLock = new object(); private readonly IDictionary<long, int> _eventCookieToLastEventIndex = new Dictionary<long, int>(); private readonly IDictionary<string, short> _eventNameToEventId = new Dictionary<string, short>(); private readonly IList<Event> _eventStaging = new List<Event>(); private readonly IList<IEventDispatcherListener> _listeners = new List<IEventDispatcherListener>(); private readonly ReactContext _reactContext; private Event[] _eventsToDispatch = new Event[16]; private int _eventsToDispatchSize = 0; private RCTEventEmitter _rctEventEmitter; private bool _hasDispatchScheduled = false; /// <summary> /// Instantiates the <see cref="EventDispatcher"/>. /// </summary> /// <param name="reactContext">The context.</param> public EventDispatcher(ReactContext reactContext) { if (reactContext == null) throw new ArgumentNullException(nameof(reactContext)); _reactContext = reactContext; _reactContext.AddLifecycleEventListener(this); } /// <summary> /// Sends the given <see cref="Event"/> to JavaScript, coalescing /// events if JavaScript is backed up. /// </summary> /// <param name="event">The event.</param> public void DispatchEvent(Event @event) { if (@event == null) throw new ArgumentNullException(nameof(@event)); foreach (var listener in _listeners) { listener.OnEventDispatch(@event); } lock (_eventsStagingLock) { _eventStaging.Add(@event); } ReactChoreographer.Instance.ActivateCallback(nameof(EventDispatcher)); } /// <summary> /// Adds a listener to this <see cref="EventDispatcher"/>. /// </summary> /// <param name="listener">The listener.</param> public void AddListener(IEventDispatcherListener listener) { _listeners.Add(listener); } /// <summary> /// Removes a listener from this <see cref="EventDispatcher"/>. /// </summary> /// <param name="listener">The listener.</param> public void RemoveListener(IEventDispatcherListener listener) { _listeners.Remove(listener); } /// <summary> /// Called when the host receives the resume event. /// </summary> public void OnResume() { if (_rctEventEmitter == null) { _rctEventEmitter = _reactContext.GetJavaScriptModule<RCTEventEmitter>(); } ReactChoreographer.Instance.JavaScriptEventsCallback += ScheduleDispatcherSafe; } /// <summary> /// Called when the host is shutting down. /// </summary> public void OnDestroy() { ClearCallback(); } /// <summary> /// Called when the host receives the suspend event. /// </summary> public void OnSuspend() { ClearCallback(); } /// <summary> /// Called before the React instance is disposed. /// </summary> public void OnReactInstanceDispose() { ClearCallback(); } private void ClearCallback() { ReactChoreographer.Instance.JavaScriptEventsCallback -= ScheduleDispatcherSafe; } private void MoveStagedEventsToDispatchQueue() { lock (_eventsStagingLock) { lock (_eventsToDispatchLock) { foreach (var @event in _eventStaging) { if (!@event.CanCoalesce) { AddEventToEventsToDispatch(@event); continue; } var eventCookie = GetEventCookie(@event.ViewTag, @event.EventName, @event.CoalescingKey); var eventToAdd = default(Event); var eventToDispose = default(Event); if (!_eventCookieToLastEventIndex.TryGetValue(eventCookie, out var lastEventIdx)) { eventToAdd = @event; _eventCookieToLastEventIndex.Add(eventCookie, _eventsToDispatchSize); } else { var lastEvent = _eventsToDispatch[lastEventIdx]; var coalescedEvent = @event.Coalesce(lastEvent); if (coalescedEvent != lastEvent) { eventToAdd = coalescedEvent; _eventCookieToLastEventIndex[eventCookie] = _eventsToDispatchSize; eventToDispose = lastEvent; _eventsToDispatch[lastEventIdx] = null; } else { eventToDispose = @event; } } if (eventToAdd != null) { AddEventToEventsToDispatch(eventToAdd); } if (eventToDispose != null) { eventToDispose.Dispose(); } } } _eventStaging.Clear(); ReactChoreographer.Instance.DeactivateCallback(nameof(EventDispatcher)); } } private long GetEventCookie(int viewTag, string eventName, short coalescingKey) { if (!_eventNameToEventId.TryGetValue(eventName, out var eventTypeId)) { if (_eventNameToEventId.Count == short.MaxValue) { throw new InvalidOperationException("Overflow of event type IDs."); } eventTypeId = (short)_eventNameToEventId.Count; _eventNameToEventId.Add(eventName, eventTypeId); } return GetEventCookie(viewTag, eventTypeId, coalescingKey); } private long GetEventCookie(int viewTag, short eventTypeId, short coalescingKey) { return ((long)viewTag) | (((long)eventTypeId) & 0xffff) << 32 | (((long)coalescingKey) & 0xffff) << 48; } private void ScheduleDispatcherSafe(object sender, object e) { try { ScheduleDispatch(sender, e); } catch (Exception ex) { _reactContext.HandleException(ex); } } private void ScheduleDispatch(object sender, object e) { DispatcherHelpers.AssertOnDispatcher(); var activity = Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, "ScheduleDispatch").Start(); MoveStagedEventsToDispatchQueue(); bool shouldDispatch; lock (_eventsToDispatchLock) { shouldDispatch = _eventsToDispatchSize > 0; } if (shouldDispatch && !Volatile.Read(ref _hasDispatchScheduled)) { _hasDispatchScheduled = true; _reactContext.RunOnJavaScriptQueueThread(() => { DispatchEvents(activity); activity?.Dispose(); }); return; } activity?.Dispose(); } private void DispatchEvents(IDisposable activity) { using (Tracer.Trace(Tracer.TRACE_TAG_REACT_BRIDGE, "DispatchEvents").Start()) { _hasDispatchScheduled = false; if (_rctEventEmitter == null) { throw new InvalidOperationException($"The '{nameof(RCTEventEmitter)}' must not be null."); } lock (_eventsToDispatchLock) { if (_eventsToDispatchSize > 1) { Array.Sort(_eventsToDispatch, 0, _eventsToDispatchSize, s_eventComparer); } for (var eventIdx = 0; eventIdx < _eventsToDispatchSize; ++eventIdx) { var @event = _eventsToDispatch[eventIdx]; if (@event == null) { continue; } @event.Dispatch(_rctEventEmitter); @event.Dispose(); } ClearEventsToDispatch(); _eventCookieToLastEventIndex.Clear(); } } } private void AddEventToEventsToDispatch(Event @event) { if (_eventsToDispatchSize == _eventsToDispatch.Length) { var temp = _eventsToDispatch; _eventsToDispatch = new Event[_eventsToDispatch.Length * 2]; Array.Copy(temp, _eventsToDispatch, _eventsToDispatchSize); } _eventsToDispatch[_eventsToDispatchSize++] = @event; } private void ClearEventsToDispatch() { Array.Clear(_eventsToDispatch, 0, _eventsToDispatchSize); _eventsToDispatchSize = 0; } } }
/* * Exchange Web Services Managed API * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.ObjectModel; /// <summary> /// Represents the base abstract class for all item and folder types. /// </summary> public abstract class ServiceObject { private object lockObject = new object(); private ExchangeService service; private PropertyBag propertyBag; private string xmlElementName; /// <summary> /// Triggers dispatch of the change event. /// </summary> internal void Changed() { if (this.OnChange != null) { this.OnChange(this); } } /// <summary> /// Throws exception if this is a new service object. /// </summary> internal void ThrowIfThisIsNew() { if (this.IsNew) { throw new InvalidOperationException(Strings.ServiceObjectDoesNotHaveId); } } /// <summary> /// Throws exception if this is not a new service object. /// </summary> internal void ThrowIfThisIsNotNew() { if (!this.IsNew) { throw new InvalidOperationException(Strings.ServiceObjectAlreadyHasId); } } /// <summary> /// This methods lets subclasses of ServiceObject override the default mechanism /// by which the XML element name associated with their type is retrieved. /// </summary> /// <returns> /// The XML element name associated with this type. /// If this method returns null or empty, the XML element name associated with this /// type is determined by the EwsObjectDefinition attribute that decorates the type, /// if present. /// </returns> /// <remarks> /// Item and folder classes that can be returned by EWS MUST rely on the EwsObjectDefinition /// attribute for XML element name determination. /// </remarks> internal virtual string GetXmlElementNameOverride() { return null; } /// <summary> /// GetXmlElementName retrieves the XmlElementName of this type based on the /// EwsObjectDefinition attribute that decorates it, if present. /// </summary> /// <returns>The XML element name associated with this type.</returns> internal string GetXmlElementName() { if (string.IsNullOrEmpty(this.xmlElementName)) { this.xmlElementName = this.GetXmlElementNameOverride(); if (string.IsNullOrEmpty(this.xmlElementName)) { lock (this.lockObject) { foreach (Attribute attribute in this.GetType().GetCustomAttributes(false)) { ServiceObjectDefinitionAttribute definitionAttribute = attribute as ServiceObjectDefinitionAttribute; if (definitionAttribute != null) { this.xmlElementName = definitionAttribute.XmlElementName; } } } } } EwsUtilities.Assert( !string.IsNullOrEmpty(this.xmlElementName), "EwsObject.GetXmlElementName", string.Format("The class {0} does not have an associated XML element name.", this.GetType().Name)); return this.xmlElementName; } /// <summary> /// Gets the name of the change XML element. /// </summary> /// <returns>XML element name,</returns> internal virtual string GetChangeXmlElementName() { return XmlElementNames.ItemChange; } /// <summary> /// Gets the name of the set field XML element. /// </summary> /// <returns>XML element name,</returns> internal virtual string GetSetFieldXmlElementName() { return XmlElementNames.SetItemField; } /// <summary> /// Gets the name of the delete field XML element. /// </summary> /// <returns>XML element name,</returns> internal virtual string GetDeleteFieldXmlElementName() { return XmlElementNames.DeleteItemField; } /// <summary> /// Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem /// or UpdateItem request so this item can be property saved or updated. /// </summary> /// <param name="isUpdateOperation">Indicates whether the operation being petrformed is an update operation.</param> /// <returns><c>true</c> if a time zone SOAP header should be emitted; otherwise, <c>false</c>.</returns> internal virtual bool GetIsTimeZoneHeaderRequired(bool isUpdateOperation) { return false; } /// <summary> /// Determines whether properties defined with ScopedDateTimePropertyDefinition require custom time zone scoping. /// </summary> /// <returns> /// <c>true</c> if this item type requires custom scoping for scoped date/time properties; otherwise, <c>false</c>. /// </returns> internal virtual bool GetIsCustomDateTimeScopingRequired() { return false; } /// <summary> /// The property bag holding property values for this object. /// </summary> internal PropertyBag PropertyBag { get { return this.propertyBag; } } /// <summary> /// Internal constructor. /// </summary> /// <param name="service">EWS service to which this object belongs.</param> internal ServiceObject(ExchangeService service) { EwsUtilities.ValidateParam(service, "service"); EwsUtilities.ValidateServiceObjectVersion(this, service.RequestedServerVersion); this.service = service; this.propertyBag = new PropertyBag(this); } /// <summary> /// Gets the schema associated with this type of object. /// </summary> public ServiceObjectSchema Schema { get { return this.GetSchema(); } } /// <summary> /// Internal method to return the schema associated with this type of object. /// </summary> /// <returns>The schema associated with this type of object.</returns> internal abstract ServiceObjectSchema GetSchema(); /// <summary> /// Gets the minimum required server version. /// </summary> /// <returns>Earliest Exchange version in which this service object type is supported.</returns> internal abstract ExchangeVersion GetMinimumRequiredServerVersion(); /// <summary> /// Loads service object from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="clearPropertyBag">if set to <c>true</c> [clear property bag].</param> internal void LoadFromXml(EwsServiceXmlReader reader, bool clearPropertyBag) { this.PropertyBag.LoadFromXml( reader, clearPropertyBag, null, /* propertySet */ false); /* summaryPropertiesOnly */ } /// <summary> /// Validates this instance. /// </summary> internal virtual void Validate() { this.PropertyBag.Validate(); } /// <summary> /// Loads service object from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="clearPropertyBag">if set to <c>true</c> [clear property bag].</param> /// <param name="requestedPropertySet">The property set.</param> /// <param name="summaryPropertiesOnly">if set to <c>true</c> [summary props only].</param> internal void LoadFromXml( EwsServiceXmlReader reader, bool clearPropertyBag, PropertySet requestedPropertySet, bool summaryPropertiesOnly) { this.PropertyBag.LoadFromXml( reader, clearPropertyBag, requestedPropertySet, summaryPropertiesOnly); } /// <summary> /// Clears the object's change log. /// </summary> internal void ClearChangeLog() { this.PropertyBag.ClearChangeLog(); } /// <summary> /// Writes service object as XML. /// </summary> /// <param name="writer">The writer.</param> internal void WriteToXml(EwsServiceXmlWriter writer) { this.PropertyBag.WriteToXml(writer); } /// <summary> /// Writes service object for update as XML. /// </summary> /// <param name="writer">The writer.</param> internal void WriteToXmlForUpdate(EwsServiceXmlWriter writer) { this.PropertyBag.WriteToXmlForUpdate(writer); } /// <summary> /// Loads the specified set of properties on the object. /// </summary> /// <param name="propertySet">The properties to load.</param> internal abstract void InternalLoad(PropertySet propertySet); /// <summary> /// Deletes the object. /// </summary> /// <param name="deleteMode">The deletion mode.</param> /// <param name="sendCancellationsMode">Indicates whether meeting cancellation messages should be sent.</param> /// <param name="affectedTaskOccurrences">Indicate which occurrence of a recurring task should be deleted.</param> internal abstract void InternalDelete( DeleteMode deleteMode, SendCancellationsMode? sendCancellationsMode, AffectedTaskOccurrence? affectedTaskOccurrences); /// <summary> /// Loads the specified set of properties. Calling this method results in a call to EWS. /// </summary> /// <param name="propertySet">The properties to load.</param> public void Load(PropertySet propertySet) { this.InternalLoad(propertySet); } /// <summary> /// Loads the first class properties. Calling this method results in a call to EWS. /// </summary> public void Load() { this.InternalLoad(PropertySet.FirstClassProperties); } /// <summary> /// Gets the value of specified property in this instance. /// </summary> /// <param name="propertyDefinition">Definition of the property to get.</param> /// <exception cref="ServiceVersionException">Raised if this property requires a later version of Exchange.</exception> /// <exception cref="PropertyException">Raised if this property hasn't been assigned or loaded. Raised for set if property cannot be updated or deleted.</exception> public object this[PropertyDefinitionBase propertyDefinition] { get { object propertyValue; PropertyDefinition propDef = propertyDefinition as PropertyDefinition; if (propDef != null) { return this.PropertyBag[propDef]; } else { ExtendedPropertyDefinition extendedPropDef = propertyDefinition as ExtendedPropertyDefinition; if (extendedPropDef != null) { if (this.TryGetExtendedProperty(extendedPropDef, out propertyValue)) { return propertyValue; } else { throw new ServiceObjectPropertyException(Strings.MustLoadOrAssignPropertyBeforeAccess, propertyDefinition); } } else { // Other subclasses of PropertyDefinitionBase are not supported. throw new NotSupportedException(string.Format( Strings.OperationNotSupportedForPropertyDefinitionType, propertyDefinition.GetType().Name)); } } } } /// <summary> /// Try to get the value of a specified extended property in this instance. /// </summary> /// <param name="propertyDefinition">The property definition.</param> /// <param name="propertyValue">The property value.</param> /// <typeparam name="T">Type of expected property value.</typeparam> /// <returns>True if property retrieved, false otherwise.</returns> internal bool TryGetExtendedProperty<T>(ExtendedPropertyDefinition propertyDefinition, out T propertyValue) { ExtendedPropertyCollection propertyCollection = this.GetExtendedProperties(); if ((propertyCollection != null) && propertyCollection.TryGetValue<T>(propertyDefinition, out propertyValue)) { return true; } else { propertyValue = default(T); return false; } } /// <summary> /// Try to get the value of a specified property in this instance. /// </summary> /// <param name="propertyDefinition">The property definition.</param> /// <param name="propertyValue">The property value.</param> /// <returns>True if property retrieved, false otherwise.</returns> public bool TryGetProperty(PropertyDefinitionBase propertyDefinition, out object propertyValue) { return this.TryGetProperty<object>(propertyDefinition, out propertyValue); } /// <summary> /// Try to get the value of a specified property in this instance. /// </summary> /// <param name="propertyDefinition">The property definition.</param> /// <param name="propertyValue">The property value.</param> /// <typeparam name="T">Type of expected property value.</typeparam> /// <returns>True if property retrieved, false otherwise.</returns> public bool TryGetProperty<T>(PropertyDefinitionBase propertyDefinition, out T propertyValue) { PropertyDefinition propDef = propertyDefinition as PropertyDefinition; if (propDef != null) { return this.PropertyBag.TryGetProperty<T>(propDef, out propertyValue); } else { ExtendedPropertyDefinition extPropDef = propertyDefinition as ExtendedPropertyDefinition; if (extPropDef != null) { return this.TryGetExtendedProperty<T>(extPropDef, out propertyValue); } else { // Other subclasses of PropertyDefinitionBase are not supported. throw new NotSupportedException(string.Format( Strings.OperationNotSupportedForPropertyDefinitionType, propertyDefinition.GetType().Name)); } } } /// <summary> /// Gets the collection of loaded property definitions. /// </summary> /// <returns>Collection of property definitions.</returns> public Collection<PropertyDefinitionBase> GetLoadedPropertyDefinitions() { Collection<PropertyDefinitionBase> propDefs = new Collection<PropertyDefinitionBase>(); foreach (PropertyDefinition propDef in this.PropertyBag.Properties.Keys) { propDefs.Add(propDef); } if (this.GetExtendedProperties() != null) { foreach (ExtendedProperty extProp in this.GetExtendedProperties()) { propDefs.Add(extProp.PropertyDefinition); } } return propDefs; } /// <summary> /// Gets the ExchangeService the object is bound to. /// </summary> public ExchangeService Service { get { return this.service; } internal set { this.service = value; } } /// <summary> /// The property definition for the Id of this object. /// </summary> /// <returns>A PropertyDefinition instance.</returns> internal virtual PropertyDefinition GetIdPropertyDefinition() { return null; } /// <summary> /// The unique Id of this object. /// </summary> /// <returns>A ServiceId instance.</returns> internal ServiceId GetId() { PropertyDefinition idPropertyDefinition = this.GetIdPropertyDefinition(); object serviceId = null; if (idPropertyDefinition != null) { this.PropertyBag.TryGetValue(idPropertyDefinition, out serviceId); } return (ServiceId)serviceId; } /// <summary> /// Indicates whether this object is a real store item, or if it's a local object /// that has yet to be saved. /// </summary> public virtual bool IsNew { get { ServiceId id = this.GetId(); return id == null ? true : !id.IsValid; } } /// <summary> /// Gets a value indicating whether the object has been modified and should be saved. /// </summary> public bool IsDirty { get { return this.PropertyBag.IsDirty; } } /// <summary> /// Gets the extended properties collection. /// </summary> /// <returns>Extended properties collection.</returns> internal virtual ExtendedPropertyCollection GetExtendedProperties() { return null; } /// <summary> /// Defines an event that is triggered when the service object changes. /// </summary> internal event ServiceObjectChangedDelegate OnChange; } }
//****************************** // Written by Peter Golde // Copyright (c) 2004-2005, Wintellect // // Use and restribution of this code is subject to the license agreement // contained in the file "License.txt" accompanying this file. //****************************** using System; using NUnit.Framework; using System.Runtime.InteropServices; namespace Wintellect.PowerCollections.Tests { /// <summary> /// An item type used when testing the RedBlackTree. /// </summary> struct TestItem { public TestItem(string key) { this.key = key; this.data = 0; } public TestItem(string key, int data) { this.key = key; this.data = data; } public string key; public int data; public override string ToString() { return string.Format("Key:{0} Data:{1}", key, data); } } /// <summary> /// Tests for testing the RedBlackTree class, using NUnit. /// </summary> [TestFixture] public class RedBlackTreeTests { internal RedBlackTree<TestItem> tree; internal class DataComparer : System.Collections.Generic.IComparer<TestItem> { public int Compare(TestItem x, TestItem y) { return string.Compare(x.key, y.key); } public bool Equals(TestItem x, TestItem y) { throw new NotSupportedException(); } public int GetHashCode(TestItem obj) { throw new NotSupportedException(); } } /// <summary> /// Insert a key and print/validate the tree. /// </summary> /// <param name="key"></param> private void InsertPrintValidate(string key) { InsertPrintValidate(key, 0, DuplicatePolicy.ReplaceFirst); } private void InsertPrintValidate(string key, int data) { InsertPrintValidate(key, data, DuplicatePolicy.ReplaceFirst); } private void InsertPrintValidate(string key, int data, DuplicatePolicy dupPolicy) { TestItem oldData; tree.Insert(new TestItem(key, data), dupPolicy, out oldData); #if DEBUG tree.Print(); tree.Validate(); #endif //DEBUG } private void InsertPrintValidate(string key, int data, DuplicatePolicy dupPolicy, int expectedoldData) { TestItem oldData; tree.Insert(new TestItem(key, data), dupPolicy, out oldData); #if DEBUG tree.Print(); tree.Validate(); #endif //DEBUG Assert.AreEqual(expectedoldData, oldData.data); } /// <summary> /// Insert a key and validate the tree. /// </summary> /// <param name="key"></param> private void InsertValidate(string key) { InsertValidate(key, 0, DuplicatePolicy.InsertLast); } private void InsertValidate(string key, int data) { InsertValidate(key, data, DuplicatePolicy.InsertLast); } private void InsertValidate(string key, int data, DuplicatePolicy dupPolicy) { TestItem oldData; tree.Insert(new TestItem(key, data), dupPolicy, out oldData); #if DEBUG tree.Validate(); #endif //DEBUG } private void InsertValidate(string key, int data, DuplicatePolicy dupPolicy, int expectedOldData) { TestItem oldData; tree.Insert(new TestItem(key, data), dupPolicy, out oldData); #if DEBUG tree.Validate(); #endif //DEBUG Assert.AreEqual(expectedOldData, oldData.data); } /// <summary> /// Delete a key, check the data in the deleted key, print and validate. /// </summary> /// <param name="key">Key to delete.</param> /// <param name="data">Expected data in the deleted key.</param> private void DeletePrintValidate(string key, int data) { DeletePrintValidate(key, data, true); } private void DeletePrintValidate(string key, int data, bool first) { TestItem itemFound; int countBefore = tree.ElementCount; bool success = tree.Delete(new TestItem(key), first ? true : false, out itemFound); #if DEBUG tree.Print(); #endif //DEBUG Assert.IsTrue(success, "Key to delete wasn't found"); Assert.AreEqual(data, itemFound.data, "Data in deleted key was incorrect."); int countAfter = tree.ElementCount; Assert.AreEqual(countBefore - 1, countAfter, "Count of elements incorrect after deletion"); #if DEBUG tree.Validate(); #endif //DEBUG } private void GlobalDeletePrintValidate(string key, int data, bool first) { TestItem itemFound; int countBefore = tree.ElementCount; bool success = tree.DeleteItemFromRange(tree.EntireRangeTester, first, out itemFound); #if DEBUG tree.Print(); #endif //DEBUG Assert.IsTrue(success, "Key to delete wasn't found"); Assert.AreEqual(key, itemFound.key, "Key in deleted key was incorrect."); Assert.AreEqual(data, itemFound.data, "Data in deleted key was incorrect."); int countAfter = tree.ElementCount; Assert.AreEqual(countBefore - 1, countAfter, "Count of elements incorrect after deletion"); #if DEBUG tree.Validate(); #endif //DEBUG } private void FindFirstKey(string key, int value) { TestItem itemFound; bool found = tree.Find(new TestItem(key), true, false, out itemFound); Assert.IsTrue(found, "Key was not found in the tree"); Assert.AreEqual(value, itemFound.data, "Wrong value found in the tree"); int foundIndex = tree.FindIndex(new TestItem(key), true); Assert.IsTrue(foundIndex >= 0); Assert.AreEqual(value, tree.GetItemByIndex(foundIndex).data); } private void FindLastKey(string key, int value) { TestItem itemFound; bool found = tree.Find(new TestItem(key), false, false, out itemFound); Assert.IsTrue(found, "Key was not found in the tree"); Assert.AreEqual(value, itemFound.data, "Wrong value found in the tree"); int foundIndex = tree.FindIndex(new TestItem(key), false); Assert.IsTrue(foundIndex >= 0); Assert.AreEqual(value, tree.GetItemByIndex(foundIndex).data); } private void FindOnlyKey(string key, int value) { FindFirstKey(key, value); FindLastKey(key, value); } private bool FindReplaceKey(string key, int newValue, int expectedOldValue) { TestItem itemFound; bool found = tree.Find(new TestItem(key, newValue), true, true, out itemFound); Assert.AreEqual(expectedOldValue, itemFound.data); return found; } /// <summary> /// Test creation of the tree. /// </summary> [Test] public void Create() { tree = new RedBlackTree<TestItem>(new DataComparer()); #if DEBUG tree.Validate(); #endif //DEBUG } /// <summary> /// Insert values into tree to test the basic insertion algorithm. Validate /// and print the tree after each step. /// </summary> [Test] public void NormalInsert() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertPrintValidate("m"); InsertPrintValidate("b"); InsertPrintValidate("t"); InsertPrintValidate("o"); InsertPrintValidate("z"); InsertPrintValidate("g"); InsertPrintValidate("a5"); InsertPrintValidate("c"); InsertPrintValidate("a2"); InsertPrintValidate("a7"); InsertPrintValidate("i"); InsertPrintValidate("h"); Assert.AreEqual(12, tree.ElementCount, "Wrong number of items in the tree."); } /// <summary> /// Insert values into tree and then find values in the tree. /// </summary> [Test] public void NormalFind() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m", 101); FindOnlyKey("m", 101); InsertValidate("b", 102); InsertValidate("t", 103); FindOnlyKey("b", 102); FindOnlyKey("t", 103); InsertValidate("o", 104); FindOnlyKey("b", 102); InsertValidate("z", 105); InsertValidate("g", 106); FindOnlyKey("g", 106); InsertValidate("a5", 107); InsertValidate("c", 8); InsertValidate("a2", 9); FindOnlyKey("z", 105); InsertValidate("a7", 10); InsertValidate("i", 11); InsertValidate("h", 112); Assert.AreEqual(12, tree.ElementCount, "Wrong number of items in the tree."); FindOnlyKey("m", 101); FindOnlyKey("b", 102); FindOnlyKey("t", 103); FindOnlyKey("o", 104); FindOnlyKey("z", 105); FindOnlyKey("g", 106); FindOnlyKey("a5", 107); FindOnlyKey("c", 8); FindOnlyKey("a2", 9); FindOnlyKey("a7", 10); FindOnlyKey("i", 11); FindOnlyKey("h", 112); } /// <summary> /// Test find with the replace option.. /// </summary> [Test] public void FindReplace() { bool b; tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m", 101); FindOnlyKey("m", 101); InsertValidate("b", 102); InsertValidate("t", 103); b = FindReplaceKey("b", 202, 102); Assert.IsTrue(b); FindOnlyKey("t", 103); InsertValidate("o", 104); FindOnlyKey("b", 202); InsertValidate("z", 105); InsertValidate("g", 106); FindOnlyKey("g", 106); b = FindReplaceKey("a5", 77, 0); Assert.IsFalse(b); b = FindReplaceKey("a5", 134, 0); Assert.IsFalse(b); b = FindReplaceKey("m", 201, 101); Assert.IsTrue(b); InsertValidate("a5", 107); InsertValidate("c", 8); InsertValidate("a2", 9); FindOnlyKey("z", 105); b = FindReplaceKey("m", 301, 201); Assert.IsTrue(b); InsertValidate("a7", 10); b = FindReplaceKey("a5", 207, 107); Assert.IsTrue(b); InsertValidate("i", 11); InsertValidate("h", 112); b = FindReplaceKey("z", 205, 105); Assert.IsTrue(b); b = FindReplaceKey("g", 206, 106); Assert.IsTrue(b); b = FindReplaceKey("g", 306, 206); Assert.IsTrue(b); Assert.AreEqual(12, tree.ElementCount, "Wrong number of items in the tree."); FindOnlyKey("m", 301); FindOnlyKey("b", 202); FindOnlyKey("t", 103); FindOnlyKey("o", 104); FindOnlyKey("z", 205); FindOnlyKey("g", 306); FindOnlyKey("a5", 207); FindOnlyKey("c", 8); FindOnlyKey("a2", 9); FindOnlyKey("a7", 10); FindOnlyKey("i", 11); FindOnlyKey("h", 112); } /// <summary> /// Check that deletion works. /// </summary> [Test] public void Delete() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertPrintValidate("m", 101); DeletePrintValidate("m", 101); InsertPrintValidate("m", 101); InsertPrintValidate("b", 102); InsertPrintValidate("t", 103); DeletePrintValidate("b", 102); DeletePrintValidate("m", 101); DeletePrintValidate("t", 103); InsertPrintValidate("m", 101); InsertPrintValidate("b", 102); InsertPrintValidate("t", 103); InsertPrintValidate("o", 104); InsertPrintValidate("z", 105); InsertPrintValidate("g", 106); InsertPrintValidate("a5", 107); InsertPrintValidate("c", 8); InsertPrintValidate("a2", 9); InsertPrintValidate("a7", 10); InsertPrintValidate("i", 11); InsertPrintValidate("h", 112); DeletePrintValidate("m", 101); DeletePrintValidate("b", 102); DeletePrintValidate("t", 103); DeletePrintValidate("o", 104); DeletePrintValidate("z", 105); DeletePrintValidate("h", 112); DeletePrintValidate("g", 106); DeletePrintValidate("a5", 107); DeletePrintValidate("c", 8); DeletePrintValidate("a2", 9); DeletePrintValidate("a7", 10); DeletePrintValidate("i", 11); } /// <summary> /// Test that deleting a non-present value works right. A bug was found where the root isn't /// colored black in this case. /// </summary> [Test] public void DeleteNotPresent() { int dummy; RedBlackTree<int> t = new RedBlackTree<int>(Comparers.DefaultComparer<int>()); t.Insert(3, DuplicatePolicy.ReplaceFirst, out dummy); t.Insert(1, DuplicatePolicy.ReplaceFirst, out dummy); t.Insert(5, DuplicatePolicy.ReplaceFirst, out dummy); t.Insert(3, DuplicatePolicy.ReplaceFirst, out dummy); t.Insert(2, DuplicatePolicy.ReplaceFirst, out dummy); t.Insert(2, DuplicatePolicy.ReplaceFirst, out dummy); t.Insert(3, DuplicatePolicy.ReplaceFirst, out dummy); t.Insert(4, DuplicatePolicy.ReplaceFirst, out dummy); bool b; int d; #if DEBUG t.Print(); #endif //DEBUG b = t.Delete(1, true, out d); Assert.IsTrue(b); #if DEBUG t.Print(); t.Validate(); #endif //DEBUG b = t.Delete(1, true, out d); Assert.IsFalse(b); #if DEBUG t.Print(); t.Validate(); #endif //DEBUG b = t.Delete(int.MinValue, true, out d); Assert.IsFalse(b); #if DEBUG t.Print(); t.Validate(); #endif //DEBUG b = t.Delete(3, true, out d); Assert.IsTrue(b); #if DEBUG t.Print(); t.Validate(); #endif //DEBUG b = t.Delete(3, true, out d); Assert.IsFalse(b); #if DEBUG t.Print(); t.Validate(); #endif //DEBUG } /// <summary> /// Insert values into tree and enumerate then to test enumeration. /// </summary> [Test] public void Enumerate() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m"); InsertValidate("b"); InsertValidate("t"); InsertValidate("o"); InsertValidate("p"); InsertValidate("g"); InsertValidate("a5"); InsertValidate("c"); InsertValidate("a2"); InsertValidate("a7"); InsertValidate("i"); InsertValidate("h"); InsertValidate("o"); InsertValidate("c"); string[] keys = new string[] {"a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }; int i = 0; foreach (TestItem item in tree) { Assert.AreEqual(item.key, keys[i], "Keys weren't enumerated in order"); ++i; } i = 0; foreach (TestItem item in tree.EnumerateRangeReversed(tree.EntireRangeTester)) { Assert.AreEqual(item.key, keys[tree.ElementCount - i - 1], "Keys weren't enumerated in reverse order"); ++i; } } private void CheckEnumerateRange(RedBlackTree<TestItem> tree, bool useFirst, string first, bool useLast, string last, string[] keys) { int i = 0; TestItem firstItem, lastItem; foreach (TestItem item in tree.EnumerateRange(tree.BoundedRangeTester(useFirst, new TestItem(first), useLast, new TestItem(last)))) { Assert.AreEqual(item.key, keys[i], "Keys weren't enumerated in order"); ++i; } i = 0; foreach (TestItem item in tree.EnumerateRangeReversed(tree.BoundedRangeTester(useFirst, new TestItem(first), useLast, new TestItem(last)))) { Assert.AreEqual(item.key, keys[keys.Length - i - 1], "Keys weren't enumerated in reverse order"); ++i; } if (i != 0) { int foundFirst = tree.FirstItemInRange(tree.BoundedRangeTester(useFirst, new TestItem(first), useLast, new TestItem(last)), out firstItem); Assert.IsTrue(foundFirst >= 0); Assert.AreEqual(keys[0], firstItem.key); Assert.AreEqual(keys[0], tree.GetItemByIndex(foundFirst).key); int foundLast = tree.LastItemInRange(tree.BoundedRangeTester(useFirst, new TestItem(first), useLast, new TestItem(last)), out lastItem); Assert.IsTrue(foundLast >= 0); Assert.AreEqual(keys[i-1], lastItem.key); Assert.AreEqual(keys[i-1], tree.GetItemByIndex(foundLast).key); Assert.AreEqual(i, foundLast - foundFirst + 1); } else { Assert.IsTrue(tree.FirstItemInRange(tree.BoundedRangeTester(useFirst, new TestItem(first), useLast, new TestItem(last)), out firstItem) < 0); Assert.IsTrue(tree.LastItemInRange(tree.BoundedRangeTester(useFirst, new TestItem(first), useLast, new TestItem(last)), out lastItem) < 0); } Assert.AreEqual(keys.Length, tree.CountRange(tree.BoundedRangeTester(useFirst, new TestItem(first), useLast, new TestItem(last)))); } [Test] public void EnumerateAndCountRange() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m"); InsertValidate("b"); InsertValidate("t"); InsertValidate("o"); InsertValidate("p"); InsertValidate("g"); InsertValidate("a5"); InsertValidate("c"); InsertValidate("a2"); InsertValidate("a7"); InsertValidate("i"); InsertValidate("h"); InsertValidate("o"); InsertValidate("c"); CheckEnumerateRange(tree, true, "a7", true, "o", new string[] { "a7", "b", "c", "c", "g", "h", "i", "m" }); CheckEnumerateRange(tree, true, "c", true, "c", new string[] { }); CheckEnumerateRange(tree, true, "c", true, "c1", new string[] { "c", "c" }); CheckEnumerateRange(tree, true, "a", true, "a1", new string[0] { }); CheckEnumerateRange(tree, true, "j", true, "k", new string[0] { }); CheckEnumerateRange(tree, true, "z", true, "a", new string[0] { }); CheckEnumerateRange(tree, true, "h5", true, "z", new string[] { "i", "m", "o", "o", "p", "t" }); CheckEnumerateRange(tree, true, "a3", true, "a8", new string[] { "a5", "a7" }); CheckEnumerateRange(tree, true, "a", true, "z", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckEnumerateRange(tree, false, "m", false, "n", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckEnumerateRange(tree, true, "c", false, "n", new string[] { "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckEnumerateRange(tree, true, "c1", false, "n", new string[] { "g", "h", "i", "m", "o", "o", "p", "t" }); CheckEnumerateRange(tree, false, "m", true, "o", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m" }); CheckEnumerateRange(tree, false, "m", true, "o3", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m", "o", "o"}); } private void CheckEnumerateRange2(RedBlackTree<TestItem> tree, bool firstInclusive, string first, bool lastInclusive, string last, System.Collections.Generic.IList<string> keys) { int i = 0; TestItem firstItem, lastItem; foreach (TestItem item in tree.EnumerateRange(tree.DoubleBoundedRangeTester(new TestItem(first), firstInclusive, new TestItem(last), lastInclusive))) { Assert.AreEqual(item.key, keys[i], "Keys weren't enumerated in order"); ++i; } i = 0; foreach (TestItem item in tree.EnumerateRangeReversed(tree.DoubleBoundedRangeTester(new TestItem(first), firstInclusive, new TestItem(last), lastInclusive))) { Assert.AreEqual(item.key, keys[keys.Count - i - 1], "Keys weren't enumerated in reverse order"); ++i; } if (i != 0) { int foundFirst = tree.FirstItemInRange(tree.DoubleBoundedRangeTester(new TestItem(first), firstInclusive, new TestItem(last), lastInclusive), out firstItem); Assert.IsTrue(foundFirst >= 0); Assert.AreEqual(keys[0], firstItem.key); Assert.AreEqual(keys[0], tree.GetItemByIndex(foundFirst).key); int foundLast = tree.LastItemInRange(tree.DoubleBoundedRangeTester(new TestItem(first), firstInclusive, new TestItem(last), lastInclusive), out lastItem); Assert.IsTrue(foundLast >= 0); Assert.AreEqual(keys[i - 1], lastItem.key); Assert.AreEqual(keys[i - 1], tree.GetItemByIndex(foundLast).key); Assert.AreEqual(i, foundLast - foundFirst + 1); } else { Assert.IsTrue(tree.FirstItemInRange(tree.DoubleBoundedRangeTester(new TestItem(first), firstInclusive, new TestItem(last), lastInclusive), out firstItem) < 0); Assert.IsTrue(tree.LastItemInRange(tree.DoubleBoundedRangeTester(new TestItem(first), firstInclusive, new TestItem(last), lastInclusive), out lastItem) < 0); } Assert.AreEqual(keys.Count, tree.CountRange(tree.DoubleBoundedRangeTester(new TestItem(first), firstInclusive, new TestItem(last), lastInclusive))); } [Test] public void EnumerateAndCountRange2() { Random rand = new Random(112); for (int iter = 0; iter < ITERATIONS; ++iter) { tree = new RedBlackTree<TestItem>(new DataComparer()); int[] a = CreateRandomArray(iter, LENGTH, LENGTH * 10, false); InsertArray(a, DuplicatePolicy.InsertLast); string[] strs = Array.ConvertAll<int, string>(a, StringFromInt); Array.Sort(strs); for (int k = 0; k < 10; ++k) { string lower, upper; do { lower = StringFromInt(rand.Next(LENGTH * 10)); upper = StringFromInt(rand.Next(LENGTH * 10)); } while (string.Compare(lower, upper) >= 0); bool lowerInclusive = (rand.Next(2) == 0); bool upperInclusive = (rand.Next(2) == 0); int lowerIndex, upperIndex; if (lowerInclusive) lowerIndex = Algorithms.FindFirstIndexWhere(strs, delegate(string x) { return string.Compare(x, lower) >= 0; }); else lowerIndex = Algorithms.FindFirstIndexWhere(strs, delegate(string x) { return string.Compare(x, lower) > 0; }); if (upperInclusive) upperIndex = Algorithms.FindLastIndexWhere(strs, delegate(string x) { return string.Compare(x, upper) <= 0; }); else upperIndex = Algorithms.FindLastIndexWhere(strs, delegate(string x) { return string.Compare(x, upper) < 0; }); CheckEnumerateRange2(tree, lowerInclusive, lower, upperInclusive, upper, Algorithms.Range(strs, lowerIndex, upperIndex - lowerIndex + 1)); } } } private void CheckDeleteRange(RedBlackTree<TestItem> tree, bool useFirst, string first, bool useLast, string last, string[] keys) { int i = 0; int count = tree.ElementCount; int deletedCount = tree.DeleteRange(tree.BoundedRangeTester(useFirst, new TestItem(first), useLast, new TestItem(last))); Assert.AreEqual(keys.Length, count - deletedCount); foreach (TestItem item in tree) { Assert.AreEqual(item.key, keys[i], "Keys weren't enumerated in order"); ++i; } } [Test] public void DeleteRange() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m"); InsertValidate("b"); InsertValidate("t"); InsertValidate("o"); InsertValidate("p"); InsertValidate("g"); InsertValidate("a5"); InsertValidate("c"); InsertValidate("a2"); InsertValidate("a7"); InsertValidate("i"); InsertValidate("h"); InsertValidate("o"); InsertValidate("c"); CheckDeleteRange(tree.Clone(), true, "a7", true, "o", new string[] { "a2", "a5", "o", "o", "p", "t" }); CheckDeleteRange(tree.Clone(), true, "c", true, "c", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckDeleteRange(tree.Clone(), true, "c", true, "c1", new string[] { "a2", "a5", "a7", "b", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckDeleteRange(tree.Clone(), true, "a", true, "a1", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckDeleteRange(tree.Clone(), true, "j", true, "k", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckDeleteRange(tree.Clone(), true, "z", true, "a", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckDeleteRange(tree.Clone(), true, "h5", true, "z", new string[] { "a2", "a5", "a7", "b", "c", "c", "g", "h" }); CheckDeleteRange(tree.Clone(), true, "a3", true, "a8", new string[] { "a2", "b", "c", "c", "g", "h", "i", "m", "o", "o", "p", "t" }); CheckDeleteRange(tree.Clone(), true, "a", true, "z", new string[] { }); CheckDeleteRange(tree.Clone(), false, "m", false, "n", new string[] { }); CheckDeleteRange(tree.Clone(), true, "c", false, "n", new string[] { "a2", "a5", "a7", "b" }); CheckDeleteRange(tree.Clone(), true, "c1", false, "n", new string[] { "a2", "a5", "a7", "b", "c", "c" }); CheckDeleteRange(tree.Clone(), false, "m", true, "o", new string[] { "o", "o", "p", "t" }); CheckDeleteRange(tree.Clone(), false, "m", true, "o3", new string[] { "p", "t" }); } [Test] public void CountEqual() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m"); InsertValidate("c"); InsertValidate("b"); InsertValidate("c"); InsertValidate("t"); InsertValidate("o"); InsertValidate("z"); InsertValidate("g"); InsertValidate("a5"); InsertValidate("c"); InsertValidate("a2"); InsertValidate("a7"); InsertValidate("c"); InsertValidate("i"); InsertValidate("h"); InsertValidate("o"); InsertValidate("c"); Assert.AreEqual(5, tree.CountRange(tree.EqualRangeTester(new TestItem("c")))); Assert.AreEqual(2, tree.CountRange(tree.EqualRangeTester(new TestItem("o")))); Assert.AreEqual(1, tree.CountRange(tree.EqualRangeTester(new TestItem("z")))); Assert.AreEqual(1, tree.CountRange(tree.EqualRangeTester(new TestItem("m")))); Assert.AreEqual(1, tree.CountRange(tree.EqualRangeTester(new TestItem("a2")))); Assert.AreEqual(0, tree.CountRange(tree.EqualRangeTester(new TestItem("e")))); } [Test] public void EnumerateEqual() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m", 1); InsertValidate("c", 2); InsertValidate("b", 3); InsertValidate("c", 4); InsertValidate("t", 5); InsertValidate("o", 6); InsertValidate("z", 7); InsertValidate("g", 8); InsertValidate("a5", 9); InsertValidate("c", 10); InsertValidate("a2", 11); InsertValidate("a7", 12); InsertValidate("c", 13); InsertValidate("i", 14); InsertValidate("h", 15); InsertValidate("o", 16); InsertValidate("c", 17); InterfaceTests.TestEnumerableElements(tree.EnumerateRange(tree.EqualRangeTester(new TestItem("c", 0))), new TestItem[] { new TestItem("c", 2), new TestItem("c", 4), new TestItem("c", 10), new TestItem("c", 13), new TestItem("c", 17) }); InterfaceTests.TestEnumerableElements(tree.EnumerateRange(tree.EqualRangeTester(new TestItem("o", 0))), new TestItem[] { new TestItem("o", 6), new TestItem("o", 16)}); InterfaceTests.TestEnumerableElements(tree.EnumerateRange(tree.EqualRangeTester(new TestItem("g", 0))), new TestItem[] { new TestItem("g", 8) }); InterfaceTests.TestEnumerableElements(tree.EnumerateRange(tree.EqualRangeTester(new TestItem("qqq", 0))), new TestItem[] { }); } [Test] public void FindIndex() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m"); InsertValidate("b"); InsertValidate("t"); InsertValidate("o"); InsertValidate("p"); InsertValidate("g"); InsertValidate("a5"); InsertValidate("c"); InsertValidate("a2"); InsertValidate("a7"); InsertValidate("i"); InsertValidate("h"); InsertValidate("o"); InsertValidate("c"); int index; index = tree.FindIndex(new TestItem("a7"), true); Assert.AreEqual(2, index); index = tree.FindIndex(new TestItem("a7"), false); Assert.AreEqual(2, index); index = tree.FindIndex(new TestItem("a2"), true); Assert.AreEqual(0, index); index = tree.FindIndex(new TestItem("a2"), false); Assert.AreEqual(0, index); index = tree.FindIndex(new TestItem("t"), true); Assert.AreEqual(13, index); index = tree.FindIndex(new TestItem("t"), false); Assert.AreEqual(13, index); index = tree.FindIndex(new TestItem("n"), true); Assert.AreEqual(-1, index); index = tree.FindIndex(new TestItem("n"), false); Assert.AreEqual(-1, index); index = tree.FindIndex(new TestItem("o"), true); Assert.AreEqual(10, index); index = tree.FindIndex(new TestItem("o"), false); Assert.AreEqual(11, index); } /// <summary> /// Insert values into tree using replace policy and then find values in the tree. /// </summary> [Test] public void ReplaceFind() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m", 101, DuplicatePolicy.ReplaceFirst, 0); FindOnlyKey("m", 101); InsertValidate("b", 102, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("t", 103, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("m", 201, DuplicatePolicy.ReplaceFirst, 101); FindOnlyKey("b", 102); FindOnlyKey("t", 103); InsertValidate("o", 104, DuplicatePolicy.ReplaceFirst, 0); FindOnlyKey("b", 102); InsertValidate("z", 105, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("g", 106, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("b", 202, DuplicatePolicy.ReplaceFirst, 102); FindOnlyKey("g", 106); InsertValidate("g", 206, DuplicatePolicy.ReplaceFirst, 106); InsertValidate("a5", 107, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("t", 203, DuplicatePolicy.ReplaceFirst, 103); InsertValidate("c", 8, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("a2", 9, DuplicatePolicy.ReplaceFirst, 0); FindOnlyKey("z", 105); InsertValidate("a7", 10, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("i", 11, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("h", 112, DuplicatePolicy.ReplaceFirst, 0); InsertValidate("z", 205, DuplicatePolicy.ReplaceFirst, 105); InsertValidate("a2", 209, DuplicatePolicy.ReplaceFirst, 9); InsertValidate("c", 208, DuplicatePolicy.ReplaceFirst, 8); InsertValidate("i", 211, DuplicatePolicy.ReplaceFirst, 11); InsertValidate("h", 212, DuplicatePolicy.ReplaceFirst, 112); Assert.AreEqual(12, tree.ElementCount, "Wrong number of items in the tree."); FindOnlyKey("m", 201); FindOnlyKey("b", 202); FindOnlyKey("t", 203); FindOnlyKey("o", 104); FindOnlyKey("z", 205); FindOnlyKey("g", 206); FindOnlyKey("a5", 107); FindOnlyKey("c", 208); FindOnlyKey("a2", 209); FindOnlyKey("a7", 10); FindOnlyKey("i", 211); FindOnlyKey("h", 212); } /// <summary> /// Insert values into tree using "do-nothing" policy and then find values in the tree. /// </summary> [Test] public void DoNothingFind() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m", 101, DuplicatePolicy.DoNothing, 0); FindOnlyKey("m", 101); InsertValidate("b", 102, DuplicatePolicy.DoNothing, 0); InsertValidate("t", 103, DuplicatePolicy.DoNothing, 0); InsertValidate("m", 201, DuplicatePolicy.DoNothing, 101); FindOnlyKey("b", 102); FindOnlyKey("t", 103); InsertValidate("o", 104, DuplicatePolicy.DoNothing, 0); FindOnlyKey("b", 102); InsertValidate("z", 105, DuplicatePolicy.DoNothing, 0); InsertValidate("g", 106, DuplicatePolicy.DoNothing, 0); InsertValidate("b", 202, DuplicatePolicy.DoNothing, 102); FindOnlyKey("g", 106); InsertValidate("g", 206, DuplicatePolicy.DoNothing, 106); InsertValidate("a5", 107, DuplicatePolicy.DoNothing, 0); InsertValidate("t", 203, DuplicatePolicy.DoNothing, 103); InsertValidate("c", 8, DuplicatePolicy.DoNothing, 0); InsertValidate("a2", 9, DuplicatePolicy.DoNothing, 0); FindOnlyKey("z", 105); InsertValidate("a7", 10, DuplicatePolicy.DoNothing, 0); InsertValidate("i", 11, DuplicatePolicy.DoNothing, 0); InsertValidate("h", 112, DuplicatePolicy.DoNothing, 0); InsertValidate("z", 205, DuplicatePolicy.DoNothing, 105); InsertValidate("a2", 209, DuplicatePolicy.DoNothing, 9); InsertValidate("c", 208, DuplicatePolicy.DoNothing, 8); InsertValidate("i", 211, DuplicatePolicy.DoNothing, 11); InsertValidate("h", 212, DuplicatePolicy.DoNothing, 112); InsertValidate("m", 401, DuplicatePolicy.DoNothing, 101); Assert.AreEqual(12, tree.ElementCount, "Wrong number of items in the tree."); FindOnlyKey("m", 101); FindOnlyKey("b", 102); FindOnlyKey("t", 103); FindOnlyKey("o", 104); FindOnlyKey("z", 105); FindOnlyKey("g", 106); FindOnlyKey("a5", 107); FindOnlyKey("c", 8); FindOnlyKey("a2", 9); FindOnlyKey("a7", 10); FindOnlyKey("i", 11); FindOnlyKey("h", 112); } /// <summary> /// Insert values into tree using insert-first policy and then find values in the tree. /// </summary> [Test] public void InsertFirstFind() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m", 101, DuplicatePolicy.InsertFirst, 0); FindOnlyKey("m", 101); InsertValidate("b", 102, DuplicatePolicy.InsertFirst, 0); InsertValidate("t", 103, DuplicatePolicy.InsertFirst, 0); InsertValidate("m", 201, DuplicatePolicy.InsertFirst, 101); FindOnlyKey("b", 102); FindOnlyKey("t", 103); InsertValidate("o", 104, DuplicatePolicy.InsertFirst, 0); FindOnlyKey("b", 102); InsertValidate("z", 105, DuplicatePolicy.InsertFirst, 0); InsertValidate("g", 106, DuplicatePolicy.InsertFirst, 0); InsertValidate("b", 202, DuplicatePolicy.InsertFirst, 102); FindOnlyKey("g", 106); InsertValidate("g", 206, DuplicatePolicy.InsertFirst, 106); InsertValidate("a5", 107, DuplicatePolicy.InsertFirst, 0); InsertValidate("t", 203, DuplicatePolicy.InsertFirst, 103); InsertValidate("c", 8, DuplicatePolicy.InsertFirst, 0); InsertValidate("a2", 9, DuplicatePolicy.InsertFirst, 0); FindOnlyKey("z", 105); InsertValidate("a7", 10, DuplicatePolicy.InsertFirst, 0); InsertValidate("i", 11, DuplicatePolicy.InsertFirst, 0); InsertValidate("h", 112, DuplicatePolicy.InsertFirst, 0); InsertValidate("z", 205, DuplicatePolicy.InsertFirst, 105); InsertValidate("a2", 209, DuplicatePolicy.InsertFirst, 9); InsertValidate("c", 208, DuplicatePolicy.InsertFirst, 8); InsertValidate("i", 211, DuplicatePolicy.InsertFirst, 11); InsertValidate("h", 212, DuplicatePolicy.InsertFirst, 112); Assert.AreEqual(21, tree.ElementCount, "Wrong number of items in the tree."); FindLastKey("m", 101); FindLastKey("b", 102); FindLastKey("t", 103); FindLastKey("o", 104); FindLastKey("z", 105); FindLastKey("g", 106); FindLastKey("a5", 107); FindLastKey("c", 8); FindLastKey("a2", 9); FindLastKey("a7", 10); FindLastKey("i", 11); FindLastKey("h", 112); FindFirstKey("m", 201); FindFirstKey("b", 202); FindFirstKey("t", 203); FindFirstKey("o", 104); FindFirstKey("z", 205); FindFirstKey("g", 206); FindFirstKey("a5", 107); FindFirstKey("c", 208); FindFirstKey("a2", 209); FindFirstKey("a7", 10); FindFirstKey("i", 211); FindFirstKey("h", 212); CheckAllIndices(); } /// <summary> /// Insert values into tree using insert-last policy and then find values in the tree. /// </summary> [Test] public void InsertLastFind() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m", 101, DuplicatePolicy.InsertLast, 0); FindOnlyKey("m", 101); InsertValidate("b", 102, DuplicatePolicy.InsertLast, 0); InsertValidate("t", 103, DuplicatePolicy.InsertLast, 0); InsertValidate("m", 201, DuplicatePolicy.InsertLast, 101); FindOnlyKey("b", 102); FindOnlyKey("t", 103); InsertValidate("o", 104, DuplicatePolicy.InsertLast, 0); FindOnlyKey("b", 102); InsertValidate("z", 105, DuplicatePolicy.InsertLast, 0); InsertValidate("g", 106, DuplicatePolicy.InsertLast, 0); InsertValidate("b", 202, DuplicatePolicy.InsertLast, 102); FindOnlyKey("g", 106); InsertValidate("g", 206, DuplicatePolicy.InsertLast, 106); InsertValidate("a5", 107, DuplicatePolicy.InsertLast, 0); InsertValidate("t", 203, DuplicatePolicy.InsertLast, 103); InsertValidate("c", 8, DuplicatePolicy.InsertLast, 0); InsertValidate("a2", 9, DuplicatePolicy.InsertLast, 0); FindOnlyKey("z", 105); InsertValidate("a7", 10, DuplicatePolicy.InsertLast, 0); InsertValidate("i", 11, DuplicatePolicy.InsertLast, 0); InsertValidate("h", 112, DuplicatePolicy.InsertLast, 0); InsertValidate("z", 205, DuplicatePolicy.InsertLast, 105); InsertValidate("a2", 209, DuplicatePolicy.InsertLast, 9); InsertValidate("c", 208, DuplicatePolicy.InsertLast, 8); InsertValidate("i", 211, DuplicatePolicy.InsertLast, 11); InsertValidate("h", 212, DuplicatePolicy.InsertLast, 112); Assert.AreEqual(21, tree.ElementCount, "Wrong number of items in the tree."); FindFirstKey("m", 101); FindFirstKey("b", 102); FindFirstKey("t", 103); FindFirstKey("o", 104); FindFirstKey("z", 105); FindFirstKey("g", 106); FindFirstKey("a5", 107); FindFirstKey("c", 8); FindFirstKey("a2", 9); FindFirstKey("a7", 10); FindFirstKey("i", 11); FindFirstKey("h", 112); FindLastKey("m", 201); FindLastKey("b", 202); FindLastKey("t", 203); FindLastKey("o", 104); FindLastKey("z", 205); FindLastKey("g", 206); FindLastKey("a5", 107); FindLastKey("c", 208); FindLastKey("a2", 209); FindLastKey("a7", 10); FindLastKey("i", 211); FindLastKey("h", 212); CheckAllIndices(); } /// <summary> /// Insert values into tree delete values in the tree, making sure first/last works. /// </summary> [Test] public void DeleteFirstLast() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("m", 101, DuplicatePolicy.InsertFirst); InsertValidate("b", 102, DuplicatePolicy.InsertFirst); InsertValidate("t", 103, DuplicatePolicy.InsertFirst); InsertValidate("m", 201, DuplicatePolicy.InsertFirst); InsertValidate("o", 104, DuplicatePolicy.InsertFirst); InsertValidate("z", 105, DuplicatePolicy.InsertFirst); InsertValidate("g", 106, DuplicatePolicy.InsertFirst); InsertValidate("b", 202, DuplicatePolicy.InsertFirst); InsertValidate("g", 206, DuplicatePolicy.InsertFirst); InsertValidate("m", 301, DuplicatePolicy.InsertFirst); InsertValidate("a5", 107, DuplicatePolicy.InsertFirst); InsertValidate("t", 203, DuplicatePolicy.InsertFirst); InsertValidate("c", 8, DuplicatePolicy.InsertFirst); InsertValidate("a2", 9, DuplicatePolicy.InsertFirst); InsertValidate("a7", 10, DuplicatePolicy.InsertFirst); InsertValidate("i", 11, DuplicatePolicy.InsertFirst); InsertValidate("h", 112, DuplicatePolicy.InsertFirst); InsertValidate("m", 401, DuplicatePolicy.InsertFirst); InsertValidate("z", 205, DuplicatePolicy.InsertFirst); InsertValidate("a2", 209, DuplicatePolicy.InsertFirst); InsertValidate("c", 208, DuplicatePolicy.InsertFirst); InsertValidate("m", 501, DuplicatePolicy.InsertFirst); InsertValidate("i", 211, DuplicatePolicy.InsertFirst); InsertValidate("h", 212, DuplicatePolicy.InsertFirst); InsertValidate("z", 305, DuplicatePolicy.InsertFirst); #if DEBUG tree.Print(); #endif //DEBUG DeletePrintValidate("m", 101, false); DeletePrintValidate("m", 501, true); DeletePrintValidate("m", 201, false); FindFirstKey("m", 401); FindLastKey("m", 301); DeletePrintValidate("m", 401, true); DeletePrintValidate("m", 301, true); DeletePrintValidate("z", 305, true); DeletePrintValidate("z", 205, true); DeletePrintValidate("z", 105, true); CheckAllIndices(); } /// <summary> /// Delete values in the tree, making sure global first/last works. /// </summary> [Test] public void GlobalDeleteFirstLast() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("a", 101, DuplicatePolicy.InsertLast); InsertValidate("b", 102, DuplicatePolicy.InsertLast); InsertValidate("t", 103, DuplicatePolicy.InsertLast); InsertValidate("a", 201, DuplicatePolicy.InsertLast); InsertValidate("o", 104, DuplicatePolicy.InsertLast); InsertValidate("z", 105, DuplicatePolicy.InsertLast); InsertValidate("g", 106, DuplicatePolicy.InsertLast); InsertValidate("b", 202, DuplicatePolicy.InsertLast); InsertValidate("g", 206, DuplicatePolicy.InsertLast); InsertValidate("a", 301, DuplicatePolicy.InsertLast); InsertValidate("a5", 107, DuplicatePolicy.InsertLast); InsertValidate("t", 203, DuplicatePolicy.InsertLast); InsertValidate("c", 8, DuplicatePolicy.InsertLast); InsertValidate("a2", 9, DuplicatePolicy.InsertLast); InsertValidate("a7", 10, DuplicatePolicy.InsertLast); InsertValidate("i", 11, DuplicatePolicy.InsertLast); InsertValidate("h", 112, DuplicatePolicy.InsertLast); InsertValidate("a", 401, DuplicatePolicy.InsertLast); InsertValidate("z", 205, DuplicatePolicy.InsertLast); InsertValidate("a2", 209, DuplicatePolicy.InsertLast); InsertValidate("c", 208, DuplicatePolicy.InsertLast); InsertValidate("a", 501, DuplicatePolicy.InsertLast); InsertValidate("i", 211, DuplicatePolicy.InsertLast); InsertValidate("h", 212, DuplicatePolicy.InsertLast); InsertValidate("z", 305, DuplicatePolicy.InsertLast); GlobalDeletePrintValidate("a", 101, true); TestItem firstItem; Assert.IsTrue(tree.FirstItemInRange(tree.EntireRangeTester, out firstItem) == 0); Assert.AreEqual("a", firstItem.key); Assert.AreEqual(201, firstItem.data); GlobalDeletePrintValidate("a", 201, true); FindFirstKey("a", 301); GlobalDeletePrintValidate("a", 301, true); DeletePrintValidate("z", 305, false); FindLastKey("z", 205); DeletePrintValidate("z", 205, false); TestItem lastItem; Assert.IsTrue(tree.LastItemInRange(tree.EntireRangeTester, out lastItem) == tree.ElementCount - 1); Assert.AreEqual("z", lastItem.key); Assert.AreEqual(105, lastItem.data); DeletePrintValidate("z", 105, false); CheckAllIndices(); } private void CheckAllIndices() { #if DEBUG tree.Validate(); #endif //DEBUG TestItem[] items = new TestItem[tree.ElementCount]; int i = 0; foreach (TestItem item in tree) items[i++] = item; for (i = tree.ElementCount - 1; i >= 0; i -= 2) { TestItem item = tree.GetItemByIndex(i); Assert.AreEqual(item.key, items[i].key); Assert.AreEqual(item.data, items[i].data); } for (i = tree.ElementCount - 2; i >= 0; i -= 2) { TestItem item = tree.GetItemByIndex(i); Assert.AreEqual(item.key, items[i].key); Assert.AreEqual(item.data, items[i].data); } #if DEBUG tree.Validate(); #endif //DEBUG } const int LENGTH = 400; // length of each random array of values. const int ITERATIONS = 30; // number of iterations /// <summary> /// Create a random array of values. /// </summary> /// <param name="seed">Seed for random number generators</param> /// <param name="length">Length of array</param> /// <param name="max">Maximum value of number. Should be much /// greater than length.</param> /// <param name="allowDups">Whether to allow duplicate elements.</param> /// <returns></returns> private int[] CreateRandomArray(int seed, int length, int max, bool allowDups) { Random rand = new Random(seed); int[] a = new int[length]; for (int i = 0; i < a.Length; ++i) a[i] = -1; for (int el = 0; el < a.Length; ++el) { int value; do { value = rand.Next(max); } while (!allowDups && Array.IndexOf(a, value) >= 0); a[el] = value; } return a; } /// <summary> /// Insert all the elements of an integer array into the tree. The /// values in the tree are the indexes of the array. /// </summary> /// <param name="a">Array of values to insert.</param> /// <param name="dupPolicy">The DuplicatePolicy to use when inserting.</param> private void InsertArray(int[] a, DuplicatePolicy dupPolicy) { TestItem dummy; for (int i = 0; i < a.Length; ++i) { string s = StringFromInt(a[i]); tree.Insert(new TestItem(s, i), dupPolicy, out dummy); #if DEBUG tree.Validate(); #endif //DEBUG } } private string StringFromInt(int i) { return string.Format("e{0}", i); } /// <summary> /// Insert LENGTH items in random order into the tree and validate /// it. Do this ITER times. /// </summary> [Test] public void InsertRandom() { for (int iter = 0; iter < ITERATIONS; ++iter) { tree = new RedBlackTree<TestItem>(new DataComparer()); int[] a = CreateRandomArray(iter, LENGTH, LENGTH * 10, true); InsertArray(a, DuplicatePolicy.InsertLast); #if DEBUG tree.Validate(); #endif //DEBUG CheckAllIndices(); Assert.AreEqual(LENGTH, tree.ElementCount, "Wrong number of items in the tree."); } } /// <summary> /// Insert LENGTH items in random order into the tree and then find them all /// Do this ITER times. /// </summary> [Test] public void FindRandom() { for (int iter = 0; iter < ITERATIONS; ++iter) { tree = new RedBlackTree<TestItem>(new DataComparer()); int[] a = CreateRandomArray(iter + 1000, LENGTH, LENGTH * 10, false); InsertArray(a, DuplicatePolicy.InsertLast); #if DEBUG tree.Validate(); #endif //DEBUG Assert.AreEqual(LENGTH, tree.ElementCount, "Wrong number of items in the tree."); for (int el = 0; el < a.Length; ++el) { FindOnlyKey(StringFromInt(a[el]), el); } } } /// <summary> /// Insert LENGTH items in random order into the tree using the "replace" policy, /// and then find them all. /// Do this ITER times. /// </summary> [Test] public void ReplaceFindRandom() { for (int iter = 0; iter < ITERATIONS; ++iter) { tree = new RedBlackTree<TestItem>(new DataComparer()); int[] a = CreateRandomArray(iter + 2000, LENGTH, LENGTH / 5, true); InsertArray(a, DuplicatePolicy.ReplaceFirst); #if DEBUG tree.Validate(); #endif //DEBUG CheckAllIndices(); for (int el = 0; el < a.Length; ++el) { FindOnlyKey(StringFromInt(a[el]), Array.LastIndexOf(a, a[el])); } } } /// <summary> /// Insert LENGTH items in random order into the tree using the "replace" policy, /// and then find them all. /// Do this ITER times. /// </summary> [Test] public void DoNothingFindRandom() { for (int iter = 0; iter < ITERATIONS; ++iter) { tree = new RedBlackTree<TestItem>(new DataComparer()); int[] a = CreateRandomArray(iter + 3000, LENGTH, LENGTH / 5, true); InsertArray(a, DuplicatePolicy.DoNothing); #if DEBUG tree.Validate(); #endif //DEBUG CheckAllIndices(); for (int el = 0; el < a.Length; ++el) { FindOnlyKey(StringFromInt(a[el]), Array.IndexOf(a, a[el])); } } } /// <summary> /// Insert LENGTH items in random order into the tree using the "replace" policy, /// and then find them all. /// Do this ITER times. /// </summary> [Test] public void InsertFirstFindRandom() { for (int iter = 0; iter < ITERATIONS; ++iter) { tree = new RedBlackTree<TestItem>(new DataComparer()); int[] a = CreateRandomArray(iter + 3000, LENGTH, LENGTH / 5, true); InsertArray(a, DuplicatePolicy.InsertFirst); #if DEBUG tree.Validate(); #endif //DEBUG CheckAllIndices(); Assert.AreEqual(LENGTH, tree.ElementCount, "Element count is wrong."); for (int el = 0; el < a.Length; ++el) { FindFirstKey(StringFromInt(a[el]), Array.LastIndexOf(a, a[el])); FindLastKey(StringFromInt(a[el]), Array.IndexOf(a, a[el])); } } } /// <summary> /// Insert LENGTH items in random order into the tree using the "replace" policy, /// and then find them all. /// Do this ITER times. /// </summary> [Test] public void InsertLastFindRandom() { for (int iter = 0; iter < ITERATIONS; ++iter) { tree = new RedBlackTree<TestItem>(new DataComparer()); int[] a = CreateRandomArray(iter + 4000, LENGTH, LENGTH / 5, true); InsertArray(a, DuplicatePolicy.InsertLast); #if DEBUG tree.Validate(); #endif //DEBUG CheckAllIndices(); Assert.AreEqual(LENGTH, tree.ElementCount, "Element count is wrong."); for (int el = 0; el < a.Length; ++el) { FindFirstKey(StringFromInt(a[el]), Array.IndexOf(a, a[el])); FindLastKey(StringFromInt(a[el]), Array.LastIndexOf(a, a[el])); } } } /// <summary> /// Insert and delete items from the tree at random, finally removing all /// the items that are in the tree. Validate the tree after each step. /// </summary> [Test] public void DeleteRandom() { for (int iter = 0; iter < ITERATIONS / 10; ++iter) { tree = new RedBlackTree<TestItem>(new DataComparer()); bool[] a = new bool[LENGTH]; Random rand = new Random(iter + 5000); TestItem itemFound; for (int i = 0; i < LENGTH * 10; ++i) { int v = rand.Next(LENGTH); string key = StringFromInt(v); if (a[v]) { // Already in the tree. Make sure we can find it, then delete it. bool b = tree.Find(new TestItem(key), true, false, out itemFound); Assert.IsTrue(b, "Couldn't find key in tree"); Assert.AreEqual(v, itemFound.data, "Data is incorrect"); b = tree.Delete(new TestItem(key), true, out itemFound); Assert.IsTrue(b, "Couldn't delete key in tree"); Assert.AreEqual(v, itemFound.data, "Data is incorrect"); #if DEBUG tree.Validate(); #endif //DEBUG CheckAllIndices(); a[v] = false; } else if (i < LENGTH * 7) { // Not in tree. Try to find and delete it. Then Add it. bool b = tree.Find(new TestItem(key), true, false, out itemFound); Assert.IsFalse(b, "Key shouldn't be in tree"); b = tree.Delete(new TestItem(key), true, out itemFound); Assert.IsFalse(b); TestItem dummy; b = tree.Insert(new TestItem(key, v), DuplicatePolicy.ReplaceFirst, out dummy); Assert.IsTrue(b, "Key shouldn't be in tree"); #if DEBUG tree.Validate(); #endif //DEBUG CheckAllIndices(); a[v] = true; } } for (int v = 0; v < LENGTH; ++v) { string key = StringFromInt(v); if (a[v]) { // Already in the tree. Make sure we can find it, then delete it. bool b = tree.Find(new TestItem(key), true, false, out itemFound); Assert.IsTrue(b, "Couldn't find key in tree"); Assert.AreEqual(v, itemFound.data, "Data is incorrect"); b = tree.Delete(new TestItem(key), true, out itemFound); Assert.IsTrue(b, "Couldn't delete key in tree"); Assert.AreEqual(v, itemFound.data, "Data is incorrect"); #if DEBUG tree.Validate(); #endif //DEBUG a[v] = false; } } } } [Test] public void ChangeDuringEnumerate() { TestItem dummy; tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("foo", 3); InsertValidate("bar", 4); InsertValidate("bingo", 5); InsertValidate("biff", 6); InsertValidate("zip", 7); InsertValidate("zap", 8); int i = 0; try { foreach (TestItem item in tree) { ++i; if (i == 4) InsertValidate("hello", 23); } Assert.Fail("Should have thrown exception"); } catch (Exception e) { Assert.IsTrue(e is InvalidOperationException); } Assert.AreEqual(4, i); // should have stopped right away. Assert.AreEqual(7, tree.ElementCount); // element should have been found. FindOnlyKey("hello", 23); // element should have been inserted. #if DEBUG tree.Validate(); #endif //DEBUG i = 0; try { foreach (TestItem item in tree.EnumerateRangeReversed(tree.BoundedRangeTester(true, new TestItem("biff", 0), true, new TestItem("zap", 0)))) { ++i; if (i == 3) DeletePrintValidate("hello", 23); } Assert.Fail("Should have thrown exception"); } catch (Exception e) { Assert.IsTrue(e is InvalidOperationException); } Assert.AreEqual(3, i); // should have stopped right away. Assert.AreEqual(6, tree.ElementCount); // element should have been deleted. Assert.IsFalse(tree.Find(new TestItem("hello", 0), true, false, out dummy)); #if DEBUG tree.Validate(); #endif //DEBUG } [Test] public void Clone() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("foo", 3); InsertValidate("bar", 4); InsertValidate("bingo", 5); InsertValidate("biff", 6); InsertValidate("zip", 7); InsertValidate("zap", 8); RedBlackTree<TestItem> clone = tree.Clone(); #if DEBUG clone.Validate(); #endif //DEBUG InsertValidate("a", 51); InsertValidate("b", 52); InsertValidate("c", 53); InsertValidate("d", 54); #if DEBUG clone.Validate(); #endif //DEBUG Assert.AreEqual(6, clone.ElementCount); string[] s_array = { "bar", "biff", "bingo", "foo", "zap", "zip" }; int i = 0; foreach(TestItem item in clone) { Assert.AreEqual(s_array[i], item.key); ++i; } tree = new RedBlackTree<TestItem>(new DataComparer()); clone = tree.Clone(); Assert.AreEqual(0, clone.ElementCount); #if DEBUG clone.Validate(); #endif //DEBUG } [Test] public void GetByIndexExceptions() { tree = new RedBlackTree<TestItem>(new DataComparer()); InsertValidate("foo", 3); InsertValidate("bar", 4); InsertValidate("bingo", 5); InsertValidate("biff", 6); InsertValidate("zip", 7); InsertValidate("zap", 8); try { TestItem item = tree.GetItemByIndex(-1); Assert.Fail("should throw"); } catch (Exception e) { Assert.IsTrue(e is ArgumentOutOfRangeException); } try { TestItem item = tree.GetItemByIndex(6); Assert.Fail("should throw"); } catch (Exception e) { Assert.IsTrue(e is ArgumentOutOfRangeException); } try { TestItem item = tree.GetItemByIndex(Int32.MaxValue); Assert.Fail("should throw"); } catch (Exception e) { Assert.IsTrue(e is ArgumentOutOfRangeException); } try { TestItem item = tree.GetItemByIndex(Int32.MinValue); Assert.Fail("should throw"); } catch (Exception e) { Assert.IsTrue(e is ArgumentOutOfRangeException); } tree = new RedBlackTree<TestItem>(new DataComparer()); try { TestItem item = tree.GetItemByIndex(0); Assert.Fail("should throw"); } catch (Exception e) { Assert.IsTrue(e is ArgumentOutOfRangeException); } } } }
#region License // // Command Line Library: CommandLineText.cs // // Author: // Giacomo Stelluti Scala (gsscoder@gmail.com) // Contributor(s): // Steven Evans // // Copyright (C) 2005 - 2012 Giacomo Stelluti Scala // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #endregion #region Using Directives using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; #endregion namespace CommandLine.Text { #region *SentenceBuilder /// <summary> /// Models an abstract sentence builder. /// </summary> public abstract class BaseSentenceBuilder { /// <summary> /// Creates the built in sentence builder. /// </summary> /// <returns> /// The built in sentence builder. /// </returns> public static BaseSentenceBuilder CreateBuiltIn () { return new EnglishSentenceBuilder (); } /// <summary> /// Gets a string containing word 'option'. /// </summary> /// <value> /// The word 'option'. /// </value> public abstract string OptionWord { get; } /// <summary> /// Gets a string containing the word 'and'. /// </summary> /// <value> /// The word 'and'. /// </value> public abstract string AndWord { get; } /// <summary> /// Gets a string containing the sentence 'required option missing'. /// </summary> /// <value> /// The sentence 'required option missing'. /// </value> public abstract string RequiredOptionMissingText { get; } /// <summary> /// Gets a string containing the sentence 'violates format'. /// </summary> /// <value> /// The sentence 'violates format'. /// </value> public abstract string ViolatesFormatText { get; } /// <summary> /// Gets a string containing the sentence 'violates mutual exclusiveness'. /// </summary> /// <value> /// The sentence 'violates mutual exclusiveness'. /// </value> public abstract string ViolatesMutualExclusivenessText { get; } /// <summary> /// Gets a string containing the error heading text. /// </summary> /// <value> /// The error heading text. /// </value> public abstract string ErrorsHeadingText { get; } } /// <summary> /// Models an english sentence builder, currently the default one. /// </summary> public class EnglishSentenceBuilder : BaseSentenceBuilder { /// <summary> /// Gets a string containing word 'option' in english. /// </summary> /// <value> /// The word 'option' in english. /// </value> public override string OptionWord { get { return "option"; } } /// <summary> /// Gets a string containing the word 'and' in english. /// </summary> /// <value> /// The word 'and' in english. /// </value> public override string AndWord { get { return "and"; } } /// <summary> /// Gets a string containing the sentence 'required option missing' in english. /// </summary> /// <value> /// The sentence 'required option missing' in english. /// </value> public override string RequiredOptionMissingText { get { return "required option is missing"; } } /// <summary> /// Gets a string containing the sentence 'violates format' in english. /// </summary> /// <value> /// The sentence 'violates format' in english. /// </value> public override string ViolatesFormatText { get { return "violates format"; } } /// <summary> /// Gets a string containing the sentence 'violates mutual exclusiveness' in english. /// </summary> /// <value> /// The sentence 'violates mutual exclusiveness' in english. /// </value> public override string ViolatesMutualExclusivenessText { get { return "violates mutual exclusiveness"; } } /// <summary> /// Gets a string containing the error heading text in english. /// </summary> /// <value> /// The error heading text in english. /// </value> public override string ErrorsHeadingText { get { return "ERROR(S):"; } } } #endregion #region Secondary Helpers /// <summary> /// Models the copyright informations part of an help text. /// You can assign it where you assign any <see cref="System.String"/> instance. /// </summary> public class CopyrightInfo { private readonly bool _isSymbolUpper; private readonly int[] _years; private readonly string? _author; private static readonly string _defaultCopyrightWord = "Copyright"; private static readonly string _symbolLower = "(c)"; private static readonly string _symbolUpper = "(C)"; private StringBuilder _builder; /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.CopyrightInfo"/> class /// specifying author and year. /// </summary> /// <param name="author">The company or person holding the copyright.</param> /// <param name="year">The year of coverage of copyright.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="author"/> is null or empty string.</exception> public CopyrightInfo (string author, int year) : this(true, author, new int[] { year }) { } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.CopyrightInfo"/> class /// specifying author and years. /// </summary> /// <param name="author">The company or person holding the copyright.</param> /// <param name="years">The years of coverage of copyright.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="author"/> is null or empty string.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown when parameter <paramref name="years"/> is not supplied.</exception> public CopyrightInfo (string author, params int[] years) : this(true, author, years) { } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.CopyrightInfo"/> class /// specifying symbol case, author and years. /// </summary> /// <param name="isSymbolUpper">The case of the copyright symbol.</param> /// <param name="author">The company or person holding the copyright.</param> /// <param name="years">The years of coverage of copyright.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="author"/> is null or empty string.</exception> /// <exception cref="System.ArgumentOutOfRangeException">Thrown when parameter <paramref name="years"/> is not supplied.</exception> public CopyrightInfo (bool isSymbolUpper, string author, params int[] years) { Assumes.NotNullOrEmpty (author, "author"); Assumes.NotZeroLength (years, "years"); const int extraLength = 10; _isSymbolUpper = isSymbolUpper; _author = author; _years = years; _builder = new StringBuilder (CopyrightWord.Length + author.Length + (4 * years.Length) + extraLength); } /// <summary> /// Returns the copyright informations as a <see cref="System.String"/>. /// </summary> /// <returns>The <see cref="System.String"/> that contains the copyright informations.</returns> public override string ToString() => $"{CopyrightWord} {(_isSymbolUpper ? _symbolUpper : _symbolLower)} {FormatYears(_years)} {_author}"; /// <summary> /// Converts the copyright informations to a <see cref="System.String"/>. /// </summary> /// <param name="info">This <see cref="CommandLine.Text.CopyrightInfo"/> instance.</param> /// <returns>The <see cref="System.String"/> that contains the copyright informations.</returns> public static implicit operator string(CopyrightInfo info) => info.ToString(); /// <summary> /// When overridden in a derived class, allows to specify a different copyright word. /// </summary> protected virtual string CopyrightWord => _defaultCopyrightWord; /// <summary> /// When overridden in a derived class, allows to specify a new algorithm to render copyright years /// as a <see cref="System.String"/> instance. /// </summary> /// <param name="years">A <see cref="System.Int32"/> array of years.</param> /// <returns>A <see cref="System.String"/> instance with copyright years.</returns> protected virtual string FormatYears(int[] years) { if (years.Length == 1) { return years[0].ToString(CultureInfo.InvariantCulture); } var yearsPart = new StringBuilder(years.Length * 6); for (int i = 0; i < years.Length; i++) { yearsPart.Append (years [i].ToString (CultureInfo.InvariantCulture)); int next = i + 1; if (next < years.Length) { yearsPart.Append(years[next] - years[i] > 1 ? " - " : ", "); } } return yearsPart.ToString(); } } /// <summary> /// Models the heading informations part of an help text. /// You can assign it where you assign any <see cref="System.String"/> instance. /// </summary> public class HeadingInfo { private readonly string _programName; private readonly string? _version; /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.HeadingInfo"/> class /// specifying program name. /// </summary> /// <param name="programName">The name of the program.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="programName"/> is null or empty string.</exception> public HeadingInfo(string programName) : this(programName, null) { } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.HeadingInfo"/> class /// specifying program name and version. /// </summary> /// <param name="programName">The name of the program.</param> /// <param name="version">The version of the program.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="programName"/> is null or empty string.</exception> public HeadingInfo(string programName, string? version) { Assumes.NotNullOrEmpty (programName, "programName"); _programName = programName; _version = version; } /// <summary> /// Returns the heading informations as a <see cref="System.String"/>. /// </summary> /// <returns>The <see cref="System.String"/> that contains the heading informations.</returns> public override string ToString() { var builder = new StringBuilder(_programName); if (!string.IsNullOrEmpty(_version)) { builder.Append(' '); builder.Append(_version); } return builder.ToString(); } /// <summary> /// Converts the heading informations to a <see cref="System.String"/>. /// </summary> /// <param name="info">This <see cref="CommandLine.Text.HeadingInfo"/> instance.</param> /// <returns>The <see cref="System.String"/> that contains the heading informations.</returns> public static implicit operator string(HeadingInfo info) => info.ToString(); /// <summary> /// Writes out a string and a new line using the program name specified in the constructor /// and <paramref name="message"/> parameter. /// </summary> /// <param name="message">The <see cref="System.String"/> message to write.</param> /// <param name="writer">The target <see cref="System.IO.TextWriter"/> derived type.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="message"/> is null or empty string.</exception> /// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="writer"/> is null.</exception> public void WriteMessage(string message, TextWriter writer) { Assumes.NotNullOrEmpty(message, "message"); Assumes.NotNull(writer, "writer"); var builder = new StringBuilder (_programName.Length + message.Length + 2); builder.Append(_programName); builder.Append(": "); builder.Append(message); writer.WriteLine (builder.ToString ()); } /// <summary> /// Writes out a string and a new line using the program name specified in the constructor /// and <paramref name="message"/> parameter to standard output stream. /// </summary> /// <param name="message">The <see cref="System.String"/> message to write.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="message"/> is null or empty string.</exception> public void WriteMessage (string message) { WriteMessage (message, Console.Out); } /// <summary> /// Writes out a string and a new line using the program name specified in the constructor /// and <paramref name="message"/> parameter to standard error stream. /// </summary> /// <param name="message">The <see cref="System.String"/> message to write.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="message"/> is null or empty string.</exception> public void WriteError (string message) { WriteMessage (message, Console.Error); } } /* internal static class AssemblyVersionAttributeUtil { public static string GetInformationalVersion(this AssemblyVersionAttribute attr) { var parts = attr.Version.Split('.'); if (parts.Length > 2) { return string.Format(CultureInfo.InvariantCulture, "{0}.{1}", parts[0], parts[1]); } return attr.Version; } } */ /* internal static class StringBuilderUtil { public static void AppendLineIfNotNullOrEmpty(this StringBuilder bldr, string value) { if (!string.IsNullOrEmpty(value)) { bldr.AppendLine(value); } } } */ #endregion #region Attributes public abstract class MultiLineTextAttribute : Attribute { string? _line1; string? _line2; string? _line3; string? _line4; string? _line5; public MultiLineTextAttribute(string line1) { Assumes.NotNullOrEmpty(line1, "line1"); _line1 = line1; } public MultiLineTextAttribute(string line1, string line2) : this(line1) { Assumes.NotNullOrEmpty(line2, "line2"); _line2 = line2; } public MultiLineTextAttribute(string line1, string line2, string line3) : this(line1, line2) { Assumes.NotNullOrEmpty(line3, "line3"); _line3 = line3; } public MultiLineTextAttribute(string line1, string line2, string line3, string line4) : this(line1, line2, line3) { Assumes.NotNullOrEmpty(line4, "line4"); _line4 = line4; } public MultiLineTextAttribute(string line1, string line2, string line3, string line4, string line5) : this(line1, line2, line3, line4) { Assumes.NotNullOrEmpty(line5, "line5"); _line5 = line5; } internal void AddToHelpText(HelpText helpText, bool before) { if (before) { MaybeAddPreOptionsLine(_line1); MaybeAddPreOptionsLine(_line2); MaybeAddPreOptionsLine(_line3); MaybeAddPreOptionsLine(_line4); MaybeAddPreOptionsLine(_line5); } else { MaybeAddPostOptionsLine(_line1); MaybeAddPostOptionsLine(_line2); MaybeAddPostOptionsLine(_line3); MaybeAddPostOptionsLine(_line4); MaybeAddPostOptionsLine(_line5); } void MaybeAddPreOptionsLine(string? text) { if (!string.IsNullOrEmpty(text)) { helpText.AddPreOptionsLine(text!); } } void MaybeAddPostOptionsLine(string? text) { if (!string.IsNullOrEmpty(text)) { helpText.AddPostOptionsLine(text!); } } } } [AttributeUsage(AttributeTargets.Assembly, Inherited=false), ComVisible(true)] public sealed class AssemblyLicenseAttribute : MultiLineTextAttribute { //public AssemblyLicenseAttribute(object fullText) // : base(fullText) //{ //} public AssemblyLicenseAttribute(string line1) : base(line1) { } public AssemblyLicenseAttribute(string line1, string line2) : base(line1, line2) { } public AssemblyLicenseAttribute(string line1, string line2, string line3) : base(line1, line2, line3) { } public AssemblyLicenseAttribute(string line1, string line2, string line3, string line4) : base(line1, line2, line3, line4) { } public AssemblyLicenseAttribute(string line1, string line2, string line3, string line4, string line5) : base(line1, line2, line3, line4, line5) { } } [AttributeUsage(AttributeTargets.Assembly, Inherited=false), ComVisible(true)] public sealed class AssemblyUsageAttribute : MultiLineTextAttribute { //public AssemblyUsageAttribute(object fullText) // : base(fullText) //{ //} public AssemblyUsageAttribute(string line1) : base(line1) { } public AssemblyUsageAttribute(string line1, string line2) : base(line1, line2) { } public AssemblyUsageAttribute(string line1, string line2, string line3) : base(line1, line2, line3) { } public AssemblyUsageAttribute(string line1, string line2, string line3, string line4) : base(line1, line2, line3, line4) { } public AssemblyUsageAttribute(string line1, string line2, string line3, string line4, string line5) : base(line1, line2, line3, line4, line5) { } } /*[AttributeUsage(AttributeTargets.Assembly, Inherited=false), ComVisible(true)] public sealed class AssemblyInformationalVersionAttribute : Attribute { public string Version { get; private set; } public AssemblyInformationalVersionAttribute (string version) { this.Version = version; } }*/ #endregion #region HelpText /// <summary> /// Handle parsing errors delegate. /// </summary> public delegate void HandleParsingErrorsDelegate(HelpText current); /// <summary> /// Provides data for the FormatOptionHelpText event. /// </summary> public class FormatOptionHelpTextEventArgs : EventArgs { private readonly BaseOptionAttribute _option; /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.FormatOptionHelpTextEventArgs"/> class. /// </summary> /// <param name="option">Option to format.</param> public FormatOptionHelpTextEventArgs (BaseOptionAttribute option) { _option = option; } /// <summary> /// Gets the option to format. /// </summary> public BaseOptionAttribute Option { get { return _option; } } } /// <summary> /// Models an help text and collects related informations. /// You can assign it in place of a <see cref="System.String"/> instance. /// </summary> public class HelpText { private const int _builderCapacity = 128; private const int _defaultMaximumLength = 80; // default console width private int? _maximumDisplayWidth; private string? _heading; private string? _copyright; private bool _additionalNewLineAfterOption; private StringBuilder _preOptionsHelp; private StringBuilder? _optionsHelp; private StringBuilder _postOptionsHelp; private BaseSentenceBuilder _sentenceBuilder; private static readonly string _defaultRequiredWord = "Required."; private bool _addDashesToOption = false; /// <summary> /// Message type enumeration. /// </summary> public enum MessageEnum : short { /// <summary> /// Parsing error due to a violation of the format of an option value. /// </summary> ParsingErrorViolatesFormat, /// <summary> /// Parsing error due to a violation of mandatory option. /// </summary> ParsingErrorViolatesRequired, /// <summary> /// Parsing error due to a violation of the mutual exclusiveness of two or more option. /// </summary> ParsingErrorViolatesExclusiveness } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class. /// </summary> public HelpText () { _preOptionsHelp = new StringBuilder(_builderCapacity); _postOptionsHelp = new StringBuilder(_builderCapacity); _sentenceBuilder = BaseSentenceBuilder.CreateBuiltIn(); } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class /// specifying the sentence builder. /// </summary> /// <param name="sentenceBuilder"> /// A <see cref="BaseSentenceBuilder"/> instance. /// </param> public HelpText (BaseSentenceBuilder sentenceBuilder) : this() { Assumes.NotNull (sentenceBuilder, "sentenceBuilder"); _sentenceBuilder = sentenceBuilder; } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class /// specifying heading informations. /// </summary> /// <param name="heading">A string with heading information or /// an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param> /// <exception cref="System.ArgumentException">Thrown when parameter <paramref name="heading"/> is null or empty string.</exception> public HelpText (string heading) : this() { Assumes.NotNullOrEmpty (heading, "heading"); _heading = heading; } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class /// specifying the sentence builder and heading informations. /// </summary> /// <param name="sentenceBuilder"> /// A <see cref="BaseSentenceBuilder"/> instance. /// </param> /// <param name="heading"> /// A string with heading information or /// an instance of <see cref="CommandLine.Text.HeadingInfo"/>. /// </param> public HelpText (BaseSentenceBuilder sentenceBuilder, string heading) : this(heading) { Assumes.NotNull (sentenceBuilder, "sentenceBuilder"); _sentenceBuilder = sentenceBuilder; } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class /// specifying heading and copyright informations. /// </summary> /// <param name="heading">A string with heading information or /// an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param> /// <param name="copyright">A string with copyright information or /// an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param> /// <exception cref="System.ArgumentException">Thrown when one or more parameters <paramref name="heading"/> are null or empty strings.</exception> public HelpText (string heading, string copyright) : this() { Assumes.NotNullOrEmpty (heading, "heading"); Assumes.NotNullOrEmpty (copyright, "copyright"); _heading = heading; _copyright = copyright; } public HelpText (BaseSentenceBuilder sentenceBuilder, string heading, string copyright) : this(heading, copyright) { Assumes.NotNull (sentenceBuilder, "sentenceBuilder"); _sentenceBuilder = sentenceBuilder; } /// <summary> /// Initializes a new instance of the <see cref="CommandLine.Text.HelpText"/> class /// specifying heading and copyright informations. /// </summary> /// <param name="heading">A string with heading information or /// an instance of <see cref="CommandLine.Text.HeadingInfo"/>.</param> /// <param name="copyright">A string with copyright information or /// an instance of <see cref="CommandLine.Text.CopyrightInfo"/>.</param> /// <param name="options">The instance that collected command line arguments parsed with <see cref="CommandLine.CommandLineParser"/> class.</param> /// <exception cref="System.ArgumentException">Thrown when one or more parameters <paramref name="heading"/> are null or empty strings.</exception> public HelpText (string heading, string copyright, object options) : this() { Assumes.NotNullOrEmpty (heading, "heading"); Assumes.NotNullOrEmpty (copyright, "copyright"); Assumes.NotNull (options, "options"); _heading = heading; _copyright = copyright; AddOptions (options); } public HelpText (BaseSentenceBuilder sentenceBuilder, string heading, string copyright, object options) : this(heading, copyright, options) { Assumes.NotNull (sentenceBuilder, "sentenceBuilder"); _sentenceBuilder = sentenceBuilder; } /// <summary> /// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults. /// </summary> /// <returns> /// An instance of <see cref="CommandLine.Text.HelpText"/> class. /// </returns> /// <param name='options'> /// The instance that collected command line arguments parsed with <see cref="CommandLine.CommandLineParser"/> class. /// </param> public static HelpText AutoBuild(object options) => AutoBuild(options, null); /// <summary> /// Creates a new instance of the <see cref="CommandLine.Text.HelpText"/> class using common defaults. /// </summary> /// <returns> /// An instance of <see cref="CommandLine.Text.HelpText"/> class. /// </returns> /// <param name='options'> /// The instance that collected command line arguments parsed with <see cref="CommandLine.CommandLineParser"/> class. /// </param> /// <param name='errDelegate'> /// A delegate used to customize the text block for reporting parsing errors. /// </param> public static HelpText AutoBuild(object options, HandleParsingErrorsDelegate? errDelegate) { var title = ReflectionUtil.GetAttribute<AssemblyTitleAttribute>(); if (title == null) { throw new InvalidOperationException("HelpText::AutoBuild() requires that you define AssemblyTitleAttribute."); } var version = ReflectionUtil.GetAttribute<AssemblyInformationalVersionAttribute>(); if (version == null) { throw new InvalidOperationException("HelpText::AutoBuild() requires that you define AssemblyInformationalVersionAttribute."); } var copyright = ReflectionUtil.GetAttribute<AssemblyCopyrightAttribute>(); if (copyright == null) { throw new InvalidOperationException("HelpText::AutoBuild() requires that you define AssemblyCopyrightAttribute."); } var auto = new HelpText { Heading = new HeadingInfo(Path.GetFileNameWithoutExtension(title.Title), version.InformationalVersion), Copyright = copyright.Copyright, AdditionalNewLineAfterOption = true, AddDashesToOption = true }; if (errDelegate != null) { var typedTarget = options as CommandLineOptionsBase; if (typedTarget != null) { errDelegate(auto); } } var license = ReflectionUtil.GetAttribute<AssemblyLicenseAttribute>(); if (license != null) { //auto.AddPreOptionsLine(license.FullText); license.AddToHelpText(auto, true); } var usage = ReflectionUtil.GetAttribute<AssemblyUsageAttribute>(); if (usage != null) { //auto.AddPreOptionsLine(usage.FullText); usage.AddToHelpText(auto, true); } auto.AddOptions(options); return auto; } public static void DefaultParsingErrorsHandler(CommandLineOptionsBase options, HelpText current) { if (options.InternalLastPostParsingState.Errors.Count > 0) { var errors = current.RenderParsingErrorsText(options, 2); // indent with two spaces if (!string.IsNullOrEmpty(errors)) { current.AddPreOptionsLine(string.Concat(Environment.NewLine, current.SentenceBuilder.ErrorsHeadingText)); //current.AddPreOptionsLine(errors); var lines = errors.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); foreach (var line in lines) { current.AddPreOptionsLine(line); } } } } /// <summary> /// Sets the heading information string. /// You can directly assign a <see cref="CommandLine.Text.HeadingInfo"/> instance. /// </summary> public string Heading { set { Assumes.NotNullOrEmpty (value, "value"); _heading = value; } } /// <summary> /// Sets the copyright information string. /// You can directly assign a <see cref="CommandLine.Text.CopyrightInfo"/> instance. /// </summary> public string Copyright { set { Assumes.NotNullOrEmpty (value, "value"); _copyright = value; } } /// <summary> /// Gets or sets the maximum width of the display. This determines word wrap when displaying the text. /// </summary> /// <value>The maximum width of the display.</value> public int MaximumDisplayWidth { get { return _maximumDisplayWidth.HasValue ? _maximumDisplayWidth.Value : _defaultMaximumLength; } set { _maximumDisplayWidth = value; } } /// <summary> /// Gets or sets the format of options for adding or removing dashes. /// It modifies behavior of <see cref="AddOptions(object)"/> method. /// </summary> public bool AddDashesToOption { get { return _addDashesToOption; } set { _addDashesToOption = value; } } /// <summary> /// Gets or sets whether to add an additional line after the description of the option. /// </summary> public bool AdditionalNewLineAfterOption { get { return _additionalNewLineAfterOption; } set { _additionalNewLineAfterOption = value; } } public BaseSentenceBuilder SentenceBuilder { get { return _sentenceBuilder; } } /// <summary> /// Adds a text line after copyright and before options usage informations. /// </summary> /// <param name="value">A <see cref="System.String"/> instance.</param> /// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="value"/> is null or empty string.</exception> public void AddPreOptionsLine (string value) { AddPreOptionsLine (value, MaximumDisplayWidth); } private void AddPreOptionsLine (string value, int maximumLength) { AddLine (_preOptionsHelp, value, maximumLength); } /// <summary> /// Adds a text line at the bottom, after options usage informations. /// </summary> /// <param name="value">A <see cref="System.String"/> instance.</param> /// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="value"/> is null or empty string.</exception> public void AddPostOptionsLine (string value) { AddLine (_postOptionsHelp, value); } /// <summary> /// Adds a text block with options usage informations. /// </summary> /// <param name="options">The instance that collected command line arguments parsed with <see cref="CommandLine.CommandLineParser"/> class.</param> /// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception> public void AddOptions (object options) { AddOptions (options, _defaultRequiredWord); } /// <summary> /// Adds a text block with options usage informations. /// </summary> /// <param name="options">The instance that collected command line arguments parsed with the <see cref="CommandLine.CommandLineParser"/> class.</param> /// <param name="requiredWord">The word to use when the option is required.</param> /// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception> /// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="requiredWord"/> is null or empty string.</exception> public void AddOptions (object options, string requiredWord) { Assumes.NotNull (options, "options"); Assumes.NotNullOrEmpty (requiredWord, "requiredWord"); AddOptions (options, requiredWord, MaximumDisplayWidth); } /// <summary> /// Adds a text block with options usage informations. /// </summary> /// <param name="options">The instance that collected command line arguments parsed with the <see cref="CommandLine.CommandLineParser"/> class.</param> /// <param name="requiredWord">The word to use when the option is required.</param> /// <param name="maximumLength">The maximum length of the help documentation.</param> /// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="options"/> is null.</exception> /// <exception cref="System.ArgumentNullException">Thrown when parameter <paramref name="requiredWord"/> is null or empty string.</exception> public void AddOptions(object options, string requiredWord, int maximumLength) { Assumes.NotNull (options, "options"); Assumes.NotNullOrEmpty (requiredWord, "requiredWord"); var optionList = ReflectionUtil.RetrievePropertyAttributeList<BaseOptionAttribute> (options); var optionHelp = ReflectionUtil.RetrieveMethodAttributeOnly<HelpOptionAttribute> (options); if (optionHelp != null) { optionList.Add (optionHelp); } if (optionList.Count == 0) { return; } int maxLength = GetMaxLength(optionList); _optionsHelp = new StringBuilder(_builderCapacity); int remainingSpace = maximumLength - (maxLength + 6); foreach (BaseOptionAttribute option in optionList) { AddOption(requiredWord, maxLength, option, remainingSpace); } } /// <summary> /// Builds a string that contains a parsing error message. /// </summary> /// <param name="options"> /// An options target <see cref="CommandLineOptionsBase"/> instance that collected command line arguments parsed with the <see cref="CommandLine.CommandLineParser"/> class. /// </param> /// <param name="indent">The level of indentation.</param> /// <returns> /// The <see cref="System.String"/> that contains the parsing error message. /// </returns> public string RenderParsingErrorsText (CommandLineOptionsBase options, int indent) { if (options.InternalLastPostParsingState.Errors.Count == 0) { return string.Empty; } var text = new StringBuilder (); foreach (var e in options.InternalLastPostParsingState.Errors) { var line = new StringBuilder (); line.Append (StringUtil.Spaces (indent)); if (!string.IsNullOrEmpty(e.BadOption.ShortName)) { line.Append ('-'); line.Append (e.BadOption.ShortName); if (!string.IsNullOrEmpty(e.BadOption.LongName)) { line.Append('/'); } } if (!string.IsNullOrEmpty(e.BadOption.LongName)) { line.Append ("--"); line.Append (e.BadOption.LongName); } line.Append (" "); if (e.ViolatesRequired) { line.Append (_sentenceBuilder.RequiredOptionMissingText); } else { line.Append (_sentenceBuilder.OptionWord); } if (e.ViolatesFormat) { line.Append (" "); line.Append (_sentenceBuilder.ViolatesFormatText); } if (e.ViolatesMutualExclusiveness) { if (e.ViolatesFormat || e.ViolatesRequired) { line.Append (" "); line.Append (_sentenceBuilder.AndWord); } line.Append (" "); line.Append (_sentenceBuilder.ViolatesMutualExclusivenessText); } line.Append ('.'); text.AppendLine (line.ToString ()); } return text.ToString (); } private void AddOption (string requiredWord, int maxLength, BaseOptionAttribute option, int widthOfHelpText) { // Only called by AddOption, after setting _optionsHelp _optionsHelp!.Append(" "); StringBuilder optionName = new StringBuilder (maxLength); if (option.HasShortName) { if (_addDashesToOption) { optionName.Append ('-'); } optionName.AppendFormat ("{0}", option.ShortName); if (option.HasLongName) { optionName.Append (", "); } } if (option.HasLongName) { if (_addDashesToOption) { optionName.Append ("--"); } optionName.AppendFormat ("{0}", option.LongName); } _optionsHelp.Append(optionName.Length < maxLength ? optionName.ToString().PadRight(maxLength) : optionName.ToString()); _optionsHelp.Append(" "); if (option.Required) { option.HelpText = String.Format ("{0} ", requiredWord) + option.HelpText; } if (!string.IsNullOrEmpty (option.HelpText)) { do { int wordBuffer = 0; var words = option.HelpText!.Split (new[] {' '}); for (int i = 0; i < words.Length; i++) { if (words [i].Length < (widthOfHelpText - wordBuffer)) { _optionsHelp.Append (words [i]); wordBuffer += words [i].Length; if ((widthOfHelpText - wordBuffer) > 1 && i != words.Length - 1) { _optionsHelp.Append (" "); wordBuffer++; } } else if (words [i].Length >= widthOfHelpText && wordBuffer == 0) { _optionsHelp.Append (words[i].Substring(0, widthOfHelpText)); wordBuffer = widthOfHelpText; break; } else { break; } } option.HelpText = option.HelpText.Substring(Math.Min(wordBuffer, option.HelpText.Length)).Trim(); if (option.HelpText.Length > 0) { _optionsHelp.Append(Environment.NewLine); _optionsHelp.Append(new string (' ', maxLength + 6)); } } while (option.HelpText.Length > widthOfHelpText); } _optionsHelp.Append(option.HelpText); _optionsHelp.Append(Environment.NewLine); if (_additionalNewLineAfterOption) { _optionsHelp.Append(Environment.NewLine); } } /// <summary> /// Returns the help informations as a <see cref="System.String"/>. /// </summary> /// <returns>The <see cref="System.String"/> that contains the help informations.</returns> public override string ToString () { var builder = new StringBuilder(); builder.Append(_heading); if (!string.IsNullOrEmpty(_copyright)) { builder.Append(Environment.NewLine); builder.Append(_copyright); } if (_preOptionsHelp.Length > 0) { builder.Append(Environment.NewLine); builder.Append(_preOptionsHelp); } if (_optionsHelp != null && _optionsHelp.Length > 0) { builder.Append(Environment.NewLine); builder.Append(Environment.NewLine); builder.Append(_optionsHelp); } if (_postOptionsHelp.Length > 0) { builder.Append(Environment.NewLine); builder.Append(_postOptionsHelp); } return builder.ToString(); } /// <summary> /// Converts the help informations to a <see cref="System.String"/>. /// </summary> /// <param name="info">This <see cref="CommandLine.Text.HelpText"/> instance.</param> /// <returns>The <see cref="System.String"/> that contains the help informations.</returns> public static implicit operator string (HelpText info) { return info.ToString (); } private void AddLine (StringBuilder builder, string value) { Assumes.NotNull (value, "value"); AddLine (builder, value, MaximumDisplayWidth); } private static void AddLine (StringBuilder builder, string value, int maximumLength) { Assumes.NotNull (value, "value"); if (builder.Length > 0) { builder.Append (Environment.NewLine); } do { int wordBuffer = 0; string[] words = value.Split (new[] { ' ' }); for (int i = 0; i < words.Length; i++) { if (words [i].Length < (maximumLength - wordBuffer)) { builder.Append (words [i]); wordBuffer += words [i].Length; if ((maximumLength - wordBuffer) > 1 && i != words.Length - 1) { builder.Append (" "); wordBuffer++; } } else if (words [i].Length >= maximumLength && wordBuffer == 0) { builder.Append (words [i].Substring (0, maximumLength)); wordBuffer = maximumLength; break; } else { break; } } value = value.Substring (Math.Min (wordBuffer, value.Length)); if (value.Length > 0) { builder.Append (Environment.NewLine); } } while (value.Length > maximumLength); builder.Append (value); } private static int GetLength (string value) { if (value == null) { return 0; } return value.Length; } private static int GetLength (StringBuilder value) { if (value == null) { return 0; } return value.Length; } //ex static private int GetMaxLength (IList<BaseOptionAttribute> optionList) { int length = 0; foreach (BaseOptionAttribute option in optionList) { int optionLength = 0; bool hasShort = option.HasShortName; bool hasLong = option.HasLongName; if (hasShort) { optionLength += option.ShortName!.Length; if (AddDashesToOption) { optionLength++; } } if (hasLong) { optionLength += option.LongName!.Length; if (AddDashesToOption) { optionLength += 2; } } if (hasShort && hasLong) { optionLength += 2; // ", " } length = Math.Max (length, optionLength); } return length; } } #endregion }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Reflection; using System.Reflection.Emit; using System.Threading; using Xunit; namespace System.Reflection.Emit.Tests { public class MethodBuilderSetReturnType { private const string TestDynamicAssemblyName = "TestDynamicAssembly"; private const string TestDynamicModuleName = "TestDynamicModule"; private const string TestDynamicTypeName = "TestDynamicType"; private const AssemblyBuilderAccess TestAssemblyBuilderAccess = AssemblyBuilderAccess.Run; private const TypeAttributes TestTypeAttributes = TypeAttributes.Abstract; private const MethodAttributes TestMethodAttributes = MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual; private const int MinStringLength = 1; private const int MaxStringLength = 128; private TypeBuilder GetTestTypeBuilder() { AssemblyName assemblyName = new AssemblyName(TestDynamicAssemblyName); AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly( assemblyName, TestAssemblyBuilderAccess); ModuleBuilder moduleBuilder = TestLibrary.Utilities.GetModuleBuilder(assemblyBuilder, TestDynamicModuleName); return moduleBuilder.DefineType(TestDynamicTypeName, TestTypeAttributes); } [Fact] public void TestWithSingleGenericParameter() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes); string[] typeParamNames = { "T" }; GenericTypeParameterBuilder[] typeParameters = builder.DefineGenericParameters(typeParamNames); Type desiredReturnType = typeParameters[0].AsType(); builder.SetReturnType(desiredReturnType); typeBuilder.CreateTypeInfo().AsType(); VerifyReturnType(builder, desiredReturnType); } [Fact] public void TestWithMultipleGenericParameters() { var methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes); string[] typeParamNames = { "T", "U" }; GenericTypeParameterBuilder[] typeParameters = builder.DefineGenericParameters(typeParamNames); Type desiredReturnType = typeParameters[1].AsType(); builder.SetReturnType(desiredReturnType); typeBuilder.CreateTypeInfo().AsType(); VerifyReturnType(builder, desiredReturnType); } [Fact] public void TestWithGenericAndNonGenericParameters() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes); string[] typeParamNames = { "T", "U" }; GenericTypeParameterBuilder[] typeParameters = builder.DefineGenericParameters(typeParamNames); Type desiredReturnType = typeof(void); builder.SetReturnType(desiredReturnType); typeBuilder.CreateTypeInfo().AsType(); VerifyReturnType(builder, desiredReturnType); } [Fact] public void TestNotSetReturnTypeOnNonGenericMethod() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); Type[] parameterTypes = new Type[] { typeof(int) }; TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes, typeof(int), parameterTypes); Type desiredReturnType = typeof(void); builder.SetReturnType(desiredReturnType); typeBuilder.CreateTypeInfo().AsType(); VerifyReturnType(builder, desiredReturnType); } [Fact] public void TestOverwriteGenericReturnTypeWithNonGenericType() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes); string[] typeParamNames = { "T", "U" }; GenericTypeParameterBuilder[] typeParameters = builder.DefineGenericParameters(typeParamNames); Type desiredReturnType = typeof(void); builder.SetReturnType(typeParameters[0].AsType()); builder.SetReturnType(desiredReturnType); typeBuilder.CreateTypeInfo().AsType(); VerifyReturnType(builder, desiredReturnType); } [Fact] public void TestOverwriteGenericReturnTypeWithGenericType() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes); string[] typeParamNames = { "T", "U" }; GenericTypeParameterBuilder[] typeParameters = builder.DefineGenericParameters(typeParamNames); Type desiredReturnType = typeParameters[1].AsType(); builder.SetReturnType(typeParameters[0].AsType()); builder.SetReturnType(desiredReturnType); typeBuilder.CreateTypeInfo().AsType(); VerifyReturnType(builder, desiredReturnType); } [Fact] public void TestOverwriteNonGenericReturnTypeWithGenericType() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); Type[] parameterTypes = new Type[] { typeof(int) }; TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes, typeof(int), parameterTypes); string[] typeParamNames = { "T", "U" }; GenericTypeParameterBuilder[] typeParameters = builder.DefineGenericParameters(typeParamNames); Type desiredReturnType = typeParameters[0].AsType(); builder.SetReturnType(desiredReturnType); typeBuilder.CreateTypeInfo().AsType(); VerifyReturnType(builder, desiredReturnType); } [Fact] public void TestAfterTypeCreated() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); Type[] parameterTypes = new Type[] { typeof(int) }; TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes, typeof(int), parameterTypes); string[] typeParamNames = { "T", "U" }; GenericTypeParameterBuilder[] typeParameters = builder.DefineGenericParameters(typeParamNames); Type desiredReturnType = typeParameters[0].AsType(); typeBuilder.CreateTypeInfo().AsType(); builder.SetReturnType(desiredReturnType); } [Fact] public void TestNotThrowsOnNull() { string methodName = null; methodName = TestLibrary.Generator.GetString(false, false, true, MinStringLength, MaxStringLength); TypeBuilder typeBuilder = GetTestTypeBuilder(); MethodBuilder builder = typeBuilder.DefineMethod(methodName, TestMethodAttributes); builder.SetReturnType(null); } private void VerifyReturnType(MethodBuilder builder, Type desiredReturnType) { MethodInfo methodInfo = builder.GetBaseDefinition(); Type actualReturnType = methodInfo.ReturnType; Assert.Equal(desiredReturnType.Name, actualReturnType.Name); Assert.True(actualReturnType.Equals(desiredReturnType)); } } }
using System; using System.Collections.Generic; namespace SimpSim.NET { public class Assembler { private readonly SymbolTable _symbolTable; private readonly InstructionByteCollection _bytes; private int _currentLineNumber; public Assembler() { _symbolTable = new SymbolTable(); _bytes = new InstructionByteCollection(); } public Instruction[] Assemble(string assemblyCode) { _symbolTable.Clear(); _bytes.Clear(); _currentLineNumber = 0; foreach (string line in GetLines(assemblyCode)) { _currentLineNumber += 1; InstructionSyntax instructionSyntax = InstructionSyntax.Parse(line, _currentLineNumber); if (!string.IsNullOrWhiteSpace(instructionSyntax.Label)) AddLabelToSymbolTable(instructionSyntax.Label); if (!string.IsNullOrWhiteSpace(instructionSyntax.Mnemonic)) AssembleLine(instructionSyntax); } Instruction[] instructions = _bytes.ToInstructions(_symbolTable); return instructions; } private IEnumerable<string> GetLines(string assemblyCode) { return (assemblyCode ?? "").Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None); } private void AddLabelToSymbolTable(string label) { _symbolTable[label] = (byte)_bytes.Count; } private void AssembleLine(InstructionSyntax instructionSyntax) { switch (instructionSyntax.Mnemonic.ToLowerInvariant()) { case "load": Load(instructionSyntax.Operands); break; case "store": Store(instructionSyntax.Operands); break; case "move": Move(instructionSyntax.Operands); break; case "addi": Addi(instructionSyntax.Operands); break; case "addf": Addf(instructionSyntax.Operands); break; case "jmpeq": JmpEQ(instructionSyntax.Operands); break; case "jmple": JmpLE(instructionSyntax.Operands); break; case "jmp": Jmp(instructionSyntax.Operands); break; case "and": And(instructionSyntax.Operands); break; case "or": Or(instructionSyntax.Operands); break; case "xor": Xor(instructionSyntax.Operands); break; case "ror": Ror(instructionSyntax.Operands); break; case "db": DataByte(instructionSyntax.Operands); break; case "org": Org(instructionSyntax.Operands); break; case "halt": Halt(instructionSyntax.Operands); break; default: throw new UnrecognizedMnemonicException(_currentLineNumber); } } private void Load(string[] operands) { if (operands.Length == 2) { if (RegisterSyntax.TryParse(operands[0], out var register) && AddressSyntax.TryParse(operands[1], _symbolTable, out var address)) { _bytes.Add(((byte)Opcode.ImmediateLoad, register.Index).Combine(), _currentLineNumber); _bytes.Add(address, _currentLineNumber); return; } if (RegisterSyntax.TryParse(operands[0], out register) && AddressSyntax.TryParse(operands[1], _symbolTable, out address, BracketExpectation.Present)) { _bytes.Add(((byte)Opcode.DirectLoad, register.Index).Combine(), _currentLineNumber); _bytes.Add(address, _currentLineNumber); return; } if (RegisterSyntax.TryParse(operands[0], out var register1) && RegisterSyntax.TryParse(operands[1], out var register2, BracketExpectation.Present)) { _bytes.Add(((byte)Opcode.IndirectLoad, (byte)0x0).Combine(), _currentLineNumber); _bytes.Add((register1.Index, register2.Index).Combine(), _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for load instruction.", _currentLineNumber); } private void Store(string[] operands) { if (operands.Length == 2) { if (RegisterSyntax.TryParse(operands[0], out var register) && AddressSyntax.TryParse(operands[1], _symbolTable, out var address, BracketExpectation.Present)) { _bytes.Add(((byte)Opcode.DirectStore, register.Index).Combine(), _currentLineNumber); _bytes.Add(address, _currentLineNumber); return; } if (RegisterSyntax.TryParse(operands[0], out var register1) && RegisterSyntax.TryParse(operands[1], out var register2, BracketExpectation.Present)) { _bytes.Add(((byte)Opcode.IndirectStore, (byte)0x0).Combine(), _currentLineNumber); _bytes.Add((register1.Index, register2.Index).Combine(), _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for store instruction.", _currentLineNumber); } private void Move(string[] operands) { if (operands.Length == 2) { if (RegisterSyntax.TryParse(operands[0], out var register1) && RegisterSyntax.TryParse(operands[1], out var register2)) { _bytes.Add(((byte)Opcode.Move, (byte)0x0).Combine(), _currentLineNumber); _bytes.Add((register2.Index, register1.Index).Combine(), _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for move instruction.", _currentLineNumber); } private void Addi(string[] operands) { if (operands.Length == 3) { if (RegisterSyntax.TryParse(operands[0], out var register1) && RegisterSyntax.TryParse(operands[1], out var register2) && RegisterSyntax.TryParse(operands[2], out var register3)) { _bytes.Add(((byte)Opcode.IntegerAdd, register1.Index).Combine(), _currentLineNumber); _bytes.Add((register2.Index, register3.Index).Combine(), _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for addi instruction.", _currentLineNumber); } private void Addf(string[] operands) { if (operands.Length == 3) { if (RegisterSyntax.TryParse(operands[0], out var register1) && RegisterSyntax.TryParse(operands[1], out var register2) && RegisterSyntax.TryParse(operands[2], out var register3)) { _bytes.Add(((byte)Opcode.FloatingPointAdd, register1.Index).Combine(), _currentLineNumber); _bytes.Add((register2.Index, register3.Index).Combine(), _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for addf instruction.", _currentLineNumber); } private void JmpEQ(string[] operands) { if (operands.Length == 2) { string[] registers = operands[0].Split('='); if (!RegisterSyntax.TryParse(registers[1], out var rightRegister) || rightRegister.Index != 0) throw new AssemblyException("Expected a comparison with R0.", _currentLineNumber); if (RegisterSyntax.TryParse(registers[0], out var leftRegister) && AddressSyntax.TryParse(operands[1], _symbolTable, out var address)) { _bytes.Add(((byte)Opcode.JumpEqual, leftRegister.Index).Combine(), _currentLineNumber); _bytes.Add(address, _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for jmpeq instruction.", _currentLineNumber); } private void JmpLE(string[] operands) { if (operands.Length == 2) { if (RegisterSyntax.TryParse(operands[0].Split('<', '=')[0], out var register) && AddressSyntax.TryParse(operands[1], _symbolTable, out var address)) { _bytes.Add(((byte)Opcode.JumpLessEqual, register.Index).Combine(), _currentLineNumber); _bytes.Add(address, _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for jmple instruction.", _currentLineNumber); } private void Jmp(string[] operands) { bool invalidSyntax = false; if (operands.Length != 1) invalidSyntax = true; else if (AddressSyntax.TryParse(operands[0], _symbolTable, out var address)) { _bytes.Add(((byte)Opcode.JumpEqual, (byte)0x0).Combine(), _currentLineNumber); _bytes.Add(address, _currentLineNumber); } else invalidSyntax = true; if (invalidSyntax) throw new AssemblyException("Expected a single address.", _currentLineNumber); } private void And(string[] operands) { if (operands.Length == 3) { if (RegisterSyntax.TryParse(operands[0], out var register1) && RegisterSyntax.TryParse(operands[1], out var register2) && RegisterSyntax.TryParse(operands[2], out var register3)) { _bytes.Add(((byte)Opcode.And, register1.Index).Combine(), _currentLineNumber); _bytes.Add((register2.Index, register3.Index).Combine(), _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for and instruction.", _currentLineNumber); } private void Or(string[] operands) { if (operands.Length == 3) { if (RegisterSyntax.TryParse(operands[0], out var register1) && RegisterSyntax.TryParse(operands[1], out var register2) && RegisterSyntax.TryParse(operands[2], out var register3)) { _bytes.Add(((byte)Opcode.Or, register1.Index).Combine(), _currentLineNumber); _bytes.Add((register2.Index, register3.Index).Combine(), _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for or instruction.", _currentLineNumber); } private void Xor(string[] operands) { if (operands.Length == 3) { if (RegisterSyntax.TryParse(operands[0], out var register1) && RegisterSyntax.TryParse(operands[1], out var register2) && RegisterSyntax.TryParse(operands[2], out var register3)) { _bytes.Add(((byte)Opcode.Xor, register1.Index).Combine(), _currentLineNumber); _bytes.Add((register2.Index, register3.Index).Combine(), _currentLineNumber); return; } } throw new AssemblyException("Invalid operands for xor instruction.", _currentLineNumber); } private void Ror(string[] operands) { if (operands.Length == 2) { if (RegisterSyntax.TryParse(operands[0], out var register) && NumberSyntax.TryParse(operands[1], out byte number)) if (number < 16) { _bytes.Add(((byte)Opcode.Ror, register.Index).Combine(), _currentLineNumber); _bytes.Add(((byte)0x0, number).Combine(), _currentLineNumber); return; } else throw new AssemblyException("Number cannot be larger than 15.", _currentLineNumber); } throw new AssemblyException("Invalid operands for ror instruction.", _currentLineNumber); } private void DataByte(string[] operands) { bool invalidSyntax = false; if (operands.Length == 0) invalidSyntax = true; else foreach (string operand in operands) if (NumberSyntax.TryParse(operand, out byte number)) _bytes.Add(number, _currentLineNumber); else if (StringLiteralSyntax.TryParse(operand, out string stringLiteral)) foreach (char c in stringLiteral) _bytes.Add((byte)c, _currentLineNumber); else { invalidSyntax = true; break; } if (invalidSyntax) throw new AssemblyException("Expected a number or string literal.", _currentLineNumber); } private void Org(string[] operands) { bool invalidSyntax = false; if (operands.Length != 1) invalidSyntax = true; else if (NumberSyntax.TryParse(operands[0], out byte number)) _bytes.OriginAddress = number; else invalidSyntax = true; if (invalidSyntax) throw new AssemblyException("Expected a single number.", _currentLineNumber); } private void Halt(string[] operands) { if (operands.Length > 0) throw new AssemblyException("Expected no operands for halt instruction.", _currentLineNumber); _bytes.Add(((byte)Opcode.Halt, (byte)0x0).Combine(), _currentLineNumber); _bytes.Add(0x00, _currentLineNumber); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Numerics.Hashing; using System.Runtime.CompilerServices; using System.Text; namespace System.Numerics { /// <summary> /// A structure encapsulating two single precision floating point values and provides hardware accelerated methods. /// </summary> public partial struct Vector2 : IEquatable<Vector2>, IFormattable { #region Public Static Properties /// <summary> /// Returns the vector (0,0). /// </summary> public static Vector2 Zero { [Intrinsic] get { return new Vector2(); } } /// <summary> /// Returns the vector (1,1). /// </summary> public static Vector2 One { [Intrinsic] get { return new Vector2(1.0f, 1.0f); } } /// <summary> /// Returns the vector (1,0). /// </summary> public static Vector2 UnitX { get { return new Vector2(1.0f, 0.0f); } } /// <summary> /// Returns the vector (0,1). /// </summary> public static Vector2 UnitY { get { return new Vector2(0.0f, 1.0f); } } #endregion Public Static Properties #region Public instance methods /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>The hash code.</returns> public override readonly int GetHashCode() { int hash = this.X.GetHashCode(); hash = HashHelpers.Combine(hash, this.Y.GetHashCode()); return hash; } /// <summary> /// Returns a boolean indicating whether the given Object is equal to this Vector2 instance. /// </summary> /// <param name="obj">The Object to compare against.</param> /// <returns>True if the Object is equal to this Vector2; False otherwise.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override readonly bool Equals(object? obj) { if (!(obj is Vector2)) return false; return Equals((Vector2)obj); } /// <summary> /// Returns a String representing this Vector2 instance. /// </summary> /// <returns>The string representation.</returns> public override readonly string ToString() { return ToString("G", CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector2 instance, using the specified format to format individual elements. /// </summary> /// <param name="format">The format of individual elements.</param> /// <returns>The string representation.</returns> public readonly string ToString(string? format) { return ToString(format, CultureInfo.CurrentCulture); } /// <summary> /// Returns a String representing this Vector2 instance, using the specified format to format individual elements /// and the given IFormatProvider. /// </summary> /// <param name="format">The format of individual elements.</param> /// <param name="formatProvider">The format provider to use when formatting elements.</param> /// <returns>The string representation.</returns> public readonly string ToString(string? format, IFormatProvider? formatProvider) { StringBuilder sb = new StringBuilder(); string separator = NumberFormatInfo.GetInstance(formatProvider).NumberGroupSeparator; sb.Append('<'); sb.Append(this.X.ToString(format, formatProvider)); sb.Append(separator); sb.Append(' '); sb.Append(this.Y.ToString(format, formatProvider)); sb.Append('>'); return sb.ToString(); } /// <summary> /// Returns the length of the vector. /// </summary> /// <returns>The vector's length.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float Length() { if (Vector.IsHardwareAccelerated) { float ls = Vector2.Dot(this, this); return MathF.Sqrt(ls); } else { float ls = X * X + Y * Y; return MathF.Sqrt(ls); } } /// <summary> /// Returns the length of the vector squared. This operation is cheaper than Length(). /// </summary> /// <returns>The vector's length squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly float LengthSquared() { if (Vector.IsHardwareAccelerated) { return Vector2.Dot(this, this); } else { return X * X + Y * Y; } } #endregion Public Instance Methods #region Public Static Methods /// <summary> /// Returns the Euclidean distance between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float Distance(Vector2 value1, Vector2 value2) { if (Vector.IsHardwareAccelerated) { Vector2 difference = value1 - value2; float ls = Vector2.Dot(difference, difference); return MathF.Sqrt(ls); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; float ls = dx * dx + dy * dy; return MathF.Sqrt(ls); } } /// <summary> /// Returns the Euclidean distance squared between the two given points. /// </summary> /// <param name="value1">The first point.</param> /// <param name="value2">The second point.</param> /// <returns>The distance squared.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float DistanceSquared(Vector2 value1, Vector2 value2) { if (Vector.IsHardwareAccelerated) { Vector2 difference = value1 - value2; return Vector2.Dot(difference, difference); } else { float dx = value1.X - value2.X; float dy = value1.Y - value2.Y; return dx * dx + dy * dy; } } /// <summary> /// Returns a vector with the same direction as the given vector, but with a length of 1. /// </summary> /// <param name="value">The vector to normalize.</param> /// <returns>The normalized vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Normalize(Vector2 value) { if (Vector.IsHardwareAccelerated) { float length = value.Length(); return value / length; } else { float ls = value.X * value.X + value.Y * value.Y; float invNorm = 1.0f / MathF.Sqrt(ls); return new Vector2( value.X * invNorm, value.Y * invNorm); } } /// <summary> /// Returns the reflection of a vector off a surface that has the specified normal. /// </summary> /// <param name="vector">The source vector.</param> /// <param name="normal">The normal of the surface being reflected off.</param> /// <returns>The reflected vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Reflect(Vector2 vector, Vector2 normal) { if (Vector.IsHardwareAccelerated) { float dot = Vector2.Dot(vector, normal); return vector - (2 * dot * normal); } else { float dot = vector.X * normal.X + vector.Y * normal.Y; return new Vector2( vector.X - 2.0f * dot * normal.X, vector.Y - 2.0f * dot * normal.Y); } } /// <summary> /// Restricts a vector between a min and max value. /// </summary> /// <param name="value1">The source vector.</param> /// <param name="min">The minimum value.</param> /// <param name="max">The maximum value.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Clamp(Vector2 value1, Vector2 min, Vector2 max) { // This compare order is very important!!! // We must follow HLSL behavior in the case user specified min value is bigger than max value. float x = value1.X; x = (min.X > x) ? min.X : x; // max(x, minx) x = (max.X < x) ? max.X : x; // min(x, maxx) float y = value1.Y; y = (min.Y > y) ? min.Y : y; // max(y, miny) y = (max.Y < y) ? max.Y : y; // min(y, maxy) return new Vector2(x,y); } /// <summary> /// Linearly interpolates between two vectors based on the given weighting. /// </summary> /// <param name="value1">The first source vector.</param> /// <param name="value2">The second source vector.</param> /// <param name="amount">Value between 0 and 1 indicating the weight of the second source vector.</param> /// <returns>The interpolated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Lerp(Vector2 value1, Vector2 value2, float amount) { return new Vector2( value1.X + (value2.X - value1.X) * amount, value1.Y + (value2.Y - value1.Y) * amount); } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix3x2 matrix) { return new Vector2( position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M31, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M32); } /// <summary> /// Transforms a vector by the given matrix. /// </summary> /// <param name="position">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 position, Matrix4x4 matrix) { return new Vector2( position.X * matrix.M11 + position.Y * matrix.M21 + matrix.M41, position.X * matrix.M12 + position.Y * matrix.M22 + matrix.M42); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix3x2 matrix) { return new Vector2( normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } /// <summary> /// Transforms a vector normal by the given matrix. /// </summary> /// <param name="normal">The source vector.</param> /// <param name="matrix">The transformation matrix.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 TransformNormal(Vector2 normal, Matrix4x4 matrix) { return new Vector2( normal.X * matrix.M11 + normal.Y * matrix.M21, normal.X * matrix.M12 + normal.Y * matrix.M22); } /// <summary> /// Transforms a vector by the given Quaternion rotation value. /// </summary> /// <param name="value">The source vector to be rotated.</param> /// <param name="rotation">The rotation to apply.</param> /// <returns>The transformed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Transform(Vector2 value, Quaternion rotation) { float x2 = rotation.X + rotation.X; float y2 = rotation.Y + rotation.Y; float z2 = rotation.Z + rotation.Z; float wz2 = rotation.W * z2; float xx2 = rotation.X * x2; float xy2 = rotation.X * y2; float yy2 = rotation.Y * y2; float zz2 = rotation.Z * z2; return new Vector2( value.X * (1.0f - yy2 - zz2) + value.Y * (xy2 - wz2), value.X * (xy2 + wz2) + value.Y * (1.0f - xx2 - zz2)); } #endregion Public Static Methods #region Public operator methods // all the below methods should be inlined as they are // implemented over JIT intrinsics /// <summary> /// Adds two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The summed vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Add(Vector2 left, Vector2 right) { return left + right; } /// <summary> /// Subtracts the second vector from the first. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The difference vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Subtract(Vector2 left, Vector2 right) { return left - right; } /// <summary> /// Multiplies two vectors together. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The product vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, Vector2 right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="right">The scalar value.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(Vector2 left, float right) { return left * right; } /// <summary> /// Multiplies a vector by the given scalar. /// </summary> /// <param name="left">The scalar value.</param> /// <param name="right">The source vector.</param> /// <returns>The scaled vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Multiply(float left, Vector2 right) { return left * right; } /// <summary> /// Divides the first vector by the second. /// </summary> /// <param name="left">The first source vector.</param> /// <param name="right">The second source vector.</param> /// <returns>The vector resulting from the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, Vector2 right) { return left / right; } /// <summary> /// Divides the vector by the given scalar. /// </summary> /// <param name="left">The source vector.</param> /// <param name="divisor">The scalar value.</param> /// <returns>The result of the division.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Divide(Vector2 left, float divisor) { return left / divisor; } /// <summary> /// Negates a given vector. /// </summary> /// <param name="value">The source vector.</param> /// <returns>The negated vector.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Vector2 Negate(Vector2 value) { return -value; } #endregion Public operator methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting.Server.Features; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Server.Kestrel.Core; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.Extensions.Hosting; using Xunit; using Xunit.Sdk; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.Extensions.DependencyInjection; namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests { public class AddressRegistrationTests : TestApplicationErrorLoggerLoggedTest { private const int MaxRetries = 10; [ConditionalFact] [HostNameIsReachable] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/27377")] public async Task RegisterAddresses_HostName_Success() { var hostName = Dns.GetHostName(); await RegisterAddresses_Success($"http://{hostName}:0", $"http://{hostName}"); } [Theory] [MemberData(nameof(AddressRegistrationDataIPv4))] public async Task RegisterAddresses_IPv4_Success(string addressInput, string testUrl) { await RegisterAddresses_Success(addressInput, testUrl); } [ConditionalTheory] [MemberData(nameof(AddressRegistrationDataIPv4Port5000Default))] [SkipOnCI] public async Task RegisterAddresses_IPv4Port5000Default_Success(string addressInput, string testUrl) { if (!CanBindToEndpoint(IPAddress.Loopback, 5000)) { return; } await RegisterAddresses_Success(addressInput, testUrl, 5000); } [ConditionalTheory] [MemberData(nameof(AddressRegistrationDataIPv4Port80))] [SkipOnCI] public async Task RegisterAddresses_IPv4Port80_Success(string addressInput, string testUrl) { if (!CanBindToEndpoint(IPAddress.Loopback, 80)) { return; } await RegisterAddresses_Success(addressInput, testUrl, 80); } [Fact] public async Task RegisterAddresses_IPv4StaticPort_Success() { await RegisterAddresses_StaticPort_Success("http://127.0.0.1", "http://127.0.0.1"); } [Fact] public async Task RegisterAddresses_IPv4LocalhostStaticPort_Success() { await RegisterAddresses_StaticPort_Success("http://localhost", "http://127.0.0.1"); } [Fact] public async Task RegisterIPEndPoint_IPv4StaticPort_Success() { await RegisterIPEndPoint_StaticPort_Success(IPAddress.Loopback, $"http://127.0.0.1"); } [ConditionalFact] [IPv6SupportedCondition] public async Task RegisterIPEndPoint_IPv6StaticPort_Success() { await RegisterIPEndPoint_StaticPort_Success(IPAddress.IPv6Loopback, $"http://[::1]"); } [ConditionalTheory] [MemberData(nameof(IPEndPointRegistrationDataDynamicPort))] [IPv6SupportedCondition] public async Task RegisterIPEndPoint_DynamicPort_Success(IPEndPoint endPoint, string testUrl) { await RegisterIPEndPoint_Success(endPoint, testUrl); } [ConditionalTheory] [MemberData(nameof(IPEndPointRegistrationDataPort443))] [IPv6SupportedCondition] public async Task RegisterIPEndPoint_Port443_Success(IPEndPoint endpoint, string testUrl) { if (!CanBindToEndpoint(endpoint.Address, 443)) { return; } await RegisterIPEndPoint_Success(endpoint, testUrl, 443); } [ConditionalTheory] [MemberData(nameof(AddressRegistrationDataIPv6))] [IPv6SupportedCondition] public async Task RegisterAddresses_IPv6_Success(string addressInput, string[] testUrls) { await RegisterAddresses_Success(addressInput, testUrls); } [ConditionalTheory] [MemberData(nameof(AddressRegistrationDataIPv6Port5000And5001Default))] [IPv6SupportedCondition] public async Task RegisterAddresses_IPv6Port5000And5001Default_Success(string addressInput, string[] testUrls) { if ((!CanBindToEndpoint(IPAddress.Loopback, 5000) || !CanBindToEndpoint(IPAddress.IPv6Loopback, 5000)) && (!CanBindToEndpoint(IPAddress.Loopback, 5001) || !CanBindToEndpoint(IPAddress.IPv6Loopback, 5001))) { return; } await RegisterAddresses_Success(addressInput, testUrls); } [ConditionalTheory] [MemberData(nameof(AddressRegistrationDataIPv6Port80))] [IPv6SupportedCondition] public async Task RegisterAddresses_IPv6Port80_Success(string addressInput, string[] testUrls) { if (!CanBindToEndpoint(IPAddress.Loopback, 80) || !CanBindToEndpoint(IPAddress.IPv6Loopback, 80)) { return; } await RegisterAddresses_Success(addressInput, testUrls); } [ConditionalTheory] [MemberData(nameof(AddressRegistrationDataIPv6ScopeId))] [IPv6SupportedCondition] [IPv6ScopeIdPresentCondition] public async Task RegisterAddresses_IPv6ScopeId_Success(string addressInput, string testUrl) { await RegisterAddresses_Success(addressInput, testUrl); } [ConditionalFact] [IPv6SupportedCondition] public async Task RegisterAddresses_IPv6StaticPort_Success() { await RegisterAddresses_StaticPort_Success("http://[::1]", "http://[::1]"); } [ConditionalFact] [IPv6SupportedCondition] public async Task RegisterAddresses_IPv6LocalhostStaticPort_Success() { await RegisterAddresses_StaticPort_Success("http://localhost", new[] { "http://localhost", "http://127.0.0.1", "http://[::1]" }); } private async Task RegisterAddresses_Success(string addressInput, string[] testUrls, int testPort = 0) { var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(serverOptions => { serverOptions.ConfigureHttpsDefaults(httpsOptions => { httpsOptions.ServerCertificate = TestResources.GetTestCertificate(); }); }) .UseUrls(addressInput) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { host.Start(); foreach (var testUrl in testUrls.Select(testUrl => $"{testUrl}:{(testPort == 0 ? host.GetPort() : testPort)}")) { var response = await HttpClientSlim.GetStringAsync(testUrl, validateCertificate: false); // Filter out the scope id for IPv6, that's not sent over the wire. "fe80::3%1" // See https://github.com/aspnet/Common/pull/369 var uri = new Uri(testUrl); if (uri.HostNameType == UriHostNameType.IPv6) { var builder = new UriBuilder(uri); var ip = IPAddress.Parse(builder.Host); builder.Host = new IPAddress(ip.GetAddressBytes()).ToString(); // Without the scope id. uri = builder.Uri; } Assert.Equal(uri.ToString(), response); } await host.StopAsync(); } } private Task RegisterAddresses_Success(string addressInput, string testUrl, int testPort = 0) => RegisterAddresses_Success(addressInput, new[] { testUrl }, testPort); private Task RegisterAddresses_StaticPort_Success(string addressInput, string[] testUrls) => RunTestWithStaticPort(port => RegisterAddresses_Success($"{addressInput}:{port}", testUrls, port)); [Fact] public async Task RegisterHttpAddress_UpgradedToHttpsByConfigureEndpointDefaults() { var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(serverOptions => { serverOptions.ConfigureEndpointDefaults(listenOptions => { listenOptions.UseHttps(TestResources.GetTestCertificate()); }); }) .UseUrls("http://127.0.0.1:0") .Configure(app => { var serverAddresses = app.ServerFeatures.Get<IServerAddressesFeature>(); app.Run(context => { Assert.Single(serverAddresses.Addresses); return context.Response.WriteAsync(serverAddresses.Addresses.First()); }); }); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { host.Start(); var expectedUrl = $"https://127.0.0.1:{host.GetPort()}"; var response = await HttpClientSlim.GetStringAsync(expectedUrl, validateCertificate: false); Assert.Equal(expectedUrl, response); await host.StopAsync(); } } private async Task RunTestWithStaticPort(Func<int, Task> test) { var retryCount = 0; var errors = new List<Exception>(); while (retryCount < MaxRetries) { try { var port = GetNextPort(); await test(port); return; } catch (XunitException) { throw; } catch (Exception ex) { errors.Add(ex); } retryCount++; } if (errors.Any()) { throw new AggregateException(errors); } } private Task RegisterAddresses_StaticPort_Success(string addressInput, string testUrl) => RegisterAddresses_StaticPort_Success(addressInput, new[] { testUrl }); private async Task RegisterIPEndPoint_Success(IPEndPoint endPoint, string testUrl, int testPort = 0) { var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.Listen(endPoint, listenOptions => { if (testUrl.StartsWith("https", StringComparison.Ordinal)) { listenOptions.UseHttps(TestResources.GetTestCertificate()); } }); }) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); var testUrlWithPort = $"{testUrl}:{(testPort == 0 ? host.GetPort() : testPort)}"; var options = ((IOptions<KestrelServerOptions>)host.Services.GetService(typeof(IOptions<KestrelServerOptions>))).Value; Assert.Single(options.ListenOptions); var response = await HttpClientSlim.GetStringAsync(testUrlWithPort, validateCertificate: false); // Compare the response with Uri.ToString(), rather than testUrl directly. // Required to handle IPv6 addresses with zone index, like "fe80::3%1" Assert.Equal(new Uri(testUrlWithPort).ToString(), response); await host.StopAsync(); } } private Task RegisterIPEndPoint_StaticPort_Success(IPAddress address, string testUrl) => RunTestWithStaticPort(port => RegisterIPEndPoint_Success(new IPEndPoint(address, port), testUrl, port)); [Fact] public async Task ListenAnyIP_IPv4_Success() { await ListenAnyIP_Success(new[] { "http://localhost", "http://127.0.0.1" }); } [ConditionalFact] [IPv6SupportedCondition] public async Task ListenAnyIP_IPv6_Success() { await ListenAnyIP_Success(new[] { "http://[::1]", "http://localhost", "http://127.0.0.1" }); } [ConditionalFact] [HostNameIsReachable] [QuarantinedTest("https://github.com/dotnet/aspnetcore/issues/27377")] public async Task ListenAnyIP_HostName_Success() { var hostName = Dns.GetHostName(); await ListenAnyIP_Success(new[] { $"http://{hostName}" }); } private async Task ListenAnyIP_Success(string[] testUrls, int testPort = 0) { var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.ListenAnyIP(testPort); }) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); foreach (var testUrl in testUrls.Select(testUrl => $"{testUrl}:{(testPort == 0 ? host.GetPort() : testPort)}")) { var response = await HttpClientSlim.GetStringAsync(testUrl, validateCertificate: false); // Compare the response with Uri.ToString(), rather than testUrl directly. // Required to handle IPv6 addresses with zone index, like "fe80::3%1" Assert.Equal(new Uri(testUrl).ToString(), response); } await host.StopAsync(); } } [Fact] public async Task ListenLocalhost_IPv4LocalhostStaticPort_Success() { await ListenLocalhost_StaticPort_Success(new[] { "http://localhost", "http://127.0.0.1" }); } [ConditionalFact] [IPv6SupportedCondition] public async Task ListenLocalhost_IPv6LocalhostStaticPort_Success() { await ListenLocalhost_StaticPort_Success(new[] { "http://localhost", "http://127.0.0.1", "http://[::1]" }); } private Task ListenLocalhost_StaticPort_Success(string[] testUrls) => RunTestWithStaticPort(port => ListenLocalhost_Success(testUrls, port)); private async Task ListenLocalhost_Success(string[] testUrls, int testPort = 0) { var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.ListenLocalhost(testPort); }) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); foreach (var testUrl in testUrls.Select(testUrl => $"{testUrl}:{(testPort == 0 ? host.GetPort() : testPort)}")) { var response = await HttpClientSlim.GetStringAsync(testUrl, validateCertificate: false); // Compare the response with Uri.ToString(), rather than testUrl directly. // Required to handle IPv6 addresses with zone index, like "fe80::3%1" Assert.Equal(new Uri(testUrl).ToString(), response); } await host.StopAsync(); } } [ConditionalFact] [SkipOnCI] public Task DefaultsServerAddress_BindsToIPv4() { if (!CanBindToEndpoint(IPAddress.Loopback, 5000)) { return Task.CompletedTask; } return RegisterDefaultServerAddresses_Success(new[] { "http://127.0.0.1:5000" }); } [ConditionalFact] [IPv6SupportedCondition] [SkipOnCI] public Task DefaultsServerAddress_BindsToIPv6() { if (!CanBindToEndpoint(IPAddress.Loopback, 5000) || !CanBindToEndpoint(IPAddress.IPv6Loopback, 5000)) { return Task.CompletedTask; } return RegisterDefaultServerAddresses_Success(new[] { "http://127.0.0.1:5000", "http://[::1]:5000" }); } [ConditionalFact] [SkipOnCI] public Task DefaultsServerAddress_BindsToIPv4WithHttps() { if (!CanBindToEndpoint(IPAddress.Loopback, 5000) || !CanBindToEndpoint(IPAddress.Loopback, 5001)) { return Task.CompletedTask; } return RegisterDefaultServerAddresses_Success( new[] { "http://127.0.0.1:5000", "https://127.0.0.1:5001" }, mockHttps: true); } [ConditionalFact] [IPv6SupportedCondition] [SkipOnCI] public Task DefaultsServerAddress_BindsToIPv6WithHttps() { if (!CanBindToEndpoint(IPAddress.Loopback, 5000) || !CanBindToEndpoint(IPAddress.IPv6Loopback, 5000) || !CanBindToEndpoint(IPAddress.Loopback, 5001) || !CanBindToEndpoint(IPAddress.IPv6Loopback, 5001)) { return Task.CompletedTask; } return RegisterDefaultServerAddresses_Success(new[] { "http://127.0.0.1:5000", "http://[::1]:5000", "https://127.0.0.1:5001", "https://[::1]:5001"}, mockHttps: true); } private async Task RegisterDefaultServerAddresses_Success(IEnumerable<string> addresses, bool mockHttps = false) { var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { if (mockHttps) { options.DefaultCertificate = TestResources.GetTestCertificate(); } }) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); Assert.Equal(5000, host.GetPort()); if (mockHttps) { Assert.Contains(5001, host.GetPorts()); } Assert.Single(LogMessages, log => log.LogLevel == LogLevel.Debug && (string.Equals(CoreStrings.FormatBindingToDefaultAddresses(Constants.DefaultServerAddress, Constants.DefaultServerHttpsAddress), log.Message, StringComparison.Ordinal) || string.Equals(CoreStrings.FormatBindingToDefaultAddress(Constants.DefaultServerAddress), log.Message, StringComparison.Ordinal))); foreach (var address in addresses) { Assert.Equal(new Uri(address).ToString(), await HttpClientSlim.GetStringAsync(address, validateCertificate: false)); } await host.StopAsync(); } } [Fact] public async Task ThrowsWhenBindingToIPv4AddressInUse() { ThrowOnCriticalErrors = false; using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(0); var port = ((IPEndPoint)socket.LocalEndPoint).Port; var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel() .UseUrls($"http://127.0.0.1:{port}") .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { var exception = Assert.Throws<IOException>(() => host.Start()); var expectedMessage = CoreStrings.FormatEndpointAlreadyInUse($"http://127.0.0.1:{port}"); Assert.Equal(expectedMessage, exception.Message); Assert.Equal(0, LogMessages.Count(log => log.LogLevel == LogLevel.Critical && log.Exception is null && log.Message.EndsWith(expectedMessage, StringComparison.Ordinal))); await host.StopAsync(); } } } [ConditionalFact] [IPv6SupportedCondition] public async Task ThrowsWhenBindingToIPv6AddressInUse() { ThrowOnCriticalErrors = false; using (var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); socket.Listen(0); var port = ((IPEndPoint)socket.LocalEndPoint).Port; var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel() .UseUrls($"http://[::1]:{port}") .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { var exception = Assert.Throws<IOException>(() => host.Start()); var expectedMessage = CoreStrings.FormatEndpointAlreadyInUse($"http://[::1]:{port}"); Assert.Equal(expectedMessage, exception.Message); Assert.Equal(0, LogMessages.Count(log => log.LogLevel == LogLevel.Critical && log.Exception is null && log.Message.EndsWith(expectedMessage, StringComparison.Ordinal))); await host.StopAsync(); } } } [Fact] public async Task OverrideDirectConfigurationWithIServerAddressesFeature_Succeeds() { var useUrlsAddress = $"http://127.0.0.1:0"; var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => { listenOptions.UseHttps(TestResources.GetTestCertificate()); }); }) .UseUrls(useUrlsAddress) .PreferHostingUrls(true) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); var port = host.GetPort(); // If this isn't working properly, we'll get the HTTPS endpoint defined in UseKestrel // instead of the HTTP endpoint defined in UseUrls. var serverAddresses = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>().Addresses; Assert.Equal(1, serverAddresses.Count); var useUrlsAddressWithPort = $"http://127.0.0.1:{port}"; Assert.Equal(serverAddresses.First(), useUrlsAddressWithPort); Assert.Single(LogMessages, log => log.LogLevel == LogLevel.Information && string.Equals(CoreStrings.FormatOverridingWithPreferHostingUrls(nameof(IServerAddressesFeature.PreferHostingUrls), useUrlsAddress), log.Message, StringComparison.Ordinal)); Assert.Equal(new Uri(useUrlsAddressWithPort).ToString(), await HttpClientSlim.GetStringAsync(useUrlsAddressWithPort)); await host.StopAsync(); } } [Fact] public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_IfPreferHostingUrlsFalse() { var useUrlsAddress = $"http://127.0.0.1:0"; var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => { listenOptions.UseHttps(TestResources.TestCertificatePath, "testPassword"); }); }) .UseUrls($"http://127.0.0.1:0") .PreferHostingUrls(false) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); var port = host.GetPort(); // If this isn't working properly, we'll get the HTTP endpoint defined in UseUrls // instead of the HTTPS endpoint defined in UseKestrel. var serverAddresses = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>().Addresses; Assert.Equal(1, serverAddresses.Count); var endPointAddress = $"https://127.0.0.1:{port}"; Assert.Equal(serverAddresses.First(), endPointAddress); Assert.Single(LogMessages, log => log.LogLevel == LogLevel.Warning && string.Equals(CoreStrings.FormatOverridingWithKestrelOptions(useUrlsAddress), log.Message, StringComparison.Ordinal)); Assert.Equal(new Uri(endPointAddress).ToString(), await HttpClientSlim.GetStringAsync(endPointAddress, validateCertificate: false)); await host.StopAsync(); } } [Fact] public async Task DoesNotOverrideDirectConfigurationWithIServerAddressesFeature_IfAddressesEmpty() { var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.Listen(new IPEndPoint(IPAddress.Loopback, 0), listenOptions => { listenOptions.UseHttps(TestResources.GetTestCertificate()); }); }) .PreferHostingUrls(true) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); var port = host.GetPort(); // If this isn't working properly, we'll not get the HTTPS endpoint defined in UseKestrel. var serverAddresses = host.Services.GetRequiredService<IServer>().Features.Get<IServerAddressesFeature>().Addresses; Assert.Equal(1, serverAddresses.Count); var endPointAddress = $"https://127.0.0.1:{port}"; Assert.Equal(serverAddresses.First(), endPointAddress); Assert.Equal(new Uri(endPointAddress).ToString(), await HttpClientSlim.GetStringAsync(endPointAddress, validateCertificate: false)); await host.StopAsync(); } } [Fact] public void ThrowsWhenBindingLocalhostToIPv4AddressInUse() { ThrowsWhenBindingLocalhostToAddressInUse(AddressFamily.InterNetwork); } [ConditionalFact] [IPv6SupportedCondition] public void ThrowsWhenBindingLocalhostToIPv6AddressInUse() { ThrowsWhenBindingLocalhostToAddressInUse(AddressFamily.InterNetworkV6); } [Fact] public async Task ThrowsWhenBindingLocalhostToDynamicPort() { IgnoredCriticalLogExceptions.Add(typeof(InvalidOperationException)); var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel() .UseUrls("http://localhost:0") .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { Assert.Throws<InvalidOperationException>(() => host.Start()); await host.StopAsync(); } } [Theory] [InlineData("ftp://localhost")] [InlineData("ssh://localhost")] public async Task ThrowsForUnsupportedAddressFromHosting(string address) { IgnoredCriticalLogExceptions.Add(typeof(InvalidOperationException)); var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel() .UseUrls(address) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { Assert.Throws<InvalidOperationException>(() => host.Start()); await host.StopAsync(); } } [Fact] public async Task CanRebindToEndPoint() { var port = GetNextPort(); var endPointAddress = $"http://127.0.0.1:{port}/"; var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.Listen(IPAddress.Loopback, port); }) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); Assert.Equal(endPointAddress, await HttpClientSlim.GetStringAsync(endPointAddress)); await host.StopAsync(); } hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.Listen(IPAddress.Loopback, port); }) .Configure(ConfigureEchoAddress); }); using (var host = hostBuilder.Build()) { await host.StartAsync(); Assert.Equal(endPointAddress, await HttpClientSlim.GetStringAsync(endPointAddress)); await host.StopAsync(); } } [ConditionalFact] [IPv6SupportedCondition] public async Task CanRebindToMultipleEndPoints() { var port = GetNextPort(); var ipv4endPointAddress = $"http://127.0.0.1:{port}/"; var ipv6endPointAddress = $"http://[::1]:{port}/"; var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.Listen(IPAddress.Loopback, port); options.Listen(IPAddress.IPv6Loopback, port); }) .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); Assert.Equal(ipv4endPointAddress, await HttpClientSlim.GetStringAsync(ipv4endPointAddress)); Assert.Equal(ipv6endPointAddress, await HttpClientSlim.GetStringAsync(ipv6endPointAddress)); await host.StopAsync(); } hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { options.Listen(IPAddress.Loopback, port); options.Listen(IPAddress.IPv6Loopback, port); }) .Configure(ConfigureEchoAddress); }); using (var host = hostBuilder.Build()) { await host.StartAsync(); Assert.Equal(ipv4endPointAddress, await HttpClientSlim.GetStringAsync(ipv4endPointAddress)); Assert.Equal(ipv6endPointAddress, await HttpClientSlim.GetStringAsync(ipv6endPointAddress)); await host.StopAsync(); } } [Theory] [InlineData("http1", HttpProtocols.Http1)] [InlineData("http2", HttpProtocols.Http2)] [InlineData("http1AndHttp2", HttpProtocols.Http1AndHttp2)] public async Task EndpointDefaultsConfig_CanSetProtocolForUrlsConfig(string input, HttpProtocols expected) { KestrelServerOptions capturedOptions = null; var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel(options => { var config = new ConfigurationBuilder().AddInMemoryCollection(new[] { new KeyValuePair<string, string>("EndpointDefaults:Protocols", input), }).Build(); options.Configure(config); capturedOptions = options; }) .UseUrls("http://127.0.0.1:0") .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { await host.StartAsync(); Assert.Single(capturedOptions.OptionsInUse); Assert.Equal(expected, capturedOptions.OptionsInUse[0].Protocols); await host.StopAsync(); } } private void ThrowsWhenBindingLocalhostToAddressInUse(AddressFamily addressFamily) { ThrowOnCriticalErrors = false; var addressInUseCount = 0; var wrongMessageCount = 0; var address = addressFamily == AddressFamily.InterNetwork ? IPAddress.Loopback : IPAddress.IPv6Loopback; var otherAddressFamily = addressFamily == AddressFamily.InterNetwork ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; while (addressInUseCount < 10 && wrongMessageCount < 10) { int port; using (var socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { // Bind first to IPv6Any to ensure both the IPv4 and IPv6 ports are available. socket.Bind(new IPEndPoint(IPAddress.IPv6Any, 0)); socket.Listen(0); port = ((IPEndPoint)socket.LocalEndPoint).Port; } using (var socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp)) { try { socket.Bind(new IPEndPoint(address, port)); socket.Listen(0); } catch (SocketException) { addressInUseCount++; continue; } var hostBuilder = TransportSelector.GetHostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseKestrel() .UseUrls($"http://localhost:{port}") .Configure(ConfigureEchoAddress); }) .ConfigureServices(AddTestLogging); using (var host = hostBuilder.Build()) { var exception = Assert.Throws<IOException>(() => host.Start()); var thisAddressString = $"http://{(addressFamily == AddressFamily.InterNetwork ? "127.0.0.1" : "[::1]")}:{port}"; var otherAddressString = $"http://{(addressFamily == AddressFamily.InterNetworkV6 ? "127.0.0.1" : "[::1]")}:{port}"; if (exception.Message == CoreStrings.FormatEndpointAlreadyInUse(otherAddressString)) { // Don't fail immediately, because it's possible that something else really did bind to the // same port for the other address family between the IPv6Any bind above and now. wrongMessageCount++; continue; } Assert.Equal(CoreStrings.FormatEndpointAlreadyInUse(thisAddressString), exception.Message); Assert.Equal(0, LogMessages.Count(log => log.LogLevel == LogLevel.Critical && log.Exception is null && log.Message.EndsWith(CoreStrings.FormatEndpointAlreadyInUse(thisAddressString), StringComparison.Ordinal))); break; } } } if (addressInUseCount >= 10) { Assert.True(false, $"The corresponding {otherAddressFamily} address was already in use 10 times."); } if (wrongMessageCount >= 10) { Assert.True(false, $"An error for a conflict with {otherAddressFamily} was thrown 10 times."); } } public static TheoryData<string, string> AddressRegistrationDataIPv4 { get { var dataset = new TheoryData<string, string>(); // Loopback dataset.Add("http://127.0.0.1:0", "http://127.0.0.1"); // Any dataset.Add("http://*:0/", "http://127.0.0.1"); dataset.Add("http://+:0/", "http://127.0.0.1"); // Non-loopback addresses var ipv4Addresses = GetIPAddresses() .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork) .Where(ip => CanBindAndConnectToEndpoint(new IPEndPoint(ip, 0))); foreach (var ip in ipv4Addresses) { dataset.Add($"http://{ip}:0/", $"http://{ip}"); } return dataset; } } public static TheoryData<string, string> AddressRegistrationDataIPv4Port5000Default => new TheoryData<string, string> { { null, "http://127.0.0.1:5000/" }, { string.Empty, "http://127.0.0.1:5000/" } }; public static TheoryData<IPEndPoint, string> IPEndPointRegistrationDataDynamicPort { get { var dataset = new TheoryData<IPEndPoint, string>(); // Loopback dataset.Add(new IPEndPoint(IPAddress.Loopback, 0), "http://127.0.0.1"); dataset.Add(new IPEndPoint(IPAddress.Loopback, 0), "https://127.0.0.1"); // IPv6 loopback dataset.Add(new IPEndPoint(IPAddress.IPv6Loopback, 0), "http://[::1]"); dataset.Add(new IPEndPoint(IPAddress.IPv6Loopback, 0), "https://[::1]"); // Any dataset.Add(new IPEndPoint(IPAddress.Any, 0), "http://127.0.0.1"); dataset.Add(new IPEndPoint(IPAddress.Any, 0), "https://127.0.0.1"); // IPv6 Any dataset.Add(new IPEndPoint(IPAddress.IPv6Any, 0), "http://127.0.0.1"); dataset.Add(new IPEndPoint(IPAddress.IPv6Any, 0), "http://[::1]"); dataset.Add(new IPEndPoint(IPAddress.IPv6Any, 0), "https://127.0.0.1"); dataset.Add(new IPEndPoint(IPAddress.IPv6Any, 0), "https://[::1]"); // Non-loopback addresses var ipv4Addresses = GetIPAddresses() .Where(ip => ip.AddressFamily == AddressFamily.InterNetwork) .Where(ip => CanBindAndConnectToEndpoint(new IPEndPoint(ip, 0))); foreach (var ip in ipv4Addresses) { dataset.Add(new IPEndPoint(ip, 0), $"http://{ip}"); dataset.Add(new IPEndPoint(ip, 0), $"https://{ip}"); } var ipv6Addresses = GetIPAddresses() .Where(ip => ip.AddressFamily == AddressFamily.InterNetworkV6) .Where(ip => ip.ScopeId == 0) .Where(ip => CanBindAndConnectToEndpoint(new IPEndPoint(ip, 0))); foreach (var ip in ipv6Addresses) { dataset.Add(new IPEndPoint(ip, 0), $"http://[{ip}]"); } return dataset; } } public static TheoryData<string, string> AddressRegistrationDataIPv4Port80 => new TheoryData<string, string> { // Default port for HTTP (80) { "http://127.0.0.1", "http://127.0.0.1" }, { "http://localhost", "http://127.0.0.1" }, { "http://*", "http://127.0.0.1" } }; public static TheoryData<IPEndPoint, string> IPEndPointRegistrationDataPort443 => new TheoryData<IPEndPoint, string> { { new IPEndPoint(IPAddress.Loopback, 443), "https://127.0.0.1" }, { new IPEndPoint(IPAddress.IPv6Loopback, 443), "https://[::1]" }, { new IPEndPoint(IPAddress.Any, 443), "https://127.0.0.1" }, { new IPEndPoint(IPAddress.IPv6Any, 443), "https://[::1]" } }; public static TheoryData<string, string[]> AddressRegistrationDataIPv6 { get { var dataset = new TheoryData<string, string[]>(); // Loopback dataset.Add($"http://[::1]:0/", new[] { $"http://[::1]" }); // Any dataset.Add($"http://*:0/", new[] { $"http://127.0.0.1", $"http://[::1]" }); dataset.Add($"http://+:0/", new[] { $"http://127.0.0.1", $"http://[::1]" }); // Non-loopback addresses var ipv6Addresses = GetIPAddresses() .Where(ip => !ip.Equals(IPAddress.IPv6Loopback)) .Where(ip => ip.AddressFamily == AddressFamily.InterNetworkV6) .Where(ip => ip.ScopeId == 0) .Where(ip => CanBindAndConnectToEndpoint(new IPEndPoint(ip, 0))); foreach (var ip in ipv6Addresses) { dataset.Add($"http://[{ip}]:0/", new[] { $"http://[{ip}]" }); } return dataset; } } public static TheoryData<string, string[]> AddressRegistrationDataIPv6Port5000And5001Default => new TheoryData<string, string[]> { { null, new[] { "http://127.0.0.1:5000/", "http://[::1]:5000/", "https://127.0.0.1:5001/", "https://[::1]:5001/" } }, { string.Empty, new[] { "http://127.0.0.1:5000/", "http://[::1]:5000/", "https://127.0.0.1:5001/", "https://[::1]:5001/" } } }; public static TheoryData<string, string[]> AddressRegistrationDataIPv6Port80 => new TheoryData<string, string[]> { // Default port for HTTP (80) { "http://[::1]", new[] { "http://[::1]/" } }, { "http://localhost", new[] { "http://127.0.0.1/", "http://[::1]/" } }, { "http://*", new[] { "http://[::1]/" } } }; public static TheoryData<string, string> AddressRegistrationDataIPv6ScopeId { get { var dataset = new TheoryData<string, string>(); var ipv6Addresses = GetIPAddresses() .Where(ip => ip.AddressFamily == AddressFamily.InterNetworkV6) .Where(ip => ip.ScopeId != 0) .Where(ip => CanBindAndConnectToEndpoint(new IPEndPoint(ip, 0))); foreach (var ip in ipv6Addresses) { dataset.Add($"http://[{ip}]:0/", $"http://[{ip}]"); } // There may be no addresses with scope IDs and we need at least one data item in the // collection, otherwise xUnit fails the test run because a theory has no data. dataset.Add("http://[::1]:0", "http://[::1]"); return dataset; } } private static IEnumerable<IPAddress> GetIPAddresses() { return NetworkInterface.GetAllNetworkInterfaces() .Where(i => i.OperationalStatus == OperationalStatus.Up) .SelectMany(i => i.GetIPProperties().UnicastAddresses) .Select(a => a.Address); } private void ConfigureEchoAddress(IApplicationBuilder app) { app.Run(context => { return context.Response.WriteAsync(context.Request.GetDisplayUrl()); }); } private static int GetNextPort() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { // Let the OS assign the next available port. Unless we cycle through all ports // on a test run, the OS will always increment the port number when making these calls. // This prevents races in parallel test runs where a test is already bound to // a given port, and a new test is able to bind to the same port due to port // reuse being enabled by default by the OS. socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); return ((IPEndPoint)socket.LocalEndPoint).Port; } } private static bool CanBindAndConnectToEndpoint(IPEndPoint endPoint) { try { using (var serverSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { serverSocket.Bind(endPoint); serverSocket.Listen(0); var socketArgs = new SocketAsyncEventArgs { RemoteEndPoint = serverSocket.LocalEndPoint }; var mre = new ManualResetEventSlim(); socketArgs.Completed += (s, e) => { mre.Set(); e.ConnectSocket?.Dispose(); }; // Connect can take a couple minutes to time out. if (Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, socketArgs)) { return mre.Wait(5000) && socketArgs.SocketError == SocketError.Success; } else { socketArgs.ConnectSocket?.Dispose(); return socketArgs.SocketError == SocketError.Success; } } } catch (SocketException) { return false; } } private static bool CanBindToEndpoint(IPAddress address, int port) { try { using (var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(address, port)); socket.Listen(0); return true; } } catch (SocketException) { return false; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update { using Microsoft.Azure.Management.Storage.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using Microsoft.Azure.Management.Storage.Fluent; /// <summary> /// The stage of the storage account update allowing to associate custom domain. /// </summary> public interface IWithCustomDomain { /// <summary> /// Specifies the user domain assigned to the storage account. /// </summary> /// <param name="customDomain">The user domain assigned to the storage account.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithCustomDomain(CustomDomain customDomain); /// <summary> /// Specifies the user domain assigned to the storage account. /// </summary> /// <param name="name">The custom domain name, which is the CNAME source.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithCustomDomain(string name); /// <summary> /// Specifies the user domain assigned to the storage account. /// </summary> /// <param name="name">The custom domain name, which is the CNAME source.</param> /// <param name="useSubDomain">Whether indirect CName validation is enabled.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithCustomDomain(string name, bool useSubDomain); } public interface IWithUpgrade : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Gets Specifies that the storage account should be upgraded to V2 kind. /// </summary> /// <summary> /// Gets the next stage of storage account update. /// </summary> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate UpgradeToGeneralPurposeAccountKindV2(); } /// <summary> /// The template for a storage account update operation, containing all the settings that can be modified. /// </summary> public interface IUpdate : Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IAppliable<Microsoft.Azure.Management.Storage.Fluent.IStorageAccount>, Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithSku, Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithCustomDomain, Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithEncryption, Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithAccessTier, Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithManagedServiceIdentity, Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithAccessTraffic, Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithNetworkAccess, Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithUpgrade, Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update.IUpdateWithTags<Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate> { } /// <summary> /// The stage of storage account update allowing to configure network access. /// </summary> public interface IWithNetworkAccess : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies that read access to the storage logging should be allowed from any network. /// </summary> /// <return>The next stage of storage account definition.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithReadAccessToLogEntriesFromAnyNetwork(); /// <summary> /// Specifies that previously added read access exception to the storage metrics from any network /// should be removed. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutReadAccessToMetricsFromAnyNetwork(); /// <summary> /// Specifies that read access to the storage metrics should be allowed from any network. /// </summary> /// <return>The next stage of storage account definition.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithReadAccessToMetricsFromAnyNetwork(); /// <summary> /// Specifies that by default access to storage account should be denied from /// all networks except from those networks specified via /// WithNetworkAccess.withAccessFromNetworkSubnet(String), /// WithNetworkAccess.withAccessFromIpAddress(String) and /// WithNetworkAccess.withAccessFromIpAddressRange(String). /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithAccessFromSelectedNetworks(); /// <summary> /// Specifies that previously allowed access from specific virtual network subnet should be removed. /// </summary> /// <param name="subnetId">The virtual network subnet id.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutNetworkSubnetAccess(string subnetId); /// <summary> /// Specifies that by default access to storage account should be allowed from /// all networks. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithAccessFromAllNetworks(); /// <summary> /// Specifies that previously added read access exception to the storage logging from any network /// should be removed. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutReadAccessToLoggingFromAnyNetwork(); /// <summary> /// Specifies that access to the storage account from a specific virtual network /// subnet should be allowed. /// </summary> /// <param name="subnetId">The virtual network subnet id.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithAccessFromNetworkSubnet(string subnetId); /// <summary> /// Specifies that access to the storage account should be allowed from applications running on /// Microsoft Azure services. /// </summary> /// <return>The next stage of storage account definition.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithAccessFromAzureServices(); /// <summary> /// Specifies that access to the storage account from a specific ip address should be allowed. /// </summary> /// <param name="ipAddress">The ip address.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithAccessFromIpAddress(string ipAddress); /// <summary> /// Specifies that access to the storage account from a specific ip range should be allowed. /// </summary> /// <param name="ipAddressCidr">The ip address range expressed in cidr format.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithAccessFromIpAddressRange(string ipAddressCidr); /// <summary> /// Specifies that previously allowed access from specific ip range should be removed. /// </summary> /// <param name="ipAddressCidr">The ip address range expressed in cidr format.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutIpAddressRangeAccess(string ipAddressCidr); /// <summary> /// Specifies that previously added access exception to the storage account from application /// running on azure should be removed. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutAccessFromAzureServices(); /// <summary> /// Specifies that previously allowed access from specific ip address should be removed. /// </summary> /// <param name="ipAddress">The ip address.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutIpAddressAccess(string ipAddress); } /// <summary> /// The stage of the storage account update allowing to configure encryption settings. /// </summary> public interface IWithEncryption : Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithEncryptionBeta { /// <summary> /// Disables encryption for blob service. /// </summary> /// <deprecated>Use IWithEncryption.WithoutBlobEncryption() instead.</deprecated> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutEncryption(); /// <summary> /// Enables encryption for blob service. /// </summary> /// <deprecated>Use WithEncryption.withBlobEncryption() instead.</deprecated> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithEncryption(); } /// <summary> /// The stage of the storage account update allowing to specify the protocol to be used to access account. /// </summary> public interface IWithAccessTraffic : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies that only https traffic should be allowed to storage account. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithOnlyHttpsTraffic(); /// <summary> /// Specifies that both http and https traffic should be allowed to storage account. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithHttpAndHttpsTraffic(); } /// <summary> /// The stage of the storage account update allowing to change the sku. /// </summary> public interface IWithSku : Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithSkuBeta { /// <summary> /// Specifies the sku of the storage account. /// </summary> /// <deprecated>Use WithSku.withSku(StorageAccountSkuType) instead.</deprecated> /// <param name="skuName">The sku.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithSku(SkuName skuName); } /// <summary> /// The stage of the storage account update allowing to enable managed service identity (MSI). /// </summary> public interface IWithManagedServiceIdentity : Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IWithManagedServiceIdentityBeta { } /// <summary> /// A blob storage account update stage allowing access tier to be specified. /// </summary> public interface IWithAccessTier { /// <summary> /// Specifies the access tier used for billing. /// Access tier cannot be changed more than once every 7 days (168 hours). /// Access tier cannot be set for StandardLRS, StandardGRS, StandardRAGRS, /// or PremiumLRS account types. /// </summary> /// <param name="accessTier">The access tier value.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithAccessTier(AccessTier accessTier); } /// <summary> /// The stage of the storage account update allowing to configure encryption settings. /// </summary> public interface IWithEncryptionBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies the KeyVault key to be used as key for encryption. /// </summary> /// <param name="keyVaultUri">The uri to KeyVault.</param> /// <param name="keyName">The KeyVault key name.</param> /// <param name="keyVersion">The KeyVault key version.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithEncryptionKeyFromKeyVault(string keyVaultUri, string keyName, string keyVersion); /// <summary> /// Disables encryption for blob service. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutBlobEncryption(); /// <summary> /// Enables encryption for file service. /// </summary> /// <return>He next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithFileEncryption(); /// <summary> /// Enables encryption for blob service. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithBlobEncryption(); /// <summary> /// Disables encryption for file service. /// </summary> /// <return>He next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithoutFileEncryption(); } /// <summary> /// The stage of the storage account update allowing to change the sku. /// </summary> public interface IWithSkuBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies the sku of the storage account. /// </summary> /// <param name="sku">The sku.</param> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithSku(StorageAccountSkuType sku); } /// <summary> /// The stage of the storage account update allowing to enable managed service identity (MSI). /// </summary> public interface IWithManagedServiceIdentityBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Specifies that implicit managed service identity (MSI) needs to be enabled. /// </summary> /// <return>The next stage of storage account update.</return> Microsoft.Azure.Management.Storage.Fluent.StorageAccount.Update.IUpdate WithSystemAssignedManagedServiceIdentity(); } }
using System; using System.IO; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; namespace ButtonMaker { /// <summary> /// Summary description for Class1. /// </summary> class BMake { /// <summary> /// The main entry point for the application. /// </summary> /// static void ResetPrimaryFrame(Graphics G, int W, int H, int D) { double a = Math.Sqrt(2) * D / 2; int A = (int) Math.Ceiling(a); G.FillRectangle(new SolidBrush(Color.FromArgb(0,255,255)), D - 1, D - 1, W - 2*D + 2, H - 2*D + 2); SolidBrush Back = new SolidBrush(Color.FromArgb(0,0,150)); G.FillPolygon(Back, new Point[] { new Point(0, D), new Point(D,0), new Point(D + A, A), new Point(A, D + A) } ); G.FillPolygon(Back, new Point[] { new Point(W - D, 0), new Point(W,D), new Point(W - A, D + A), new Point(W - D - A, A) } ); G.FillPolygon(Back, new Point[] { new Point(W - D, H), new Point(W,H - D), new Point(W - A, H - D - A), new Point(W - D - A, H - A) } ); G.FillPolygon(Back, new Point[] { new Point(0, H - D), new Point(D,H), new Point(D + A, H - A), new Point(A, H - D - A) } ); G.FillRectangle(Back, 0, D, D, H - 2 * D); G.FillRectangle(Back, W - D, D, D, H - 2 * D); G.FillRectangle(Back, D, 0, W - 2 * D, D); G.FillRectangle(Back, D, H - D, W - 2 * D, D); } static void BuildBump(Graphics G, int W, int H, int E) { Pen Highlight = new Pen(new SolidBrush(Color.FromArgb(0,0,200)), E); Pen Shadow = new Pen(new SolidBrush(Color.FromArgb(0,0,100)), E); G.FillRectangle(new SolidBrush(Color.FromArgb(0,0,150)),0,0,W,H); G.DrawPath(Highlight, new GraphicsPath(new Point[] { new Point(0,H), new Point(0,0), new Point(W, 0) }, new byte[]{1,1,1})); G.DrawPath(Shadow, new GraphicsPath(new Point[] { new Point(0,H), new Point(W,H), new Point(W, 0) }, new byte[]{1,1,1})); } static void BuildFrame(Graphics G, int W, int H, int D, int E) { Pen Highlight = new Pen(new SolidBrush(Color.FromArgb(0,0,200)), E); Pen Shadow = new Pen(new SolidBrush(Color.FromArgb(0,0,100)), E); Pen Neutral = new Pen(new SolidBrush(Color.FromArgb(0,0,150)), E); double a = Math.Sqrt(2) * D / 2; int A = (int) Math.Ceiling(a); ResetPrimaryFrame(G, W, H, D); G.DrawPath(Neutral, new GraphicsPath( new Point[] { new Point(W / 2, D), new Point(W - 2 * A, D), new Point( W - D, 2 * A), new Point(W - D, H / 2) }, new byte[] {1,1,1,1} )); G.DrawPath(Neutral, new GraphicsPath( new Point[] { new Point(W / 2, H - D), new Point(2 * A, H - D), new Point(D, H - 2 * A), new Point(D, H / 2) }, new byte[] {1,1,1,1} )); G.DrawPath(Shadow, new GraphicsPath( new Point[] { new Point(D, H - 2 * A), new Point(D, 2 * A), new Point(2 * A, D), new Point(W - 2 * A, D) }, new byte[] {1,1,1,1} )); G.DrawPath(Highlight, new GraphicsPath( new Point[] { new Point(W - D, 2 * A), new Point(W - D, H - 2 * A), new Point(W - 2 * A, H - D), new Point(2 * A, H - D) }, new byte[] {1,1,1,1} )); G.DrawPath(Neutral, new GraphicsPath( new Point[] { new Point(D, 0), new Point(W - D, 0), new Point( W, D), new Point(W, H - D) }, new byte[] {1,1,1,1} )); G.DrawPath(Neutral, new GraphicsPath( new Point[] { new Point(0, D), new Point(0, H - D), new Point( D, H), new Point(W - D, H) }, new byte[] {1,1,1,1} )); G.DrawPath(Highlight, new GraphicsPath( new Point[] { new Point(W - D, 0), new Point(D, 0), new Point(0, D), new Point(0, H - D) }, new byte[] {1,1,1,1} )); G.DrawPath(Shadow, new GraphicsPath( new Point[] { new Point(W, D), new Point(W, H - D), new Point(W - D, H), new Point(D, H) }, new byte[] {1,1,1,1} )); } static Color Mix(Color C, bool Blk, bool Wte, bool Ble, bool Red, bool Grn) { if(Blk) { return Color.FromArgb((int) (C.R * 0.5),(int) (C.G * 0.5),(int) (C.B * 0.5)); } if(Wte) { return Color.FromArgb((int) (C.R * 0.5 + 125),(int) (C.G * 0.5 + 125),(int) (C.B * 0.5 + 125)); } if(Ble) { return Color.FromArgb(C.R,C.G,(int) (C.B * 0.5 + 125)); } if(Red) { return Color.FromArgb((int) (C.R * 0.5 + 125),C.G,C.B); } if(Grn) { return Color.FromArgb(C.R, (int) (C.G * 0.5 + 125),C.B); } return C; } static Bitmap ProduceFrame(int Width, int Height, int DimFrame, int BevelDim, Bitmap FrameSource, Bitmap BackSource) { Bitmap Frame = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics G = Graphics.FromImage(Frame); G.Clear(Color.White); BuildFrame(G, Width, Height, DimFrame, BevelDim); for(int X = 0; X < Frame.Width; X++) { for(int Y = 0; Y < Frame.Height; Y++) { Color TestFrame = Frame.GetPixel(X,Y); if(TestFrame.B < 250) Frame.SetPixel(X,Y, Mix(FrameSource.GetPixel(X % FrameSource.Width, Y % FrameSource.Height), TestFrame.B < 140, TestFrame.B > 160, false, false, false)); else if(TestFrame.R < 10) { Frame.SetPixel(X,Y, Mix(BackSource.GetPixel(X % FrameSource.Width, Y % FrameSource.Height), false, false, false, false, false)); } else Frame.SetPixel(X,Y, Color.Transparent); } } G.Dispose(); return Frame; } static Bitmap ProduceFrameButton(string Txt, Color TxtC, Font F, int DimFrame, int BevelDim, Bitmap FrameSource, Bitmap BackSource, bool Red, bool Blue, bool Green, bool Disabled) { Bitmap Button = new Bitmap(2, 2); Graphics G = Graphics.FromImage(Button); SizeF TxtS = G.MeasureString(Txt, F); int TextWidth = (int) (TxtS.Width + DimFrame / 2); int TextHeight = (int) (TxtS.Height + DimFrame / 2); int ButtonWidth = TextWidth + 2 * DimFrame; int ButtonHeight = TextHeight + 2 * DimFrame; G.Dispose(); Button.Dispose(); Button = new Bitmap(ButtonWidth, ButtonHeight, PixelFormat.Format32bppArgb); G = Graphics.FromImage(Button); G.Clear(Color.White); BuildFrame(G, ButtonWidth, ButtonHeight, DimFrame, BevelDim); for(int X = 0; X < Button.Width; X++) { for(int Y = 0; Y < Button.Height; Y++) { bool Trans = false; Color TestFrame = Button.GetPixel(X,Y); if(TestFrame.B < 250) Button.SetPixel(X,Y, Mix(FrameSource.GetPixel(X % FrameSource.Width, Y % FrameSource.Height), TestFrame.B < 140, TestFrame.B > 160, false, false, false)); else if(TestFrame.R < 10) { Button.SetPixel(X,Y, Mix(BackSource.GetPixel(X % FrameSource.Width, Y % FrameSource.Height), false, false, Blue, Red, Green)); } else { Button.SetPixel(X,Y, Color.Transparent); Trans = true; } if(Disabled && ! Trans) { Color KalEl = Button.GetPixel(X,Y); Button.SetPixel(X,Y, Mix(KalEl,true,false,false,false,false) ); } } } if(!Disabled) G.DrawString(Txt, F, new SolidBrush(TxtC), DimFrame + DimFrame / 2, DimFrame + DimFrame / 2); else G.DrawString(Txt, F, new SolidBrush(Color.DarkGray), DimFrame + DimFrame / 2, DimFrame + DimFrame / 2); G.Dispose(); return Button; } static Bitmap ProduceBump(int Width, int Height, int BumpDim, Bitmap Source) { Bitmap Frame = new Bitmap(Width, Height, PixelFormat.Format32bppArgb); Graphics G = Graphics.FromImage(Frame); BuildBump(G, Width, Height, BumpDim); for(int X = 0; X < Frame.Width; X++) { for(int Y = 0; Y < Frame.Height; Y++) { Color TestFrame = Frame.GetPixel(X,Y); if(TestFrame.B < 250) Frame.SetPixel(X,Y, Mix(Source.GetPixel(X % Source.Width, Y % Source.Height), TestFrame.B < 140, TestFrame.B > 160, false, false, false)); else { Frame.SetPixel(X,Y, Color.Transparent); } } } return Frame; } static Bitmap ProduceBumpButton(string Txt, Color TxtC, Font F, int BevelDim, Bitmap BackSource, bool Red, bool Blue, bool Green, bool Disabled) { Bitmap Button = new Bitmap(2, 2); Graphics G = Graphics.FromImage(Button); SizeF TxtS = G.MeasureString(Txt, F); int TextWidth = (int) (TxtS.Width + BevelDim ); int TextHeight = (int) (TxtS.Height + BevelDim ); int ButtonWidth = TextWidth + 4 * BevelDim; int ButtonHeight = TextHeight + 4 * BevelDim; G.Dispose(); Button.Dispose(); Button = new Bitmap(ButtonWidth, ButtonHeight, PixelFormat.Format32bppArgb); G = Graphics.FromImage(Button); G.Clear(Color.White); BuildBump(G, ButtonWidth, ButtonHeight, BevelDim); for(int X = 0; X < Button.Width; X++) { for(int Y = 0; Y < Button.Height; Y++) { bool Trans = false; Color TestFrame = Button.GetPixel(X,Y); if(TestFrame.B < 250) Button.SetPixel(X,Y, Mix(BackSource.GetPixel(X % BackSource.Width, Y % BackSource.Height), TestFrame.B < 140, TestFrame.B > 160, Blue, Red, Green)); else { Button.SetPixel(X,Y, Color.Transparent); Trans = true; } if(Disabled && ! Trans) { Color KalEl = Button.GetPixel(X,Y); Button.SetPixel(X,Y, Mix(KalEl,true,false,false,false,false) ); } } } if(!Disabled) G.DrawString(Txt, F, new SolidBrush(TxtC), 2 * BevelDim, 2 * BevelDim); else G.DrawString(Txt, F, new SolidBrush(Color.DarkGray), 2 * BevelDim, 2 * BevelDim); G.Dispose(); return Button; } static void MakeFrameButton(string Txt, string Signal) { Console.WriteLine("Making: " + Txt); ProduceFrameButton(Txt, Color.White, new Font("Verdana",14), 7, 2, new Bitmap("marb123.jpg"), new Bitmap("marb025.jpg"), false, false, false, false).Save(Signal + "_Idle.png", ImageFormat.Png); ProduceFrameButton(Txt, Color.White, new Font("Verdana",14), 7, 2, new Bitmap("marb123.jpg"), new Bitmap("marb025.jpg"), false, true, false, false).Save(Signal + "_Hover.png", ImageFormat.Png); ProduceFrameButton(Txt, Color.White, new Font("Verdana",14), 7, 2, new Bitmap("marb123.jpg"), new Bitmap("marb025.jpg"), true, false, false, false).Save(Signal + "_Click.png", ImageFormat.Png); ProduceFrameButton(Txt, Color.White, new Font("Verdana",14), 7, 2, new Bitmap("marb123.jpg"), new Bitmap("marb025.jpg"), false, false, false, true).Save(Signal + "_Disabled.png", ImageFormat.Png); } static void MakeBumpButton(string Txt, string Signal) { ProduceBumpButton(Txt, Color.White, new Font("Verdana",14), 2, new Bitmap("Grad.bmp"), false, false, false, false).Save(Signal + "_Idle.png", ImageFormat.Png); ProduceBumpButton(Txt, Color.White, new Font("Verdana",14), 2, new Bitmap("Grad.bmp"), false, true, false, false).Save(Signal + "_Hover.png", ImageFormat.Png); ProduceBumpButton(Txt, Color.White, new Font("Verdana",14), 2, new Bitmap("Grad.bmp"), true, false, false, false).Save(Signal + "_Click.png", ImageFormat.Png); ProduceBumpButton(Txt, Color.White, new Font("Verdana",14), 2, new Bitmap("Grad.bmp"), false, false, false, true).Save(Signal + "_Disabled.png", ImageFormat.Png); } static void MakeFrame(string Frame, int width, int height) { ProduceFrame(width, height, 8, 3, new Bitmap("ply01.jpg"), new Bitmap("BRICK_56.JPG")).Save(Frame + ".png", ImageFormat.Png); } [STAThread] static void Main(string[] args) { ProduceBump(100,100,2,new Bitmap("marb123.jpg")).Save("Test.png", ImageFormat.Png); MakeBumpButton("Exit", "Exit"); MakeBumpButton("Options", "Options"); MakeBumpButton("Continue", "Continue"); MakeFrame("MainMenu", 176, 200); /* MakeFrame("MainMenu", 176, 200); MakeFrameButton("Exit", "Exit"); MakeFrameButton("Options", "Options"); MakeFrameButton("Continue", "Continue"); */ // ProduceButton("Warp", Color.White, new Font("Verdana",14), 7, 2, new Bitmap("marb123.jpg"), new Bitmap("marb025.jpg"), false, false, false).Save("Warp.png", ImageFormat.Png); // ProduceFrame(480, 480, 8, 3, new Bitmap("marb123.jpg"), new Bitmap("marb025.jpg")).Save("Window.png", ImageFormat.Png); } } }
/** * \file NETGeographicLib\ProjectionsPanel.cs * \brief NETGeographicLib projection example * * NETGeographicLib.AzimuthalEquidistant, * NETGeographicLib.CassiniSoldner, and * NETGeographicLib.Gnomonic example. * * NETGeographicLib is copyright (c) Scott Heiman (2013) * GeographicLib is Copyright (c) Charles Karney (2010-2012) * <charles@karney.com> and licensed under the MIT/X11 License. * For more information, see * https://geographiclib.sourceforge.io/ **********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using NETGeographicLib; namespace Projections { public partial class ProjectionsPanel : UserControl { enum ProjectionTypes { AzimuthalEquidistant = 0, CassiniSoldner = 1, Gnomonic = 2 } ProjectionTypes m_type; AzimuthalEquidistant m_azimuthal = null; CassiniSoldner m_cassini = null; Gnomonic m_gnomonic = null; Geodesic m_geodesic = null; public ProjectionsPanel() { InitializeComponent(); try { m_geodesic = new Geodesic(); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } m_majorRadiusTextBox.Text = m_geodesic.MajorRadius.ToString(); m_flatteningTextBox.Text = m_geodesic.Flattening.ToString(); m_lat0TextBox.Text = m_lon0TextBox.Text = "0"; m_projectionComboBox.SelectedIndex = 0; m_functionComboBox.SelectedIndex = 0; } private void OnProjectectionType(object sender, EventArgs e) { m_type = (ProjectionTypes)m_projectionComboBox.SelectedIndex; switch (m_type) { case ProjectionTypes.AzimuthalEquidistant: m_azimuthal = new AzimuthalEquidistant(m_geodesic); break; case ProjectionTypes.CassiniSoldner: double lat0 = Double.Parse( m_lat0TextBox.Text ); double lon0 = Double.Parse( m_lon0TextBox.Text ); m_cassini = new CassiniSoldner(lat0, lon0, m_geodesic); break; case ProjectionTypes.Gnomonic: m_gnomonic = new Gnomonic(m_geodesic); break; } } private void OnSet(object sender, EventArgs e) { try { double a = Double.Parse(m_majorRadiusTextBox.Text); double f = Double.Parse(m_flatteningTextBox.Text); m_geodesic = new Geodesic(a, f); } catch ( Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void OnFunction(object sender, EventArgs e) { switch (m_functionComboBox.SelectedIndex) { case 0: m_latitudeTextBox.ReadOnly = m_longitudeTextBox.ReadOnly = false; m_xTextBox.ReadOnly = m_yTextBox.ReadOnly = true; break; case 1: m_latitudeTextBox.ReadOnly = m_longitudeTextBox.ReadOnly = true; m_xTextBox.ReadOnly = m_yTextBox.ReadOnly = false; break; } } private void OnConvert(object sender, EventArgs e) { try { switch (m_type) { case ProjectionTypes.AzimuthalEquidistant: ConvertAzimuthalEquidistant(); break; case ProjectionTypes.CassiniSoldner: ConvertCassiniSoldner(); break; case ProjectionTypes.Gnomonic: ConvertGnomonic(); break; } } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void ConvertAzimuthalEquidistant() { double lat0 = Double.Parse(m_lat0TextBox.Text); double lon0 = Double.Parse(m_lon0TextBox.Text); double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, azi = 0.0, rk = 0.0; switch (m_functionComboBox.SelectedIndex) { case 0: lat = Double.Parse(m_latitudeTextBox.Text); lon = Double.Parse(m_longitudeTextBox.Text); m_azimuthal.Forward(lat0, lon0, lat, lon, out x, out y, out azi, out rk); m_xTextBox.Text = x.ToString(); m_yTextBox.Text = y.ToString(); break; case 1: x = Double.Parse(m_xTextBox.Text); y = Double.Parse(m_yTextBox.Text); m_azimuthal.Reverse(lat0, lon0, x, y, out lat, out lon, out azi, out rk); m_latitudeTextBox.Text = lat.ToString(); m_longitudeTextBox.Text = lon.ToString(); break; } m_azimuthTextBox.Text = azi.ToString(); m_scaleTextBox.Text = rk.ToString(); } private void ConvertCassiniSoldner() { double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, azi = 0.0, rk = 0.0; switch (m_functionComboBox.SelectedIndex) { case 0: lat = Double.Parse(m_latitudeTextBox.Text); lon = Double.Parse(m_longitudeTextBox.Text); m_cassini.Forward(lat, lon, out x, out y, out azi, out rk); m_xTextBox.Text = x.ToString(); m_yTextBox.Text = y.ToString(); break; case 1: x = Double.Parse(m_xTextBox.Text); y = Double.Parse(m_yTextBox.Text); m_cassini.Reverse(x, y, out lat, out lon, out azi, out rk); m_latitudeTextBox.Text = lat.ToString(); m_longitudeTextBox.Text = lon.ToString(); break; } m_azimuthTextBox.Text = azi.ToString(); m_scaleTextBox.Text = rk.ToString(); } private void ConvertGnomonic() { double lat0 = Double.Parse(m_lat0TextBox.Text); double lon0 = Double.Parse(m_lon0TextBox.Text); double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, azi = 0.0, rk = 0.0; switch (m_functionComboBox.SelectedIndex) { case 0: lat = Double.Parse(m_latitudeTextBox.Text); lon = Double.Parse(m_longitudeTextBox.Text); m_gnomonic.Forward(lat0, lon0, lat, lon, out x, out y, out azi, out rk); m_xTextBox.Text = x.ToString(); m_yTextBox.Text = y.ToString(); break; case 1: x = Double.Parse(m_xTextBox.Text); y = Double.Parse(m_yTextBox.Text); m_gnomonic.Reverse(lat0, lon0, x, y, out lat, out lon, out azi, out rk); m_latitudeTextBox.Text = lat.ToString(); m_longitudeTextBox.Text = lon.ToString(); break; } m_azimuthTextBox.Text = azi.ToString(); m_scaleTextBox.Text = rk.ToString(); } private void OnValidate(object sender, EventArgs e) { try { double lat = 0.0, lon = 0.0, x = 0.0, y = 0.0, x1 = 0.0, y1 = 0.0, azi = 0.0, rk = 0.0; AzimuthalEquidistant azimuthal = new AzimuthalEquidistant(m_geodesic); azimuthal = new AzimuthalEquidistant(); azimuthal.Forward(32.0, -86.0, 33.0, -87.0, out x, out y, out azi, out rk); azimuthal.Forward(32.0, -86.0, 33.0, -87.0, out x1, out y1); if (x != x1 || y != y1) throw new Exception("Error in AzimuthalEquidistant.Forward"); azimuthal.Reverse(32.0, -86.0, x, y, out lat, out lon, out azi, out rk); azimuthal.Reverse(32.0, -86.0, x, y, out x1, out y1); if ( x1 != lat || y1 != lon ) throw new Exception("Error in AzimuthalEquidistant.Reverse"); CassiniSoldner cassini = new CassiniSoldner(32.0, -86.0, m_geodesic); cassini = new CassiniSoldner(32.0, -86.0); cassini.Reset(31.0, -87.0); cassini.Forward(32.0, -86.0, out x, out y, out azi, out rk); cassini.Forward(32.0, -86.0, out x1, out y1); if (x != x1 || y != y1) throw new Exception("Error in CassiniSoldner.Forward"); cassini.Reverse(x, y, out lat, out lon, out azi, out rk); cassini.Reverse(x, y, out x1, out y1); if (x1 != lat || y1 != lon) throw new Exception("Error in CassiniSoldner.Reverse"); Gnomonic gnomonic = new Gnomonic(m_geodesic); gnomonic = new Gnomonic(); gnomonic.Forward(32.0, -86.0, 31.0, -87.0, out x, out y, out azi, out rk); gnomonic.Forward(32.0, -86.0, 31.0, -87.0, out x1, out y1); if (x != x1 || y != y1) throw new Exception("Error in Gnomonic.Forward"); gnomonic.Reverse(32.0, -86.0, x, y, out lat, out lon, out azi, out rk); gnomonic.Reverse(32.0, -86.0, x, y, out x1, out y1); if (x1 != lat || y1 != lon) throw new Exception("Error in Gnomonic.Reverse"); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } MessageBox.Show("No errors detected", "OK", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay // //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. /** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Text; using Thrift.Protocol; namespace Netfox.SnooperMessenger.Protocol { #if !SILVERLIGHT [Serializable] #endif public partial class MNMessagesSyncAttachment : TBase { private string _Id; private string _Mimetype; private string _Filename; private long _Fbid; private long _Filesize; private MNMessagesSyncAttachmentAppAttribution _Attributioninfo; private string _Xmagraphql; private MNMessagesSyncImageMetadata _Imagemetadata; private MNMessagesSyncVideoMetadata _Videometadata; public string Id { get { return _Id; } set { __isset.Id = true; this._Id = value; } } public string Mimetype { get { return _Mimetype; } set { __isset.Mimetype = true; this._Mimetype = value; } } public string Filename { get { return _Filename; } set { __isset.Filename = true; this._Filename = value; } } public long Fbid { get { return _Fbid; } set { __isset.Fbid = true; this._Fbid = value; } } public long Filesize { get { return _Filesize; } set { __isset.Filesize = true; this._Filesize = value; } } public MNMessagesSyncAttachmentAppAttribution Attributioninfo { get { return _Attributioninfo; } set { __isset.Attributioninfo = true; this._Attributioninfo = value; } } public string Xmagraphql { get { return _Xmagraphql; } set { __isset.Xmagraphql = true; this._Xmagraphql = value; } } public MNMessagesSyncImageMetadata Imagemetadata { get { return _Imagemetadata; } set { __isset.Imagemetadata = true; this._Imagemetadata = value; } } public MNMessagesSyncVideoMetadata Videometadata { get { return _Videometadata; } set { __isset.Videometadata = true; this._Videometadata = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool Id; public bool Mimetype; public bool Filename; public bool Fbid; public bool Filesize; public bool Attributioninfo; public bool Xmagraphql; public bool Imagemetadata; public bool Videometadata; } public MNMessagesSyncAttachment() { } public void Read (TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.String) { Id = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.String) { Mimetype = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.String) { Filename = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 4: if (field.Type == TType.I64) { Fbid = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 5: if (field.Type == TType.I64) { Filesize = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 6: if (field.Type == TType.Struct) { Attributioninfo = new MNMessagesSyncAttachmentAppAttribution(); Attributioninfo.Read(iprot); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 7: if (field.Type == TType.String) { Xmagraphql = iprot.ReadString(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 8: if (field.Type == TType.Struct) { Imagemetadata = new MNMessagesSyncImageMetadata(); Imagemetadata.Read(iprot); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 9: if (field.Type == TType.Struct) { Videometadata = new MNMessagesSyncVideoMetadata(); Videometadata.Read(iprot); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } } public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("MNMessagesSyncAttachment"); oprot.WriteStructBegin(struc); TField field = new TField(); if (Id != null && __isset.Id) { field.Name = "Id"; field.Type = TType.String; field.ID = 1; oprot.WriteFieldBegin(field); oprot.WriteString(Id); oprot.WriteFieldEnd(); } if (Mimetype != null && __isset.Mimetype) { field.Name = "Mimetype"; field.Type = TType.String; field.ID = 2; oprot.WriteFieldBegin(field); oprot.WriteString(Mimetype); oprot.WriteFieldEnd(); } if (Filename != null && __isset.Filename) { field.Name = "Filename"; field.Type = TType.String; field.ID = 3; oprot.WriteFieldBegin(field); oprot.WriteString(Filename); oprot.WriteFieldEnd(); } if (__isset.Fbid) { field.Name = "Fbid"; field.Type = TType.I64; field.ID = 4; oprot.WriteFieldBegin(field); oprot.WriteI64(Fbid); oprot.WriteFieldEnd(); } if (__isset.Filesize) { field.Name = "Filesize"; field.Type = TType.I64; field.ID = 5; oprot.WriteFieldBegin(field); oprot.WriteI64(Filesize); oprot.WriteFieldEnd(); } if (Attributioninfo != null && __isset.Attributioninfo) { field.Name = "Attributioninfo"; field.Type = TType.Struct; field.ID = 6; oprot.WriteFieldBegin(field); Attributioninfo.Write(oprot); oprot.WriteFieldEnd(); } if (Xmagraphql != null && __isset.Xmagraphql) { field.Name = "Xmagraphql"; field.Type = TType.String; field.ID = 7; oprot.WriteFieldBegin(field); oprot.WriteString(Xmagraphql); oprot.WriteFieldEnd(); } if (Imagemetadata != null && __isset.Imagemetadata) { field.Name = "Imagemetadata"; field.Type = TType.Struct; field.ID = 8; oprot.WriteFieldBegin(field); Imagemetadata.Write(oprot); oprot.WriteFieldEnd(); } if (Videometadata != null && __isset.Videometadata) { field.Name = "Videometadata"; field.Type = TType.Struct; field.ID = 9; oprot.WriteFieldBegin(field); Videometadata.Write(oprot); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { StringBuilder __sb = new StringBuilder("MNMessagesSyncAttachment("); bool __first = true; if (Id != null && __isset.Id) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Id: "); __sb.Append(Id); } if (Mimetype != null && __isset.Mimetype) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Mimetype: "); __sb.Append(Mimetype); } if (Filename != null && __isset.Filename) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Filename: "); __sb.Append(Filename); } if (__isset.Fbid) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Fbid: "); __sb.Append(Fbid); } if (__isset.Filesize) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Filesize: "); __sb.Append(Filesize); } if (Attributioninfo != null && __isset.Attributioninfo) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Attributioninfo: "); __sb.Append(Attributioninfo== null ? "<null>" : Attributioninfo.ToString()); } if (Xmagraphql != null && __isset.Xmagraphql) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Xmagraphql: "); __sb.Append(Xmagraphql); } if (Imagemetadata != null && __isset.Imagemetadata) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Imagemetadata: "); __sb.Append(Imagemetadata== null ? "<null>" : Imagemetadata.ToString()); } if (Videometadata != null && __isset.Videometadata) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Videometadata: "); __sb.Append(Videometadata== null ? "<null>" : Videometadata.ToString()); } __sb.Append(")"); return __sb.ToString(); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Yort.OnlineEftpos { /// <summary> /// Core class for communication with the PayMark Online Eftpos API. Provides methods for performing transactions such as payments and refunds. /// </summary> public sealed class OnlineEftposClient : IOnlineEftposClient, IDisposable { #region Fields & Constants private readonly OnlineEftposRequestAuthoriser _RequestAuthoriser; private readonly OnlineEftposApiRouter _ApiRouter; private readonly HttpClient _HttpClient; private readonly bool _HttpClientIsOwned; private const string OnlineEftposContentType = "application/vnd.paymark_api+json"; #endregion #region Constructors /// <summary> /// Minium constructor. /// </summary> /// <param name="credentialProvider">A <see cref="IOnlineEftposCredentialProvider"/> instance that can provide credentials used to obtain a token from the API for subsequent calls. See <see cref="OnlineEftposCredentialsProvider"/> for default implementations, or create your own.</param> /// <param name="apiVersion">A value from the <see cref="ApiVersion"/> enum specifying the version of the Online Eftpos API this client connects to.</param> /// <param name="apiEnvironment">A value from the <see cref="ApiEnvironment"/> enum specifying either a test or live environment for this client to connect to.</param> /// <seealso cref="ApiVersion"/> /// <seealso cref="ApiEnvironment"/> public OnlineEftposClient(IOnlineEftposCredentialProvider credentialProvider, OnlineEftposApiVersion apiVersion, OnlineEftposApiEnvironment apiEnvironment) : this(credentialProvider, apiVersion, apiEnvironment, CreateDefaultHttpClient()) { _HttpClientIsOwned = true; } /// <summary> /// Full constructor. /// </summary> /// <param name="credentialProvider">A <see cref="IOnlineEftposCredentialProvider"/> instance that can provide credentials used to obtain a token from the API for subsequent calls. See SecureStringOnlineEftposCredentialProvider (if available) or <see cref="OnlineEftposCredentialsProvider"/> for default implementations, or create your own.</param> /// <param name="apiVersion">A value from the <see cref="ApiVersion"/> enum specifying the version of the Online Eftpos API this client connects to.</param> /// <param name="apiEnvironment">A value from the <see cref="ApiEnvironment"/> enum specifying either a test or live environment for this client to connect to.</param> /// <param name="httpClient">A instance of <see cref="HttpClient"/> that will be used by this instance to perform all HTTP communication with the Online Eftpos API.</param> /// <seealso cref="ApiVersion"/> /// <seealso cref="ApiEnvironment"/> public OnlineEftposClient(IOnlineEftposCredentialProvider credentialProvider, OnlineEftposApiVersion apiVersion, OnlineEftposApiEnvironment apiEnvironment, HttpClient httpClient) { credentialProvider.GuardNull(nameof(credentialProvider)); httpClient.GuardNull(nameof(httpClient)); //Ensure TLS 1.2 is enabled, as it is required. #if !DOESNOTSUPPORT_TLS12 if ((System.Net.ServicePointManager.SecurityProtocol & System.Net.SecurityProtocolType.Tls12) != System.Net.SecurityProtocolType.Tls12) { System.Net.ServicePointManager.SecurityProtocol = (System.Net.ServicePointManager.SecurityProtocol | System.Net.SecurityProtocolType.Tls12); } #endif _HttpClient = httpClient; _ApiRouter = new OnlineEftposApiRouter(apiEnvironment, apiVersion); _RequestAuthoriser = new OnlineEftposRequestAuthoriser(credentialProvider, _HttpClient, _ApiRouter); } #endregion #region IOnlineEftposClient Members /// <summary> /// Returns a value indicating the version of the Online Eftpos API this client will connect to. /// </summary> /// <remarks> /// <para>This property is read only, the value is provided when the object is instantiated via the constructor.</para> /// </remarks> /// <seealso cref="OnlineEftposClient(IOnlineEftposCredentialProvider, OnlineEftposApiVersion, OnlineEftposApiEnvironment)"/> /// <seealso cref="OnlineEftposClient(IOnlineEftposCredentialProvider, OnlineEftposApiVersion, OnlineEftposApiEnvironment, HttpClient)"/> public OnlineEftposApiVersion ApiVersion { get { return _ApiRouter.Version; } } /// <summary> /// Returns a value indicating the sandbox or production environment of the Online Eftpos API this client will connect to. /// </summary> /// <remarks> /// <para>This property is read only, the value is provided when the object is instantiated via the constructor.</para> /// </remarks> /// <seealso cref="OnlineEftposClient(IOnlineEftposCredentialProvider, OnlineEftposApiVersion, OnlineEftposApiEnvironment)"/> /// <seealso cref="OnlineEftposClient(IOnlineEftposCredentialProvider, OnlineEftposApiVersion, OnlineEftposApiEnvironment, HttpClient)"/> public OnlineEftposApiEnvironment ApiEnvironment { get { return _ApiRouter.Environment; } } #region Payment Members /// <summary> /// Starts a payment transaction. Sends a request for payment to the API, which will be forwarded to the payer for approval. /// </summary> /// <remarks> /// <para>Use the <seealso cref="CheckPaymentStatus(string)"/> method to obtain updated status information after the request has been submitted. Usually this is done in response to an HTTP callback from the API.</para> /// </remarks> /// <param name="paymentRequest">An instance of the <seealso cref="OnlineEftposPaymentRequest"/> class that provides details of the requested payment.</param> /// <returns>A task whose result is an instance of <seealso cref="OnlineEftposPaymentStatus"/> which describes the result of a successfully submitted payment.</returns> /// <exception cref="OnlineEftposAuthenticationException">Thrown if a token cannot be obtained from the API. Usually this indicates incorrect credentials.</exception> /// <exception cref="OnlineEftposException">Thrown if an exception occurs or error information is returned from the API.</exception> /// <seealso cref="OnlineEftposPaymentRequest"/> /// <seealso cref="OnlineEftposPaymentStatus"/> /// <seealso cref="CheckPaymentStatus(string)"/> public async Task<OnlineEftposPaymentStatus> RequestPayment(OnlineEftposPaymentRequest paymentRequest) { paymentRequest.GuardNull(nameof(paymentRequest)); paymentRequest.EnsureValid(); return await SendApiRequest<OnlineEftposPaymentRequest, OnlineEftposPaymentStatus>(paymentRequest, "transaction/oepayment", HttpMethod.Post, System.Net.HttpStatusCode.Created).ConfigureAwait(false); } /// <summary> /// Returns updated status information for a previously submitted payment request. /// </summary> /// <param name="transactionId">The unique id of a payment to retrieve the status of.</param> /// <returns>A task whose result is an instance of <seealso cref="OnlineEftposPaymentStatus"/> which describes the result of a successfully submitted payment.</returns> /// <seealso cref="RequestPayment(OnlineEftposPaymentRequest)"/> /// <exception cref="OnlineEftposAuthenticationException">Thrown if a token cannot be obtained from the API. Usually this indicates incorrect credentials.</exception> /// <exception cref="OnlineEftposException">Thrown if an exception occurs or error information is returned from the API.</exception> /// <seealso cref="OnlineEftposPaymentStatus"/> public async Task<OnlineEftposPaymentStatus> CheckPaymentStatus(string transactionId) { transactionId.GuardNullEmptyOrWhitespace(nameof(transactionId)); var safeTransactionId = Uri.EscapeDataString(transactionId); return await SendApiRequest<OnlineEftposPaymentStatus>($"transaction/oepayment/{safeTransactionId}").ConfigureAwait(false); } /// <summary> /// Searches for payments based on one or more provided criteria and returns a <see cref="OnlineEftposPaymentSearchResult"/> containing any found transactions. /// </summary> /// <remarks> /// <para>The <see cref="OnlineEftposPaymentSearchResult"/> returned also contains information such as pagination url's for searches with many results.</para> /// </remarks> /// <param name="options">A <see cref="OnlineEftposPaymentSearchOptions"/> instance containing the search criteria and options for the search.</param> /// <returns>An <see cref="OnlineEftposPaymentSearchResult"/> instance containing the initial search results and any related meta-data.</returns> public async Task<OnlineEftposPaymentSearchResult> PaymentSearch(OnlineEftposPaymentSearchOptions options) { options.GuardNull(nameof(options)); var requestUri = options.PaginationUri; if (requestUri == null) { var queryStr = options.BuildSearchQueryString(); if (String.IsNullOrEmpty(queryStr)) throw new ArgumentException("No search criteria specified.", nameof(options)); requestUri = _ApiRouter.GetUrl($"transaction/oepayment/?{queryStr}"); } var requestMessage = new HttpRequestMessage() { Method = HttpMethod.Get, RequestUri = requestUri, }; var result = await SendApiRequest<OnlineEftposPaymentSearchResult>(HttpStatusCode.OK, requestMessage).ConfigureAwait(false); result.Links = result.Links ?? new HateoasLink[] { }; result.Payments = result.Payments ?? new OnlineEftposPaymentStatus[] { }; return result; } #endregion #region Refund Members /// <summary> /// Sends a refund for a previous payment to the original payer. /// </summary> /// <param name="refundRequest">An instance of the <seealso cref="OnlineEftposRefundRequest"/> class that provides details of the refund to issue.</param> /// <returns>A task whose result is an instance of <seealso cref="OnlineEftposRefundRequest"/> which describes the result of a successfull submitted refund.</returns> /// <seealso cref="RequestPayment(OnlineEftposPaymentRequest)"/> /// <exception cref="OnlineEftposAuthenticationException">Thrown if a token cannot be obtained from the API. Usually this indicates incorrect credentials.</exception> /// <exception cref="OnlineEftposException">Thrown if an exception occurs or error information is returned from the API.</exception> /// <seealso cref="OnlineEftposRefundStatus"/> /// <seealso cref="CheckRefundStatus(string)"/> public async Task<OnlineEftposRefundStatus> SendRefund(OnlineEftposRefundRequest refundRequest) { refundRequest.GuardNull(nameof(refundRequest)); refundRequest.EnsureValid(); return await SendApiRequest<OnlineEftposRefundRequest, OnlineEftposRefundStatus>(refundRequest, "transaction/oerefund", HttpMethod.Post, System.Net.HttpStatusCode.Created).ConfigureAwait(false); } /// <summary> /// Returns updated status information for a previously submitted refund. /// </summary> /// <param name="transactionId">The unique id of a refund to retrieve the status of.</param> /// <returns>A task whose result is an instance of <seealso cref="OnlineEftposRefundStatus"/> which describes the result of a successfully submitted refund.</returns> /// <seealso cref="SendRefund(OnlineEftposRefundRequest)"/> /// <exception cref="OnlineEftposAuthenticationException">Thrown if a token cannot be obtained from the API. Usually this indicates incorrect credentials.</exception> /// <exception cref="OnlineEftposException">Thrown if an exception occurs or error information is returned from the API.</exception> /// <seealso cref="OnlineEftposRefundStatus"/> public async Task<OnlineEftposRefundStatus> CheckRefundStatus(string transactionId) { transactionId.GuardNullEmptyOrWhitespace(nameof(transactionId)); var safeTransactionId = Uri.EscapeDataString(transactionId); return await SendApiRequest<OnlineEftposRefundStatus>($"transaction/oerefund/{safeTransactionId}").ConfigureAwait(false); } /// <summary> /// Searches for refunds based on one or more provided criteria and returns a <see cref="OnlineEftposRefundSearchResult"/> containing any found transactions. /// </summary> /// <remarks> /// <para>The <see cref="OnlineEftposRefundSearchResult"/> returned also contains information such as pagination url's for searches with many results.</para> /// </remarks> /// <param name="options">A <see cref="OnlineEftposRefundSearchOptions"/> instance containing the search criteria and options for the search.</param> /// <returns>An <see cref="OnlineEftposRefundSearchResult"/> instance containing the initial search results and any related meta-data.</returns> public async Task<OnlineEftposRefundSearchResult> RefundSearch(OnlineEftposRefundSearchOptions options) { options.GuardNull(nameof(options)); var requestUri = options.PaginationUri; if (requestUri == null) { var queryStr = options.BuildSearchQueryString(); if (String.IsNullOrEmpty(queryStr)) throw new ArgumentException("No search criteria specified.", nameof(options)); requestUri = _ApiRouter.GetUrl($"transaction/oerefund/?{queryStr}"); } var requestMessage = new HttpRequestMessage() { Method = HttpMethod.Get, RequestUri = requestUri, }; var result = await SendApiRequest<OnlineEftposRefundSearchResult>(HttpStatusCode.OK, requestMessage).ConfigureAwait(false); result.Links = result.Links ?? new HateoasLink[] { }; result.Refunds = result.Refunds ?? new OnlineEftposRefundStatus[] { }; return result; } #endregion #endregion #region Private Members private static HttpClient CreateDefaultHttpClient() { var retVal = new HttpClient(); retVal.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("Yort.OnlineEftpos", OnlineEftposGlobals.GetVersionString())); retVal.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue(OnlineEftposGlobals.UserAgentComment)); return retVal; } private async Task<RS> SendApiRequest<RS>(string endpointRelativePath) { var requestMessage = new HttpRequestMessage() { Method = HttpMethod.Get, RequestUri = _ApiRouter.GetUrl(endpointRelativePath), }; requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(OnlineEftposContentType)); await _RequestAuthoriser.AuthoriseRequest(requestMessage).ConfigureAwait(false); var result = await _HttpClient.SendAsync(requestMessage).ConfigureAwait(false); if (result.StatusCode == System.Net.HttpStatusCode.OK) return JsonConvert.DeserializeObject<RS>(await result.Content.ReadAsStringAsync().ConfigureAwait(false)); else { var apiError = JsonConvert.DeserializeObject<OnlineEftposApiError>(await result.Content.ReadAsStringAsync().ConfigureAwait(false)); throw new OnlineEftposApiException(result.StatusCode, result.ReasonPhrase, apiError); } } private async Task<RS> SendApiRequest<RQ, RS>(RQ requestContent, string endpointRelativePath, HttpMethod endpointHttpMethod, HttpStatusCode expectedResponseStatus) { var requestMessage = new HttpRequestMessage() { Content = new System.Net.Http.StringContent(JsonConvert.SerializeObject(requestContent), null, OnlineEftposContentType), Method = endpointHttpMethod, RequestUri = _ApiRouter.GetUrl(endpointRelativePath), }; return await SendApiRequest<RS>(expectedResponseStatus, requestMessage); } private async Task<RS> SendApiRequest<RS>(HttpStatusCode expectedResponseStatus, HttpRequestMessage requestMessage) { requestMessage.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(OnlineEftposContentType)); //At time of writingt Paymark will fail the request if the charset is included, it seems //the content type must be an exact string match to the OnlineEftposContentType constant. //Clear the char set here to prevent 415 errors. if (requestMessage.Content?.Headers?.ContentType != null) requestMessage.Content.Headers.ContentType.CharSet = null; await _RequestAuthoriser.AuthoriseRequest(requestMessage).ConfigureAwait(false); var result = await _HttpClient.SendAsync(requestMessage).ConfigureAwait(false); if (result.StatusCode == expectedResponseStatus) return JsonConvert.DeserializeObject<RS>(await result.Content.ReadAsStringAsync().ConfigureAwait(false)); else { var apiError = JsonConvert.DeserializeObject<OnlineEftposApiError>(await result.Content.ReadAsStringAsync().ConfigureAwait(false)); throw new OnlineEftposApiException(result.StatusCode, result.ReasonPhrase, apiError); } } /// <summary> /// Deletes a trust/autopay relationship previously established via <see cref="RequestPayment(OnlineEftposPaymentRequest)"/>. /// </summary> /// <param name="options">The details of the trust/autopay relationship to delete.</param> /// <returns>An <see cref="OnlineEftposDeleteTrustResult"/> instance containing details about the result of the request.</returns> public async Task<OnlineEftposDeleteTrustResult> DeleteTrust(OnlineEftposDeleteTrustOptions options) { options.GuardNull(nameof(options)); options.EnsureValid(); return await SendApiRequest<OnlineEftposDeleteTrustRequest, OnlineEftposDeleteTrustResult>(new OnlineEftposDeleteTrustRequest(), "oemerchanttrust/" + options.TrustId, HttpMethod.Put, System.Net.HttpStatusCode.OK).ConfigureAwait(false); } #endregion #region IDisposable Members /// <summary> /// Disposes this instance and all internal resources, except the HttpClient provided in the constructor. /// </summary> public void Dispose() { if (_RequestAuthoriser != null) _RequestAuthoriser.Dispose(); if (_HttpClientIsOwned) _HttpClient.Dispose(); } #endregion } }
#region Copyright //////////////////////////////////////////////////////////////////////////////// // The following FIT Protocol software provided may be used with FIT protocol // devices only and remains the copyrighted property of Dynastream Innovations Inc. // The software is being provided on an "as-is" basis and as an accommodation, // and therefore all warranties, representations, or guarantees of any kind // (whether express, implied or statutory) including, without limitation, // warranties of merchantability, non-infringement, or fitness for a particular // purpose, are specifically disclaimed. // // Copyright 2015 Dynastream Innovations Inc. //////////////////////////////////////////////////////////////////////////////// // ****WARNING**** This file is auto-generated! Do NOT edit this file. // Profile Version = 16.10Release // Tag = development-akw-16.10.00-0 //////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.IO; namespace Dynastream.Fit { /// <summary> /// The Subfield class represents an alternative field definition used /// by dynamic fields. They can only be associated with a containing /// field object. /// </summary> public class Subfield { #region Internal Classes /// <summary> /// The SubfieldMap class tracks the reference field/value pairs which indicate a field /// should use the alternate subfield definition rather than the usual defn (allows Dynamic Fields) /// </summary> private class SubfieldMap { private byte refFieldNum; private object refFieldValue; internal SubfieldMap(byte refFieldNum, object refFieldValue) { this.refFieldNum = refFieldNum; this.refFieldValue = refFieldValue; } internal SubfieldMap(SubfieldMap subfieldMap) { this.refFieldNum = subfieldMap.refFieldNum; this.refFieldValue = subfieldMap.refFieldValue; } /// <summary> /// Checks if the reference fields in a given message indicate the subfield (alternate) /// definition should be used /// </summary> /// <param name="mesg">message of interest</param> /// <returns>true if the subfield is active</returns> internal bool CanMesgSupport(Mesg mesg) { Field field = mesg.GetField(refFieldNum); if (field != null) { object value = field.GetValue(0, Fit.SubfieldIndexMainField); // Float refvalues are not supported if (Convert.ToInt64(value) == Convert.ToInt64(refFieldValue)) { return true; } } return false; } } #endregion Internal Classes #region Fields private string name; private byte type; private float scale; private float offset; private string units; private List<SubfieldMap> maps; private List<FieldComponent> components; #endregion // Fields #region Properties internal string Name { get { return name; } } internal byte Type { get { return type; } } internal float Scale { get { return scale; } } internal float Offset { get { return offset; } } internal string Units { get { return units; } } internal List<FieldComponent> Components { get { return components; } } #endregion // Properties #region Constructors internal Subfield(Subfield subfield) { if (subfield == null) { this.name = "unknown"; this.type = 0; this.scale = 1f; this.offset = 0f; this.units = ""; this.maps = new List<SubfieldMap>(); this.components = new List<FieldComponent>(); return; } this.name = subfield.name; this.type = subfield.type; this.scale = subfield.scale; this.offset = subfield.offset; this.units = subfield.units; this.maps = new List<SubfieldMap>(); foreach (SubfieldMap map in subfield.maps) { this.maps.Add(new SubfieldMap(map)); } this.components = new List<FieldComponent>(); foreach (FieldComponent comp in subfield.components) { this.components.Add(new FieldComponent(comp)); } } internal Subfield(string name, byte type, float scale, float offset, string units) { this.name = name; this.type = type; this.scale = scale; this.offset = offset; this.units = units; this.maps = new List<SubfieldMap>(); this.components = new List<FieldComponent>(); } #endregion // Constructors #region Methods internal void AddMap(byte refFieldNum, object refFieldValue) { maps.Add(new SubfieldMap(refFieldNum, refFieldValue)); } internal void AddComponent(FieldComponent newComponent) { components.Add(newComponent); } /// <summary> /// Checks if the reference fields in a given message indicate the subfield (alternate) /// definition should be used /// </summary> /// <param name="mesg">message of interest</param> /// <returns>true if the subfield is active</returns> public bool CanMesgSupport(Mesg mesg) { foreach (SubfieldMap map in maps) { if (map.CanMesgSupport(mesg)) { return true; } } return false; } #endregion // Methods } // Class } // namespace
#define LOG_MEMORY_PERF_COUNTERS using Microsoft.Extensions.Logging; using Orleans.Runtime; using System; using System.Diagnostics; using System.Management; using System.Threading; using System.Threading.Tasks; namespace Orleans.Statistics { internal class PerfCounterEnvironmentStatistics : IHostEnvironmentStatistics, ILifecycleParticipant<ISiloLifecycle>, ILifecycleObserver, IDisposable { private readonly ILogger logger; private const float KB = 1024f; private PerformanceCounter cpuCounterPF; private PerformanceCounter availableMemoryCounterPF; #if LOG_MEMORY_PERF_COUNTERS private PerformanceCounter timeInGCPF; private PerformanceCounter[] genSizesPF; private PerformanceCounter allocatedBytesPerSecPF; private PerformanceCounter promotedMemoryFromGen1PF; private PerformanceCounter numberOfInducedGCsPF; private PerformanceCounter largeObjectHeapSizePF; private PerformanceCounter promotedFinalizationMemoryFromGen0PF; #endif private SafeTimer cpuUsageTimer; private readonly TimeSpan CPU_CHECK_PERIOD = TimeSpan.FromSeconds(5); private readonly TimeSpan INITIALIZATION_TIMEOUT = TimeSpan.FromMinutes(1); private bool countersAvailable; public long MemoryUsage { get { return GC.GetTotalMemory(false); } } /// /// <summary>Amount of physical memory on the machine</summary> /// public long? TotalPhysicalMemory { get; private set; } /// /// <summary>Amount of memory available to processes running on the machine</summary> /// public long? AvailableMemory { get { return availableMemoryCounterPF != null ? Convert.ToInt64(availableMemoryCounterPF.NextValue()) : (long?)null; } } public float? CpuUsage { get; private set; } private static string GCGenCollectionCount { get { return String.Format("gen0={0}, gen1={1}, gen2={2}", GC.CollectionCount(0), GC.CollectionCount(1), GC.CollectionCount(2)); } } #if LOG_MEMORY_PERF_COUNTERS private string GCGenSizes { get { if (genSizesPF == null) return String.Empty; return String.Format("gen0={0:0.00}, gen1={1:0.00}, gen2={2:0.00}", genSizesPF[0].NextValue() / KB, genSizesPF[1].NextValue() / KB, genSizesPF[2].NextValue() / KB); } } #endif public PerfCounterEnvironmentStatistics(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger<PerfCounterEnvironmentStatistics>(); try { Task.Run(() => { InitCpuMemoryCounters(); }).WaitWithThrow(INITIALIZATION_TIMEOUT); } catch (TimeoutException) { logger.Warn(ErrorCode.PerfCounterConnectError, "Timeout occurred during initialization of CPU & Memory perf counters"); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void InitCpuMemoryCounters() { try { cpuCounterPF = new PerformanceCounter("Processor", "% Processor Time", "_Total", true); availableMemoryCounterPF = new PerformanceCounter("Memory", "Available Bytes", true); #if LOG_MEMORY_PERF_COUNTERS string thisProcess = Process.GetCurrentProcess().ProcessName; timeInGCPF = new PerformanceCounter(".NET CLR Memory", "% Time in GC", thisProcess, true); genSizesPF = new PerformanceCounter[] { new PerformanceCounter(".NET CLR Memory", "Gen 0 heap size", thisProcess, true), new PerformanceCounter(".NET CLR Memory", "Gen 1 heap size", thisProcess, true), new PerformanceCounter(".NET CLR Memory", "Gen 2 heap size", thisProcess, true) }; allocatedBytesPerSecPF = new PerformanceCounter(".NET CLR Memory", "Allocated Bytes/sec", thisProcess, true); promotedMemoryFromGen1PF = new PerformanceCounter(".NET CLR Memory", "Promoted Memory from Gen 1", thisProcess, true); numberOfInducedGCsPF = new PerformanceCounter(".NET CLR Memory", "# Induced GC", thisProcess, true); largeObjectHeapSizePF = new PerformanceCounter(".NET CLR Memory", "Large Object Heap size", thisProcess, true); promotedFinalizationMemoryFromGen0PF = new PerformanceCounter(".NET CLR Memory", "Promoted Finalization-Memory from Gen 0", thisProcess, true); #endif //.NET on Windows without mono const string Query = "SELECT Capacity FROM Win32_PhysicalMemory"; var searcher = new ManagementObjectSearcher(Query); long Capacity = 0; foreach (ManagementObject WniPART in searcher.Get()) Capacity += Convert.ToInt64(WniPART.Properties["Capacity"].Value); if (Capacity == 0) throw new Exception("No physical ram installed on machine?"); TotalPhysicalMemory = Capacity; countersAvailable = true; } catch (Exception) { logger.Warn(ErrorCode.PerfCounterConnectError, "Error initializing CPU & Memory perf counters - you need to repair Windows perf counter config on this machine with 'lodctr /r' command"); } } private void CheckCpuUsage(object m) { if (cpuCounterPF != null) { var currentUsage = cpuCounterPF.NextValue(); // We calculate a decaying average for CPU utilization CpuUsage = (CpuUsage + 2 * currentUsage) / 3; } else { CpuUsage = 0; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")] public void Dispose() { cpuCounterPF?.Dispose(); availableMemoryCounterPF?.Dispose(); timeInGCPF?.Dispose(); if (genSizesPF != null) foreach (var item in genSizesPF) { item?.Dispose(); } allocatedBytesPerSecPF?.Dispose(); promotedMemoryFromGen1PF?.Dispose(); numberOfInducedGCsPF?.Dispose(); largeObjectHeapSizePF?.Dispose(); promotedFinalizationMemoryFromGen0PF?.Dispose(); cpuUsageTimer?.Dispose(); } #region Lifecycle public Task OnStart(CancellationToken ct) { if (!countersAvailable) { logger.Warn(ErrorCode.PerfCounterNotRegistered, "CPU & Memory perf counters did not initialize correctly - try repairing Windows perf counter config on this machine with 'lodctr /r' command"); } if (cpuCounterPF != null) { cpuUsageTimer = new SafeTimer(this.logger, CheckCpuUsage, null, CPU_CHECK_PERIOD, CPU_CHECK_PERIOD); } try { if (cpuCounterPF != null) { // Read initial value of CPU Usage counter CpuUsage = cpuCounterPF.NextValue(); } } catch (InvalidOperationException) { // Can sometimes get exception accessing CPU Usage counter for first time in some runtime environments CpuUsage = 0; } FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_CPUUSAGE, () => CpuUsage.Value); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_TOTALMEMORYKB, () => (long)((MemoryUsage + KB - 1.0) / KB)); // Round up #if LOG_MEMORY_PERF_COUNTERS // print GC stats in the silo log file. StringValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_GENCOLLECTIONCOUNT, () => GCGenCollectionCount); StringValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_GENSIZESKB, () => GCGenSizes); if (timeInGCPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PERCENTOFTIMEINGC, () => timeInGCPF.NextValue()); } if (allocatedBytesPerSecPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_ALLOCATEDBYTESINKBPERSEC, () => allocatedBytesPerSecPF.NextValue() / KB); } if (promotedMemoryFromGen1PF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PROMOTEDMEMORYFROMGEN1KB, () => promotedMemoryFromGen1PF.NextValue() / KB); } if (largeObjectHeapSizePF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_LARGEOBJECTHEAPSIZEKB, () => largeObjectHeapSizePF.NextValue() / KB); } if (promotedFinalizationMemoryFromGen0PF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_PROMOTEDMEMORYFROMGEN0KB, () => promotedFinalizationMemoryFromGen0PF.NextValue() / KB); } if (numberOfInducedGCsPF != null) { FloatValueStatistic.FindOrCreate(StatisticNames.RUNTIME_GC_NUMBEROFINDUCEDGCS, () => numberOfInducedGCsPF.NextValue()); } IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_MEMORY_TOTALPHYSICALMEMORYMB, () => (long)((TotalPhysicalMemory / KB) / KB)); if (availableMemoryCounterPF != null) { IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_MEMORY_AVAILABLEMEMORYMB, () => (long)((AvailableMemory / KB) / KB)); // Round up } #endif IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_DOT_NET_THREADPOOL_INUSE_WORKERTHREADS, () => { int maXworkerThreads; int maXcompletionPortThreads; ThreadPool.GetMaxThreads(out maXworkerThreads, out maXcompletionPortThreads); int workerThreads; int completionPortThreads; // GetAvailableThreads Retrieves the difference between the maximum number of thread pool threads // and the number currently active. // So max-Available is the actual number in use. If it goes beyond min, it means we are stressing the thread pool. ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); return maXworkerThreads - workerThreads; }); IntValueStatistic.FindOrCreate(StatisticNames.RUNTIME_DOT_NET_THREADPOOL_INUSE_COMPLETIONPORTTHREADS, () => { int maxWorkerThreads; int maxCompletionPortThreads; ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionPortThreads); int workerThreads; int completionPortThreads; ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); return maxCompletionPortThreads - completionPortThreads; }); return Task.CompletedTask; } public Task OnStop(CancellationToken ct) { cpuUsageTimer?.Dispose(); cpuUsageTimer = null; return Task.CompletedTask; } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(ServiceLifecycleStage.RuntimeInitialize, this); } #endregion Lifecycle } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel; using System.Threading; using System.Security; using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.Eventing { public class EventProvider : IDisposable { [SecurityCritical] private UnsafeNativeMethods.EtwEnableCallback _etwCallback; // Trace Callback function private long _regHandle; // Trace Registration Handle private byte _level; // Tracing Level private long _anyKeywordMask; // Trace Enable Flags private long _allKeywordMask; // Match all keyword private int _enabled; // Enabled flag from Trace callback private Guid _providerId; // Control Guid private int _disposed; // when 1, provider has unregister [ThreadStatic] private static WriteEventErrorCode t_returnCode; // thread slot to keep last error [ThreadStatic] private static Guid t_activityId; private const int s_basicTypeAllocationBufferSize = 16; private const int s_etwMaxNumberArguments = 32; private const int s_etwAPIMaxStringCount = 8; private const int s_maxEventDataDescriptors = 128; private const int s_traceEventMaximumSize = 65482; private const int s_traceEventMaximumStringSize = 32724; [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] public enum WriteEventErrorCode : int { // check mapping to runtime codes NoError = 0, NoFreeBuffers = 1, EventTooBig = 2 } [StructLayout(LayoutKind.Explicit, Size = 16)] private struct EventData { [FieldOffset(0)] internal ulong DataPointer; [FieldOffset(8)] internal uint Size; [FieldOffset(12)] internal int Reserved; } private enum ActivityControl : uint { EVENT_ACTIVITY_CTRL_GET_ID = 1, EVENT_ACTIVITY_CTRL_SET_ID = 2, EVENT_ACTIVITY_CTRL_CREATE_ID = 3, EVENT_ACTIVITY_CTRL_GET_SET_ID = 4, EVENT_ACTIVITY_CTRL_CREATE_SET_ID = 5 } /// <summary> /// Constructor for EventProvider class. /// </summary> /// <param name="providerGuid"> /// Unique GUID among all trace sources running on a system /// </param> [SecuritySafeCritical] [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "guid")] public EventProvider(Guid providerGuid) { _providerId = providerGuid; // // EtwRegister the ProviderId with ETW // EtwRegister(); } /// <summary> /// This method registers the controlGuid of this class with ETW. /// We need to be running on Vista or above. If not an /// PlatformNotSupported exception will be thrown. /// If for some reason the ETW EtwRegister call failed /// a NotSupported exception will be thrown. /// </summary> [System.Security.SecurityCritical] private unsafe void EtwRegister() { uint status; _etwCallback = new UnsafeNativeMethods.EtwEnableCallback(EtwEnableCallBack); status = UnsafeNativeMethods.EventRegister(ref _providerId, _etwCallback, null, ref _regHandle); if (status != 0) { throw new Win32Exception((int)status); } } // // implement Dispose Pattern to early deregister from ETW insted of waiting for // the finalizer to call deregistration. // Once the user is done with the provider it needs to call Close() or Dispose() // If neither are called the finalizer will unregister the provider anyway // public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } [System.Security.SecuritySafeCritical] protected virtual void Dispose(bool disposing) { // // explicit cleanup is done by calling Dispose with true from // Dispose() or Close(). The disposing argument is ignored because there // are no unmanaged resources. // The finalizer calls Dispose with false. // // // check if the object has been already disposed // if (_disposed == 1) return; if (Interlocked.Exchange(ref _disposed, 1) != 0) { // somebody is already disposing the provider return; } // // Disables Tracing in the provider, then unregister // _enabled = 0; Deregister(); } /// <summary> /// This method deregisters the controlGuid of this class with ETW. /// </summary> public virtual void Close() { Dispose(); } ~EventProvider() { Dispose(false); } /// <summary> /// This method un-registers from ETW. /// </summary> [System.Security.SecurityCritical] private unsafe void Deregister() { // // Unregister from ETW using the RegHandle saved from // the register call. // if (_regHandle != 0) { UnsafeNativeMethods.EventUnregister(_regHandle); _regHandle = 0; } } [System.Security.SecurityCritical] private unsafe void EtwEnableCallBack( [In] ref System.Guid sourceId, [In] int isEnabled, [In] byte setLevel, [In] long anyKeyword, [In] long allKeyword, [In] void* filterData, [In] void* callbackContext ) { _enabled = isEnabled; _level = setLevel; _anyKeywordMask = anyKeyword; _allKeywordMask = allKeyword; return; } /// <summary> /// IsEnabled, method used to test if provider is enabled. /// </summary> public bool IsEnabled() { return (_enabled != 0) ? true : false; } /// <summary> /// IsEnabled, method used to test if event is enabled. /// </summary> /// <param name="level"> /// Level to test /// </param> /// <param name="keywords"> /// Keyword to test /// </param> public bool IsEnabled(byte level, long keywords) { // // If not enabled at all, return false. // if (_enabled == 0) { return false; } // This also covers the case of Level == 0. if ((level <= _level) || (_level == 0)) { // // Check if Keyword is enabled // if ((keywords == 0) || (((keywords & _anyKeywordMask) != 0) && ((keywords & _allKeywordMask) == _allKeywordMask))) { return true; } } return false; } public static WriteEventErrorCode GetLastWriteEventError() { return t_returnCode; } // // Helper function to set the last error on the thread // private static void SetLastError(int error) { switch (error) { case UnsafeNativeMethods.ERROR_ARITHMETIC_OVERFLOW: case UnsafeNativeMethods.ERROR_MORE_DATA: t_returnCode = WriteEventErrorCode.EventTooBig; break; case UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY: t_returnCode = WriteEventErrorCode.NoFreeBuffers; break; } } [System.Security.SecurityCritical] private static unsafe string EncodeObject(ref object data, EventData* dataDescriptor, byte* dataBuffer) /*++ Routine Description: This routine is used by WriteEvent to unbox the object type and to fill the passed in ETW data descriptor. Arguments: data - argument to be decoded dataDescriptor - pointer to the descriptor to be filled dataBuffer - storage buffer for storing user data, needed because cant get the address of the object Return Value: null if the object is a basic type other than string. String otherwise --*/ { dataDescriptor->Reserved = 0; string sRet = data as string; if (sRet != null) { dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; } if (data == null) { dataDescriptor->Size = 0; dataDescriptor->DataPointer = 0; } else if (data is IntPtr) { dataDescriptor->Size = (uint)sizeof(IntPtr); IntPtr* intptrPtr = (IntPtr*)dataBuffer; *intptrPtr = (IntPtr)data; dataDescriptor->DataPointer = (ulong)intptrPtr; } else if (data is int) { dataDescriptor->Size = (uint)sizeof(int); int* intptrPtr = (int*)dataBuffer; *intptrPtr = (int)data; dataDescriptor->DataPointer = (ulong)intptrPtr; } else if (data is long) { dataDescriptor->Size = (uint)sizeof(long); long* longptr = (long*)dataBuffer; *longptr = (long)data; dataDescriptor->DataPointer = (ulong)longptr; } else if (data is uint) { dataDescriptor->Size = (uint)sizeof(uint); uint* uintptr = (uint*)dataBuffer; *uintptr = (uint)data; dataDescriptor->DataPointer = (ulong)uintptr; } else if (data is UInt64) { dataDescriptor->Size = (uint)sizeof(ulong); UInt64* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->DataPointer = (ulong)ulongptr; } else if (data is char) { dataDescriptor->Size = (uint)sizeof(char); char* charptr = (char*)dataBuffer; *charptr = (char)data; dataDescriptor->DataPointer = (ulong)charptr; } else if (data is byte) { dataDescriptor->Size = (uint)sizeof(byte); byte* byteptr = (byte*)dataBuffer; *byteptr = (byte)data; dataDescriptor->DataPointer = (ulong)byteptr; } else if (data is short) { dataDescriptor->Size = (uint)sizeof(short); short* shortptr = (short*)dataBuffer; *shortptr = (short)data; dataDescriptor->DataPointer = (ulong)shortptr; } else if (data is sbyte) { dataDescriptor->Size = (uint)sizeof(sbyte); sbyte* sbyteptr = (sbyte*)dataBuffer; *sbyteptr = (sbyte)data; dataDescriptor->DataPointer = (ulong)sbyteptr; } else if (data is ushort) { dataDescriptor->Size = (uint)sizeof(ushort); ushort* ushortptr = (ushort*)dataBuffer; *ushortptr = (ushort)data; dataDescriptor->DataPointer = (ulong)ushortptr; } else if (data is float) { dataDescriptor->Size = (uint)sizeof(float); float* floatptr = (float*)dataBuffer; *floatptr = (float)data; dataDescriptor->DataPointer = (ulong)floatptr; } else if (data is double) { dataDescriptor->Size = (uint)sizeof(double); double* doubleptr = (double*)dataBuffer; *doubleptr = (double)data; dataDescriptor->DataPointer = (ulong)doubleptr; } else if (data is bool) { dataDescriptor->Size = (uint)sizeof(bool); bool* boolptr = (bool*)dataBuffer; *boolptr = (bool)data; dataDescriptor->DataPointer = (ulong)boolptr; } else if (data is Guid) { dataDescriptor->Size = (uint)sizeof(Guid); Guid* guidptr = (Guid*)dataBuffer; *guidptr = (Guid)data; dataDescriptor->DataPointer = (ulong)guidptr; } else if (data is decimal) { dataDescriptor->Size = (uint)sizeof(decimal); decimal* decimalptr = (decimal*)dataBuffer; *decimalptr = (decimal)data; dataDescriptor->DataPointer = (ulong)decimalptr; } else if (data is Boolean) { dataDescriptor->Size = (uint)sizeof(bool); Boolean* booleanptr = (Boolean*)dataBuffer; *booleanptr = (bool)data; dataDescriptor->DataPointer = (ulong)booleanptr; } else { // To our eyes, everything else is a just a string sRet = data.ToString(); dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; } return null; } /// <summary> /// WriteMessageEvent, method to write a string with level and Keyword. /// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId(). /// </summary> /// <param name="eventMessage"> /// Message to write /// </param> /// <param name="eventLevel"> /// Level to test /// </param> /// <param name="eventKeywords"> /// Keyword to test /// </param> [System.Security.SecurityCritical] public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKeywords) { int status = 0; if (eventMessage == null) { throw new ArgumentNullException("eventMessage"); } if (IsEnabled(eventLevel, eventKeywords)) { if (eventMessage.Length > s_traceEventMaximumStringSize) { t_returnCode = WriteEventErrorCode.EventTooBig; return false; } unsafe { fixed (char* pdata = eventMessage) { status = (int)UnsafeNativeMethods.EventWriteString(_regHandle, eventLevel, eventKeywords, pdata); } if (status != 0) { SetLastError(status); return false; } } } return true; } /// <summary> /// WriteMessageEvent, method to write a string with level=0 and Keyword=0 /// The activity ID will be propagated only if the call stays on the same native thread as SetActivityId(). /// </summary> /// <param name="eventMessage"> /// Message to log /// </param> public bool WriteMessageEvent(string eventMessage) { return WriteMessageEvent(eventMessage, 0, 0); } /// <summary> /// WriteEvent method to write parameters with event schema properties. /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="eventPayload"> /// </param> public bool WriteEvent(ref EventDescriptor eventDescriptor, params object[] eventPayload) { return WriteTransferEvent(ref eventDescriptor, Guid.Empty, eventPayload); } /// <summary> /// WriteEvent, method to write a string with event schema properties. /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="data"> /// string to log. /// </param> [System.Security.SecurityCritical] [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public bool WriteEvent(ref EventDescriptor eventDescriptor, string data) { uint status = 0; if (data == null) { throw new ArgumentNullException("dataString"); } if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { if (data.Length > s_traceEventMaximumStringSize) { t_returnCode = WriteEventErrorCode.EventTooBig; return false; } EventData userData; userData.Size = (uint)((data.Length + 1) * 2); userData.Reserved = 0; unsafe { fixed (char* pdata = data) { Guid activityId = GetActivityId(); userData.DataPointer = (ulong)pdata; status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, null, 1, &userData); } } } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteEvent, method to be used by generated code on a derived class. /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="dataCount"> /// number of event descriptors /// </param> /// <param name="data"> /// pointer do the event data /// </param> [System.Security.SecurityCritical] protected bool WriteEvent(ref EventDescriptor eventDescriptor, int dataCount, IntPtr data) { uint status = 0; unsafe { Guid activityId = GetActivityId(); status = UnsafeNativeMethods.EventWriteTransfer( _regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, null, (uint)dataCount, (void*)data); } if (status != 0) { SetLastError((int)status); return false; } return true; } /// <summary> /// WriteTransferEvent, method to write a parameters with event schema properties. /// </summary> /// <param name="eventDescriptor"> /// Event Descriptor for this event. /// </param> /// <param name="relatedActivityId"> /// </param> /// <param name="eventPayload"> /// </param> [System.Security.SecurityCritical] public bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, params object[] eventPayload) { uint status = 0; if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { Guid activityId = GetActivityId(); unsafe { int argCount = 0; EventData* userDataPtr = null; if ((eventPayload != null) && (eventPayload.Length != 0)) { argCount = eventPayload.Length; if (argCount > s_etwMaxNumberArguments) { // // too many arguments to log // throw new ArgumentOutOfRangeException("eventPayload", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxArgExceeded, s_etwMaxNumberArguments)); } uint totalEventSize = 0; int index; int stringIndex = 0; int[] stringPosition = new int[s_etwAPIMaxStringCount]; // used to keep the position of strings in the eventPayload parameter string[] dataString = new string[s_etwAPIMaxStringCount]; // string arrays from the eventPayload parameter EventData* userData = stackalloc EventData[argCount]; // allocation for the data descriptors userDataPtr = (EventData*)userData; byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * argCount]; // 16 byte for unboxing non-string argument byte* currentBuffer = dataBuffer; // // The loop below goes through all the arguments and fills in the data // descriptors. For strings save the location in the dataString array. // Calculates the total size of the event by adding the data descriptor // size value set in EncodeObjec method. // for (index = 0; index < eventPayload.Length; index++) { string isString; isString = EncodeObject(ref eventPayload[index], userDataPtr, currentBuffer); currentBuffer += s_basicTypeAllocationBufferSize; totalEventSize += userDataPtr->Size; userDataPtr++; if (isString != null) { if (stringIndex < s_etwAPIMaxStringCount) { dataString[stringIndex] = isString; stringPosition[stringIndex] = index; stringIndex++; } else { throw new ArgumentOutOfRangeException("eventPayload", string.Format(CultureInfo.CurrentCulture, DotNetEventingStrings.ArgumentOutOfRange_MaxStringsExceeded, s_etwAPIMaxStringCount)); } } } if (totalEventSize > s_traceEventMaximumSize) { t_returnCode = WriteEventErrorCode.EventTooBig; return false; } fixed (char* v0 = dataString[0], v1 = dataString[1], v2 = dataString[2], v3 = dataString[3], v4 = dataString[4], v5 = dataString[5], v6 = dataString[6], v7 = dataString[7]) { userDataPtr = (EventData*)userData; if (dataString[0] != null) { userDataPtr[stringPosition[0]].DataPointer = (ulong)v0; } if (dataString[1] != null) { userDataPtr[stringPosition[1]].DataPointer = (ulong)v1; } if (dataString[2] != null) { userDataPtr[stringPosition[2]].DataPointer = (ulong)v2; } if (dataString[3] != null) { userDataPtr[stringPosition[3]].DataPointer = (ulong)v3; } if (dataString[4] != null) { userDataPtr[stringPosition[4]].DataPointer = (ulong)v4; } if (dataString[5] != null) { userDataPtr[stringPosition[5]].DataPointer = (ulong)v5; } if (dataString[6] != null) { userDataPtr[stringPosition[6]].DataPointer = (ulong)v6; } if (dataString[7] != null) { userDataPtr[stringPosition[7]].DataPointer = (ulong)v7; } } } status = UnsafeNativeMethods.EventWriteTransfer(_regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, (relatedActivityId == Guid.Empty) ? null : &relatedActivityId, (uint)argCount, userDataPtr); } } if (status != 0) { SetLastError((int)status); return false; } return true; } [System.Security.SecurityCritical] protected bool WriteTransferEvent(ref EventDescriptor eventDescriptor, Guid relatedActivityId, int dataCount, IntPtr data) { uint status = 0; Guid activityId = GetActivityId(); unsafe { status = UnsafeNativeMethods.EventWriteTransfer( _regHandle, ref eventDescriptor, (activityId == Guid.Empty) ? null : &activityId, &relatedActivityId, (uint)dataCount, (void*)data); } if (status != 0) { SetLastError((int)status); return false; } return true; } [System.Security.SecurityCritical] private static Guid GetActivityId() { return t_activityId; } [System.Security.SecurityCritical] public static void SetActivityId(ref Guid id) { t_activityId = id; UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_SET_ID, ref id); } [System.Security.SecurityCritical] public static Guid CreateActivityId() { Guid newId = new Guid(); UnsafeNativeMethods.EventActivityIdControl((int)ActivityControl.EVENT_ACTIVITY_CTRL_CREATE_ID, ref newId); return newId; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Gigya.Common.Contracts.Exceptions; using Gigya.Microdot.Fakes; using Gigya.Microdot.Interfaces.SystemWrappers; using Gigya.Microdot.ServiceDiscovery; using Gigya.Microdot.ServiceDiscovery.Config; using Gigya.Microdot.Testing.Shared; using Gigya.Microdot.Testing.Shared.Utils; using Metrics; using Ninject; using NSubstitute; using NUnit.Framework; using Shouldly; namespace Gigya.Microdot.UnitTests.Discovery { [TestFixture,Parallelizable(ParallelScope.Fixtures)] public class ConsulDiscoveryMasterFallBackTest { private const string ServiceVersion = "1.2.30.1234"; private string _serviceName; private const string MASTER_ENVIRONMENT = "prod"; private const string ORIGINATING_ENVIRONMENT = "fake_env"; private readonly TimeSpan _timeOut = TimeSpan.FromSeconds(5); private Dictionary<string, string> _configDic; private TestingKernel<ConsoleLog> _unitTestingKernel; private Dictionary<string, ConsulClientMock> _consulClient; private IEnvironment _environment; private ManualConfigurationEvents _configRefresh; private IDateTime _dateTimeMock; private int id; private const int Repeat = 1; [SetUp] public void SetUp() { _serviceName = $"ServiceName{++id}"; _environment = Substitute.For<IEnvironment>(); _environment.Zone.Returns("il3"); _environment.DeploymentEnvironment.Returns(ORIGINATING_ENVIRONMENT); _configDic = new Dictionary<string, string> {{"Discovery.EnvironmentFallbackEnabled", "true"}}; _unitTestingKernel = new TestingKernel<ConsoleLog>(k => { k.Rebind<IEnvironment>().ToConstant(_environment); k.Rebind<IDiscoverySourceLoader>().To<DiscoverySourceLoader>().InSingletonScope(); SetupConsulClientMocks(); k.Rebind<Func<string, IConsulClient>>().ToMethod(_ => (s => _consulClient[s])); _dateTimeMock = Substitute.For<IDateTime>(); _dateTimeMock.Delay(Arg.Any<TimeSpan>()).Returns(c => Task.Delay(TimeSpan.FromMilliseconds(100))); k.Rebind<IDateTime>().ToConstant(_dateTimeMock); }, _configDic); _configRefresh = _unitTestingKernel.Get<ManualConfigurationEvents>(); var environment = _unitTestingKernel.Get<IEnvironment>(); Assert.AreEqual(_environment, environment); } [TearDown] public void Teardown() { _unitTestingKernel?.Dispose(); _configDic?.Clear(); _configDic = null; _configRefresh = null; _consulClient?.Clear(); _consulClient = null; } private void SetupConsulClientMocks() { _consulClient = new Dictionary<string, ConsulClientMock>(); CreateConsulMock(MasterService); CreateConsulMock(OriginatingService); } private void CreateConsulMock(string serviceName) { var mock = new ConsulClientMock(); mock.SetResult(new EndPointsResult { EndPoints = new EndPoint[] {new ConsulEndPoint {HostName = "dumy", Version = ServiceVersion}}, IsQueryDefined = true }); _consulClient[serviceName] = mock; } [TearDown] public void TearDown() { _unitTestingKernel.Dispose(); foreach (var consulClient in _consulClient) { consulClient.Value.Dispose(); } } [Test] [Repeat(Repeat)] public async Task QueryNotDefinedShouldFallBackToMaster() { SetMockToReturnHost(MasterService); SetMockToReturnServiceNotDefined(OriginatingService); var nextHost = GetServiceDiscovey().GetNextHost(); nextHost.Result.HostName.ShouldBe(MasterService); } [Test] [Repeat(Repeat)] public async Task FallBackToMasterShouldNotHaveOriginatingServiceHealth() { SetMockToReturnHost(MasterService); SetMockToReturnServiceNotDefined(OriginatingService); var nextHost = await GetServiceDiscovey().GetNextHost(); HealthChecks.GetStatus().Results.Single(_ => _.Name == MasterService).Check.IsHealthy.ShouldBeTrue(); HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == OriginatingService); } [Test] [Repeat(Repeat)] public async Task NoFallBackShouldNotHavMasterServiceHealth() { SetMockToReturnServiceNotDefined(MasterService); SetMockToReturnHost(OriginatingService); var nextHost = await GetServiceDiscovey().GetNextHost(); HealthChecks.GetStatus().Results.Single(_ => _.Name == OriginatingService).Check.IsHealthy.ShouldBeTrue(); HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == MasterService); } [Test] [Repeat(Repeat)] public async Task CreateServiceDiscoveyWithoutGetNextHostNoServiceHealthShouldAppear() { SetMockToReturnHost(MasterService); SetMockToReturnServiceNotDefined(OriginatingService); var serviceDiscovey = GetServiceDiscovey(); HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == MasterService); HealthChecks.GetStatus().Results.ShouldNotContain(_ => _.Name == OriginatingService); } [Test] [Repeat(Repeat)] public async Task ScopeZoneShouldUseServiceNameAsConsoleQuery() { _unitTestingKernel.Get<Func<DiscoveryConfig>>()().Services[_serviceName].Scope = ServiceScope.Zone; SetMockToReturnHost(_serviceName); var nextHost = GetServiceDiscovey().GetNextHost(); (await nextHost).HostName.ShouldBe(_serviceName); } [Test] [Repeat(Repeat)] public async Task WhenQueryDeleteShouldFallBackToMaster() { var reloadInterval = TimeSpan.FromMilliseconds(5); _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); SetMockToReturnHost(MasterService); SetMockToReturnHost(OriginatingService); var discovey = GetServiceDiscovey(); var waitForEvents = discovey.EndPointsChanged.WhenEventReceived(_timeOut); var nextHost = discovey.GetNextHost(); (await nextHost).HostName.ShouldBe(OriginatingService); SetMockToReturnServiceNotDefined(OriginatingService); await waitForEvents; nextHost = discovey.GetNextHost(); (await nextHost).HostName.ShouldBe(MasterService); } [Test] [Repeat(Repeat)] public async Task WhenQueryAddShouldNotFallBackToMaster() { var reloadInterval = TimeSpan.FromMilliseconds(5); _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); SetMockToReturnHost(MasterService); SetMockToReturnServiceNotDefined(OriginatingService); var discovey = GetServiceDiscovey(); var nextHost = discovey.GetNextHost(); (await nextHost).HostName.ShouldBe(MasterService); var waitForEvents = discovey.EndPointsChanged.WhenEventReceived(_timeOut); SetMockToReturnHost(OriginatingService); await waitForEvents; nextHost = GetServiceDiscovey().GetNextHost(); nextHost.Result.HostName.ShouldBe(OriginatingService); } [Test] [Repeat(Repeat)] public async Task ShouldNotFallBackToMasterOnConsulError() { SetMockToReturnHost(MasterService); SetMockToReturnError(OriginatingService); var exception = Should.Throw<EnvironmentException>(() => GetServiceDiscovey().GetNextHost()); exception.UnencryptedTags["responseLog"].ShouldBe("Error response log"); exception.UnencryptedTags["queryDefined"].ShouldBe("True"); exception.UnencryptedTags["consulError"].ShouldNotBeNullOrEmpty(); exception.UnencryptedTags["requestedService"].ShouldBe(OriginatingService); } [Test] [Repeat(Repeat)] public async Task QueryDefinedShouldNotFallBackToMaster() { SetMockToReturnHost(MasterService); SetMockToReturnHost(OriginatingService); var nextHost = GetServiceDiscovey().GetNextHost(); (await nextHost).HostName.ShouldBe(OriginatingService); } [Test] [Repeat(Repeat)] public void MasterShouldNotFallBack() { _environment = Substitute.For<IEnvironment>(); _environment.Zone.Returns("il3"); _environment.DeploymentEnvironment.Returns(MASTER_ENVIRONMENT); _unitTestingKernel.Rebind<IEnvironment>().ToConstant(_environment); SetMockToReturnServiceNotDefined(MasterService); Should.Throw<EnvironmentException>(() => GetServiceDiscovey().GetNextHost()); } [Test] [Repeat(Repeat)] public async Task EndPointsChangedShouldNotFireWhenNothingChange() { TimeSpan reloadInterval = TimeSpan.FromMilliseconds(5); _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); int numOfEvent = 0; SetMockToReturnHost(MasterService); SetMockToReturnHost(OriginatingService); //in the first time can fire one or two event var discovey = GetServiceDiscovey(); discovey.GetNextHost(); discovey.EndPointsChanged.LinkTo(new ActionBlock<string>(x => numOfEvent++)); Thread.Sleep(200); numOfEvent = 0; for (int i = 0; i < 5; i++) { discovey.GetNextHost(); Thread.Sleep((int) reloadInterval.TotalMilliseconds * 10); } numOfEvent.ShouldBe(0); } [Test] [Repeat(Repeat)] public async Task EndPointsChangedShouldFireConfigChange() { SetMockToReturnHost(MasterService); SetMockToReturnHost(OriginatingService); //in the first time can fire one or two event var discovey = GetServiceDiscovey(); var waitForEvents = discovey.EndPointsChanged.StartCountingEvents(); await discovey.GetNextHost(); _configDic[$"Discovery.Services.{_serviceName}.Hosts"] = "localhost"; _configDic[$"Discovery.Services.{_serviceName}.Source"] = "Config"; Task waitForChangeEvent = waitForEvents.WhenNextEventReceived(); await _configRefresh.ApplyChanges<DiscoveryConfig>(); await waitForChangeEvent; var host = await discovey.GetNextHost(); host.HostName.ShouldBe("localhost"); waitForEvents.ReceivedEvents.Count.ShouldBe(1); } [Test] [Repeat(Repeat)] public async Task GetAllEndPointsChangedShouldFireConfigChange() { SetMockToReturnHost(MasterService); SetMockToReturnHost(OriginatingService); //in the first time can fire one or two event var discovey = GetServiceDiscovey(); //wait for discovey to be initialize!! var endPoints = await discovey.GetAllEndPoints(); endPoints.Single().HostName.ShouldBe(OriginatingService); var waitForEvents = discovey.EndPointsChanged.StartCountingEvents(); _configDic[$"Discovery.Services.{_serviceName}.Source"] = "Config"; _configDic[$"Discovery.Services.{_serviceName}.Hosts"] = "localhost"; Console.WriteLine("RaiseChangeEvent"); Task waitForChangeEvent = waitForEvents.WhenNextEventReceived(); _configRefresh.RaiseChangeEvent(); await waitForChangeEvent; waitForEvents.ReceivedEvents.Count.ShouldBe(1); endPoints = await discovey.GetAllEndPoints(); endPoints.Single().HostName.ShouldBe("localhost"); waitForEvents.ReceivedEvents.Count.ShouldBe(1); } [Test] [Repeat(Repeat)] public async Task EndPointsChangedShouldFireWhenHostChange() { var reloadInterval = TimeSpan.FromMilliseconds(5); _configDic[$"Discovery.Services.{_serviceName}.ReloadInterval"] = reloadInterval.ToString(); SetMockToReturnHost(MasterService); SetMockToReturnHost(OriginatingService); var discovey = GetServiceDiscovey(); await discovey.GetAllEndPoints(); var wait = discovey.EndPointsChanged.StartCountingEvents(); bool UseOriginatingService(int i) => i % 2 == 0; for (int i = 1; i < 6; i++) { var waitForNextEvent = wait.WhenNextEventReceived(); //act if (UseOriginatingService(i)) SetMockToReturnHost(OriginatingService); else SetMockToReturnServiceNotDefined(OriginatingService); await waitForNextEvent; //assert wait.ReceivedEvents.Count.ShouldBe(i); var nextHost = (await discovey.GetNextHost()).HostName; if (UseOriginatingService(i)) nextHost.ShouldBe(OriginatingService); else nextHost.ShouldBe(MasterService); } } private void SetMockToReturnHost(string serviceName) { if (!_consulClient.ContainsKey(serviceName)) CreateConsulMock(serviceName); _consulClient[serviceName].SetResult( new EndPointsResult { EndPoints = new EndPoint[] {new ConsulEndPoint {HostName = serviceName, Version = ServiceVersion}}, RequestLog = "<Mock consul request log>", ResponseLog = "<Mock consul response>", ActiveVersion = ServiceVersion, IsQueryDefined = true }); } private void SetMockToReturnServiceNotDefined(string serviceName) { _consulClient[serviceName].SetResult(new EndPointsResult {IsQueryDefined = false}); } private void SetMockToReturnError(string serviceName) { _consulClient[serviceName].SetResult( new EndPointsResult { Error = new EnvironmentException("Mock: some error"), IsQueryDefined = true, ResponseLog = "Error response log" }); } [Test] public void ServiceDiscoveySameNameShouldBeTheSame() { Assert.AreEqual(GetServiceDiscovey(), GetServiceDiscovey()); } private readonly ReachabilityChecker _reachabilityChecker = x => Task.FromResult(true); private IServiceDiscovery GetServiceDiscovey() { var discovery = _unitTestingKernel.Get<Func<string, ReachabilityChecker, IServiceDiscovery>>()(_serviceName, _reachabilityChecker); Task.Delay(200).GetAwaiter() .GetResult(); // let ConsulClient return the expected result before getting the dicovery object return discovery; } private string MasterService => ConsulServiceName(_serviceName, MASTER_ENVIRONMENT); private string OriginatingService => ConsulServiceName(_serviceName, ORIGINATING_ENVIRONMENT); private static string ConsulServiceName(string serviceName, string deploymentEnvironment) => $"{serviceName}-{deploymentEnvironment}"; } }
namespace StockSharp.Algo.Storages { using System; using System.Collections.Generic; using System.Net; using System.IO; using Ecng.Common; using Ecng.Serialization; using Ecng.ComponentModel; using Ecng.Collections; using StockSharp.BusinessEntities; using StockSharp.Messages; using StockSharp.Algo.Storages.Remote; /// <summary> /// Remote storage of market data working via <see cref="RemoteStorageClient"/>. /// </summary> public class RemoteMarketDataDrive : BaseMarketDataDrive { private sealed class RemoteStorageDrive : IMarketDataStorageDrive { private readonly RemoteMarketDataDrive _parent; private readonly SecurityId _securityId; private readonly DataType _dataType; private readonly StorageFormats _format; public RemoteStorageDrive(RemoteMarketDataDrive parent, SecurityId securityId, DataType dataType, StorageFormats format) { if (securityId.IsDefault()) throw new ArgumentNullException(nameof(securityId)); if (dataType == null) throw new ArgumentNullException(nameof(dataType)); // TODO //if (drive == null) // throw new ArgumentNullException(nameof(drive)); _parent = parent ?? throw new ArgumentNullException(nameof(parent)); _securityId = securityId; _dataType = dataType ?? throw new ArgumentNullException(nameof(dataType)); _format = format; } IMarketDataDrive IMarketDataStorageDrive.Drive => _parent; private IEnumerable<DateTime> _dates; private DateTime _prevDatesSync; IEnumerable<DateTime> IMarketDataStorageDrive.Dates { get { if (_prevDatesSync.IsDefault() || (DateTime.Now - _prevDatesSync).TotalSeconds > 3) { _dates = _parent.CreateClient().GetDates(_securityId, _dataType, _format); _prevDatesSync = DateTime.Now; } return _dates; } } void IMarketDataStorageDrive.ClearDatesCache() { //_parent.Invoke(f => f.ClearDatesCache(_parent.SessionId, _security.Id, _dataType, _arg)); } void IMarketDataStorageDrive.Delete(DateTime date) => _parent.CreateClient().Delete(_securityId, _dataType, _format, date); void IMarketDataStorageDrive.SaveStream(DateTime date, Stream stream) => _parent.CreateClient().SaveStream(_securityId, _dataType, _format, date, stream); Stream IMarketDataStorageDrive.LoadStream(DateTime date) => _parent.CreateClient().LoadStream(_securityId, _dataType, _format, date); } private readonly SynchronizedDictionary<Tuple<SecurityId, DataType, StorageFormats>, RemoteStorageDrive> _remoteStorages = new(); private readonly Func<IMessageAdapter> _createAdapter; /// <summary> /// Default value for <see cref="Address"/>. /// </summary> public static readonly EndPoint DefaultAddress = "127.0.0.1:5002".To<EndPoint>(); /// <summary> /// Default value for <see cref="TargetCompId"/>. /// </summary> public static readonly string DefaultTargetCompId = "StockSharpHydraMD"; /// <summary> /// Initializes a new instance of the <see cref="RemoteMarketDataDrive"/>. /// </summary> public RemoteMarketDataDrive() : this(DefaultAddress) { } /// <summary> /// Initializes a new instance of the <see cref="RemoteMarketDataDrive"/>. /// </summary> /// <param name="address">Server address.</param> public RemoteMarketDataDrive(EndPoint address) : this(address, () => ServicesRegistry.AdapterProvider.CreateTransportAdapter(new IncrementalIdGenerator())) { } /// <summary> /// Initializes a new instance of the <see cref="RemoteMarketDataDrive"/>. /// </summary> /// <param name="address">Server address.</param> /// <param name="adapter">Message adapter.</param> public RemoteMarketDataDrive(EndPoint address, IMessageAdapter adapter) : this(address, adapter.TypedClone) { if (adapter is null) throw new ArgumentNullException(nameof(adapter)); } private RemoteMarketDataDrive(EndPoint address, Func<IMessageAdapter> createAdapter) { Address = address; _createAdapter = createAdapter; } /// <summary> /// Information about the login and password for access to remote storage. /// </summary> public ServerCredentials Credentials { get; } = new ServerCredentials(); private EndPoint _address = DefaultAddress; /// <summary> /// Server address. /// </summary> public EndPoint Address { get => _address; set => _address = value ?? throw new ArgumentNullException(nameof(value)); } private string _targetCompId = DefaultTargetCompId; /// <summary> /// Target ID. /// </summary> public string TargetCompId { get => _targetCompId; set { if (value.IsEmpty()) throw new ArgumentNullException(nameof(value)); _targetCompId = value; } } /// <inheritdoc /> public override string Path { get => Address.To<string>(); set { if (value.IsEmpty()) throw new ArgumentNullException(nameof(value)); if (value.StartsWithIgnoreCase("net.tcp://")) { var uri = value.To<Uri>(); value = $"{uri.Host}:{uri.Port}"; } Address = value.To<EndPoint>(); } } private RemoteStorageClient CreateClient() { var adapter = _createAdapter(); ((IAddressAdapter<EndPoint>)adapter).Address = Address; ((ILoginPasswordAdapter)adapter).Password = Credentials.Password; var login = Credentials.Email; if (login.IsEmpty()) login = "stocksharp"; ((ISenderTargetAdapter)adapter).SenderCompId = login; ((ISenderTargetAdapter)adapter).TargetCompId = TargetCompId; return new RemoteStorageClient(adapter); } /// <inheritdoc /> public override IEnumerable<SecurityId> AvailableSecurities => CreateClient().AvailableSecurities; /// <inheritdoc /> public override IEnumerable<DataType> GetAvailableDataTypes(SecurityId securityId, StorageFormats format) => CreateClient().GetAvailableDataTypes(securityId, format); /// <inheritdoc /> public override IMarketDataStorageDrive GetStorageDrive(SecurityId securityId, DataType dataType, StorageFormats format) { if (dataType is null) throw new ArgumentNullException(nameof(dataType)); return _remoteStorages.SafeAdd(Tuple.Create(securityId, dataType, format), key => new RemoteStorageDrive(this, securityId, dataType, format)); } /// <inheritdoc /> public override void Verify() => CreateClient().Verify(); /// <inheritdoc /> public override void LookupSecurities(SecurityLookupMessage criteria, ISecurityProvider securityProvider, Action<SecurityMessage> newSecurity, Func<bool> isCancelled, Action<int, int> updateProgress) => CreateClient().LookupSecurities(criteria, securityProvider, newSecurity, isCancelled, updateProgress); /// <inheritdoc /> public override void Load(SettingsStorage storage) { base.Load(storage); TargetCompId = storage.GetValue(nameof(TargetCompId), TargetCompId); Credentials.Load(storage.GetValue<SettingsStorage>(nameof(Credentials))); } /// <inheritdoc /> public override void Save(SettingsStorage storage) { base.Save(storage); storage.SetValue(nameof(TargetCompId), TargetCompId); storage.SetValue(nameof(Credentials), Credentials.Save()); } } }
// 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.Concurrent; using System.IO; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; // NOTE: // Currently the managed handler is opt-in on both Windows and Unix, due to still being a nascent implementation // that's missing features, robustness, perf, etc. One opts into it currently by setting an environment variable, // which makes it a bit difficult to test. There are two straightforward ways to test it: // - This file contains test classes that derive from the other test classes in the project that create // HttpClient{Handler} instances, and in the ctor sets the env var and in Dispose removes the env var. // That has the effect of running all of those same tests again, but with the managed handler enabled. // - By setting the env var prior to running tests, every test will implicitly use the managed handler, // at which point the tests in this file are duplicative and can be commented out. namespace System.Net.Http.Functional.Tests { public sealed class ManagedHandler_HttpClientTest : HttpClientTest, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_DiagnosticsTest : DiagnosticsTest, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientEKUTest : HttpClientEKUTest, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test : HttpClientHandler_DangerousAcceptAllCertificatesValidator_Test, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientHandler_ClientCertificates_Test : HttpClientHandler_ClientCertificates_Test, IDisposable { public ManagedHandler_HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output) : base(output) { } protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientHandler_DefaultProxyCredentials_Test : HttpClientHandler_DefaultProxyCredentials_Test, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientHandler_MaxConnectionsPerServer_Test : HttpClientHandler_MaxConnectionsPerServer_Test, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientHandler_ServerCertificates_Test : HttpClientHandler_ServerCertificates_Test, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_PostScenarioTest : PostScenarioTest, IDisposable { public ManagedHandler_PostScenarioTest(ITestOutputHelper output) : base(output) { } protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_ResponseStreamTest : ResponseStreamTest, IDisposable { public ManagedHandler_ResponseStreamTest(ITestOutputHelper output) : base(output) { } protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientHandler_SslProtocols_Test : HttpClientHandler_SslProtocols_Test, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_SchSendAuxRecordHttpTest : SchSendAuxRecordHttpTest, IDisposable { public ManagedHandler_SchSendAuxRecordHttpTest(ITestOutputHelper output) : base(output) { } protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientMiniStress : HttpClientMiniStress, IDisposable { protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_HttpClientHandlerTest : HttpClientHandlerTest, IDisposable { public ManagedHandler_HttpClientHandlerTest(ITestOutputHelper output) : base(output) { } protected override bool UseManagedHandler => true; } public sealed class ManagedHandler_DefaultCredentialsTest : DefaultCredentialsTest, IDisposable { public ManagedHandler_DefaultCredentialsTest(ITestOutputHelper output) : base(output) { } protected override bool UseManagedHandler => true; } // TODO #23141: Socket's don't support canceling individual operations, so ReadStream on NetworkStream // isn't cancelable once the operation has started. We either need to wrap the operation with one that's // "cancelable", meaning that the underlying operation will still be running even though we've returned "canceled", // or we need to just recognize that cancellation in such situations can be left up to the caller to do the // same thing if it's really important. //public sealed class ManagedHandler_CancellationTest : CancellationTest, IDisposable //{ // public ManagedHandler_CancellationTest(ITestOutputHelper output) : base(output) { } // protected override bool UseManagedHandler => true; //} // TODO #23142: The managed handler doesn't currently track how much data was written for the response headers. //public sealed class ManagedHandler_HttpClientHandler_MaxResponseHeadersLength_Test : HttpClientHandler_MaxResponseHeadersLength_Test, IDisposable //{ // protected override bool UseManagedHandler => true; //} public sealed class ManagedHandler_HttpClientHandler_DuplexCommunication_Test : HttpClientTestBase, IDisposable { protected override bool UseManagedHandler => true; [Fact] public async Task SendBytesBackAndForthBetweenClientAndServer_Success() { using (HttpClient client = CreateHttpClient()) using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); var ep = (IPEndPoint)listener.LocalEndPoint; var clientToServerStream = new ProducerConsumerStream(); clientToServerStream.WriteByte(0); var reqMsg = new HttpRequestMessage { RequestUri = new Uri($"http://{ep.Address}:{ep.Port}/"), Content = new StreamContent(clientToServerStream), }; Task<HttpResponseMessage> req = client.SendAsync(reqMsg, HttpCompletionOption.ResponseHeadersRead); using (Socket server = await listener.AcceptAsync()) using (var serverStream = new NetworkStream(server, ownsSocket: false)) { // Skip request headers. while (true) { if (serverStream.ReadByte() == '\r') { serverStream.ReadByte(); break; } while (serverStream.ReadByte() != '\r') { } serverStream.ReadByte(); } // Send response headers. await server.SendAsync( new ArraySegment<byte>(Encoding.ASCII.GetBytes($"HTTP/1.1 200 OK\r\nConnection: close\r\nDate: {DateTimeOffset.UtcNow:R}\r\n\r\n")), SocketFlags.None); HttpResponseMessage resp = await req; Stream serverToClientStream = await resp.Content.ReadAsStreamAsync(); // Communication should now be open between the client and server. // Ping pong bytes back and forth. for (byte i = 0; i < 100; i++) { // Send a byte from the client to the server. The server will receive // the byte as a chunk. if (i > 0) clientToServerStream.WriteByte(i); // 0 was already seeded when the stream was created above Assert.Equal('1', serverStream.ReadByte()); Assert.Equal('\r', serverStream.ReadByte()); Assert.Equal('\n', serverStream.ReadByte()); Assert.Equal(i, serverStream.ReadByte()); Assert.Equal('\r', serverStream.ReadByte()); Assert.Equal('\n', serverStream.ReadByte()); // Send a byte from the server to the client. The client will receive // the byte on its own, with HttpClient stripping away the chunk encoding. serverStream.WriteByte(i); Assert.Equal(i, serverToClientStream.ReadByte()); } clientToServerStream.DoneWriting(); server.Shutdown(SocketShutdown.Send); Assert.Equal(-1, clientToServerStream.ReadByte()); } } } private sealed class ProducerConsumerStream : Stream { private readonly BlockingCollection<byte[]> _buffers = new BlockingCollection<byte[]>(); private ArraySegment<byte> _remaining; public override void Write(byte[] buffer, int offset, int count) { if (count > 0) { byte[] tmp = new byte[count]; Buffer.BlockCopy(buffer, offset, tmp, 0, count); _buffers.Add(tmp); } } public override int Read(byte[] buffer, int offset, int count) { if (count > 0) { if (_remaining.Count == 0) { if (!_buffers.TryTake(out byte[] tmp, Timeout.Infinite)) { return 0; } _remaining = new ArraySegment<byte>(tmp, 0, tmp.Length); } if (_remaining.Count <= count) { count = _remaining.Count; Buffer.BlockCopy(_remaining.Array, _remaining.Offset, buffer, offset, count); _remaining = default(ArraySegment<byte>); } else { Buffer.BlockCopy(_remaining.Array, _remaining.Offset, buffer, offset, count); _remaining = new ArraySegment<byte>(_remaining.Array, _remaining.Offset + count, _remaining.Count - count); } } return count; } public void DoneWriting() => _buffers.CompleteAdding(); public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; public override long Length => throw new NotImplementedException(); public override long Position { get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) => throw new NotImplementedException(); public override void SetLength(long value) => throw new NotImplementedException(); } } public sealed class ManagedHandler_HttpClientHandler_ConnectionPooling_Test : HttpClientTestBase, IDisposable { protected override bool UseManagedHandler => true; // TODO: Currently the subsequent tests sometimes fail/hang with WinHttpHandler / CurlHandler. // In theory they should pass with any handler that does appropriate connection pooling. // We should understand why they sometimes fail there and ideally move them to be // used by all handlers this test project tests. [Fact] public async Task MultipleIterativeRequests_SameConnectionReused() { using (HttpClient client = CreateHttpClient()) using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); var ep = (IPEndPoint)listener.LocalEndPoint; var uri = new Uri($"http://{ep.Address}:{ep.Port}/"); string responseBody = "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 0\r\n" + "\r\n"; Task<string> firstRequest = client.GetStringAsync(uri); using (Socket server = await listener.AcceptAsync()) using (var serverStream = new NetworkStream(server, ownsSocket: false)) using (var serverReader = new StreamReader(serverStream)) { while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync())); await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None); await firstRequest; Task<Socket> secondAccept = listener.AcceptAsync(); // shouldn't complete Task<string> additionalRequest = client.GetStringAsync(uri); while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync())); await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None); await additionalRequest; Assert.False(secondAccept.IsCompleted, $"Second accept should never complete"); } } } [OuterLoop("Incurs a delay")] [Fact] public async Task ServerDisconnectsAfterInitialRequest_SubsequentRequestUsesDifferentConnection() { using (HttpClient client = CreateHttpClient()) using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(100); var ep = (IPEndPoint)listener.LocalEndPoint; var uri = new Uri($"http://{ep.Address}:{ep.Port}/"); string responseBody = "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 0\r\n" + "\r\n"; // Make multiple requests iteratively. for (int i = 0; i < 2; i++) { Task<string> request = client.GetStringAsync(uri); using (Socket server = await listener.AcceptAsync()) using (var serverStream = new NetworkStream(server, ownsSocket: false)) using (var serverReader = new StreamReader(serverStream)) { while (!string.IsNullOrWhiteSpace(await serverReader.ReadLineAsync())); await server.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None); await request; server.Shutdown(SocketShutdown.Both); if (i == 0) { await Task.Delay(2000); // give client time to see the closing before next connect } } } } } [Fact] public async Task ServerSendsConnectionClose_SubsequentRequestUsesDifferentConnection() { using (HttpClient client = CreateHttpClient()) using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(100); var ep = (IPEndPoint)listener.LocalEndPoint; var uri = new Uri($"http://{ep.Address}:{ep.Port}/"); string responseBody = "HTTP/1.1 200 OK\r\n" + $"Date: {DateTimeOffset.UtcNow:R}\r\n" + "Content-Length: 0\r\n" + "Connection: close\r\n" + "\r\n"; // Make multiple requests iteratively. Task<string> request1 = client.GetStringAsync(uri); using (Socket server1 = await listener.AcceptAsync()) using (var serverStream1 = new NetworkStream(server1, ownsSocket: false)) using (var serverReader1 = new StreamReader(serverStream1)) { while (!string.IsNullOrWhiteSpace(await serverReader1.ReadLineAsync())); await server1.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None); await request1; Task<string> request2 = client.GetStringAsync(uri); using (Socket server2 = await listener.AcceptAsync()) using (var serverStream2 = new NetworkStream(server2, ownsSocket: false)) using (var serverReader2 = new StreamReader(serverStream2)) { while (!string.IsNullOrWhiteSpace(await serverReader2.ReadLineAsync())); await server2.SendAsync(new ArraySegment<byte>(Encoding.ASCII.GetBytes(responseBody)), SocketFlags.None); await request2; } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using System.Net.Internals; using System.Net.Sockets; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; namespace System.Net { /// <devdoc> /// <para>Provides simple /// domain name resolution functionality.</para> /// </devdoc> public static class Dns { // Host names any longer than this automatically fail at the winsock level. // If the host name is 255 chars, the last char must be a dot. private const int MaxHostName = 255; [Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static IPHostEntry GetHostByName(string hostName) { NameResolutionPal.EnsureSocketsAreInitialized(); if (hostName == null) { throw new ArgumentNullException(nameof(hostName)); } // See if it's an IP Address. IPAddress address; if (IPAddress.TryParse(hostName, out address)) { return NameResolutionUtilities.GetUnresolvedAnswer(address); } return InternalGetHostByName(hostName, false); } private static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName); IPHostEntry ipHostEntry = null; if (hostName.Length > MaxHostName // If 255 chars, the last one must be a dot. || hostName.Length == MaxHostName && hostName[MaxHostName - 1] != '.') { throw new ArgumentOutOfRangeException(nameof(hostName), SR.Format(SR.net_toolong, nameof(hostName), MaxHostName.ToString(NumberFormatInfo.CurrentInfo))); } // // IPv6 Changes: IPv6 requires the use of getaddrinfo() rather // than the traditional IPv4 gethostbyaddr() / gethostbyname(). // getaddrinfo() is also protocol independent in that it will also // resolve IPv4 names / addresses. As a result, it is the preferred // resolution mechanism on platforms that support it (Windows 5.1+). // If getaddrinfo() is unsupported, IPv6 resolution does not work. // // Consider : If IPv6 is disabled, we could detect IPv6 addresses // and throw an unsupported platform exception. // // Note : Whilst getaddrinfo is available on WinXP+, we only // use it if IPv6 is enabled (platform is part of that // decision). This is done to minimize the number of // possible tests that are needed. // if (includeIPv6 || SocketProtocolSupportPal.OSSupportsIPv6) { // // IPv6 enabled: use getaddrinfo() to obtain DNS information. // int nativeErrorCode; SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, out ipHostEntry, out nativeErrorCode); if (errorCode != SocketError.Success) { throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode); } } else { ipHostEntry = NameResolutionPal.GetHostByName(hostName); } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } // GetHostByName [Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static IPHostEntry GetHostByAddress(string address) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address); NameResolutionPal.EnsureSocketsAreInitialized(); if (address == null) { throw new ArgumentNullException(nameof(address)); } IPHostEntry ipHostEntry = InternalGetHostByAddress(IPAddress.Parse(address), false); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } // GetHostByAddress [Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static IPHostEntry GetHostByAddress(IPAddress address) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address); NameResolutionPal.EnsureSocketsAreInitialized(); if (address == null) { throw new ArgumentNullException(nameof(address)); } IPHostEntry ipHostEntry = InternalGetHostByAddress(address, false); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } // GetHostByAddress // Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods). private static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6) { if (NetEventSource.IsEnabled) NetEventSource.Info(null, address); // // IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions // for resolution of IPv6 addresses. // if (SocketProtocolSupportPal.OSSupportsIPv6 || includeIPv6) { // // Try to get the data for the host from it's address // // We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string // will only return that address and not the full list. // Do a reverse lookup to get the host name. SocketError errorCode; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(address, out errorCode, out nativeErrorCode); if (errorCode == SocketError.Success) { // Do the forward lookup to get the IPs for that host name IPHostEntry hostEntry; errorCode = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode); if (errorCode == SocketError.Success) { return hostEntry; } if (NetEventSource.IsEnabled) NetEventSource.Error(null, SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode)); // One of two things happened: // 1. There was a ptr record in dns, but not a corollary A/AAA record. // 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix. // - Workaround, Check "Use this connection's dns suffix in dns registration" on that network // adapter's advanced dns settings. // Just return the resolved host name and no IPs. return hostEntry; } throw SocketExceptionFactory.CreateSocketException(errorCode, nativeErrorCode); } // // If IPv6 is not enabled (maybe config switch) but we've been // given an IPv6 address then we need to bail out now. // else { if (address.AddressFamily == AddressFamily.InterNetworkV6) { // // Protocol not supported // throw new SocketException((int)SocketError.ProtocolNotSupported); } // // Use gethostbyaddr() to try to resolve the IP address // // End IPv6 Changes // return NameResolutionPal.GetHostByAddr(address); } } // InternalGetHostByAddress /***************************************************************************** Function : gethostname Abstract: Queries the hostname from DNS Input Parameters: Returns: String ******************************************************************************/ /// <devdoc> /// <para>Gets the host name of the local machine.</para> /// </devdoc> public static string GetHostName() { if (NetEventSource.IsEnabled) NetEventSource.Info(null, null); NameResolutionPal.EnsureSocketsAreInitialized(); return NameResolutionPal.GetHostName(); } [Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static IPHostEntry Resolve(string hostName) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName); NameResolutionPal.EnsureSocketsAreInitialized(); if (hostName == null) { throw new ArgumentNullException(nameof(hostName)); } // See if it's an IP Address. IPAddress address; IPHostEntry ipHostEntry; if (IPAddress.TryParse(hostName, out address) && (address.AddressFamily != AddressFamily.InterNetworkV6 || SocketProtocolSupportPal.OSSupportsIPv6)) { try { ipHostEntry = InternalGetHostByAddress(address, false); } catch (SocketException ex) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex); ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address); } } else { ipHostEntry = InternalGetHostByName(hostName, false); } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } private class ResolveAsyncResult : ContextAwareResult { // Forward lookup internal ResolveAsyncResult(string hostName, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { this.hostName = hostName; this.includeIPv6 = includeIPv6; } // Reverse lookup internal ResolveAsyncResult(IPAddress address, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { this.includeIPv6 = includeIPv6; this.address = address; } internal readonly string hostName; internal bool includeIPv6; internal IPAddress address; } private static void ResolveCallback(object context) { ResolveAsyncResult result = (ResolveAsyncResult)context; IPHostEntry hostEntry; try { if (result.address != null) { hostEntry = InternalGetHostByAddress(result.address, result.includeIPv6); } else { hostEntry = InternalGetHostByName(result.hostName, result.includeIPv6); } } catch (OutOfMemoryException) { throw; } catch (Exception exception) { result.InvokeCallback(exception); return; } result.InvokeCallback(hostEntry); } // Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical // If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the original address is returned. private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, bool includeIPv6, bool throwOnIIPAny, AsyncCallback requestCallback, object state) { if (hostName == null) { throw new ArgumentNullException(nameof(hostName)); } if (NetEventSource.IsEnabled) NetEventSource.Info(null, hostName); // See if it's an IP Address. IPAddress address; ResolveAsyncResult asyncResult; if (IPAddress.TryParse(hostName, out address)) { if (throwOnIIPAny && (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))) { throw new ArgumentException(SR.net_invalid_ip_addr, nameof(hostName)); } asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback); if (justReturnParsedIp) { IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address); asyncResult.StartPostingAsyncOp(false); asyncResult.InvokeCallback(hostEntry); asyncResult.FinishPostingAsyncOp(); return asyncResult; } } else { asyncResult = new ResolveAsyncResult(hostName, null, includeIPv6, state, requestCallback); } // Set up the context, possibly flow. asyncResult.StartPostingAsyncOp(false); // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return asyncResult; } private static IAsyncResult HostResolutionBeginHelper(IPAddress address, bool flowContext, bool includeIPv6, AsyncCallback requestCallback, object state) { if (address == null) { throw new ArgumentNullException(nameof(address)); } if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.net_invalid_ip_addr, nameof(address)); } if (NetEventSource.IsEnabled) NetEventSource.Info(null, address); // Set up the context, possibly flow. ResolveAsyncResult asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback); if (flowContext) { asyncResult.StartPostingAsyncOp(false); } // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return asyncResult; } private static IPHostEntry HostResolutionEndHelper(IAsyncResult asyncResult) { // // parameter validation // if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } ResolveAsyncResult castedResult = asyncResult as ResolveAsyncResult; if (castedResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndResolve))); } if (NetEventSource.IsEnabled) NetEventSource.Info(null); castedResult.InternalWaitForCompletion(); castedResult.EndCalled = true; Exception exception = castedResult.Result as Exception; if (exception != null) { ExceptionDispatchInfo.Throw(exception); } return (IPHostEntry)castedResult.Result; } [Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static IAsyncResult BeginGetHostByName(string hostName, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName); NameResolutionPal.EnsureSocketsAreInitialized(); IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, true, true, false, requestCallback, stateObject); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult); return asyncResult; } // BeginGetHostByName [Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static IPHostEntry EndGetHostByName(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult); NameResolutionPal.EnsureSocketsAreInitialized(); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } // EndGetHostByName() public static IPHostEntry GetHostEntry(string hostNameOrAddress) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress); NameResolutionPal.EnsureSocketsAreInitialized(); if (hostNameOrAddress == null) { throw new ArgumentNullException(nameof(hostNameOrAddress)); } // See if it's an IP Address. IPAddress address; IPHostEntry ipHostEntry; if (IPAddress.TryParse(hostNameOrAddress, out address)) { if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress))); } ipHostEntry = InternalGetHostByAddress(address, true); } else { ipHostEntry = InternalGetHostByName(hostNameOrAddress, true); } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } public static IPHostEntry GetHostEntry(IPAddress address) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address); NameResolutionPal.EnsureSocketsAreInitialized(); if (address == null) { throw new ArgumentNullException(nameof(address)); } if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(address))); } IPHostEntry ipHostEntry = InternalGetHostByAddress(address, true); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } // GetHostEntry public static IPAddress[] GetHostAddresses(string hostNameOrAddress) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress); NameResolutionPal.EnsureSocketsAreInitialized(); if (hostNameOrAddress == null) { throw new ArgumentNullException(nameof(hostNameOrAddress)); } // See if it's an IP Address. IPAddress address; IPAddress[] addresses; if (IPAddress.TryParse(hostNameOrAddress, out address)) { if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.Format(SR.net_invalid_ip_addr, nameof(hostNameOrAddress))); } addresses = new IPAddress[] { address }; } else { // InternalGetHostByName works with IP addresses (and avoids a reverse-lookup), but we need // explicit handling in order to do the ArgumentException and guarantee the behavior. addresses = InternalGetHostByName(hostNameOrAddress, true).AddressList; } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, addresses); return addresses; } public static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress); NameResolutionPal.EnsureSocketsAreInitialized(); IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, false, true, true, requestCallback, stateObject); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult); return asyncResult; } // BeginResolve public static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, address); NameResolutionPal.EnsureSocketsAreInitialized(); IAsyncResult asyncResult = HostResolutionBeginHelper(address, true, true, requestCallback, stateObject); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult); return asyncResult; } // BeginResolve public static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } // EndResolve() public static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostNameOrAddress); NameResolutionPal.EnsureSocketsAreInitialized(); IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, true, true, true, requestCallback, state); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult); return asyncResult; } // BeginResolve public static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry.AddressList; } // EndResolveToAddresses [Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static IAsyncResult BeginResolve(string hostName, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, hostName); NameResolutionPal.EnsureSocketsAreInitialized(); IAsyncResult asyncResult = HostResolutionBeginHelper(hostName, false, false, false, requestCallback, stateObject); if (NetEventSource.IsEnabled) NetEventSource.Exit(null, asyncResult); return asyncResult; } // BeginResolve [Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead. http://go.microsoft.com/fwlink/?linkid=14202")] public static IPHostEntry EndResolve(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(null, asyncResult); IPHostEntry ipHostEntry; try { ipHostEntry = HostResolutionEndHelper(asyncResult); } catch (SocketException ex) { IPAddress address = ((ResolveAsyncResult)asyncResult).address; if (address == null) throw; // BeginResolve was called with a HostName, not an IPAddress if (NetEventSource.IsEnabled) NetEventSource.Error(null, ex); ipHostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address); } if (NetEventSource.IsEnabled) NetEventSource.Exit(null, ipHostEntry); return ipHostEntry; } // EndResolve() //************* Task-based async public methods ************************* public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress) { NameResolutionPal.EnsureSocketsAreInitialized(); return Task<IPAddress[]>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostAddresses(arg, requestCallback, stateObject), asyncResult => EndGetHostAddresses(asyncResult), hostNameOrAddress, null); } public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address) { NameResolutionPal.EnsureSocketsAreInitialized(); return Task<IPHostEntry>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject), asyncResult => EndGetHostEntry(asyncResult), address, null); } public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress) { NameResolutionPal.EnsureSocketsAreInitialized(); return Task<IPHostEntry>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject), asyncResult => EndGetHostEntry(asyncResult), hostNameOrAddress, null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using UnityEngine; namespace UnityEditor.VFX { // Attribute used to normalize a Vector or float [System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class NormalizeAttribute : PropertyAttribute { } // Attribute used to display a float in degrees in the UI [System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class AngleAttribute : PropertyAttribute { } // Attribute used to constrain a property to a Regex query [System.AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)] public sealed class RegexAttribute : PropertyAttribute { public RegexAttribute(string _pattern, int _maxLength = int.MaxValue) { pattern = _pattern; maxLength = _maxLength; } public string pattern { get; set; } public int maxLength { get; set; } } [Serializable] class VFXPropertyAttribute { private static readonly Dictionary<System.Type, Func<object, VFXPropertyAttribute>> s_RegisteredAttributes = new Dictionary<System.Type, Func<object, VFXPropertyAttribute>>() { { typeof(RangeAttribute), o => new VFXPropertyAttribute(Type.kRange, (o as RangeAttribute).min, (o as RangeAttribute).max) }, { typeof(MinAttribute), o => new VFXPropertyAttribute(Type.kMin, (o as MinAttribute).min) }, { typeof(NormalizeAttribute), o => new VFXPropertyAttribute(Type.kNormalize) }, { typeof(TooltipAttribute), o => new VFXPropertyAttribute(Type.kTooltip, (o as TooltipAttribute).tooltip) }, { typeof(AngleAttribute), o => new VFXPropertyAttribute(Type.kAngle) }, { typeof(ShowAsColorAttribute), o => new VFXPropertyAttribute(Type.kColor) }, { typeof(RegexAttribute), o => new VFXPropertyAttribute(Type.kRegex, (o as RegexAttribute).pattern, (o as RegexAttribute).maxLength) }, { typeof(DelayedAttribute), o => new VFXPropertyAttribute(Type.kDelayed) }, }; public static VFXPropertyAttribute[] Create(params object[] attributes) { return attributes.SelectMany(a => s_RegisteredAttributes.Where(o => o.Key.IsAssignableFrom(a.GetType())) .Select(o => o.Value(a))).ToArray(); } public static VFXExpression ApplyToExpressionGraph(VFXPropertyAttribute[] attributes, VFXExpression exp) { if (attributes != null) { foreach (VFXPropertyAttribute attribute in attributes) { switch (attribute.m_Type) { case Type.kRange: exp = VFXOperatorUtility.Clamp(exp, VFXValue.Constant(attribute.m_Min), VFXValue.Constant(attribute.m_Max)); break; case Type.kMin: exp = new VFXExpressionMax(exp, VFXOperatorUtility.CastFloat(VFXValue.Constant(attribute.m_Min), exp.valueType)); break; case Type.kNormalize: exp = VFXOperatorUtility.Normalize(exp); break; case Type.kTooltip: case Type.kAngle: case Type.kColor: case Type.kRegex: case Type.kDelayed: break; default: throw new NotImplementedException(); } } } return exp; } public static void ApplyToGUI(VFXPropertyAttribute[] attributes, ref string label, ref string tooltip) { if (attributes != null) { foreach (VFXPropertyAttribute attribute in attributes) { switch (attribute.m_Type) { case Type.kRange: break; case Type.kMin: label += " (Min: " + attribute.m_Min + ")"; break; case Type.kNormalize: label += " (Normalized)"; break; case Type.kTooltip: tooltip = attribute.m_Tooltip; break; case Type.kAngle: label += " (Angle)"; break; case Type.kColor: case Type.kRegex: case Type.kDelayed: break; default: throw new NotImplementedException(); } } } } public static Vector2 FindRange(VFXPropertyAttribute[] attributes) { if (attributes != null) { VFXPropertyAttribute attribute = attributes.FirstOrDefault(o => o.m_Type == Type.kRange); if (attribute != null) return new Vector2(attribute.m_Min, attribute.m_Max); attribute = attributes.FirstOrDefault(o => o.m_Type == Type.kMin); if (attribute != null) return new Vector2(attribute.m_Min, Mathf.Infinity); } return Vector2.zero; } public static bool IsAngle(VFXPropertyAttribute[] attributes) { if (attributes != null) return attributes.Any(o => o.m_Type == Type.kAngle); return false; } public static bool IsColor(VFXPropertyAttribute[] attributes) { if (attributes != null) return attributes.Any(o => o.m_Type == Type.kColor); return false; } public static bool IsDelayed(VFXPropertyAttribute[] attributes) { if (attributes != null) return attributes.Any(o => o.m_Type == Type.kDelayed); return false; } public static string ApplyRegex(VFXPropertyAttribute[] attributes, object obj) { if (attributes != null) { var attrib = attributes.FirstOrDefault(o => o.m_Type == Type.kRegex); if (attrib != null) { string str = (string)obj; str = Regex.Replace(str, attrib.m_Regex, ""); return str.Substring(0, Math.Min(str.Length, attrib.m_RegexMaxLength)); } } return null; } public enum Type { kRange, kMin, kNormalize, kTooltip, kAngle, kColor, kRegex, kDelayed } public VFXPropertyAttribute(Type type, float min = -Mathf.Infinity, float max = Mathf.Infinity) { m_Type = type; m_Min = min; m_Max = max; } public VFXPropertyAttribute(Type type, string str, int regexMaxLength = int.MaxValue) { m_Type = type; m_Min = -Mathf.Infinity; m_Max = Mathf.Infinity; if (type == Type.kTooltip) { m_Tooltip = str; } else { m_Regex = str; m_RegexMaxLength = regexMaxLength; } } [SerializeField] private Type m_Type; [SerializeField] private float m_Min; [SerializeField] private float m_Max; [SerializeField] private string m_Tooltip; [SerializeField] private string m_Regex; [SerializeField] private int m_RegexMaxLength; } }
// 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 RegexWriter class is internal to the Regex package. // It builds a block of regular expression codes (RegexCode) // from a RegexTree parse tree. // Implementation notes: // // This step is as simple as walking the tree and emitting // sequences of codes. // using System.Collections; using System.Collections.Generic; using System.Globalization; namespace System.Text.RegularExpressions { internal sealed class RegexWriter { private int[] _intStack; private int _depth; private int[] _emitted; private int _curpos; private readonly Dictionary<string, int> _stringhash; private readonly List<String> _stringtable; private bool _counting; private int _count; private int _trackcount; private Hashtable _caps; private const int BeforeChild = 64; private const int AfterChild = 128; /// <summary> /// This is the only function that should be called from outside. /// It takes a RegexTree and creates a corresponding RegexCode. /// </summary> internal static RegexCode Write(RegexTree t) { RegexWriter w = new RegexWriter(); RegexCode retval = w.RegexCodeFromRegexTree(t); #if DEBUG if (t.Debug) { t.Dump(); retval.Dump(); } #endif return retval; } // Private constructor; can't be created outside private RegexWriter() { _intStack = new int[32]; _emitted = new int[32]; _stringhash = new Dictionary<string, int>(); _stringtable = new List<String>(); } /// <summary> /// To avoid recursion, we use a simple integer stack. /// This is the push. /// </summary> private void PushInt(int i) { if (_depth >= _intStack.Length) { int[] expanded = new int[_depth * 2]; Array.Copy(_intStack, 0, expanded, 0, _depth); _intStack = expanded; } _intStack[_depth++] = i; } /// <summary> /// <c>true</c> if the stack is empty. /// </summary> private bool EmptyStack() { return _depth == 0; } /// <summary> /// This is the pop. /// </summary> private int PopInt() { return _intStack[--_depth]; } /// <summary> /// Returns the current position in the emitted code. /// </summary> private int CurPos() { return _curpos; } /// <summary> /// Fixes up a jump instruction at the specified offset /// so that it jumps to the specified jumpDest. /// </summary> private void PatchJump(int offset, int jumpDest) { _emitted[offset + 1] = jumpDest; } /// <summary> /// Emits a zero-argument operation. Note that the emit /// functions all run in two modes: they can emit code, or /// they can just count the size of the code. /// </summary> private void Emit(int op) { if (_counting) { _count += 1; if (RegexCode.OpcodeBacktracks(op)) _trackcount += 1; return; } _emitted[_curpos++] = op; } /// <summary> /// Emits a one-argument operation. /// </summary> private void Emit(int op, int opd1) { if (_counting) { _count += 2; if (RegexCode.OpcodeBacktracks(op)) _trackcount += 1; return; } _emitted[_curpos++] = op; _emitted[_curpos++] = opd1; } /// <summary> /// Emits a two-argument operation. /// </summary> private void Emit(int op, int opd1, int opd2) { if (_counting) { _count += 3; if (RegexCode.OpcodeBacktracks(op)) _trackcount += 1; return; } _emitted[_curpos++] = op; _emitted[_curpos++] = opd1; _emitted[_curpos++] = opd2; } /// <summary> /// Returns an index in the string table for a string; /// uses a hashtable to eliminate duplicates. /// </summary> private int StringCode(String str) { if (_counting) return 0; if (str == null) str = String.Empty; Int32 i; if (!_stringhash.TryGetValue(str, out i)) { i = _stringtable.Count; _stringhash[str] = i; _stringtable.Add(str); } return i; } /// <summary> /// When generating code on a regex that uses a sparse set /// of capture slots, we hash them to a dense set of indices /// for an array of capture slots. Instead of doing the hash /// at match time, it's done at compile time, here. /// </summary> private int MapCapnum(int capnum) { if (capnum == -1) return -1; if (_caps != null) return (int)_caps[capnum]; else return capnum; } /// <summary> /// The top level RegexCode generator. It does a depth-first walk /// through the tree and calls EmitFragment to emits code before /// and after each child of an interior node, and at each leaf. /// /// It runs two passes, first to count the size of the generated /// code, and second to generate the code. /// /// We should time it against the alternative, which is /// to just generate the code and grow the array as we go. /// </summary> private RegexCode RegexCodeFromRegexTree(RegexTree tree) { RegexNode curNode; int curChild; int capsize; RegexPrefix fcPrefix; RegexPrefix prefix; int anchors; RegexBoyerMoore bmPrefix; bool rtl; // construct sparse capnum mapping if some numbers are unused if (tree._capnumlist == null || tree._captop == tree._capnumlist.Length) { capsize = tree._captop; _caps = null; } else { capsize = tree._capnumlist.Length; _caps = tree._caps; for (int i = 0; i < tree._capnumlist.Length; i++) _caps[tree._capnumlist[i]] = i; } _counting = true; for (; ;) { if (!_counting) _emitted = new int[_count]; curNode = tree._root; curChild = 0; Emit(RegexCode.Lazybranch, 0); for (; ;) { if (curNode._children == null) { EmitFragment(curNode._type, curNode, 0); } else if (curChild < curNode._children.Count) { EmitFragment(curNode._type | BeforeChild, curNode, curChild); curNode = (RegexNode)curNode._children[curChild]; PushInt(curChild); curChild = 0; continue; } if (EmptyStack()) break; curChild = PopInt(); curNode = curNode._next; EmitFragment(curNode._type | AfterChild, curNode, curChild); curChild++; } PatchJump(0, CurPos()); Emit(RegexCode.Stop); if (!_counting) break; _counting = false; } fcPrefix = RegexFCD.FirstChars(tree); prefix = RegexFCD.Prefix(tree); rtl = ((tree._options & RegexOptions.RightToLeft) != 0); CultureInfo culture = (tree._options & RegexOptions.CultureInvariant) != 0 ? CultureInfo.InvariantCulture : CultureInfo.CurrentCulture; if (prefix != null && prefix.Prefix.Length > 0) bmPrefix = new RegexBoyerMoore(prefix.Prefix, prefix.CaseInsensitive, rtl, culture); else bmPrefix = null; anchors = RegexFCD.Anchors(tree); return new RegexCode(_emitted, _stringtable, _trackcount, _caps, capsize, bmPrefix, fcPrefix, anchors, rtl); } /// <summary> /// The main RegexCode generator. It does a depth-first walk /// through the tree and calls EmitFragment to emits code before /// and after each child of an interior node, and at each leaf. /// </summary> private void EmitFragment(int nodetype, RegexNode node, int curIndex) { int bits = 0; if (nodetype <= RegexNode.Ref) { if (node.UseOptionR()) bits |= RegexCode.Rtl; if ((node._options & RegexOptions.IgnoreCase) != 0) bits |= RegexCode.Ci; } switch (nodetype) { case RegexNode.Concatenate | BeforeChild: case RegexNode.Concatenate | AfterChild: case RegexNode.Empty: break; case RegexNode.Alternate | BeforeChild: if (curIndex < node._children.Count - 1) { PushInt(CurPos()); Emit(RegexCode.Lazybranch, 0); } break; case RegexNode.Alternate | AfterChild: { if (curIndex < node._children.Count - 1) { int LBPos = PopInt(); PushInt(CurPos()); Emit(RegexCode.Goto, 0); PatchJump(LBPos, CurPos()); } else { int I; for (I = 0; I < curIndex; I++) { PatchJump(PopInt(), CurPos()); } } break; } case RegexNode.Testref | BeforeChild: switch (curIndex) { case 0: Emit(RegexCode.Setjump); PushInt(CurPos()); Emit(RegexCode.Lazybranch, 0); Emit(RegexCode.Testref, MapCapnum(node._m)); Emit(RegexCode.Forejump); break; } break; case RegexNode.Testref | AfterChild: switch (curIndex) { case 0: { int Branchpos = PopInt(); PushInt(CurPos()); Emit(RegexCode.Goto, 0); PatchJump(Branchpos, CurPos()); Emit(RegexCode.Forejump); if (node._children.Count > 1) break; // else fallthrough goto case 1; } case 1: PatchJump(PopInt(), CurPos()); break; } break; case RegexNode.Testgroup | BeforeChild: switch (curIndex) { case 0: Emit(RegexCode.Setjump); Emit(RegexCode.Setmark); PushInt(CurPos()); Emit(RegexCode.Lazybranch, 0); break; } break; case RegexNode.Testgroup | AfterChild: switch (curIndex) { case 0: Emit(RegexCode.Getmark); Emit(RegexCode.Forejump); break; case 1: int Branchpos = PopInt(); PushInt(CurPos()); Emit(RegexCode.Goto, 0); PatchJump(Branchpos, CurPos()); Emit(RegexCode.Getmark); Emit(RegexCode.Forejump); if (node._children.Count > 2) break; // else fallthrough goto case 2; case 2: PatchJump(PopInt(), CurPos()); break; } break; case RegexNode.Loop | BeforeChild: case RegexNode.Lazyloop | BeforeChild: if (node._n < Int32.MaxValue || node._m > 1) Emit(node._m == 0 ? RegexCode.Nullcount : RegexCode.Setcount, node._m == 0 ? 0 : 1 - node._m); else Emit(node._m == 0 ? RegexCode.Nullmark : RegexCode.Setmark); if (node._m == 0) { PushInt(CurPos()); Emit(RegexCode.Goto, 0); } PushInt(CurPos()); break; case RegexNode.Loop | AfterChild: case RegexNode.Lazyloop | AfterChild: { int StartJumpPos = CurPos(); int Lazy = (nodetype - (RegexNode.Loop | AfterChild)); if (node._n < Int32.MaxValue || node._m > 1) Emit(RegexCode.Branchcount + Lazy, PopInt(), node._n == Int32.MaxValue ? Int32.MaxValue : node._n - node._m); else Emit(RegexCode.Branchmark + Lazy, PopInt()); if (node._m == 0) PatchJump(PopInt(), StartJumpPos); } break; case RegexNode.Group | BeforeChild: case RegexNode.Group | AfterChild: break; case RegexNode.Capture | BeforeChild: Emit(RegexCode.Setmark); break; case RegexNode.Capture | AfterChild: Emit(RegexCode.Capturemark, MapCapnum(node._m), MapCapnum(node._n)); break; case RegexNode.Require | BeforeChild: // NOTE: the following line causes lookahead/lookbehind to be // NON-BACKTRACKING. It can be commented out with (*) Emit(RegexCode.Setjump); Emit(RegexCode.Setmark); break; case RegexNode.Require | AfterChild: Emit(RegexCode.Getmark); // NOTE: the following line causes lookahead/lookbehind to be // NON-BACKTRACKING. It can be commented out with (*) Emit(RegexCode.Forejump); break; case RegexNode.Prevent | BeforeChild: Emit(RegexCode.Setjump); PushInt(CurPos()); Emit(RegexCode.Lazybranch, 0); break; case RegexNode.Prevent | AfterChild: Emit(RegexCode.Backjump); PatchJump(PopInt(), CurPos()); Emit(RegexCode.Forejump); break; case RegexNode.Greedy | BeforeChild: Emit(RegexCode.Setjump); break; case RegexNode.Greedy | AfterChild: Emit(RegexCode.Forejump); break; case RegexNode.One: case RegexNode.Notone: Emit(node._type | bits, (int)node._ch); break; case RegexNode.Notoneloop: case RegexNode.Notonelazy: case RegexNode.Oneloop: case RegexNode.Onelazy: if (node._m > 0) Emit(((node._type == RegexNode.Oneloop || node._type == RegexNode.Onelazy) ? RegexCode.Onerep : RegexCode.Notonerep) | bits, (int)node._ch, node._m); if (node._n > node._m) Emit(node._type | bits, (int)node._ch, node._n == Int32.MaxValue ? Int32.MaxValue : node._n - node._m); break; case RegexNode.Setloop: case RegexNode.Setlazy: if (node._m > 0) Emit(RegexCode.Setrep | bits, StringCode(node._str), node._m); if (node._n > node._m) Emit(node._type | bits, StringCode(node._str), (node._n == Int32.MaxValue) ? Int32.MaxValue : node._n - node._m); break; case RegexNode.Multi: Emit(node._type | bits, StringCode(node._str)); break; case RegexNode.Set: Emit(node._type | bits, StringCode(node._str)); break; case RegexNode.Ref: Emit(node._type | bits, MapCapnum(node._m)); break; case RegexNode.Nothing: case RegexNode.Bol: case RegexNode.Eol: case RegexNode.Boundary: case RegexNode.Nonboundary: case RegexNode.ECMABoundary: case RegexNode.NonECMABoundary: case RegexNode.Beginning: case RegexNode.Start: case RegexNode.EndZ: case RegexNode.End: Emit(node._type); break; default: throw new ArgumentException(SR.Format(SR.UnexpectedOpcode, nodetype.ToString(CultureInfo.CurrentCulture))); } } } }
//depot/DevDiv/private/Whidbey_Xws/ndp/fx/src/Net/System/UriScheme.cs#4 - edit change 914456 (text) /*++ Copyright (c) Microsoft Corporation Module Name: UriScheme.cs Abstract: Provides extensibility contract for System.Uri The contains only public API definition. For remaining internal stuff please refer to the _UriSyntax.cs file. Author: Alexei Vopilov 19-Dec-2003 Revision History: Alexei Vopilov 60-July-2004 - Changed the extensiblity model to be based purely on derivation, also has cut Config extensibility option --*/ namespace System { using System.Net; using System.Globalization; using System.Security.Permissions; // // The class is used as a base for custom uri parsing and derived Uri factoring. // A set of protected .ctors allows to hookup on the builtin parser behaviors. // // A developer must implement at least internal default .ctor to participate in the Uri extensibility game. // public abstract partial class UriParser { internal string SchemeName { get { return m_Scheme; } } internal int DefaultPort { get { return m_Port; } } private const UriSyntaxFlags SchemeOnlyFlags = UriSyntaxFlags.MayHavePath; // This is a "scheme-only" base parser, everything after the scheme is // returned as the path component. // The user parser will need to do the majority of the work itself. // // However when the ctor is called from OnCreateUri context the calling parser // settings will later override the result on the base class // protected UriParser(): this (SchemeOnlyFlags) { } // // Is called on each Uri ctor for every non-simple parser i.e. the one that does have // user code. // protected virtual UriParser OnNewUri() { return this; } // // Is called whenever a parser gets registered with some scheme // The base implementaion is a nop. // protected virtual void OnRegister(string schemeName, int defaultPort) { } // // Parses and validates a Uri object, is called at the Uri ctor time. // // This method returns a non null parsingError if Uri being created is invalid: // protected virtual void InitializeAndValidate(Uri uri, out UriFormatException parsingError) { parsingError = uri.ParseMinimal(); } // // Resolves a relative Uri object into new AbsoluteUri. // // baseUri - The baseUri used to resolve this Uri. // relativeuri - A relative Uri string passed by the application. // // This method returns: // The result Uri value used to represent a new Uri // protected virtual string Resolve(Uri baseUri, Uri relativeUri, out UriFormatException parsingError) { if (baseUri.UserDrivenParsing) throw new InvalidOperationException(SR.GetString(SR.net_uri_UserDrivenParsing, this.GetType().FullName)); if (!baseUri.IsAbsoluteUri) throw new InvalidOperationException(SR.GetString(SR.net_uri_NotAbsolute)); string newUriString = null; bool userEscaped = false; Uri result = Uri.ResolveHelper(baseUri, relativeUri, ref newUriString, ref userEscaped, out parsingError); if (parsingError != null) return null; if (result != null) return result.OriginalString; return newUriString; } // // // protected virtual bool IsBaseOf(Uri baseUri, Uri relativeUri) { return baseUri.IsBaseOfHelper(relativeUri); } // // This method is invoked to allow a cutsom parser to override the // internal parser when serving application with Uri componenet strings. // The output format depends on the "format" parameter // // Parameters: // uriComponents - Which components are to be retrieved. // uriFormat - The requested output format. // // This method returns: // The final result. The base impementaion could be invoked to get a suggested value // protected virtual string GetComponents(Uri uri, UriComponents components, UriFormat format) { if (((components & UriComponents.SerializationInfoString) != 0) && components != UriComponents.SerializationInfoString) throw new ArgumentOutOfRangeException("components", components, SR.GetString(SR.net_uri_NotJustSerialization)); if ((format & ~UriFormat.SafeUnescaped) != 0) throw new ArgumentOutOfRangeException("format"); if (uri.UserDrivenParsing) throw new InvalidOperationException(SR.GetString(SR.net_uri_UserDrivenParsing, this.GetType().FullName)); if (!uri.IsAbsoluteUri) throw new InvalidOperationException(SR.GetString(SR.net_uri_NotAbsolute)); return uri.GetComponentsHelper(components, format); } // // // protected virtual bool IsWellFormedOriginalString(Uri uri) { return uri.InternalIsWellFormedOriginalString(); } // // Static Registration methods // // // Registers a custom Uri parser based on a scheme string // public static void Register(UriParser uriParser, string schemeName, int defaultPort) { ExceptionHelper.InfrastructurePermission.Demand(); if (uriParser == null) throw new ArgumentNullException("uriParser"); if (schemeName == null) throw new ArgumentNullException("schemeName"); if (schemeName.Length == 1) throw new ArgumentOutOfRangeException("schemeName"); if (!Uri.CheckSchemeName(schemeName)) throw new ArgumentOutOfRangeException("schemeName"); if ((defaultPort >= 0xFFFF || defaultPort < 0) && defaultPort != -1) throw new ArgumentOutOfRangeException("defaultPort"); schemeName = schemeName.ToLower(CultureInfo.InvariantCulture); FetchSyntax(uriParser, schemeName, defaultPort); } // // Is a Uri scheme known to System.Uri? // public static bool IsKnownScheme(string schemeName) { if (schemeName == null) throw new ArgumentNullException("schemeName"); if (!Uri.CheckSchemeName(schemeName)) throw new ArgumentOutOfRangeException("schemeName"); UriParser syntax = UriParser.GetSyntax(schemeName.ToLower(CultureInfo.InvariantCulture)); return syntax != null && syntax.NotAny(UriSyntaxFlags.V1_UnknownUri); } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.Reflection; using System.IO; using System.Globalization; using System.Threading; namespace AlterCollation { public class MainForm : Form, IScriptExecuteCallback { #region Windows Form Designer generated code /// <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); } private System.Windows.Forms.CheckBox dropAllE; private System.Windows.Forms.Button cancelB; private System.Windows.Forms.ComboBox languageE; private System.Windows.Forms.Label languageL; private System.Windows.Forms.Label labelNote2; private System.Windows.Forms.Label labelNote1; private System.Windows.Forms.ComboBox collationE; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.Button scriptB; private System.Windows.Forms.RichTextBox feedbackL; private System.Windows.Forms.Button executeB; private System.Windows.Forms.Label collationL; private System.Windows.Forms.Label databaseL; private System.Windows.Forms.Label passwordL; private System.Windows.Forms.Label userIdL; private System.Windows.Forms.Label serverL; private System.Windows.Forms.TextBox passwordE; private System.Windows.Forms.TextBox userIdE; private System.Windows.Forms.CheckBox integratedE; private System.Windows.Forms.TextBox databaseE; private System.Windows.Forms.TextBox serverE; private System.Windows.Forms.CheckBox singleUserE; private System.Windows.Forms.Timer cancelTimer; /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.cancelB = new System.Windows.Forms.Button(); this.languageE = new System.Windows.Forms.ComboBox(); this.languageL = new System.Windows.Forms.Label(); this.dropAllE = new System.Windows.Forms.CheckBox(); this.labelNote2 = new System.Windows.Forms.Label(); this.labelNote1 = new System.Windows.Forms.Label(); this.collationE = new System.Windows.Forms.ComboBox(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.scriptB = new System.Windows.Forms.Button(); this.feedbackL = new System.Windows.Forms.RichTextBox(); this.executeB = new System.Windows.Forms.Button(); this.collationL = new System.Windows.Forms.Label(); this.databaseL = new System.Windows.Forms.Label(); this.passwordL = new System.Windows.Forms.Label(); this.userIdL = new System.Windows.Forms.Label(); this.serverL = new System.Windows.Forms.Label(); this.passwordE = new System.Windows.Forms.TextBox(); this.userIdE = new System.Windows.Forms.TextBox(); this.integratedE = new System.Windows.Forms.CheckBox(); this.databaseE = new System.Windows.Forms.TextBox(); this.serverE = new System.Windows.Forms.TextBox(); this.cancelTimer = new System.Windows.Forms.Timer(this.components); this.singleUserE = new System.Windows.Forms.CheckBox(); this.SuspendLayout(); // // cancelB // this.cancelB.Location = new System.Drawing.Point(240, 211); this.cancelB.Name = "cancelB"; this.cancelB.Size = new System.Drawing.Size(88, 24); this.cancelB.TabIndex = 41; this.cancelB.Text = "Cancel"; this.cancelB.Click += new System.EventHandler(this.cancelB_Click); // // languageE // this.languageE.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.languageE.Location = new System.Drawing.Point(144, 160); this.languageE.Name = "languageE"; this.languageE.Size = new System.Drawing.Size(184, 21); this.languageE.TabIndex = 40; this.languageE.DropDown += new System.EventHandler(this.languageE_DropDown); // // languageL // this.languageL.Location = new System.Drawing.Point(5, 163); this.languageL.Name = "languageL"; this.languageL.Size = new System.Drawing.Size(120, 16); this.languageL.TabIndex = 39; this.languageL.Text = "Full Text Language:"; // // dropAllE // this.dropAllE.ImageAlign = System.Drawing.ContentAlignment.TopLeft; this.dropAllE.Location = new System.Drawing.Point(336, 144); this.dropAllE.Name = "dropAllE"; this.dropAllE.Size = new System.Drawing.Size(256, 32); this.dropAllE.TabIndex = 38; this.dropAllE.Text = "Drop All Keys and Constraints. (By Default only the required items are dropped)"; this.dropAllE.TextAlign = System.Drawing.ContentAlignment.TopLeft; // // labelNote2 // this.labelNote2.Location = new System.Drawing.Point(336, 88); this.labelNote2.Name = "labelNote2"; this.labelNote2.Size = new System.Drawing.Size(256, 56); this.labelNote2.TabIndex = 35; this.labelNote2.Text = "NOTE: Once the script has been executed you will see any error messages shown in " + "red in the window below directly after the SQL code that failed"; // // labelNote1 // this.labelNote1.Location = new System.Drawing.Point(336, 8); this.labelNote1.Name = "labelNote1"; this.labelNote1.Size = new System.Drawing.Size(256, 80); this.labelNote1.TabIndex = 34; this.labelNote1.Text = "NOTE: If you change from a case insensitive to a case sensitive collation order y" + "ou may find errors occur when recreating functions and check constraints - this " + "is because your SQL code will be parsed in a case sensitive manner."; // // collationE // this.collationE.Location = new System.Drawing.Point(144, 133); this.collationE.Name = "collationE"; this.collationE.Size = new System.Drawing.Size(184, 21); this.collationE.TabIndex = 31; this.collationE.DropDown += new System.EventHandler(this.collationE_DropDown); // // progressBar // this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar.Location = new System.Drawing.Point(8, 251); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(584, 23); this.progressBar.TabIndex = 36; // // scriptB // this.scriptB.Location = new System.Drawing.Point(128, 211); this.scriptB.Name = "scriptB"; this.scriptB.Size = new System.Drawing.Size(104, 24); this.scriptB.TabIndex = 33; this.scriptB.Text = "Script Only"; this.scriptB.Click += new System.EventHandler(this.scriptB_Click); // // feedbackL // this.feedbackL.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.feedbackL.DetectUrls = false; this.feedbackL.Location = new System.Drawing.Point(8, 291); this.feedbackL.Name = "feedbackL"; this.feedbackL.ReadOnly = true; this.feedbackL.Size = new System.Drawing.Size(584, 152); this.feedbackL.TabIndex = 37; this.feedbackL.Text = ""; // // executeB // this.executeB.Location = new System.Drawing.Point(8, 211); this.executeB.Name = "executeB"; this.executeB.Size = new System.Drawing.Size(112, 24); this.executeB.TabIndex = 32; this.executeB.Text = "Script and Execute"; this.executeB.Click += new System.EventHandler(this.executeB_Click); // // collationL // this.collationL.Location = new System.Drawing.Point(8, 136); this.collationL.Name = "collationL"; this.collationL.Size = new System.Drawing.Size(120, 16); this.collationL.TabIndex = 30; this.collationL.Text = "Collation:"; // // databaseL // this.databaseL.Location = new System.Drawing.Point(8, 110); this.databaseL.Name = "databaseL"; this.databaseL.Size = new System.Drawing.Size(120, 16); this.databaseL.TabIndex = 28; this.databaseL.Text = "Database:"; // // passwordL // this.passwordL.Enabled = false; this.passwordL.Location = new System.Drawing.Point(8, 84); this.passwordL.Name = "passwordL"; this.passwordL.Size = new System.Drawing.Size(120, 16); this.passwordL.TabIndex = 26; this.passwordL.Text = "Password:"; // // userIdL // this.userIdL.Enabled = false; this.userIdL.Location = new System.Drawing.Point(8, 59); this.userIdL.Name = "userIdL"; this.userIdL.Size = new System.Drawing.Size(120, 16); this.userIdL.TabIndex = 24; this.userIdL.Text = "User ID:"; // // serverL // this.serverL.Location = new System.Drawing.Point(8, 11); this.serverL.Name = "serverL"; this.serverL.Size = new System.Drawing.Size(120, 16); this.serverL.TabIndex = 21; this.serverL.Text = "Server:"; // // passwordE // this.passwordE.Enabled = false; this.passwordE.Location = new System.Drawing.Point(144, 81); this.passwordE.Name = "passwordE"; this.passwordE.Size = new System.Drawing.Size(184, 20); this.passwordE.TabIndex = 27; this.passwordE.Text = ""; // // userIdE // this.userIdE.Enabled = false; this.userIdE.Location = new System.Drawing.Point(144, 55); this.userIdE.Name = "userIdE"; this.userIdE.Size = new System.Drawing.Size(184, 20); this.userIdE.TabIndex = 25; this.userIdE.Text = ""; // // integratedE // this.integratedE.Checked = true; this.integratedE.CheckState = System.Windows.Forms.CheckState.Checked; this.integratedE.Location = new System.Drawing.Point(144, 29); this.integratedE.Name = "integratedE"; this.integratedE.Size = new System.Drawing.Size(184, 24); this.integratedE.TabIndex = 23; this.integratedE.Text = "Integrated Security"; this.integratedE.CheckedChanged += new System.EventHandler(this.integratedE_CheckedChanged); // // databaseE // this.databaseE.Location = new System.Drawing.Point(144, 107); this.databaseE.Name = "databaseE"; this.databaseE.Size = new System.Drawing.Size(184, 20); this.databaseE.TabIndex = 29; this.databaseE.Text = ""; // // serverE // this.serverE.Location = new System.Drawing.Point(144, 11); this.serverE.Name = "serverE"; this.serverE.Size = new System.Drawing.Size(184, 20); this.serverE.TabIndex = 22; this.serverE.Text = ""; this.serverE.TextChanged += new System.EventHandler(this.serverE_TextChanged); // // cancelTimer // this.cancelTimer.Interval = 5000; this.cancelTimer.Tick += new System.EventHandler(this.cancelTimer_Tick); // // singleUserE // this.singleUserE.Checked = true; this.singleUserE.CheckState = System.Windows.Forms.CheckState.Checked; this.singleUserE.Location = new System.Drawing.Point(336, 184); this.singleUserE.Name = "singleUserE"; this.singleUserE.Size = new System.Drawing.Size(256, 48); this.singleUserE.TabIndex = 42; this.singleUserE.Text = "Switch database to single user mode while running script. This is the safest opt" + "ion but does not work with database mirroring."; // // MainForm // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(600, 454); this.Controls.Add(this.singleUserE); this.Controls.Add(this.cancelB); this.Controls.Add(this.languageE); this.Controls.Add(this.languageL); this.Controls.Add(this.dropAllE); this.Controls.Add(this.labelNote2); this.Controls.Add(this.labelNote1); this.Controls.Add(this.collationE); this.Controls.Add(this.progressBar); this.Controls.Add(this.scriptB); this.Controls.Add(this.feedbackL); this.Controls.Add(this.executeB); this.Controls.Add(this.collationL); this.Controls.Add(this.databaseL); this.Controls.Add(this.passwordL); this.Controls.Add(this.userIdL); this.Controls.Add(this.serverL); this.Controls.Add(this.passwordE); this.Controls.Add(this.userIdE); this.Controls.Add(this.integratedE); this.Controls.Add(this.databaseE); this.Controls.Add(this.serverE); this.Name = "MainForm"; this.Text = "Change Collation"; this.ResumeLayout(false); } #endregion private bool textLanguagePopulated; private bool collationPopulated; private ViewMode viewMode; private bool executeScriptOnly; private bool canceled; //private delegate ScriptStepCollection GenerateScript(IScriptExecuteCallback callback, string server, string userId, string password, string database, bool dropAllConstraints, string collation, FullTextLanguage language); private delegate void UpdateUICallback(int step); private delegate bool ScriptErrorCallback(ScriptStep step, Exception ex); private delegate void ScriptCompleteCallback(ScriptStepCollection script); private delegate void ScriptCompleteErrorCallback(Exception ex); private delegate void ExecuteCompleteCallback(); private ScriptStepCollection executingScript; private int lastReportedStep; private Thread workerThread; private WorkerThreadArguments workerThreadArguments; private class WorkerThreadArguments { private bool scriptOnly; private IScriptExecuteCallback callback; private string server; private string userId; private string password; private string database; private bool dropAllConstraints; private string collation; private FullTextLanguage language; private bool setSingleUser; public WorkerThreadArguments(bool scriptOnly, IScriptExecuteCallback callback, string server, string userId, string password, string database, bool dropAllConstraints, string collation, FullTextLanguage language, bool setSingleUser) { this.scriptOnly = scriptOnly; this.callback = callback; this.server = server; this.userId = userId; this.password = password; this.database = database; this.dropAllConstraints = dropAllConstraints; this.collation = collation; this.language = language; this.setSingleUser =setSingleUser; } public bool ScriptOnly { get { return scriptOnly; } } public IScriptExecuteCallback Callback { get { return callback; } } public string Server { get { return server; } } public string UserId { get { return userId; } } public string Password { get { return password; } } public string Database { get { return database; } } public bool DropAllConstraints { get { return dropAllConstraints; } } public string Collation { get { return collation; } } public FullTextLanguage Language { get { return language; } } public bool SetSingleUser { get {return setSingleUser;} } } private enum ViewMode { Normal, Running, Aborting } public MainForm() { InitializeComponent(); } private void Script() { if ((viewMode == ViewMode.Running)) { MessageBox.Show("Already Running Something"); } else { ViewModeSet(ViewMode.Running); feedbackL.Clear(); if (workerThread!=null) throw new InvalidOperationException("Oops worker thread still running"); //workerThread = new Thread( workerThreadArguments =new WorkerThreadArguments(true,this, serverE.Text, userIdE.Text, passwordE.Text, databaseE.Text, dropAllE.Checked, collationE.Text, languageE.SelectedItem as FullTextLanguage, singleUserE.Checked); workerThread = new Thread(new ThreadStart(ScriptThreadProc)); workerThread.Start(); } } private void ScriptThreadProc() { //WorkerThreadArguments arguments = (WorkerThreadArguments)threadArguments; CollationChanger collationChanger = new CollationChanger(); ScriptStepCollection script = null; SqlConnection connection = null; try { script = collationChanger.GenerateScript(workerThreadArguments.Callback, workerThreadArguments.Server, workerThreadArguments.UserId, workerThreadArguments.Password, workerThreadArguments.Database, workerThreadArguments.DropAllConstraints, workerThreadArguments.Collation, workerThreadArguments.Language, workerThreadArguments.SetSingleUser); if (workerThreadArguments.ScriptOnly) { BeginInvoke(new ScriptCompleteCallback(ScriptComplete), new object[] {script}); } else { connection = new SqlConnection(Utils.ConnectionString(workerThreadArguments.Server, workerThreadArguments.UserId, workerThreadArguments.Password)); connection.Open(); script.Execute(connection, workerThreadArguments.Callback); BeginInvoke(new ExecuteCompleteCallback(ExecuteComplete)); } } catch (ThreadAbortException) { throw; } catch (Exception ex) { BeginInvoke(new ScriptCompleteErrorCallback(ScriptComplete), new object[] { ex}); } finally { if (connection != null) connection.Dispose(); } lock (this) { workerThread = null; } } private void ExecuteComplete() { if (!canceled) MessageBox.Show("Execution Complete", this.Text); progressBar.Value = progressBar.Maximum; ViewModeSet(ViewMode.Normal); } /// <summary> /// callback from worker thread when something goes wrong /// </summary> /// <param name="ex"></param> private void ScriptComplete(Exception ex) { MessageBox.Show(ex.Message, this.Text); progressBar.Value = progressBar.Maximum; ViewModeSet(ViewMode.Normal); } /// <summary> /// callback from worker thread when it went OK /// </summary> /// <param name="script"></param> private void ScriptComplete(ScriptStepCollection script) { if (script!=null) WriteScriptToWindow(script); progressBar.Value = progressBar.Maximum; ViewModeSet(ViewMode.Normal); } private void WriteScriptToWindow(ScriptStepCollection script) { feedbackL.Clear(); foreach (ScriptStep step in script) { feedbackL.AppendText(step.CommandText); feedbackL.AppendText("\n\nGO\n\n"); } } private void ViewModeSet(ViewMode viewMode) { this.viewMode = viewMode; serverE.Enabled = viewMode == ViewMode.Normal; integratedE.Enabled = viewMode == ViewMode.Normal; userIdE.Enabled = viewMode == ViewMode.Normal && !integratedE.Checked; passwordE.Enabled = viewMode == ViewMode.Normal && !integratedE.Checked; databaseE.Enabled = viewMode == ViewMode.Normal; collationE.Enabled = viewMode == ViewMode.Normal; languageE.Enabled = viewMode == ViewMode.Normal; scriptB.Enabled = viewMode == ViewMode.Normal; executeB.Enabled = viewMode == ViewMode.Normal; dropAllE.Enabled = viewMode == ViewMode.Normal; cancelB.Enabled = viewMode == ViewMode.Running; singleUserE.Enabled = viewMode == ViewMode.Normal; cancelTimer.Enabled = viewMode == ViewMode.Aborting; switch (viewMode) { case ViewMode.Running: canceled = false; break; case ViewMode.Aborting: canceled = true; break; case ViewMode.Normal: break; } } //private void ExecuteDo() //{ // canceled = false; // ScriptRunner scriptRunner = new ScriptRunner(); // scriptRunner.Execute(serverE.Text, userIdE.Text, passwordE.Text,databaseE.Text, dropAllE.Checked, collationE.Text, (FullTextLanguage)languageE.SelectedItem); // ExecuteComplete(); //} protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); ViewModeSet(ViewMode.Normal); } private void executeB_Click(object sender, EventArgs e) { if ((viewMode == ViewMode.Running)) { MessageBox.Show("Already Running Something"); } else { if (MessageBox.Show("This program will now execute a script to alter the collation of your database. This may take a long time and may result in data loss. Please ensure that all your data is backed up.\n\nExclusive database access is required to complete the process so before running use the sp_who command to verify that there are no users connected to your database.", "Confirm", MessageBoxButtons.OKCancel, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button2) == DialogResult.OK) { ViewModeSet(ViewMode.Running); feedbackL.Clear(); if (workerThread != null) throw new InvalidOperationException("Oops worker thread still running"); workerThreadArguments = new WorkerThreadArguments(false, this, serverE.Text, userIdE.Text, passwordE.Text, databaseE.Text, dropAllE.Checked, collationE.Text, languageE.SelectedItem as FullTextLanguage, singleUserE.Checked); workerThread = new Thread(new ThreadStart(ScriptThreadProc)); workerThread.Start(); } } } private void integratedE_CheckedChanged(object sender, EventArgs e) { if (integratedE.Checked) { userIdE.Text = string.Empty; passwordE.Text = string.Empty; } userIdE.Enabled = !integratedE.Checked; userIdL.Enabled = !integratedE.Checked; passwordE.Enabled = !integratedE.Checked; passwordL.Enabled = !integratedE.Checked; } private void scriptB_Click(object sender, EventArgs e) { Script(); } private void languageE_DropDown(object sender, EventArgs e) { if (!textLanguagePopulated) { textLanguagePopulated = true; SqlConnection con = new SqlConnection(); try { SqlCommand cmd; int ixName; int ixLcid; SqlDataReader dr; Version serverVersion; con.ConnectionString = Utils.ConnectionString(serverE.Text, userIdE.Text, passwordE.Text); con.Open(); serverVersion = new Version(con.ServerVersion); cmd = con.CreateCommand(); if (serverVersion.Major>=9) { cmd.CommandType = CommandType.Text; cmd.CommandText = "select * from sys.fulltext_languages"; } else { cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "master..xp_MSFullText"; } dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); if (serverVersion.Major>=9) { ixName = dr.GetOrdinal("name"); } else { ixName = dr.GetOrdinal("Language"); } ixLcid = dr.GetOrdinal("LCID"); languageE.Items.Clear(); languageE.Items.Add(new FullTextLanguage("<Unchanged>", int.MinValue)); while (dr.Read()) { languageE.Items.Add(new FullTextLanguage(dr.GetString(ixName), dr.GetInt32(ixLcid))); } } catch (SqlException) { textLanguagePopulated = false; } catch (Exception) { textLanguagePopulated = false; throw; } finally { con.Dispose(); } } } private void cancelB_Click(object sender, EventArgs e) { ViewModeSet(ViewMode.Aborting); } private void serverE_TextChanged(object sender, EventArgs e) { collationPopulated = false; textLanguagePopulated = false; collationE.Items.Clear(); languageE.Items.Clear(); languageE.Items.Add(new FullTextLanguage("<Unchanged>", int.MinValue)); } private void collationE_DropDown(object sender, EventArgs e) { //populate the list if (!collationPopulated) { collationPopulated = true; SqlConnection con = new SqlConnection(); try { SqlCommand cmd; int ixName; SqlDataReader dr; con.ConnectionString = Utils.ConnectionString(serverE.Text, userIdE.Text, passwordE.Text); con.Open(); cmd = con.CreateCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "select name from ::fn_helpCollations()"; dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); ixName = dr.GetOrdinal("name"); collationE.Items.Clear(); while (dr.Read()) { collationE.Items.Add(dr.GetString(ixName)); } } catch (SqlException) { collationPopulated = false; } catch (Exception) { collationPopulated = false; throw; } finally { con.Dispose(); } } } private void UpdateUI(int step) { lock(this) { if (lastReportedStep == -1) { feedbackL.Clear(); lastReportedStep =0; } ScriptStep scriptItem; for (int index = lastReportedStep; index < step; index++) { scriptItem = executingScript[index]; feedbackL.AppendText(scriptItem.CommandText); feedbackL.AppendText("\n\nGO\n\n"); } progressBar.Maximum = executingScript.Count; progressBar.Value = step; lastReportedStep = step; } } private bool ScriptError(ScriptStep step, Exception exception) { SqlException ex = exception as SqlException; if (ex == null) { MessageBox.Show("Unexpeced error"); return false; } for (int stepIndex = 0; stepIndex < executingScript.Count; stepIndex++) { if (object.ReferenceEquals(executingScript[stepIndex], step)) { UpdateUI(stepIndex+1); break; } } foreach (SqlError e in ex.Errors) { if (e.Class >= 11) { feedbackL.SelectionColor = Color.Red; } else { feedbackL.SelectionColor = Color.Black; } feedbackL.AppendText(string.Format("{0} - {1}", e.Number, e.Message)); feedbackL.AppendText("\n"); } if (ex.Class >= 11) { string commandText = step.CommandText; if (commandText.Length > 1000) commandText = commandText.Substring(0, 1000) + "......"; string message = string.Format("An error occured while executing the SQL Statement\n\n '{0}'\n\n{1}\n\nDo you which to continue running the script anyway?", commandText, ex.Message); if (!(MessageBox.Show(this,message, "Error", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)) { canceled = true; feedbackL.SelectionColor = Color.Red; feedbackL.AppendText("Canceled"); feedbackL.AppendText("\n"); } } return !canceled; } #region IScriptExecuteCallback Members bool IScriptExecuteCallback.Error(ScriptStep step, Exception exception) { return (bool) this.Invoke(new ScriptErrorCallback(ScriptError), new object [] {step, exception}); } bool IScriptExecuteCallback.Progress(ScriptStep script, int step, int stepMax) { if (!canceled) this.BeginInvoke(new UpdateUICallback(UpdateUI), new object[] {step}); return !canceled; } void IScriptExecuteCallback.ExecutionStarting(ScriptStepCollection script) { lock(this) { executingScript = script; lastReportedStep = -1; } } #endregion private void cancelTimer_Tick(object sender, EventArgs e) { lock(this) { if (workerThread != null) workerThread.Abort(); workerThread = null; } progressBar.Value = progressBar.Maximum; ViewModeSet(ViewMode.Normal); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Microsoft.DiaSymReader; using Xunit; using Roslyn.Test.PdbUtilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable { private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance(); public override void Dispose() { base.Dispose(); foreach (var instance in _runtimeInstances) { instance.Dispose(); } _runtimeInstances.Free(); } internal RuntimeInstance CreateRuntimeInstance( Compilation compilation, bool includeSymbols = true) { byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); return CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), references.AddIntrinsicAssembly(), exeBytes, includeSymbols ? new SymReader(pdbBytes) : null); } internal RuntimeInstance CreateRuntimeInstance( string assemblyName, ImmutableArray<MetadataReference> references, byte[] exeBytes, ISymUnmanagedReader symReader, bool includeLocalSignatures = true) { var exeReference = AssemblyMetadata.CreateFromImage(exeBytes).GetReference(display: assemblyName); var modulesBuilder = ArrayBuilder<ModuleInstance>.GetInstance(); // Create modules for the references modulesBuilder.AddRange(references.Select(r => r.ToModuleInstance(fullImage: null, symReader: null, includeLocalSignatures: includeLocalSignatures))); // Create a module for the exe. modulesBuilder.Add(exeReference.ToModuleInstance(exeBytes, symReader, includeLocalSignatures: includeLocalSignatures)); var modules = modulesBuilder.ToImmutableAndFree(); modules.VerifyAllModules(); var instance = new RuntimeInstance(modules); _runtimeInstances.Add(instance); return instance; } internal static void GetContextState( RuntimeInstance runtime, string methodOrTypeName, out ImmutableArray<MetadataBlock> blocks, out Guid moduleVersionId, out ISymUnmanagedReader symReader, out int methodOrTypeToken, out int localSignatureToken) { var moduleInstances = runtime.Modules; blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock); var compilation = blocks.ToCompilation(); var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName); var module = (PEModuleSymbol)methodOrType.ContainingModule; var id = module.Module.GetModuleVersionIdOrThrow(); var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id); moduleVersionId = id; symReader = (ISymUnmanagedReader)moduleInstance.SymReader; Handle methodOrTypeHandle; if (methodOrType.Kind == SymbolKind.Method) { methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle; localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle); } else { methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle; localSignatureToken = -1; } MetadataReader reader = null; // null should be ok methodOrTypeToken = reader.GetToken(methodOrTypeHandle); } internal static EvaluationContext CreateMethodContext( RuntimeInstance runtime, string methodName, int atLineNumber = -1, CSharpMetadataContext previous = default(CSharpMetadataContext)) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); int ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber); return EvaluationContext.CreateMethodContext( previous, blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken); } internal static EvaluationContext CreateTypeContext( RuntimeInstance runtime, string typeName) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int localSignatureToken; GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); return EvaluationContext.CreateTypeContext( default(CSharpMetadataContext), blocks, moduleVersionId, typeToken); } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, int atLineNumber = -1, bool includeSymbols = true) { ResultProperties resultProperties; string error; var result = Evaluate(source, outputKind, methodName, expr, out resultProperties, out error, atLineNumber, DefaultInspectionContext.Instance, includeSymbols); Assert.Null(error); return result; } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, out ResultProperties resultProperties, out string error, int atLineNumber = -1, InspectionContext inspectionContext = null, bool includeSymbols = true) { var compilation0 = CreateCompilationWithMscorlib( source, options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe); var runtime = CreateRuntimeInstance(compilation0, includeSymbols); var context = CreateMethodContext(runtime, methodName, atLineNumber); var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( inspectionContext ?? DefaultInspectionContext.Instance, expr, DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return testData; } /// <summary> /// Verify all type parameters from the method /// are from that method or containing types. /// </summary> internal static void VerifyTypeParameters(MethodSymbol method) { Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType)); AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(method.TypeArguments, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument)); AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type)); VerifyTypeParameters(method.ContainingType); } internal static void VerifyLocal( CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None, string expectedILOpt = null, bool expectedGeneric = false, [CallerFilePath]string expectedValueSourcePath = null, [CallerLineNumber]int expectedValueSourceLine = 0) { ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>( testData, typeName, localAndMethod, expectedMethodName, expectedLocalName, expectedFlags, VerifyTypeParameters, expectedILOpt, expectedGeneric, expectedValueSourcePath, expectedValueSourceLine); } /// <summary> /// Verify all type parameters from the type /// are from that type or containing types. /// </summary> internal static void VerifyTypeParameters(NamedTypeSymbol type) { AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(type.TypeArguments, typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument)); var container = type.ContainingType; if ((object)container != null) { VerifyTypeParameters(container); } } internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature) { string methodOrTypeName = signature; string[] parameterTypeNames = null; var parameterListStart = methodOrTypeName.IndexOf('('); if (parameterListStart > -1) { parameterTypeNames = methodOrTypeName.Substring(parameterListStart).Trim('(', ')').Split(','); methodOrTypeName = methodOrTypeName.Substring(0, parameterListStart); } var candidates = compilation.GetMembers(methodOrTypeName); Assert.Equal(parameterTypeNames == null, candidates.Length == 1); Symbol methodOrType = null; foreach (var candidate in candidates) { methodOrType = candidate; if ((parameterTypeNames == null) || parameterTypeNames.SequenceEqual(methodOrType.GetParameters().Select(p => p.Type.Name))) { // Found a match. break; } } Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'."); return methodOrType; } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using Hyak.Common; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// Objects that provide system or application data. /// </summary> public partial class ConfigurationSet { private string _adminPassword; /// <summary> /// Optional. Specifies the string representing the administrator /// password to use for the virtual machine. If the VM will be created /// from a 'Specialized' VM image, the password is not required. /// </summary> public string AdminPassword { get { return this._adminPassword; } set { this._adminPassword = value; } } private string _adminUserName; /// <summary> /// Optional. Specifies the name that is used to rename the default /// administrator account. If the VM will be created from a /// 'Specialized' VM image, the user name is not required. /// </summary> public string AdminUserName { get { return this._adminUserName; } set { this._adminUserName = value; } } private string _computerName; /// <summary> /// Optional. Specifies the computer name for the virtual machine. If /// the computer name is not specified, a name is created based on the /// name of the role. Computer names must be 1 to 15 characters in /// length. This element is only used with the /// WindowsProvisioningConfiguration set. /// </summary> public string ComputerName { get { return this._computerName; } set { this._computerName = value; } } private string _configurationSetType; /// <summary> /// Optional. Specifies the configuration type for the configuration /// set. /// </summary> public string ConfigurationSetType { get { return this._configurationSetType; } set { this._configurationSetType = value; } } private string _customData; /// <summary> /// Optional. Optional. Provides base64 encoded custom data to be /// passed to VM. /// </summary> public string CustomData { get { return this._customData; } set { this._customData = value; } } private bool? _disableSshPasswordAuthentication; /// <summary> /// Optional. Specifies whether or not SSH authentication is disabled /// for the password. This element is only used with the /// LinuxProvisioningConfiguration set. By default this value is set /// to true. /// </summary> public bool? DisableSshPasswordAuthentication { get { return this._disableSshPasswordAuthentication; } set { this._disableSshPasswordAuthentication = value; } } private DomainJoinSettings _domainJoin; /// <summary> /// Optional. Contains properties that specify a domain to which the /// virtual machine will be joined. This element is only used with the /// WindowsProvisioningConfiguration set. /// </summary> public DomainJoinSettings DomainJoin { get { return this._domainJoin; } set { this._domainJoin = value; } } private bool? _enableAutomaticUpdates; /// <summary> /// Optional. Specifies whether automatic updates are enabled for the /// virtual machine. This element is only used with the /// WindowsProvisioningConfiguration set. The default value is false. /// </summary> public bool? EnableAutomaticUpdates { get { return this._enableAutomaticUpdates; } set { this._enableAutomaticUpdates = value; } } private string _hostName; /// <summary> /// Optional. Specifies the host name for the VM. Host names are ASCII /// character strings 1 to 64 characters in length. This element is /// only used with the LinuxProvisioningConfiguration set. /// </summary> public string HostName { get { return this._hostName; } set { this._hostName = value; } } private IList<InputEndpoint> _inputEndpoints; /// <summary> /// Optional. Contains a collection of external endpoints for the /// virtual machine. This element is only used with the /// NetworkConfigurationSet type. /// </summary> public IList<InputEndpoint> InputEndpoints { get { return this._inputEndpoints; } set { this._inputEndpoints = value; } } private IList<NetworkInterface> _networkInterfaces; /// <summary> /// Optional. /// </summary> public IList<NetworkInterface> NetworkInterfaces { get { return this._networkInterfaces; } set { this._networkInterfaces = value; } } private string _networkSecurityGroup; /// <summary> /// Optional. Gets or sets the Network Security Group associated with /// this role. Optional /// </summary> public string NetworkSecurityGroup { get { return this._networkSecurityGroup; } set { this._networkSecurityGroup = value; } } private IList<ConfigurationSet.PublicIP> _publicIPs; /// <summary> /// Optional. Optional. A set of public IPs. Currently, only one /// additional public IP per role is supported in an IaaS deployment. /// The IP address is in addition to the default VIP for the /// deployment. /// </summary> public IList<ConfigurationSet.PublicIP> PublicIPs { get { return this._publicIPs; } set { this._publicIPs = value; } } private bool? _resetPasswordOnFirstLogon; /// <summary> /// Optional. Specifies whether password should be reset the first time /// the administrator logs in. /// </summary> public bool? ResetPasswordOnFirstLogon { get { return this._resetPasswordOnFirstLogon; } set { this._resetPasswordOnFirstLogon = value; } } private SshSettings _sshSettings; /// <summary> /// Optional. Specifies the SSH public keys and key pairs to populate /// in the image during provisioning. This element is only used with /// the LinuxProvisioningConfiguration set. /// </summary> public SshSettings SshSettings { get { return this._sshSettings; } set { this._sshSettings = value; } } private string _staticVirtualNetworkIPAddress; /// <summary> /// Optional. Specifies a Customer Address, i.e. an IP address assigned /// to a VM in a VNet's SubNet. For example: 10.0.0.4. /// </summary> public string StaticVirtualNetworkIPAddress { get { return this._staticVirtualNetworkIPAddress; } set { this._staticVirtualNetworkIPAddress = value; } } private IList<StoredCertificateSettings> _storedCertificateSettings; /// <summary> /// Optional. Contains a list of service certificates with which to /// provision to the new role. This element is only used with the /// WindowsProvisioningConfiguration set. /// </summary> public IList<StoredCertificateSettings> StoredCertificateSettings { get { return this._storedCertificateSettings; } set { this._storedCertificateSettings = value; } } private IList<string> _subnetNames; /// <summary> /// Optional. The list of Virtual Network subnet names that the /// deployment belongs to. This element is only used with the /// NetworkConfigurationSet type. /// </summary> public IList<string> SubnetNames { get { return this._subnetNames; } set { this._subnetNames = value; } } private string _timeZone; /// <summary> /// Optional. Specifies the time zone for the virtual machine. This /// element is only used with the WindowsProvisioningConfiguration /// set. For a complete list of supported time zone entries, you can /// refer to the values listed in the registry entry /// HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows /// NT\\CurrentVersion\\Time Zones on a computer running Windows 7, /// Windows Server 2008, and Windows Server 2008 R2 or you can use the /// tzutil command-line tool to list the valid time. The tzutil tool /// is installed by default on Windows 7, Windows Server 2008, and /// Windows Server 2008 R2. /// </summary> public string TimeZone { get { return this._timeZone; } set { this._timeZone = value; } } private string _userName; /// <summary> /// Optional. Specifies the name of a user to be created in the sudoer /// group of the virtual machine. User names are ASCII character /// strings 1 to 32 characters in length. This element is only used /// with the LinuxProvisioningConfiguration set. /// </summary> public string UserName { get { return this._userName; } set { this._userName = value; } } private string _userPassword; /// <summary> /// Optional. Specifies the password for user name. Passwords are ASCII /// character strings 6 to 72 characters in length. This element is /// only used with the LinuxProvisioningConfiguration set. /// </summary> public string UserPassword { get { return this._userPassword; } set { this._userPassword = value; } } private WindowsRemoteManagementSettings _windowsRemoteManagement; /// <summary> /// Optional. Configures the Windows Remote Management service on the /// virtual machine, which enables remote Windows PowerShell. /// </summary> public WindowsRemoteManagementSettings WindowsRemoteManagement { get { return this._windowsRemoteManagement; } set { this._windowsRemoteManagement = value; } } /// <summary> /// Initializes a new instance of the ConfigurationSet class. /// </summary> public ConfigurationSet() { this.InputEndpoints = new LazyList<InputEndpoint>(); this.NetworkInterfaces = new LazyList<NetworkInterface>(); this.PublicIPs = new LazyList<ConfigurationSet.PublicIP>(); this.StoredCertificateSettings = new LazyList<StoredCertificateSettings>(); this.SubnetNames = new LazyList<string>(); } /// <summary> /// An additional public IP that will be created for the role. The /// public IP will be an additional IP for the role. The role /// continues to be addressable via the default deployment VIP. /// </summary> public partial class PublicIP { private string _domainNameLabel; /// <summary> /// Optional. The DNS name of the public IP. /// </summary> public string DomainNameLabel { get { return this._domainNameLabel; } set { this._domainNameLabel = value; } } private int? _idleTimeoutInMinutes; /// <summary> /// Optional. The idle timeout in minutes for this Public IP. /// </summary> public int? IdleTimeoutInMinutes { get { return this._idleTimeoutInMinutes; } set { this._idleTimeoutInMinutes = value; } } private string _name; /// <summary> /// Optional. The name of the public IP. /// </summary> public string Name { get { return this._name; } set { this._name = value; } } /// <summary> /// Initializes a new instance of the PublicIP class. /// </summary> public PublicIP() { } } } }
#if (UNITY_WINRT || UNITY_WP_8_1) && !UNITY_EDITOR && !UNITY_WP8 #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Reflection; using System.Linq; namespace Newtonsoft.Json.Utilities { internal static class TypeExtensions { private static Newtonsoft.Json.Utilities.BindingFlags DefaultFlags = Newtonsoft.Json.Utilities.BindingFlags.Public | Newtonsoft.Json.Utilities.BindingFlags.Static | Newtonsoft.Json.Utilities.BindingFlags.Instance; public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo) { return propertyInfo.GetGetMethod(false); } public static MethodInfo GetGetMethod(this PropertyInfo propertyInfo, bool nonPublic) { MethodInfo getMethod = propertyInfo.GetMethod; if (getMethod != null && (getMethod.IsPublic || nonPublic)) return getMethod; return null; } public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo) { return propertyInfo.GetSetMethod(false); } public static MethodInfo GetSetMethod(this PropertyInfo propertyInfo, bool nonPublic) { MethodInfo setMethod = propertyInfo.SetMethod; if (setMethod != null && (setMethod.IsPublic || nonPublic)) return setMethod; return null; } public static bool IsSubclassOf(this Type type, Type c) { return type.GetTypeInfo().IsSubclassOf(c); } public static bool IsAssignableFrom(this Type type, Type c) { return type.GetTypeInfo().IsAssignableFrom(c.GetTypeInfo()); } public static MethodInfo Method(this Delegate d) { return d.GetMethodInfo(); } public static MemberTypes MemberType(this MemberInfo memberInfo) { if (memberInfo is PropertyInfo) return MemberTypes.Property; else if (memberInfo is FieldInfo) return MemberTypes.Field; else if (memberInfo is EventInfo) return MemberTypes.Event; else if (memberInfo is MethodInfo) return MemberTypes.Method; else return MemberTypes.Other; } public static bool ContainsGenericParameters(this Type type) { return type.GetTypeInfo().ContainsGenericParameters; } public static bool IsInterface(this Type type) { return type.GetTypeInfo().IsInterface; } public static bool IsGenericType(this Type type) { return type.GetTypeInfo().IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.GetTypeInfo().IsGenericTypeDefinition; } public static Type BaseType(this Type type) { return type.GetTypeInfo().BaseType; } public static bool IsEnum(this Type type) { return type.GetTypeInfo().IsEnum; } public static bool IsClass(this Type type) { return type.GetTypeInfo().IsClass; } public static bool IsSealed(this Type type) { return type.GetTypeInfo().IsSealed; } public static MethodInfo GetBaseDefinition(this MethodInfo method) { return method.GetRuntimeBaseDefinition(); } public static bool IsDefined(this Type type, Type attributeType, bool inherit) { return type.GetTypeInfo().CustomAttributes.Any(a => a.AttributeType == attributeType); } public static MethodInfo GetMethod(this Type type, string name) { return type.GetMethod(name, DefaultFlags); } public static MethodInfo GetMethod(this Type type, string name, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetDeclaredMethod(name); } public static MethodInfo GetMethod(this Type type, IList<Type> parameterTypes) { return type.GetMethod(null, parameterTypes); } public static MethodInfo GetMethod(this Type type, string name, IList<Type> parameterTypes) { return type.GetMethod(name, DefaultFlags, null, parameterTypes, null); } public static MethodInfo GetMethod(this Type type, string name, Newtonsoft.Json.Utilities.BindingFlags bindingFlags, object placeHolder1, IList<Type> parameterTypes, object placeHolder2) { return type.GetTypeInfo().DeclaredMethods.Where(m => { if (name != null && m.Name != name) return false; if (!TestAccessibility(m, bindingFlags)) return false; return m.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes); }).SingleOrDefault(); } public static PropertyInfo GetProperty(this Type type, string name, Newtonsoft.Json.Utilities.BindingFlags bindingFlags, object placeholder1, Type propertyType, IList<Type> indexParameters, object placeholder2) { return type.GetTypeInfo().DeclaredProperties.Where(p => { if (name != null && name != p.Name) return false; if (propertyType != null && propertyType != p.PropertyType) return false; if (indexParameters != null) { if (!p.GetIndexParameters().Select(ip => ip.ParameterType).SequenceEqual(indexParameters)) return false; } return true; }).SingleOrDefault(); } public static IEnumerable<MemberInfo> GetMember(this Type type, string name, MemberTypes memberType, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetMembersRecursive().Where(m => { if (name != null && name != m.Name) return false; if (m.MemberType() != memberType) return false; if (!TestAccessibility(m, bindingFlags)) return false; return true; }); } public static IEnumerable<ConstructorInfo> GetConstructors(this Type type) { return type.GetConstructors(DefaultFlags); } public static IEnumerable<ConstructorInfo> GetConstructors(this Type type, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { return type.GetConstructors(bindingFlags, null); } private static IEnumerable<ConstructorInfo> GetConstructors(this Type type, Newtonsoft.Json.Utilities.BindingFlags bindingFlags, IList<Type> parameterTypes) { return type.GetTypeInfo().DeclaredConstructors.Where(c => { if (!TestAccessibility(c, bindingFlags)) return false; if (parameterTypes != null && !c.GetParameters().Select(p => p.ParameterType).SequenceEqual(parameterTypes)) return false; return true; }); } public static ConstructorInfo GetConstructor(this Type type, IList<Type> parameterTypes) { return type.GetConstructor(DefaultFlags, null, parameterTypes, null); } public static ConstructorInfo GetConstructor(this Type type, Newtonsoft.Json.Utilities.BindingFlags bindingFlags, object placeholder1, IList<Type> parameterTypes, object placeholder2) { return type.GetConstructors(bindingFlags, parameterTypes).SingleOrDefault(); } public static MemberInfo[] GetMember(this Type type, string member) { return type.GetMember(member, DefaultFlags); } public static MemberInfo[] GetMember(this Type type, string member, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetMembersRecursive().Where(m => m.Name == member && TestAccessibility(m, bindingFlags)).ToArray(); } public static MemberInfo GetField(this Type type, string member) { return type.GetField(member, DefaultFlags); } public static MemberInfo GetField(this Type type, string member, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetDeclaredField(member); } public static IEnumerable<PropertyInfo> GetProperties(this Type type, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { IList<PropertyInfo> properties = (bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.DeclaredOnly)) ? type.GetTypeInfo().DeclaredProperties.ToList() : type.GetTypeInfo().GetPropertiesRecursive(); return properties.Where(p => TestAccessibility(p, bindingFlags)); } private static IList<MemberInfo> GetMembersRecursive(this TypeInfo type) { TypeInfo t = type; IList<MemberInfo> members = new List<MemberInfo>(); while (t != null) { foreach (var member in t.DeclaredMembers) { if (!members.Any(p => p.Name == member.Name)) members.Add(member); } t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; } return members; } private static IList<PropertyInfo> GetPropertiesRecursive(this TypeInfo type) { TypeInfo t = type; IList<PropertyInfo> properties = new List<PropertyInfo>(); while (t != null) { foreach (var member in t.DeclaredProperties) { if (!properties.Any(p => p.Name == member.Name)) properties.Add(member); } t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; } return properties; } private static IList<FieldInfo> GetFieldsRecursive(this TypeInfo type) { TypeInfo t = type; IList<FieldInfo> fields = new List<FieldInfo>(); while (t != null) { foreach (var member in t.DeclaredFields) { if (!fields.Any(p => p.Name == member.Name)) fields.Add(member); } t = (t.BaseType != null) ? t.BaseType.GetTypeInfo() : null; } return fields; } public static IEnumerable<MethodInfo> GetMethods(this Type type, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().DeclaredMethods; } public static PropertyInfo GetProperty(this Type type, string name) { return type.GetProperty(name, DefaultFlags); } public static PropertyInfo GetProperty(this Type type, string name, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { return type.GetTypeInfo().GetDeclaredProperty(name); } public static IEnumerable<FieldInfo> GetFields(this Type type) { return type.GetFields(DefaultFlags); } public static IEnumerable<FieldInfo> GetFields(this Type type, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { IList<FieldInfo> fields = (bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.DeclaredOnly)) ? type.GetTypeInfo().DeclaredFields.ToList() : type.GetTypeInfo().GetFieldsRecursive(); return fields.Where(f => TestAccessibility(f, bindingFlags)).ToList(); } private static bool TestAccessibility(PropertyInfo member, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { if (member.GetMethod != null && TestAccessibility(member.GetMethod, bindingFlags)) return true; if (member.SetMethod != null && TestAccessibility(member.SetMethod, bindingFlags)) return true; return false; } private static bool TestAccessibility(MemberInfo member, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { if (member is FieldInfo) { return TestAccessibility((FieldInfo)member, bindingFlags); } else if (member is MethodBase) { return TestAccessibility((MethodBase)member, bindingFlags); } else if (member is PropertyInfo) { return TestAccessibility((PropertyInfo)member, bindingFlags); } throw new Exception("Unexpected member type."); } private static bool TestAccessibility(FieldInfo member, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { bool visibility = (member.IsPublic && bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.Public)) || (!member.IsPublic && bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.NonPublic)); bool instance = (member.IsStatic && bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.Static)) || (!member.IsStatic && bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.Instance)); return visibility && instance; } private static bool TestAccessibility(MethodBase member, Newtonsoft.Json.Utilities.BindingFlags bindingFlags) { bool visibility = (member.IsPublic && bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.Public)) || (!member.IsPublic && bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.NonPublic)); bool instance = (member.IsStatic && bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.Static)) || (!member.IsStatic && bindingFlags.HasFlag(Newtonsoft.Json.Utilities.BindingFlags.Instance)); return visibility && instance; } public static Type[] GetGenericArguments(this Type type) { return type.GetTypeInfo().GenericTypeArguments; } public static IEnumerable<Type> GetInterfaces(this Type type) { return type.GetTypeInfo().ImplementedInterfaces; } public static IEnumerable<MethodInfo> GetMethods(this Type type) { return type.GetTypeInfo().DeclaredMethods; } public static bool IsAbstract(this Type type) { return type.GetTypeInfo().IsAbstract; } public static bool IsVisible(this Type type) { return type.GetTypeInfo().IsVisible; } public static bool IsValueType(this Type type) { return type.GetTypeInfo().IsValueType; } public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match) { Type current = type; while (current != null) { if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal)) { match = current; return true; } current = current.BaseType(); } foreach (Type i in type.GetInterfaces()) { if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) { match = type; return true; } } match = null; return false; } public static bool AssignableToTypeName(this Type type, string fullTypeName) { Type match; return type.AssignableToTypeName(fullTypeName, out match); } public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes) { var methods = type.GetMethods().Where(method => method.Name == name); foreach (var method in methods) { if (method.HasParameters(parameterTypes)) return method; } return null; } public static bool HasParameters(this MethodInfo method, params Type[] parameterTypes) { var methodParameters = method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); if (methodParameters.Length != parameterTypes.Length) return false; for (int i = 0; i < methodParameters.Length; i++) if (methodParameters[i].ToString() != parameterTypes[i].ToString()) return false; return true; } public static IEnumerable<Type> GetAllInterfaces(this Type target) { foreach (var i in target.GetInterfaces()) { yield return i; foreach (var ci in i.GetInterfaces()) { yield return ci; } } } public static IEnumerable<MethodInfo> GetAllMethods(this Type target) { var allTypes = target.GetAllInterfaces().ToList(); allTypes.Add(target); return from type in allTypes from method in type.GetMethods() select method; } } } #endif
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Diagnostics; using System.Runtime; using System.ServiceModel; using System.ServiceModel.Diagnostics; using System.Threading; using System.ServiceModel.Diagnostics.Application; // Graph maintainence algorithms. sealed class ConnectAlgorithms : IConnectAlgorithms { static Random random = new Random(); int wantedConnectionCount = 0; EventWaitHandle addNeighbor = new EventWaitHandle(true, EventResetMode.ManualReset); EventWaitHandle maintainerClosed = new EventWaitHandle(false, EventResetMode.ManualReset); EventWaitHandle welcomeReceived = new EventWaitHandle(false, EventResetMode.ManualReset); Dictionary<Uri, PeerNodeAddress> nodeAddresses = new Dictionary<Uri, PeerNodeAddress>(); PeerNodeConfig config; Dictionary<Uri, PeerNodeAddress> pendingConnectedNeighbor = new Dictionary<Uri, PeerNodeAddress>(); object thisLock = new object(); IPeerMaintainer maintainer = null; bool disposed = false; public void Initialize(IPeerMaintainer maintainer, PeerNodeConfig config, int wantedConnectionCount, Dictionary<EndpointAddress, Referral> referralCache) { this.maintainer = maintainer; this.config = config; this.wantedConnectionCount = wantedConnectionCount; UpdateEndpointsCollection(referralCache.Values); // Add to the endpoints connection anything in the referralsCache // Hook up the event handlers maintainer.NeighborClosed += OnNeighborClosed; maintainer.NeighborConnected += OnNeighborConnected; maintainer.MaintainerClosed += OnMaintainerClosed; maintainer.ReferralsAdded += OnReferralsAdded; } // instance lock object ThisLock { get { return thisLock; } } public void Connect(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); addNeighbor.Set(); // We are trying to add a neighbor List<IAsyncResult> results = new List<IAsyncResult>(); List<WaitHandle> handles = new List<WaitHandle>(); // While we have more to endpoints try and we have connections pending and we are not connected upto ideal yet, and the maintainer is still open while (results.Count != 0 || (((nodeAddresses.Count != 0 || pendingConnectedNeighbor.Count != 0) && maintainer.IsOpen) && maintainer.ConnectedNeighborCount < wantedConnectionCount)) { try { handles.Clear(); foreach (IAsyncResult iar in results) { handles.Add(iar.AsyncWaitHandle); } handles.Add(welcomeReceived); // One of our connect requests resulted in a welcome or neighborManager was shutting down handles.Add(maintainerClosed); // One of our connect requests resulted in a welcome or neighborManager was shutting down handles.Add(addNeighbor); // Make the last waithandle the add a neighbor signal int index = WaitHandle.WaitAny(handles.ToArray(), config.ConnectTimeout, false); if (index == results.Count) // welcomeReceived was signalled { welcomeReceived.Reset(); } else if (index == results.Count + 1) // maintainerClosed was signalled { maintainerClosed.Reset(); lock (ThisLock) { nodeAddresses.Clear(); } } else if (index == results.Count + 2) // addNeighbor was signalled { // We need to open a new neighbor if (nodeAddresses.Count > 0) { if (pendingConnectedNeighbor.Count + maintainer.ConnectedNeighborCount < wantedConnectionCount) { PeerNodeAddress epr = null; lock (ThisLock) { if (nodeAddresses.Count == 0 || !maintainer.IsOpen) // nodeAddresses or maintainer is closed got updated better cycle { addNeighbor.Reset(); continue; } int index2 = random.Next() % nodeAddresses.Count; ICollection<Uri> keys = nodeAddresses.Keys; int i = 0; Uri key = null; foreach (Uri uri in keys) { if (i++ == index2) { key = uri; break; } } Fx.Assert(key != null, "key cannot be null here"); epr = nodeAddresses[key]; Fx.Assert(epr != null, "epr cannot be null here"); nodeAddresses.Remove(key); } if (maintainer.FindDuplicateNeighbor(epr) == null && pendingConnectedNeighbor.ContainsKey(GetEndpointUri(epr)) == false) { lock (ThisLock) { pendingConnectedNeighbor.Add(GetEndpointUri(epr), epr); } // If the neighborManager is not open this call is going to throw. // It throws ObjectDisposed exception. // This check merely eliminates the perf hit, this check is not strictly necessary // but cuts down the window for the ---- that will result in a throw to a miniscule level // We ---- the throw because we are closing down try { if (maintainer.IsOpen) { if (DiagnosticUtility.ShouldTraceInformation) { PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord(SR.GetString(SR.PeerMaintainerConnect, epr, this.config.MeshId)); TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity), record, this, null); } IAsyncResult iar = maintainer.BeginOpenNeighbor(epr, timeoutHelper.RemainingTime(), null, epr); results.Add(iar); } } catch (Exception e) { if (Fx.IsFatal(e)) throw; if (DiagnosticUtility.ShouldTraceInformation) { PeerMaintainerTraceRecord record = new PeerMaintainerTraceRecord(SR.GetString(SR.PeerMaintainerConnectFailure, epr, this.config.MeshId, e.Message)); TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.PeerMaintainerActivity, SR.GetString(SR.TraceCodePeerMaintainerActivity), record, this, null); } // I need to remove the epr just began because the BeginOpen threw. // However Object Disposed can arise as a result of a ---- between PeerNode.Close() // and Connect trying to reconnect nodes. pendingConnectedNeighbor.Remove(GetEndpointUri(epr)); if (!(e is ObjectDisposedException)) throw; DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } } } } if (nodeAddresses.Count == 0 || pendingConnectedNeighbor.Count + maintainer.ConnectedNeighborCount == wantedConnectionCount) { addNeighbor.Reset(); } } else if (index != WaitHandle.WaitTimeout) { // We have completed this thing remove it from results IAsyncResult iar = results[index]; results.RemoveAt(index); IPeerNeighbor neighbor = null; try { // Get opened neighbor and fire NeighborOpened notification neighbor = maintainer.EndOpenNeighbor(iar); } catch (Exception e) { if (Fx.IsFatal(e)) throw; pendingConnectedNeighbor.Remove(GetEndpointUri((PeerNodeAddress)iar.AsyncState)); throw; } } else { //A timeout occured no connections progressed, try some more connections //This may result in more than wantedConnectionCount connections if the timeout connections were // merely being slow pendingConnectedNeighbor.Clear(); results.Clear(); addNeighbor.Set(); } } catch (CommunicationException e) { // mostly likely the endpoint could not be reached, but any channel exception means we should try another node DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); addNeighbor.Set(); } catch (TimeoutException e) { if (TD.OpenTimeoutIsEnabled()) { TD.OpenTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); addNeighbor.Set(); } } } void IDisposable.Dispose() { if (!disposed) { lock (ThisLock) { if (!disposed) { disposed = true; maintainer.ReferralsAdded -= OnReferralsAdded; maintainer.MaintainerClosed -= OnMaintainerClosed; maintainer.NeighborClosed -= OnNeighborClosed; maintainer.NeighborConnected -= OnNeighborConnected; addNeighbor.Close(); maintainerClosed.Close(); welcomeReceived.Close(); } } } } // This method exists to minimize code churn if PeerNodeAddress is refactored later to derive from EndpointAddress static Uri GetEndpointUri(PeerNodeAddress address) { return address.EndpointAddress.Uri; } // Algorithm to prune connections // This implementation will reduce the number of connections to config.IdealNeighbors // by examining LinkUtility and selecting the neighbor with the lowest and then disconnecting it public void PruneConnections() { while (maintainer.NonClosingNeighborCount > config.IdealNeighbors && maintainer.IsOpen) { IPeerNeighbor leastUseful = maintainer.GetLeastUsefulNeighbor(); if (leastUseful == null) break; maintainer.CloseNeighbor(leastUseful, PeerCloseReason.NotUsefulNeighbor); } } // Helper method for updating the end points list public void UpdateEndpointsCollection(ICollection<PeerNodeAddress> src) { if (src != null) { lock (ThisLock) { foreach (PeerNodeAddress address in src) { UpdateEndpointsCollection(address); } } } } public void UpdateEndpointsCollection(ICollection<Referral> src) { if (src != null) { lock (ThisLock) { foreach (Referral referral in src) { UpdateEndpointsCollection(referral.Address); } } } } void UpdateEndpointsCollection(PeerNodeAddress address) { // Don't accept invalid addresses if (PeerValidateHelper.ValidNodeAddress(address)) { Uri key = GetEndpointUri(address); if (!nodeAddresses.ContainsKey(key) && key != GetEndpointUri(maintainer.GetListenAddress())) { nodeAddresses[key] = address; } } } // When a connection occurs remove it from the list to look at void OnNeighborClosed(IPeerNeighbor neighbor) { if (neighbor.ListenAddress != null) { Uri address = GetEndpointUri(neighbor.ListenAddress); if (!disposed) { lock (ThisLock) { if (!disposed) { if (address != null && pendingConnectedNeighbor.ContainsKey(address)) { pendingConnectedNeighbor.Remove(address); addNeighbor.Set(); } } } } } } // When a connection occurs remove it from the list to look at void OnNeighborConnected(IPeerNeighbor neighbor) { Uri address = GetEndpointUri(neighbor.ListenAddress); if (!disposed) { lock (ThisLock) { if (!disposed) { if (address != null && pendingConnectedNeighbor.ContainsKey(address)) { pendingConnectedNeighbor.Remove(address); } welcomeReceived.Set(); } } } } void OnMaintainerClosed() { if (!disposed) { lock (ThisLock) { if (!disposed) { maintainerClosed.Set(); } } } } // When a connection occurs add those to the group I look at void OnReferralsAdded(IList<Referral> referrals, IPeerNeighbor neighbor) { bool added = false; // Do some stuff here foreach (Referral referral in referrals) { if (!disposed) { lock (ThisLock) { if (!disposed) { if (!maintainer.IsOpen) return; Uri key = GetEndpointUri(referral.Address); if (key != GetEndpointUri(maintainer.GetListenAddress())) // make sure the referral is not mine { if (!nodeAddresses.ContainsKey(key) && !pendingConnectedNeighbor.ContainsKey(key) && maintainer.FindDuplicateNeighbor(referral.Address) == null) { nodeAddresses[key] = referral.Address; added = true; } } } } } } if (added) { if (maintainer.ConnectedNeighborCount < wantedConnectionCount) { addNeighbor.Set(); } } } } }
// // 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.Sql.LegacySdk; using Microsoft.Azure.Management.Sql.LegacySdk.Models; namespace Microsoft.Azure.Management.Sql.LegacySdk { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public static partial class SecurityAlertPolicyOperationsExtensions { /// <summary> /// Creates or updates an Azure SQL Database security alert policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the security /// alert policy applies. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Azure /// SQL Database security alert policy. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse CreateOrUpdateDatabaseSecurityAlertPolicy(this ISecurityAlertPolicyOperations operations, string resourceGroupName, string serverName, string databaseName, DatabaseSecurityAlertPolicyCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ISecurityAlertPolicyOperations)s).CreateOrUpdateDatabaseSecurityAlertPolicyAsync(resourceGroupName, serverName, databaseName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an Azure SQL Database security alert policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the security /// alert policy applies. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Azure /// SQL Database security alert policy. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> CreateOrUpdateDatabaseSecurityAlertPolicyAsync(this ISecurityAlertPolicyOperations operations, string resourceGroupName, string serverName, string databaseName, DatabaseSecurityAlertPolicyCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateDatabaseSecurityAlertPolicyAsync(resourceGroupName, serverName, databaseName, parameters, CancellationToken.None); } /// <summary> /// Creates or updates an Azure SQL Server security alert policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Azure /// SQL Database security alert policy. /// </param> /// <returns> /// Response to Azure Sql Server security alert policy create or update /// operation. /// </returns> public static ServerSecurityAlertPolicyCreateOrUpdateResponse CreateOrUpdateServerSecurityAlertPolicy(this ISecurityAlertPolicyOperations operations, string resourceGroupName, string serverName, ServerSecurityAlertPolicyCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((ISecurityAlertPolicyOperations)s).CreateOrUpdateServerSecurityAlertPolicyAsync(resourceGroupName, serverName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates an Azure SQL Server security alert policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='parameters'> /// Required. The required parameters for creating or updating a Azure /// SQL Database security alert policy. /// </param> /// <returns> /// Response to Azure Sql Server security alert policy create or update /// operation. /// </returns> public static Task<ServerSecurityAlertPolicyCreateOrUpdateResponse> CreateOrUpdateServerSecurityAlertPolicyAsync(this ISecurityAlertPolicyOperations operations, string resourceGroupName, string serverName, ServerSecurityAlertPolicyCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateServerSecurityAlertPolicyAsync(resourceGroupName, serverName, parameters, CancellationToken.None); } /// <summary> /// Returns an Azure SQL Database security alert policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the security /// alert policy applies. /// </param> /// <returns> /// Represents the response to a get database security alert policy /// request. /// </returns> public static DatabaseSecurityAlertPolicyGetResponse GetDatabaseSecurityAlertPolicy(this ISecurityAlertPolicyOperations operations, string resourceGroupName, string serverName, string databaseName) { return Task.Factory.StartNew((object s) => { return ((ISecurityAlertPolicyOperations)s).GetDatabaseSecurityAlertPolicyAsync(resourceGroupName, serverName, databaseName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns an Azure SQL Database security alert policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <param name='databaseName'> /// Required. The name of the Azure SQL Database for which the security /// alert policy applies. /// </param> /// <returns> /// Represents the response to a get database security alert policy /// request. /// </returns> public static Task<DatabaseSecurityAlertPolicyGetResponse> GetDatabaseSecurityAlertPolicyAsync(this ISecurityAlertPolicyOperations operations, string resourceGroupName, string serverName, string databaseName) { return operations.GetDatabaseSecurityAlertPolicyAsync(resourceGroupName, serverName, databaseName, CancellationToken.None); } /// <summary> /// Gets the status of an Azure Sql Server security alert policy create /// or update operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Server blob auditing status link returned by the /// CreateOrUpdate operation /// </param> /// <returns> /// Response for long running Azure Sql server threat detection create /// or update operations. /// </returns> public static ServerSecurityAlertPolicyOperationResponse GetOperationStatus(this ISecurityAlertPolicyOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((ISecurityAlertPolicyOperations)s).GetOperationStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the status of an Azure Sql Server security alert policy create /// or update operation. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Server blob auditing status link returned by the /// CreateOrUpdate operation /// </param> /// <returns> /// Response for long running Azure Sql server threat detection create /// or update operations. /// </returns> public static Task<ServerSecurityAlertPolicyOperationResponse> GetOperationStatusAsync(this ISecurityAlertPolicyOperations operations, string operationStatusLink) { return operations.GetOperationStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Returns an Azure SQL Database security alert policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <returns> /// Represents the response to a get server security alert policy /// request. /// </returns> public static ServerSecurityAlertPolicyGetResponse GetServerSecurityAlertPolicy(this ISecurityAlertPolicyOperations operations, string resourceGroupName, string serverName) { return Task.Factory.StartNew((object s) => { return ((ISecurityAlertPolicyOperations)s).GetServerSecurityAlertPolicyAsync(resourceGroupName, serverName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns an Azure SQL Database security alert policy. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Sql.LegacySdk.ISecurityAlertPolicyOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the Resource Group to which the server /// belongs. /// </param> /// <param name='serverName'> /// Required. The name of the Azure SQL Database Server on which the /// database is hosted. /// </param> /// <returns> /// Represents the response to a get server security alert policy /// request. /// </returns> public static Task<ServerSecurityAlertPolicyGetResponse> GetServerSecurityAlertPolicyAsync(this ISecurityAlertPolicyOperations operations, string resourceGroupName, string serverName) { return operations.GetServerSecurityAlertPolicyAsync(resourceGroupName, serverName, CancellationToken.None); } } }
using MatterHackers.VectorMath; //---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // Rounded rectangle vertex generator // //---------------------------------------------------------------------------- using System; using System.Collections.Generic; namespace MatterHackers.Agg.VertexSource { //------------------------------------------------------------rounded_rect // // See Implemantation agg_rounded_rect.cpp // public class RoundedRect : IVertexSource { private RectangleDouble bounds; private Vector2 leftBottomRadius; private Vector2 rightBottomRadius; private Vector2 rightTopRadius; private Vector2 leftTopRadius; private int state; private Arc currentProcessingArc = new Arc(); public RoundedRect(double left, double bottom, double right, double top, double radius) { bounds = new RectangleDouble(left, bottom, right, top); leftBottomRadius.x = radius; leftBottomRadius.y = radius; rightBottomRadius.x = radius; rightBottomRadius.y = radius; rightTopRadius.x = radius; rightTopRadius.y = radius; leftTopRadius.x = radius; leftTopRadius.y = radius; if (left > right) { bounds.Left = right; bounds.Right = left; } if (bottom > top) { bounds.Bottom = top; bounds.Top = bottom; } } public RoundedRect(RectangleDouble bounds, double r) : this(bounds.Left, bounds.Bottom, bounds.Right, bounds.Top, r) { } public RoundedRect(RectangleInt bounds, double r) : this(bounds.Left, bounds.Bottom, bounds.Right, bounds.Top, r) { } public void rect(double left, double bottom, double right, double top) { bounds = new RectangleDouble(left, bottom, right, top); if (left > right) { bounds.Left = right; bounds.Right = left; } if (bottom > top) { bounds.Bottom = top; bounds.Top = bottom; } } public void radius(double r) { leftBottomRadius.x = leftBottomRadius.y = rightBottomRadius.x = rightBottomRadius.y = rightTopRadius.x = rightTopRadius.y = leftTopRadius.x = leftTopRadius.y = r; } public void radius(double rx, double ry) { leftBottomRadius.x = rightBottomRadius.x = rightTopRadius.x = leftTopRadius.x = rx; leftBottomRadius.y = rightBottomRadius.y = rightTopRadius.y = leftTopRadius.y = ry; } public void radius(double leftBottomRadius, double rightBottomRadius, double rightTopRadius, double leftTopRadius) { this.leftBottomRadius = new Vector2(leftBottomRadius, leftBottomRadius); this.rightBottomRadius = new Vector2(rightBottomRadius, rightBottomRadius); this.rightTopRadius = new Vector2(rightTopRadius, rightTopRadius); this.leftTopRadius = new Vector2(leftTopRadius, leftTopRadius); } public void radius(double rx1, double ry1, double rx2, double ry2, double rx3, double ry3, double rx4, double ry4) { leftBottomRadius.x = rx1; leftBottomRadius.y = ry1; rightBottomRadius.x = rx2; rightBottomRadius.y = ry2; rightTopRadius.x = rx3; rightTopRadius.y = ry3; leftTopRadius.x = rx4; leftTopRadius.y = ry4; } public void normalize_radius() { double dx = Math.Abs(bounds.Top - bounds.Bottom); double dy = Math.Abs(bounds.Right - bounds.Left); double k = 1.0; double t; t = dx / (leftBottomRadius.x + rightBottomRadius.x); if (t < k) k = t; t = dx / (rightTopRadius.x + leftTopRadius.x); if (t < k) k = t; t = dy / (leftBottomRadius.y + rightBottomRadius.y); if (t < k) k = t; t = dy / (rightTopRadius.y + leftTopRadius.y); if (t < k) k = t; if (k < 1.0) { leftBottomRadius.x *= k; leftBottomRadius.y *= k; rightBottomRadius.x *= k; rightBottomRadius.y *= k; rightTopRadius.x *= k; rightTopRadius.y *= k; leftTopRadius.x *= k; leftTopRadius.y *= k; } } public void approximation_scale(double s) { currentProcessingArc.approximation_scale(s); } public double approximation_scale() { return currentProcessingArc.approximation_scale(); } public IEnumerable<VertexData> Vertices() { currentProcessingArc.init(bounds.Left + leftBottomRadius.x, bounds.Bottom + leftBottomRadius.y, leftBottomRadius.x, leftBottomRadius.y, Math.PI, Math.PI + Math.PI * 0.5); foreach (VertexData vertexData in currentProcessingArc.Vertices()) { if (ShapePath.is_stop(vertexData.command)) { break; } yield return vertexData; } currentProcessingArc.init(bounds.Right - rightBottomRadius.x, bounds.Bottom + rightBottomRadius.y, rightBottomRadius.x, rightBottomRadius.y, Math.PI + Math.PI * 0.5, 0.0); foreach (VertexData vertexData in currentProcessingArc.Vertices()) { if (ShapePath.is_move_to(vertexData.command)) { // skip the initial moveto continue; } if (ShapePath.is_stop(vertexData.command)) { break; } yield return vertexData; } currentProcessingArc.init(bounds.Right - rightTopRadius.x, bounds.Top - rightTopRadius.y, rightTopRadius.x, rightTopRadius.y, 0.0, Math.PI * 0.5); foreach (VertexData vertexData in currentProcessingArc.Vertices()) { if (ShapePath.is_move_to(vertexData.command)) { // skip the initial moveto continue; } if (ShapePath.is_stop(vertexData.command)) { break; } yield return vertexData; } currentProcessingArc.init(bounds.Left + leftTopRadius.x, bounds.Top - leftTopRadius.y, leftTopRadius.x, leftTopRadius.y, Math.PI * 0.5, Math.PI); foreach (VertexData vertexData in currentProcessingArc.Vertices()) { if (ShapePath.is_move_to(vertexData.command)) { // skip the initial moveto continue; } if (ShapePath.is_stop(vertexData.command)) { break; } yield return vertexData; } yield return new VertexData(ShapePath.FlagsAndCommand.CommandEndPoly | ShapePath.FlagsAndCommand.FlagClose | ShapePath.FlagsAndCommand.FlagCCW, new Vector2()); yield return new VertexData(ShapePath.FlagsAndCommand.CommandStop, new Vector2()); } public void rewind(int unused) { state = 0; } public ShapePath.FlagsAndCommand vertex(out double x, out double y) { x = 0; y = 0; ShapePath.FlagsAndCommand cmd = ShapePath.FlagsAndCommand.CommandStop; switch (state) { case 0: currentProcessingArc.init(bounds.Left + leftBottomRadius.x, bounds.Bottom + leftBottomRadius.y, leftBottomRadius.x, leftBottomRadius.y, Math.PI, Math.PI + Math.PI * 0.5); currentProcessingArc.rewind(0); state++; goto case 1; case 1: cmd = currentProcessingArc.vertex(out x, out y); if (ShapePath.is_stop(cmd)) { state++; } else { return cmd; } goto case 2; case 2: currentProcessingArc.init(bounds.Right - rightBottomRadius.x, bounds.Bottom + rightBottomRadius.y, rightBottomRadius.x, rightBottomRadius.y, Math.PI + Math.PI * 0.5, 0.0); currentProcessingArc.rewind(0); state++; goto case 3; case 3: cmd = currentProcessingArc.vertex(out x, out y); if (ShapePath.is_stop(cmd)) { state++; } else { return ShapePath.FlagsAndCommand.CommandLineTo; } goto case 4; case 4: currentProcessingArc.init(bounds.Right - rightTopRadius.x, bounds.Top - rightTopRadius.y, rightTopRadius.x, rightTopRadius.y, 0.0, Math.PI * 0.5); currentProcessingArc.rewind(0); state++; goto case 5; case 5: cmd = currentProcessingArc.vertex(out x, out y); if (ShapePath.is_stop(cmd)) { state++; } else { return ShapePath.FlagsAndCommand.CommandLineTo; } goto case 6; case 6: currentProcessingArc.init(bounds.Left + leftTopRadius.x, bounds.Top - leftTopRadius.y, leftTopRadius.x, leftTopRadius.y, Math.PI * 0.5, Math.PI); currentProcessingArc.rewind(0); state++; goto case 7; case 7: cmd = currentProcessingArc.vertex(out x, out y); if (ShapePath.is_stop(cmd)) { state++; } else { return ShapePath.FlagsAndCommand.CommandLineTo; } goto case 8; case 8: cmd = ShapePath.FlagsAndCommand.CommandEndPoly | ShapePath.FlagsAndCommand.FlagClose | ShapePath.FlagsAndCommand.FlagCCW; state++; break; } return cmd; } }; }
using System; using System.Threading.Tasks; namespace CSharpFunctionalExtensions { public static partial class AsyncResultExtensionsBothOperands { /// <summary> /// Returns a new failure result if the predicate is false. Otherwise returns the starting result. /// </summary> public static async Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<T, Task<bool>> predicate, string errorMessage) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; if (!await predicate(result.Value).DefaultAwait()) return Result.Failure<T>(errorMessage); return result; } /// <summary> /// Returns a new failure result if the predicate is false. Otherwise returns the starting result. /// </summary> public static async Task<Result<T, E>> Ensure<T, E>(this Task<Result<T, E>> resultTask, Func<T, Task<bool>> predicate, E error) { Result<T, E> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; if (!await predicate(result.Value).DefaultAwait()) return Result.Failure<T, E>(error); return result; } /// <summary> /// Returns a new failure result if the predicate is false. Otherwise returns the starting result. /// </summary> public static async Task<Result<T, E>> Ensure<T, E>(this Task<Result<T, E>> resultTask, Func<T, Task<bool>> predicate, Func<T, E> errorPredicate) { Result<T, E> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; if (!await predicate(result.Value).DefaultAwait()) return Result.Failure<T, E>(errorPredicate(result.Value)); return result; } /// <summary> /// Returns a new failure result if the predicate is false. Otherwise returns the starting result. /// </summary> public static async Task<Result<T, E>> Ensure<T, E>(this Task<Result<T, E>> resultTask, Func<T, Task<bool>> predicate, Func<T, Task<E>> errorPredicate) { Result<T, E> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; if (!await predicate(result.Value).DefaultAwait()) return Result.Failure<T, E>(await errorPredicate(result.Value).DefaultAwait()); return result; } /// <summary> /// Returns a new failure result if the predicate is false. Otherwise returns the starting result. /// </summary> public static async Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<T, Task<bool>> predicate, Func<T, string> errorPredicate) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; if (!await predicate(result.Value).DefaultAwait()) return Result.Failure<T>(errorPredicate(result.Value)); return result; } /// <summary> /// Returns a new failure result if the predicate is false. Otherwise returns the starting result. /// </summary> public static async Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<T, Task<bool>> predicate, Func<T, Task<string>> errorPredicate) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; if (!await predicate(result.Value).DefaultAwait()) return Result.Failure<T>(await errorPredicate(result.Value).DefaultAwait()); return result; } /// <summary> /// Returns a new failure result if the predicate is false. Otherwise returns the starting result. /// </summary> public static async Task<Result> Ensure(this Task<Result> resultTask, Func<Task<bool>> predicate, string errorMessage) { Result result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; if (!await predicate().DefaultAwait()) return Result.Failure(errorMessage); return result; } /// <summary> /// Returns a new failure result if the predicate is a failure result. Otherwise returns the starting result. /// </summary> public static async Task<Result> Ensure(this Task<Result> resultTask, Func<Task<Result>> predicate) { Result result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; var predicateResult = await predicate(); if (predicateResult.IsFailure) return Result.Failure(predicateResult.Error); return result; } /// <summary> /// Returns a new failure result if the predicate is a failure result. Otherwise returns the starting result. /// </summary> public static async Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<Task<Result>> predicate) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; var predicateResult = await predicate(); if (predicateResult.IsFailure) return Result.Failure<T>(predicateResult.Error); return result; } /// <summary> /// Returns a new failure result if the predicate is a failure result. Otherwise returns the starting result. /// </summary> public static async Task<Result> Ensure<T>(this Task<Result> resultTask, Func<Task<Result<T>>> predicate) { Result result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; var predicateResult = await predicate(); if (predicateResult.IsFailure) return Result.Failure<T>(predicateResult.Error); return result; } /// <summary> /// Returns a new failure result if the predicate is a failure result. Otherwise returns the starting result. /// </summary> public static async Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<Task<Result<T>>> predicate) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; var predicateResult = await predicate(); if (predicateResult.IsFailure) return Result.Failure<T>(predicateResult.Error); return result; } /// <summary> /// Returns a new failure result if the predicate is a failure result. Otherwise returns the starting result. /// </summary> public static async Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<T,Task<Result>> predicate) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; var predicateResult = await predicate(result.Value); if (predicateResult.IsFailure) return Result.Failure<T>(predicateResult.Error); return result; } /// <summary> /// Returns a new failure result if the predicate is a failure result. Otherwise returns the starting result. /// </summary> public static async Task<Result<T>> Ensure<T>(this Task<Result<T>> resultTask, Func<T,Task<Result<T>>> predicate) { Result<T> result = await resultTask.DefaultAwait(); if (result.IsFailure) return result; var predicateResult = await predicate(result.Value); if (predicateResult.IsFailure) return Result.Failure<T>(predicateResult.Error); return result; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * 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.IO; using System.Reflection; using System.Text; using Nini.Config; using OpenMetaverse; using System.Threading; using log4net; using OpenMetaverse.Imaging; using CSJ2K; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Region.CoreModules.Agent.TextureSender; namespace OpenSim.Region.CoreModules.Agent.TextureSender { public class CSJ2KDecoderModule : IRegionModule, IJ2KDecoder { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary>Cache for decoded layer data</summary> private J2KDecodeFileCache fCache; /// <summary>List of client methods to notify of results of decode</summary> private readonly Dictionary<UUID, List<DecodedCallback>> m_notifyList = new Dictionary<UUID, List<DecodedCallback>>(); /// <summary>Reference to a scene (doesn't matter which one as long as it can load the cache module)</summary> private Scene m_scene; #region IRegionModule public CSJ2KDecoderModule() { } public string Name { get { return "CSJ2KDecoderModule"; } } public bool IsSharedModule { get { return true; } } public void Initialize(Scene scene, IConfigSource source) { if (m_scene == null) m_scene = scene; bool useFileCache = false; IConfig myConfig = source.Configs["J2KDecoder"]; if (myConfig != null) { if (myConfig.GetString("J2KDecoderModule", Name) != Name) return; useFileCache = myConfig.GetBoolean("J2KDecoderFileCacheEnabled", false); } else { m_log.DebugFormat("[J2K DECODER MODULE] No decoder specified, Using defaults"); } m_log.DebugFormat("[J2K DECODER MODULE] Using {0} decoder. File Cache is {1}", Name, (useFileCache ? "enabled" : "disabled")); fCache = new J2KDecodeFileCache(useFileCache, J2KDecodeFileCache.CacheFolder); scene.RegisterModuleInterface<IJ2KDecoder>(this); } public void PostInitialize() { } public void Close() { } #endregion IRegionModule #region IJ2KDecoder public void BeginDecode(UUID assetID, byte[] j2kData, DecodedCallback callback) { OpenJPEG.J2KLayerInfo[] result; bool decodedSuccessfully = false; lock (fCache) { decodedSuccessfully = fCache.TryLoadCacheForAsset(assetID, out result); } if (decodedSuccessfully) { callback(assetID, result); return; } // Not cached, we need to decode it. // Add to notify list and start decoding. // Next request for this asset while it's decoding will only be added to the notify list // once this is decoded, requests will be served from the cache and all clients in the notifylist will be updated bool decode = false; lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { m_notifyList[assetID].Add(callback); } else { List<DecodedCallback> notifylist = new List<DecodedCallback>(); notifylist.Add(callback); m_notifyList.Add(assetID, notifylist); decode = true; } } // Do Decode! if (decode) Decode(assetID, j2kData); } public bool Decode(UUID assetID, byte[] j2kData) { OpenJPEG.J2KLayerInfo[] layers; return Decode(assetID, j2kData, out layers); } public bool Decode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers) { bool decodedSuccessfully = true; lock (fCache) { decodedSuccessfully = fCache.TryLoadCacheForAsset(assetID, out layers); } if (!decodedSuccessfully) decodedSuccessfully = DoJ2KDecode(assetID, j2kData, out layers); // Notify Interested Parties lock (m_notifyList) { if (m_notifyList.ContainsKey(assetID)) { foreach (DecodedCallback d in m_notifyList[assetID]) { if (d != null) d.DynamicInvoke(assetID, layers); } m_notifyList.Remove(assetID); } } return (decodedSuccessfully); } #endregion IJ2KDecoder /// <summary> /// Decode Jpeg2000 Asset Data /// </summary> /// <param name="assetID">UUID of Asset</param> /// <param name="j2kData">JPEG2000 data</param> /// <param name="layers">layer data</param> /// <param name="components">number of components</param> /// <returns>true if decode was successful. false otherwise.</returns> private bool DoJ2KDecode(UUID assetID, byte[] j2kData, out OpenJPEG.J2KLayerInfo[] layers) { bool decodedSuccessfully = true; int DecodeTime = Environment.TickCount; layers = new OpenJPEG.J2KLayerInfo[0]; // Dummy result for if it fails. Informs that there's only full quality try { using (MemoryStream ms = new MemoryStream(j2kData)) { List<int> layerStarts = CSJ2K.J2kImage.GetLayerBoundaries(ms); if (layerStarts != null && layerStarts.Count > 0) { layers = new OpenJPEG.J2KLayerInfo[layerStarts.Count]; for (int i = 0; i < layerStarts.Count; i++) { OpenJPEG.J2KLayerInfo layer = new OpenJPEG.J2KLayerInfo(); if (i == 0) layer.Start = 0; else layer.Start = layerStarts[i]; if (i == layerStarts.Count - 1) layer.End = j2kData.Length; else layer.End = layerStarts[i + 1] - 1; layers[i] = layer; } } } } catch (Exception ex) { m_log.Warn("[J2KDecoderModule]: CSJ2K threw an exception decoding texture " + assetID + ": " + ex.Message); decodedSuccessfully = false; } if (layers.Length == 0) { m_log.Warn("[J2KDecoderModule]: Failed to decode layer data for texture " + assetID + ", guessing sane defaults"); // Layer decoding completely failed. Guess at sane defaults for the layer boundaries layers = CreateDefaultLayers(j2kData.Length); decodedSuccessfully = false; } else { int elapsed = Environment.TickCount - DecodeTime; if (elapsed >= 50) m_log.InfoFormat("[J2KDecoderModule]: {0} Decode Time: {1}", elapsed, assetID); // Cache Decoded layers fCache.SaveCacheForAsset(assetID, layers); } return decodedSuccessfully; } private OpenJPEG.J2KLayerInfo[] CreateDefaultLayers(int j2kLength) { OpenJPEG.J2KLayerInfo[] layers = new OpenJPEG.J2KLayerInfo[5]; for (int i = 0; i < layers.Length; i++) layers[i] = new OpenJPEG.J2KLayerInfo(); // These default layer sizes are based on a small sampling of real-world texture data // with extra padding thrown in for good measure. This is a worst case fallback plan // and may not gracefully handle all real world data layers[0].Start = 0; layers[1].Start = (int)((float)j2kLength * 0.02f); layers[2].Start = (int)((float)j2kLength * 0.05f); layers[3].Start = (int)((float)j2kLength * 0.20f); layers[4].Start = (int)((float)j2kLength * 0.50f); layers[0].End = layers[1].Start - 1; layers[1].End = layers[2].Start - 1; layers[2].End = layers[3].Start - 1; layers[3].End = layers[4].Start - 1; layers[4].End = j2kLength; return layers; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class IOperationTests : SemanticModelTestBase { [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_ObjectExpressionStringType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { object o = myStr; bool b = /*<bind>*/o is string/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'o is string') Operand: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') IsType: System.String "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_IntExpressionIntType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { int myInt = 3; bool b = /*<bind>*/myInt is int/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'myInt is int') Operand: ILocalReferenceOperation: myInt (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'myInt') IsType: System.Int32 "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0183: The given expression is always of the provided ('int') type // bool b = /*<bind>*/myInt is int/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysTrue, "myInt is int").WithArguments("int").WithLocation(13, 32) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_ObjectExpressionUserDefinedType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { TestType tt = null; object o = tt; bool b = /*<bind>*/o is TestType/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'o is TestType') Operand: ILocalReferenceOperation: o (OperationKind.LocalReference, Type: System.Object) (Syntax: 'o') IsType: TestIsOperator.TestType "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_NullExpressionUserDefinedType() { string source = @" namespace TestIsOperator { class TestType { } class C { static void M(string myStr) { TestType tt = null; object o = tt; bool b = /*<bind>*/null is TestType/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'null is TestType') Operand: ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null') IsType: TestIsOperator.TestType "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0184: The given expression is never of the provided ('TestType') type // bool b = /*<bind>*/null is TestType/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is TestType").WithArguments("TestIsOperator.TestType").WithLocation(14, 32) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperator_IntExpressionEnumType() { string source = @" class IsTest { static void Main() { var b = /*<bind>*/1 is color/*</bind>*/; System.Console.WriteLine(b); } } enum color { } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: '1 is color') Operand: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') IsType: color "; var expectedDiagnostics = new DiagnosticDescription[] { // CS0184: The given expression is never of the provided ('color') type // var b = /*<bind>*/1 is color/*</bind>*/; Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is color").WithArguments("color").WithLocation(6, 27) }; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionIntType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is int/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is int') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: System.Int32 "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionObjectType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/u is object/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'u is object') Operand: IParameterReferenceOperation: u (OperationKind.ParameterReference, Type: U) (Syntax: 'u') IsType: System.Object "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionDifferentTypeParameterType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is U/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is U') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: U "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation)] [Fact] public void TestIsOperatorGeneric_TypeParameterExpressionSameTypeParameterType() { string source = @" namespace TestIsOperatorGeneric { class C { public static void M<T, U, W>(T t, U u) where T : class where U : class { bool test = /*<bind>*/t is T/*</bind>*/; } } } "; string expectedOperationTree = @" IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 't is T') Operand: IParameterReferenceOperation: t (OperationKind.ParameterReference, Type: T) (Syntax: 't') IsType: T "; var expectedDiagnostics = DiagnosticDescription.None; VerifyOperationTreeAndDiagnosticsForTest<BinaryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void IsTypeFlow_01() { string source = @" class C { public static void M2(C1 c, bool b) /*<bind>*/{ b = c is C1; }/*</bind>*/ public class C1 { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = c is C1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = c is C1') Left: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') Right: IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: 'c is C1') Operand: IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c') IsType: C.C1 Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void IsTypeFlow_02() { string source = @" class C { public static void M2(C1 c1, C1 c2, bool b) /*<bind>*/{ b = (c1 ?? c2) is C1; }/*</bind>*/ public class C1 { } } "; var expectedDiagnostics = DiagnosticDescription.None; string expectedFlowGraph = @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (2) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b') Value: IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c1') Jump if True (Regular) to Block[B3] IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'c1') Operand: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B2] Block[B2] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1') Value: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1') Next (Regular) Block[B4] Block[B3] - Block Predecessors: [B1] Statements (1) IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c2') Value: IParameterReferenceOperation: c2 (OperationKind.ParameterReference, Type: C.C1) (Syntax: 'c2') Next (Regular) Block[B4] Block[B4] - Block Predecessors: [B2] [B3] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'b = (c1 ?? c2) is C1;') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Boolean) (Syntax: 'b = (c1 ?? c2) is C1') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Boolean, IsImplicit) (Syntax: 'b') Right: IIsTypeOperation (OperationKind.IsType, Type: System.Boolean) (Syntax: '(c1 ?? c2) is C1') Operand: IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: C.C1, IsImplicit) (Syntax: 'c1 ?? c2') IsType: C.C1 Next (Regular) Block[B5] Block[B5] - Exit Predecessors: [B4] Statements (0) "; VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics); } } }
// // http://code.google.com/p/servicestack/wiki/TypeSerializer // ServiceStack.Text: .NET C# POCO Type Text Serializer. // // Authors: // Demis Bellot (demis.bellot@gmail.com) // // Copyright 2011 Liquidbit Ltd. // // Licensed under the same terms of ServiceStack: new BSD license. // using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using ServiceStack.Text.Common; using ServiceStack.Text.Jsv; namespace ServiceStack.Text { /// <summary> /// Creates an instance of a Type from a string value /// </summary> public static class TypeSerializer { private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false); public const string DoubleQuoteString = "\"\""; /// <summary> /// Determines whether the specified type is convertible from string. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if the specified type is convertible from string; otherwise, <c>false</c>. /// </returns> public static bool CanCreateFromString(Type type) { return JsvReader.GetParseFn(type) != null; } /// <summary> /// Parses the specified value. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public static T DeserializeFromString<T>(string value) { if (string.IsNullOrEmpty(value)) return default(T); return (T)JsvReader<T>.Parse(value); } public static T DeserializeFromReader<T>(TextReader reader) { return DeserializeFromString<T>(reader.ReadToEnd()); } /// <summary> /// Parses the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="value">The value.</param> /// <returns></returns> public static object DeserializeFromString(string value, Type type) { return value == null ? null : JsvReader.GetParseFn(type)(value); } public static object DeserializeFromReader(TextReader reader, Type type) { return DeserializeFromString(reader.ReadToEnd(), type); } public static string SerializeToString<T>(T value) { if (value == null) return null; if (typeof(T) == typeof(string)) return value as string; if (typeof(T) == typeof(object) || typeof(T).IsAbstract || typeof(T).IsInterface) { if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = true; var result = SerializeToString(value, value.GetType()); if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = false; return result; } var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { JsvWriter<T>.WriteObject(writer, value); } return sb.ToString(); } public static string SerializeToString(object value, Type type) { if (value == null) return null; if (type == typeof(string)) return value as string; var sb = new StringBuilder(); using (var writer = new StringWriter(sb, CultureInfo.InvariantCulture)) { JsvWriter.GetWriteFn(type)(writer, value); } return sb.ToString(); } public static void SerializeToWriter<T>(T value, TextWriter writer) { if (value == null) return; if (typeof(T) == typeof(string)) { writer.Write(value); return; } if (typeof(T) == typeof(object)) { if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = true; SerializeToWriter(value, value.GetType(), writer); if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = false; return; } JsvWriter<T>.WriteObject(writer, value); } public static void SerializeToWriter(object value, Type type, TextWriter writer) { if (value == null) return; if (type == typeof(string)) { writer.Write(value); return; } JsvWriter.GetWriteFn(type)(writer, value); } public static void SerializeToStream<T>(T value, Stream stream) { if (value == null) return; if (typeof(T) == typeof(object)) { if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = true; SerializeToStream(value, value.GetType(), stream); if (typeof(T).IsAbstract || typeof(T).IsInterface) JsState.IsWritingDynamic = false; return; } var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsvWriter<T>.WriteObject(writer, value); writer.Flush(); } public static void SerializeToStream(object value, Type type, Stream stream) { var writer = new StreamWriter(stream, UTF8EncodingWithoutBom); JsvWriter.GetWriteFn(type)(writer, value); writer.Flush(); } public static T Clone<T>(T value) { var serializedValue = SerializeToString(value); var cloneObj = DeserializeFromString<T>(serializedValue); return cloneObj; } public static T DeserializeFromStream<T>(Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString<T>(reader.ReadToEnd()); } } public static object DeserializeFromStream(Type type, Stream stream) { using (var reader = new StreamReader(stream, UTF8EncodingWithoutBom)) { return DeserializeFromString(reader.ReadToEnd(), type); } } /// <summary> /// Useful extension method to get the Dictionary[string,string] representation of any POCO type. /// </summary> /// <returns></returns> public static Dictionary<string, string> ToStringDictionary<T>(this T obj) where T : class { var jsv = SerializeToString(obj); var map = DeserializeFromString<Dictionary<string, string>>(jsv); return map; } /// <summary> /// Recursively prints the contents of any POCO object in a human-friendly, readable format /// </summary> /// <returns></returns> public static string Dump<T>(this T instance) { return SerializeAndFormat(instance); } public static string SerializeAndFormat<T>(this T instance) { var dtoStr = SerializeToString(instance); var formatStr = JsvFormatter.Format(dtoStr); return formatStr; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NUnit.Framework; using CorruptIndexException = Lucene.Net.Index.CorruptIndexException; using IndexReader = Lucene.Net.Index.IndexReader; using IndexSearcher = Lucene.Net.Search.IndexSearcher; using Query = Lucene.Net.Search.Query; using QueryUtils = Lucene.Net.Search.QueryUtils; using ScoreDoc = Lucene.Net.Search.ScoreDoc; using TopDocs = Lucene.Net.Search.TopDocs; namespace Lucene.Net.Search.Function { /// <summary> Test search based on OrdFieldSource and ReverseOrdFieldSource. /// <p/> /// Tests here create an index with a few documents, each having /// an indexed "id" field. /// The ord values of this field are later used for scoring. /// <p/> /// The order tests use Hits to verify that docs are ordered as expected. /// <p/> /// The exact score tests use TopDocs top to verify the exact score. /// </summary> [TestFixture] public class TestOrdValues:FunctionTestSetup { /* @override constructor */ public TestOrdValues(System.String name):base(name, false) { } public TestOrdValues() : base() { } /// <summary>Test OrdFieldSource </summary> [Test] public virtual void TestOrdFieldRank() { DoTestRank(ID_FIELD, true); } /// <summary>Test ReverseOrdFieldSource </summary> [Test] public virtual void TestReverseOrdFieldRank() { DoTestRank(ID_FIELD, false); } // Test that queries based on reverse/ordFieldScore scores correctly private void DoTestRank(System.String field, bool inOrder) { IndexSearcher s = new IndexSearcher(dir, true); ValueSource vs; if (inOrder) { vs = new OrdFieldSource(field); } else { vs = new ReverseOrdFieldSource(field); } Query q = new ValueSourceQuery(vs); Log("test: " + q); QueryUtils.Check(q, s); ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(N_DOCS, h.Length, "All docs should be matched!"); System.String prevID = inOrder?"IE":"IC"; // smaller than all ids of docs in this test ("ID0001", etc.) for (int i = 0; i < h.Length; i++) { System.String resID = s.Doc(h[i].Doc).Get(ID_FIELD); Log(i + ". score=" + h[i].Score + " - " + resID); Log(s.Explain(q, h[i].Doc)); if (inOrder) { Assert.IsTrue(String.CompareOrdinal(resID, prevID) < 0, "res id " + resID + " should be < prev res id " + prevID); } else { Assert.IsTrue(String.CompareOrdinal(resID, prevID) > 0, "res id " + resID + " should be > prev res id " + prevID); } prevID = resID; } } /// <summary>Test exact score for OrdFieldSource </summary> [Test] public virtual void TestOrdFieldExactScore() { DoTestExactScore(ID_FIELD, true); } /// <summary>Test exact score for ReverseOrdFieldSource </summary> [Test] public virtual void TestReverseOrdFieldExactScore() { DoTestExactScore(ID_FIELD, false); } // Test that queries based on reverse/ordFieldScore returns docs with expected score. private void DoTestExactScore(System.String field, bool inOrder) { IndexSearcher s = new IndexSearcher(dir, true); ValueSource vs; if (inOrder) { vs = new OrdFieldSource(field); } else { vs = new ReverseOrdFieldSource(field); } Query q = new ValueSourceQuery(vs); TopDocs td = s.Search(q, null, 1000); Assert.AreEqual(N_DOCS, td.TotalHits, "All docs should be matched!"); ScoreDoc[] sd = td.ScoreDocs; for (int i = 0; i < sd.Length; i++) { float score = sd[i].Score; System.String id = s.IndexReader.Document(sd[i].Doc).Get(ID_FIELD); Log("-------- " + i + ". Explain doc " + id); Log(s.Explain(q, sd[i].Doc)); float expectedScore = N_DOCS - i; Assert.AreEqual(expectedScore, score, TEST_SCORE_TOLERANCE_DELTA, "score of result " + i + " shuould be " + expectedScore + " != " + score); System.String expectedId = inOrder?Id2String(N_DOCS - i):Id2String(i + 1); // reverse ==> smaller values first Assert.IsTrue(expectedId.Equals(id), "id of result " + i + " shuould be " + expectedId + " != " + score); } } /// <summary>Test caching OrdFieldSource </summary> [Test] public virtual void TestCachingOrd() { DoTestCaching(ID_FIELD, true); } /// <summary>Test caching for ReverseOrdFieldSource </summary> [Test] public virtual void TesCachingReverseOrd() { DoTestCaching(ID_FIELD, false); } // Test that values loaded for FieldScoreQuery are cached properly and consumes the proper RAM resources. private void DoTestCaching(System.String field, bool inOrder) { IndexSearcher s = new IndexSearcher(dir, true); System.Object innerArray = null; bool warned = false; // print warning once for (int i = 0; i < 10; i++) { ValueSource vs; if (inOrder) { vs = new OrdFieldSource(field); } else { vs = new ReverseOrdFieldSource(field); } ValueSourceQuery q = new ValueSourceQuery(vs); ScoreDoc[] h = s.Search(q, null, 1000).ScoreDocs; try { Assert.AreEqual(N_DOCS, h.Length, "All docs should be matched!"); IndexReader[] readers = s.IndexReader.GetSequentialSubReaders(); for (int j = 0; j < readers.Length; j++) { IndexReader reader = readers[j]; if (i == 0) { innerArray = q.valSrc.GetValues(reader).InnerArray; } else { Log(i + ". compare: " + innerArray + " to " + q.valSrc.GetValues(reader).InnerArray); Assert.AreSame(innerArray, q.valSrc.GetValues(reader).InnerArray, "field values should be cached and reused!"); } } } catch (System.NotSupportedException) { if (!warned) { System.Console.Error.WriteLine("WARNING: " + TestName() + " cannot fully test values of " + q); warned = true; } } } ValueSource vs2; ValueSourceQuery q2; ScoreDoc[] h2; // verify that different values are loaded for a different field System.String field2 = INT_FIELD; Assert.IsFalse(field.Equals(field2)); // otherwise this test is meaningless. if (inOrder) { vs2 = new OrdFieldSource(field2); } else { vs2 = new ReverseOrdFieldSource(field2); } q2 = new ValueSourceQuery(vs2); h2 = s.Search(q2, null, 1000).ScoreDocs; Assert.AreEqual(N_DOCS, h2.Length, "All docs should be matched!"); IndexReader[] readers2 = s.IndexReader.GetSequentialSubReaders(); for (int j = 0; j < readers2.Length; j++) { IndexReader reader = readers2[j]; try { Log("compare (should differ): " + innerArray + " to " + q2.valSrc.GetValues(reader).InnerArray); Assert.AreNotSame(innerArray, q2.valSrc.GetValues(reader).InnerArray, "different values shuold be loaded for a different field!"); } catch (System.NotSupportedException) { if (!warned) { System.Console.Error.WriteLine("WARNING: " + TestName() + " cannot fully test values of " + q2); warned = true; } } } // verify new values are reloaded (not reused) for a new reader s = new IndexSearcher(dir, true); if (inOrder) { vs2 = new OrdFieldSource(field); } else { vs2 = new ReverseOrdFieldSource(field); } q2 = new ValueSourceQuery(vs2); h2 = s.Search(q2, null, 1000).ScoreDocs; Assert.AreEqual(N_DOCS, h2.Length, "All docs should be matched!"); readers2 = s.IndexReader.GetSequentialSubReaders(); for (int j = 0; j < readers2.Length; j++) { IndexReader reader = readers2[j]; try { Log("compare (should differ): " + innerArray + " to " + q2.valSrc.GetValues(reader).InnerArray); Assert.AreNotSame(innerArray, q2.valSrc.GetValues(reader).InnerArray, "cached field values should not be reused if reader as changed!"); } catch (System.NotSupportedException) { if (!warned) { System.Console.Error.WriteLine("WARNING: " + TestName() + " cannot fully test values of " + q2); warned = true; } } } } private System.String TestName() { return Lucene.Net.TestCase.GetFullName(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Globalization; using Xunit; namespace System.Tests { public class ConvertToStringTests { [Fact] public static void FromBoxedObject() { object[] testValues = { // Boolean true, false, // Byte byte.MinValue, (byte)100, byte.MaxValue, // Decimal decimal.Zero, decimal.One, decimal.MinusOne, decimal.MaxValue, decimal.MinValue, 1.234567890123456789012345678m, 1234.56m, -1234.56m, // Double -12.2364, -12.236465923406483, -1.7753E-83, +12.345e+234, +12e+1, double.NegativeInfinity, double.PositiveInfinity, double.NaN, // Int16 short.MinValue, 0, short.MaxValue, // Int32 int.MinValue, 0, int.MaxValue, // Int64 long.MinValue, (long)0, long.MaxValue, // SByte sbyte.MinValue, (sbyte)0, sbyte.MaxValue, // Single -12.2364f, -12.2364659234064826243f, (float)+12.345e+234, +12e+1f, float.NegativeInfinity, float.PositiveInfinity, float.NaN, // TimeSpan TimeSpan.Zero, TimeSpan.Parse("1999.9:09:09"), TimeSpan.Parse("-1111.1:11:11"), TimeSpan.Parse("1:23:45"), TimeSpan.Parse("-2:34:56"), // UInt16 ushort.MinValue, (ushort)100, ushort.MaxValue, // UInt32 uint.MinValue, (uint)100, uint.MaxValue, // UInt64 ulong.MinValue, (ulong)100, ulong.MaxValue }; string[] expectedValues = { // Boolean "True", "False", // Byte "0", "100", "255", // Decimal "0", "1", "-1", "79228162514264337593543950335", "-79228162514264337593543950335", "1.234567890123456789012345678", "1234.56", "-1234.56", // Double "-12.2364", "-12.2364659234065", "-1.7753E-83", "1.2345E+235", "120", "-Infinity", "Infinity", "NaN", // Int16 "-32768", "0", "32767", // Int32 "-2147483648", "0", "2147483647", // Int64 "-9223372036854775808", "0", "9223372036854775807", // SByte "-128", "0", "127", // Single "-12.2364", "-12.23647", "Infinity", "120", "-Infinity", "Infinity", "NaN", // TimeSpan "00:00:00", "1999.09:09:09", "-1111.01:11:11", "01:23:45", "-02:34:56", // UInt16 "0", "100", "65535", // UInt32 "0", "100", "4294967295", // UInt64 "0", "100", "18446744073709551615", }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo)); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)] public static void FromBoxedObject_NotNetFramework() { object[] testValues = { // Single -1.7753e-83f, }; string[] expectedValues = { // Single "-0", }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo)); } } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)] public static void FromBoxedObject_NetFramework() { object[] testValues = { // Single -1.7753e-83f, }; string[] expectedValues = { // Single "0", }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], NumberFormatInfo.InvariantInfo)); } } [Fact] public static void FromObject() { Assert.Equal("System.Tests.ConvertToStringTests", Convert.ToString(new ConvertToStringTests())); } [Fact] public static void FromDateTime() { DateTime[] testValues = { new DateTime(2000, 8, 15, 16, 59, 59), new DateTime(1, 1, 1, 1, 1, 1) }; string[] expectedValues = { "08/15/2000 16:59:59", "01/01/0001 01:01:01" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(testValues[i].ToString(), Convert.ToString(testValues[i])); Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], DateTimeFormatInfo.InvariantInfo)); } } [Fact] public static void FromChar() { char[] testValues = { 'a', 'A', '@', '\n' }; string[] expectedValues = { "a", "A", "@", "\n" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i])); Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], CultureInfo.InvariantCulture)); } } private static void Verify<TInput>(Func<TInput, string> convert, Func<TInput, IFormatProvider, string> convertWithFormatProvider, TInput[] testValues, string[] expectedValues, IFormatProvider formatProvider = null) { Assert.Equal(expectedValues.Length, testValues.Length); if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], convert(testValues[i])); Assert.Equal(expectedValues[i], convertWithFormatProvider(testValues[i], formatProvider)); } } [Fact] public static void FromByteBase2() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "1100100", "11111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromByteBase8() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "144", "377" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromByteBase10() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "100", "255" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromByteBase16() { byte[] testValues = { byte.MinValue, 100, byte.MaxValue }; string[] expectedValues = { "0", "64", "ff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromByteInvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(byte.MaxValue, 13)); } [Fact] public static void FromInt16Base2() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "1000000000000000", "0", "111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt16Base8() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "100000", "0", "77777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt16Base10() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "-32768", "0", "32767" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt16Base16() { short[] testValues = { short.MinValue, 0, short.MaxValue }; string[] expectedValues = { "8000", "0", "7fff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt16InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(short.MaxValue, 0)); } [Fact] public static void FromInt32Base2() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "10000000000000000000000000000000", "0", "1111111111111111111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt32Base8() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "20000000000", "0", "17777777777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt32Base10() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "-2147483648", "0", "2147483647" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt32Base16() { int[] testValues = { int.MinValue, 0, int.MaxValue }; string[] expectedValues = { "80000000", "0", "7fffffff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt32InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(int.MaxValue, 9)); } [Fact] public static void FromInt64Base2() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "1000000000000000000000000000000000000000000000000000000000000000", "0", "111111111111111111111111111111111111111111111111111111111111111" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 2)); } } [Fact] public static void FromInt64Base8() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "1000000000000000000000", "0", "777777777777777777777" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 8)); } } [Fact] public static void FromInt64Base10() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "-9223372036854775808", "0", "9223372036854775807" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 10)); } } [Fact] public static void FromInt64Base16() { long[] testValues = { long.MinValue, 0, long.MaxValue }; string[] expectedValues = { "8000000000000000", "0", "7fffffffffffffff" }; for (int i = 0; i < testValues.Length; i++) { Assert.Equal(expectedValues[i], Convert.ToString(testValues[i], 16)); } } [Fact] public static void FromInt64InvalidBase() { AssertExtensions.Throws<ArgumentException>(null, () => Convert.ToString(long.MaxValue, 1)); } [Fact] public static void FromBoolean() { bool[] testValues = new[] { true, false }; for (int i = 0; i < testValues.Length; i++) { string expected = testValues[i].ToString(); string actual = Convert.ToString(testValues[i]); Assert.Equal(expected, actual); actual = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(expected, actual); } } [Fact] public static void FromSByte() { sbyte[] testValues = new sbyte[] { sbyte.MinValue, -1, 0, 1, sbyte.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromByte() { byte[] testValues = new byte[] { byte.MinValue, 0, 1, 100, byte.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt16Array() { short[] testValues = new short[] { short.MinValue, -1000, -1, 0, 1, 1000, short.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt16Array() { ushort[] testValues = new ushort[] { ushort.MinValue, 0, 1, 1000, ushort.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt32Array() { int[] testValues = new int[] { int.MinValue, -1000, -1, 0, 1, 1000, int.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt32Array() { uint[] testValues = new uint[] { uint.MinValue, 0, 1, 1000, uint.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromInt64Array() { long[] testValues = new long[] { long.MinValue, -1000, -1, 0, 1, 1000, long.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromUInt64Array() { ulong[] testValues = new ulong[] { ulong.MinValue, 0, 1, 1000, ulong.MaxValue }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromSingleArray() { float[] testValues = new float[] { float.MinValue, 0.0f, 1.0f, 1000.0f, float.MaxValue, float.NegativeInfinity, float.PositiveInfinity, float.Epsilon, float.NaN }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDoubleArray() { double[] testValues = new double[] { double.MinValue, 0.0, 1.0, 1000.0, double.MaxValue, double.NegativeInfinity, double.PositiveInfinity, double.Epsilon, double.NaN }; // Vanilla Test Cases for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDecimalArray() { decimal[] testValues = new decimal[] { decimal.MinValue, decimal.Parse("-1.234567890123456789012345678", NumberFormatInfo.InvariantInfo), (decimal)0.0, (decimal)1.0, (decimal)1000.0, decimal.MaxValue, decimal.One, decimal.Zero, decimal.MinusOne }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(NumberFormatInfo.CurrentInfo), result); } } [Fact] public static void FromDateTimeArray() { DateTime[] testValues = new DateTime[] { DateTime.Parse("08/15/2000 16:59:59", DateTimeFormatInfo.InvariantInfo), DateTime.Parse("01/01/0001 01:01:01", DateTimeFormatInfo.InvariantInfo) }; IFormatProvider formatProvider = DateTimeFormatInfo.GetInstance(new CultureInfo("en-US")); for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], formatProvider); string expected = testValues[i].ToString(formatProvider); Assert.Equal(expected, result); } } [Fact] public static void FromString() { string[] testValues = new string[] { "Hello", " ", "", "\0" }; for (int i = 0; i < testValues.Length; i++) { string result = Convert.ToString(testValues[i]); Assert.Equal(testValues[i].ToString(), result); result = Convert.ToString(testValues[i], NumberFormatInfo.CurrentInfo); Assert.Equal(testValues[i].ToString(), result); } } [Fact] public static void FromIFormattable() { FooFormattable foo = new FooFormattable(3); string result = Convert.ToString(foo); Assert.Equal("FooFormattable: 3", result); result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("System.Globalization.NumberFormatInfo: 3", result); foo = null; result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("", result); } [Fact] public static void FromNonIConvertible() { Foo foo = new Foo(3); string result = Convert.ToString(foo); Assert.Equal("System.Tests.ConvertToStringTests+Foo", result); result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("System.Tests.ConvertToStringTests+Foo", result); foo = null; result = Convert.ToString(foo, NumberFormatInfo.CurrentInfo); Assert.Equal("", result); } private class FooFormattable : IFormattable { private int _value; public FooFormattable(int value) { _value = value; } public string ToString(string format, IFormatProvider formatProvider) { if (formatProvider != null) { return string.Format("{0}: {1}", formatProvider, _value); } else { return string.Format("FooFormattable: {0}", (_value)); } } } private class Foo { private int _value; public Foo(int value) { _value = value; } public string ToString(IFormatProvider provider) { if (provider != null) { return string.Format("{0}: {1}", provider, _value); } else { return string.Format("Foo: {0}", _value); } } } } }
namespace Volante { using System; public class TestEnumeratorResult : TestResult { public TimeSpan InsertTime; public TimeSpan IterationTime; } public class TestEnumerator : ITest { class Record : Persistent { internal String strKey; internal long intKey; } class Indices : Persistent { internal IIndex<string, Record> strIndex; internal IIndex<long, Record> intIndex; } public void Run(TestConfig config) { int count = config.Count; var res = new TestEnumeratorResult(); config.Result = res; var start = DateTime.Now; IDatabase db = config.GetDatabase(); Indices root = (Indices)db.Root; Tests.Assert(root == null); root = new Indices(); root.strIndex = db.CreateIndex<string, Record>(IndexType.NonUnique); root.intIndex = db.CreateIndex<long, Record>(IndexType.NonUnique); db.Root = root; IIndex<long, Record> intIndex = root.intIndex; IIndex<string, Record> strIndex = root.strIndex; Record[] records; long key = 1999; int i, j; for (i = 0; i < count; i++) { key = (3141592621L * key + 2718281829L) % 1000000007L; Record rec = new Record(); rec.intKey = key; rec.strKey = Convert.ToString(key); for (j = (int)(key % 10); --j >= 0; ) { intIndex[rec.intKey] = rec; strIndex[rec.strKey] = rec; } } db.Commit(); res.InsertTime = DateTime.Now - start; start = DateTime.Now; key = 1999; for (i = 0; i < count; i++) { key = (3141592621L * key + 2718281829L) % 1000000007L; Key fromInclusive = new Key(key); Key fromInclusiveStr = new Key(Convert.ToString(key)); Key fromExclusive = new Key(key, false); Key fromExclusiveStr = new Key(Convert.ToString(key), false); key = (3141592621L * key + 2718281829L) % 1000000007L; Key tillInclusive = new Key(key); Key tillInclusiveStr = new Key(Convert.ToString(key)); Key tillExclusive = new Key(key, false); Key tillExclusiveStr = new Key(Convert.ToString(key), false); // int key ascent order records = intIndex.Get(fromInclusive, tillInclusive); j = 0; foreach (Record rec in intIndex.Range(fromInclusive, tillInclusive, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = intIndex.Get(fromInclusive, tillExclusive); j = 0; foreach (Record rec in intIndex.Range(fromInclusive, tillExclusive, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = intIndex.Get(fromExclusive, tillInclusive); j = 0; foreach (Record rec in intIndex.Range(fromExclusive, tillInclusive, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = intIndex.Get(fromExclusive, tillExclusive); j = 0; foreach (Record rec in intIndex.Range(fromExclusive, tillExclusive, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = intIndex.Get(fromInclusive, null); j = 0; foreach (Record rec in intIndex.Range(fromInclusive, null, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = intIndex.Get(fromExclusive, null); j = 0; foreach (Record rec in intIndex.Range(fromExclusive, null, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = intIndex.Get(null, tillInclusive); j = 0; foreach (Record rec in intIndex.Range(null, tillInclusive, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = intIndex.Get(null, tillExclusive); j = 0; foreach (Record rec in intIndex.Range(null, tillExclusive, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = intIndex.ToArray(); j = 0; foreach (Record rec in intIndex) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); // int key descent order records = intIndex.Get(fromInclusive, tillInclusive); j = records.Length; foreach (Record rec in intIndex.Range(fromInclusive, tillInclusive, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = intIndex.Get(fromInclusive, tillExclusive); j = records.Length; foreach (Record rec in intIndex.Range(fromInclusive, tillExclusive, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = intIndex.Get(fromExclusive, tillInclusive); j = records.Length; foreach (Record rec in intIndex.Range(fromExclusive, tillInclusive, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = intIndex.Get(fromExclusive, tillExclusive); j = records.Length; foreach (Record rec in intIndex.Range(fromExclusive, tillExclusive, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = intIndex.Get(fromInclusive, null); j = records.Length; foreach (Record rec in intIndex.Range(fromInclusive, null, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = intIndex.Get(fromExclusive, null); j = records.Length; foreach (Record rec in intIndex.Range(fromExclusive, null, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = intIndex.Get(null, tillInclusive); j = records.Length; foreach (Record rec in intIndex.Range(null, tillInclusive, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = intIndex.Get(null, tillExclusive); j = records.Length; foreach (Record rec in intIndex.Range(null, tillExclusive, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = intIndex.ToArray(); j = records.Length; foreach (Record rec in intIndex.Reverse()) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); // str key ascent order records = strIndex.Get(fromInclusiveStr, tillInclusiveStr); j = 0; foreach (Record rec in strIndex.Range(fromInclusiveStr, tillInclusiveStr, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = strIndex.Get(fromInclusiveStr, tillExclusiveStr); j = 0; foreach (Record rec in strIndex.Range(fromInclusiveStr, tillExclusiveStr, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = strIndex.Get(fromExclusiveStr, tillInclusiveStr); j = 0; foreach (Record rec in strIndex.Range(fromExclusiveStr, tillInclusiveStr, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = strIndex.Get(fromExclusiveStr, tillExclusiveStr); j = 0; foreach (Record rec in strIndex.Range(fromExclusiveStr, tillExclusiveStr, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = strIndex.Get(fromInclusiveStr, null); j = 0; foreach (Record rec in strIndex.Range(fromInclusiveStr, null, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = strIndex.Get(fromExclusiveStr, null); j = 0; foreach (Record rec in strIndex.Range(fromExclusiveStr, null, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = strIndex.Get(null, tillInclusiveStr); j = 0; foreach (Record rec in strIndex.Range(null, tillInclusiveStr, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = strIndex.Get(null, tillExclusiveStr); j = 0; foreach (Record rec in strIndex.Range(null, tillExclusiveStr, IterationOrder.AscentOrder)) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); records = strIndex.ToArray(); j = 0; foreach (Record rec in strIndex) { Tests.Assert(rec == records[j++]); } Tests.Assert(j == records.Length); // str key descent order records = strIndex.Get(fromInclusiveStr, tillInclusiveStr); j = records.Length; foreach (Record rec in strIndex.Range(fromInclusiveStr, tillInclusiveStr, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = strIndex.Get(fromInclusiveStr, tillExclusiveStr); j = records.Length; foreach (Record rec in strIndex.Range(fromInclusiveStr, tillExclusiveStr, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = strIndex.Get(fromExclusiveStr, tillInclusiveStr); j = records.Length; foreach (Record rec in strIndex.Range(fromExclusiveStr, tillInclusiveStr, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = strIndex.Get(fromExclusiveStr, tillExclusiveStr); j = records.Length; foreach (Record rec in strIndex.Range(fromExclusiveStr, tillExclusiveStr, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = strIndex.Get(fromInclusiveStr, null); j = records.Length; foreach (Record rec in strIndex.Range(fromInclusiveStr, null, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = strIndex.Get(fromExclusiveStr, null); j = records.Length; foreach (Record rec in strIndex.Range(fromExclusiveStr, null, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = strIndex.Get(null, tillInclusiveStr); j = records.Length; foreach (Record rec in strIndex.Range(null, tillInclusiveStr, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = strIndex.Get(null, tillExclusiveStr); j = records.Length; foreach (Record rec in strIndex.Range(null, tillExclusiveStr, IterationOrder.DescentOrder)) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); records = strIndex.ToArray(); j = records.Length; foreach (Record rec in strIndex.Reverse()) { Tests.Assert(rec == records[--j]); } Tests.Assert(j == 0); } res.IterationTime = DateTime.Now - start; strIndex.Clear(); intIndex.Clear(); Tests.Assert(!strIndex.GetEnumerator().MoveNext()); Tests.Assert(!intIndex.GetEnumerator().MoveNext()); Tests.Assert(!strIndex.Reverse().GetEnumerator().MoveNext()); Tests.Assert(!intIndex.Reverse().GetEnumerator().MoveNext()); db.Commit(); db.Gc(); db.Close(); } } }
// 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.Collections.Generic; using System.Diagnostics; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Mods; using osu.Game.Screens.Play.HUD; using osuTK; namespace osu.Game.Screens.Play { /// <summary> /// Displays beatmap metadata inside <see cref="PlayerLoader"/> /// </summary> public class BeatmapMetadataDisplay : Container { private readonly IWorkingBeatmap beatmap; private readonly Bindable<IReadOnlyList<Mod>> mods; private readonly Drawable logoFacade; private LoadingSpinner loading; public IBindable<IReadOnlyList<Mod>> Mods => mods; public bool Loading { set { if (value) loading.Show(); else loading.Hide(); } } public BeatmapMetadataDisplay(IWorkingBeatmap beatmap, Bindable<IReadOnlyList<Mod>> mods, Drawable logoFacade) { this.beatmap = beatmap; this.logoFacade = logoFacade; this.mods = new Bindable<IReadOnlyList<Mod>>(); this.mods.BindTo(mods); } private IBindable<StarDifficulty?> starDifficulty; private FillFlowContainer versionFlow; private StarRatingDisplay starRatingDisplay; [BackgroundDependencyLoader] private void load(BeatmapDifficultyCache difficultyCache) { var metadata = beatmap.BeatmapInfo.Metadata; AutoSizeAxes = Axes.Both; Children = new Drawable[] { new FillFlowContainer { AutoSizeAxes = Axes.Both, Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, Direction = FillDirection.Vertical, Children = new[] { logoFacade.With(d => { d.Anchor = Anchor.TopCentre; d.Origin = Anchor.TopCentre; }), new OsuSpriteText { Text = new RomanisableString(metadata.TitleUnicode, metadata.Title), Font = OsuFont.GetFont(size: 36, italics: true), Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, Margin = new MarginPadding { Top = 15 }, }, new OsuSpriteText { Text = new RomanisableString(metadata.ArtistUnicode, metadata.Artist), Font = OsuFont.GetFont(size: 26, italics: true), Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, }, new Container { Size = new Vector2(300, 60), Margin = new MarginPadding(10), Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre, CornerRadius = 10, Masking = true, Children = new Drawable[] { new Sprite { RelativeSizeAxes = Axes.Both, Texture = beatmap?.Background, Origin = Anchor.Centre, Anchor = Anchor.Centre, FillMode = FillMode.Fill, }, loading = new LoadingLayer(true) } }, versionFlow = new FillFlowContainer { AutoSizeAxes = Axes.Both, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Direction = FillDirection.Vertical, Spacing = new Vector2(5f), Margin = new MarginPadding { Bottom = 40 }, Children = new Drawable[] { new OsuSpriteText { Text = beatmap?.BeatmapInfo?.DifficultyName, Font = OsuFont.GetFont(size: 26, italics: true), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, starRatingDisplay = new StarRatingDisplay(default) { Alpha = 0f, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, } } }, new GridContainer { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, AutoSizeAxes = Axes.Both, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), }, ColumnDimensions = new[] { new Dimension(GridSizeMode.AutoSize), new Dimension(GridSizeMode.AutoSize), }, Content = new[] { new Drawable[] { new MetadataLineLabel("Source"), new MetadataLineInfo(metadata.Source) }, new Drawable[] { new MetadataLineLabel("Mapper"), new MetadataLineInfo(metadata.Author.Username) } } }, new ModDisplay { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Top = 20 }, Current = mods }, }, } }; starDifficulty = difficultyCache.GetBindableDifficulty(beatmap.BeatmapInfo); Loading = true; } protected override void LoadComplete() { base.LoadComplete(); if (starDifficulty.Value != null) { starRatingDisplay.Current.Value = starDifficulty.Value.Value; starRatingDisplay.Show(); } else { starRatingDisplay.Hide(); starDifficulty.ValueChanged += d => { Debug.Assert(d.NewValue != null); starRatingDisplay.Current.Value = d.NewValue.Value; versionFlow.AutoSizeDuration = 300; versionFlow.AutoSizeEasing = Easing.OutQuint; starRatingDisplay.FadeIn(300, Easing.InQuint); }; } } private class MetadataLineLabel : OsuSpriteText { public MetadataLineLabel(string text) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; Margin = new MarginPadding { Right = 5 }; Colour = OsuColour.Gray(0.8f); Text = text; } } private class MetadataLineInfo : OsuSpriteText { public MetadataLineInfo(string text) { Margin = new MarginPadding { Left = 5 }; Text = string.IsNullOrEmpty(text) ? @"-" : text; } } } }
using System; using System.Linq; using System.IO; using System.Text.RegularExpressions; using System.Collections.Generic; using BigDataPipeline.Interfaces; namespace FileListenerPlugin { public class S3Transfer : IFileTransfer { AWSS3Helper client; static Dictionary<string, string> awsEndpointMap = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase); static string[] serviceSchemes = new[] { "s3" }; /// <summary> /// Gets the URI scheme names that this intance can handle. /// </summary> public IEnumerable<string> GetSchemeNames () { return serviceSchemes; } public FileServiceConnectionInfo ParseConnectionUri (string connectionUri, IEnumerable<KeyValuePair<string, string>> extraOptions) { var info = new FileServiceConnectionInfo (connectionUri, extraOptions); // initialize list of valid endpoints if (awsEndpointMap == null) { var map = new Dictionary<string, string> (StringComparer.OrdinalIgnoreCase); foreach (var endpoint in Amazon.RegionEndpoint.EnumerableAllRegions) { map[endpoint.SystemName] = endpoint.SystemName; map[endpoint.SystemName.Replace("-", "")] = endpoint.SystemName; map[endpoint.GuessEndpointForService ("s3").Hostname] = endpoint.SystemName; var hostName = endpoint.GetEndpointForService ("s3").Hostname; map[hostName] = endpoint.SystemName; } awsEndpointMap = map; } // analise endpoint var missingEndpoint = false; if (String.IsNullOrWhiteSpace (info.Host)) { info.Host = Amazon.RegionEndpoint.USEast1.SystemName; } else if (awsEndpointMap.ContainsKey (info.Host)) { info.Host = awsEndpointMap[info.Host]; } else { // in this case the s3 endpoint is missing and we should expect that the BUCKET name was parsed as the HOST // but the uri parse transforms to lowecase the host, so we should parse it again! missingEndpoint = true; // force the default endpoint, if it is missing info.Host = Amazon.RegionEndpoint.USEast1.SystemName; } // parse bucket name if (!missingEndpoint) { var i = info.FullPath.IndexOf ('/', 1); if (i < 0) throw new Exception ("Invalid S3 file search path"); info.Set ("bucketName", info.FullPath.Substring (0, i).Trim ('/')); info.FullPath = info.FullPath.Substring (i + 1); info.BasePath = info.BasePath.Substring (i + 1); } else { // if endpoint is missing, we can assume that the current host is actually the AWS S3 Bucket var i = info.ConnectionUri.IndexOf('/', 5); // search for "/" skiping "s3://" if (i < 0) throw new Exception ("Invalid S3 file search path"); info.Set ("bucketName", info.ConnectionUri.Substring (5, i - 5).Trim ('/')); } return info; } public FileServiceConnectionInfo Details { get; private set; } public bool Status { get; private set; } public string LastError { get; private set; } private void _setStatus (Exception message) { string msg = null; if (message != null && message.Message != null) { msg = message.Message; if (message.InnerException != null && message.InnerException.Message != null) msg += "; " + message.InnerException.Message; } _setStatus (false, msg); } private void _setStatus (bool status, string message = null) { Status = status; LastError = message; } public bool Open (FileServiceConnectionInfo details) { Details = details; if (Details.RetryCount <= 0) Details.RetryCount = 1; return Open (); } private bool Open () { if (IsOpened ()) return true; var bucketName = Details.Get ("bucketName", ""); // sanity checks if (String.IsNullOrEmpty (bucketName)) { _setStatus (false, "Empty S3 Bucket Name"); return false; } // check for empty login/password if (String.IsNullOrEmpty (Details.Login) && String.IsNullOrEmpty (Details.Password)) { Details.Login = Details.Get ("awsAccessKey", Details.Login); Details.Password = Details.Get ("awsSecretAccessKey", Details.Password); } var s3Region = Amazon.RegionEndpoint.GetBySystemName (Details.Get ("awsRegion", "us-east-1")); if (s3Region.DisplayName == "Unknown") { _setStatus (false, "Invalid S3 Region Endpoint"); return false; } for (var i = 0; i < Details.RetryCount; i++) { try { client = new AWSS3Helper (Details.Login, Details.Password, bucketName, s3Region, true); _setStatus (true); } catch (Exception ex) { _setStatus (ex); Close (); } if (client != null) break; System.Threading.Thread.Sleep (Details.RetryWaitMs); } return IsOpened (); } private string PreparePath (string folder) { if (String.IsNullOrEmpty (folder)) folder = "/"; folder = folder.Replace ('\\', '/'); if (!folder.StartsWith ("/")) folder = "/" + folder; return folder; } public bool IsOpened () { return client != null; } public void Dispose () { Close (); } private void Close () { if (client != null) { try { using (var ptr = client) { client = null; } } catch (Exception ex) { _setStatus (ex); } } client = null; } private IEnumerable<FileTransferInfo> _listFiles (string folder, System.Text.RegularExpressions.Regex pattern, bool recursive) { _setStatus (true); if (!Open ()) yield break; folder = PreparePath (folder); foreach (var f in client.ListFiles (folder, recursive, false, true)) if ((pattern == null || pattern.IsMatch (f.Key))) yield return new FileTransferInfo (f.Key, f.Size, f.LastModified, f.LastModified); } public IEnumerable<FileTransferInfo> ListFiles() { return ListFiles (Details.BasePath, Details.FullPath.TrimStart ('/'), !Details.SearchTopDirectoryOnly); } public IEnumerable<FileTransferInfo> ListFiles (string folder, bool recursive) { return ListFiles (folder, null, recursive); } public IEnumerable<FileTransferInfo> ListFiles (string folder, string fileMask, bool recursive) { var pattern = String.IsNullOrEmpty (fileMask) ? null : new System.Text.RegularExpressions.Regex (FileTransferHelpers.WildcardToRegex (fileMask), System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline); return _listFiles (folder, pattern, recursive); } public StreamTransferInfo GetFileStream (string file) { _setStatus (true); // download files return new StreamTransferInfo { FileName = file, FileStream = client.ReadFile (file, true) }; } public IEnumerable<StreamTransferInfo> GetFileStreams (string folder, string fileMask, bool recursive) { _setStatus (true); // download files foreach (var f in ListFiles (folder, fileMask, recursive)) { StreamTransferInfo file = null; try { file = new StreamTransferInfo { FileName = f.FileName, FileStream = client.ReadFile (f.FileName, false) }; } catch (Exception ex) { LastError = ex.Message; // skip file } if (file != null) yield return file; } } public IEnumerable<StreamTransferInfo> GetFileStreams () { _setStatus (true); // download files foreach (var f in ListFiles ()) { yield return new StreamTransferInfo { FileName = f.FileName, FileStream = client.ReadFile (f.FileName, false) }; } } public FileTransferInfo GetFile (string file, string outputDirectory, bool deleteOnSuccess) { outputDirectory = outputDirectory.Replace ('\\', '/'); if (!outputDirectory.EndsWith ("/")) outputDirectory += "/"; FileTransferHelpers.CreateDirectory (outputDirectory); // download files var f = GetFileStream (file); string newFile = System.IO.Path.Combine (outputDirectory, System.IO.Path.GetFileName (f.FileName)); FileTransferHelpers.DeleteFile (newFile); try { using (var output = new FileStream (newFile, FileMode.Create, FileAccess.Write, FileShare.Delete, FileServiceConnectionInfo.DefaultWriteBufferSize)) { f.FileStream.CopyTo (output, FileServiceConnectionInfo.DefaultWriteBufferSize >> 2); } // check if we must remove file if (deleteOnSuccess) { FileTransferHelpers.DeleteFile (f.FileName); } _setStatus (true); } catch (Exception ex) { _setStatus (ex); FileTransferHelpers.DeleteFile (newFile); newFile = null; } finally { f.FileStream.Close (); } // check if file was downloaded if (newFile != null) { var info = new System.IO.FileInfo (newFile); if (info.Exists) return new FileTransferInfo (newFile, info.Length, info.CreationTime, info.LastWriteTime); } return null; } public string GetFileAsText (string file) { using (var reader = new StreamReader (GetFileStream (file).FileStream, FileTransferHelpers.TryGetEncoding (Details.Get ("encoding", "ISO-8859-1")), true)) return reader.ReadToEnd (); } public IEnumerable<FileTransferInfo> GetFiles (string folder, string fileMask, bool recursive, string outputDirectory, bool deleteOnSuccess) { outputDirectory = outputDirectory.Replace ('\\', '/'); if (!outputDirectory.EndsWith ("/")) outputDirectory += "/"; FileTransferHelpers.CreateDirectory (outputDirectory); // download files foreach (var f in GetFileStreams (folder, fileMask, recursive)) { string newFile = null; // download file try { newFile = System.IO.Path.Combine (outputDirectory, System.IO.Path.GetFileName (f.FileName)); FileTransferHelpers.DeleteFile (newFile); using (var file = new FileStream (newFile, FileMode.Create, FileAccess.Write, FileShare.Delete, FileServiceConnectionInfo.DefaultWriteBufferSize)) { f.FileStream.CopyTo (file, FileServiceConnectionInfo.DefaultWriteBufferSize >> 2); } f.FileStream.Close (); f.FileStream = null; // check if we must remove file if (deleteOnSuccess && System.IO.File.Exists (newFile)) { client.DeleteFile (f.FileName); } _setStatus (true); break; } catch (Exception ex) { _setStatus (ex); Close (); FileTransferHelpers.DeleteFile (newFile); newFile = null; // delay in case of network error System.Threading.Thread.Sleep (Details.RetryWaitMs); // try to reopen Open (); } finally { if (f.FileStream != null) f.FileStream.Close (); } // check if file was downloaded if (newFile != null) { var info = new System.IO.FileInfo (newFile); if (info.Exists) yield return new FileTransferInfo (newFile, info.Length, info.CreationTime, info.LastWriteTime); } } } public IEnumerable<FileTransferInfo> GetFiles (string outputDirectory, bool deleteOnSuccess) { if (Details.HasWildCardSearch) return GetFiles (Details.BasePath, Details.SearchPattern, !Details.SearchTopDirectoryOnly, outputDirectory, deleteOnSuccess); else return GetFiles (Details.FullPath, null, !Details.SearchTopDirectoryOnly, outputDirectory, deleteOnSuccess); } public bool RemoveFiles (IEnumerable<string> files) { _setStatus (false); var enumerator = files.GetEnumerator (); string file = null; for (int i = 0; i < Details.RetryCount; i++) { // try to open if (!Open ()) continue; try { if (file == null) { enumerator.MoveNext (); } do { file = PreparePath (enumerator.Current); client.DeleteFile (file); } while (enumerator.MoveNext ()); _setStatus (true); break; } catch (Exception ex) { _setStatus (ex); // disconnect on error Close (); // delay in case of network error System.Threading.Thread.Sleep (Details.RetryWaitMs); } } return Status; } public bool RemoveFile (string file) { _setStatus (false); for (int i = 0; i < Details.RetryCount; i++) { // try to open if (!Open ()) continue; try { file = PreparePath (file); client.DeleteFile (file, true); _setStatus (true); } catch (Exception ex) { _setStatus (ex); // disconnect on error Close (); // delay in case of network error System.Threading.Thread.Sleep (Details.RetryWaitMs); } } return Status; } public bool SendFile (string localFilename) { return SendFile (localFilename, System.IO.Path.Combine (Details.BasePath, System.IO.Path.GetFileName (localFilename))); } public bool SendFile (string localFilename, string destFilename) { using (var file = new FileStream (localFilename, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.Read, FileServiceConnectionInfo.DefaultReadBufferSize)) { return SendFile (file, destFilename, false); } } public bool SendFile (Stream localFile, string destFullPath, bool closeInputStream) { // try to upload file for (int i = 0; i < Details.RetryCount; i++) { // try to open if (!Open ()) return false; try { // upload using (Stream ostream = new S3UploadStream (client, destFullPath, Details.Get ("useReducedRedundancy", false), true, Details.Get ("makePublic", false), Details.Get ("partSize", 20 * 1024 * 1024))) { using (var file = localFile) { file.CopyTo (ostream, FileServiceConnectionInfo.DefaultWriteBufferSize >> 2); } } _setStatus (true); return true; } catch (Exception ex) { _setStatus (ex); // disconnect on error Close (); } finally { if (closeInputStream) localFile.Close(); } } return false; } public bool MoveFile (string localFilename, string destFilename) { _setStatus (false, "Operation not supported"); return Status; } public Stream OpenWrite () { return OpenWrite (Details.FullPath); } public Stream OpenWrite (string destFullPath) { // upload return new S3UploadStream (client, destFullPath, Details.Get ("useReducedRedundancy", false), true, Details.Get ("makePublic", false), Details.Get ("partSize", 20 * 1024 * 1024)); } } }
// 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 Xunit; using Xunit.Abstractions; namespace System.Security.Cryptography.X509Certificates.Tests { public class CertTests { private readonly ITestOutputHelper _log; public CertTests(ITestOutputHelper output) { _log = output; } [Fact] public static void X509CertTest() { string certSubject = @"CN=Microsoft Corporate Root Authority, OU=ITG, O=Microsoft, L=Redmond, S=WA, C=US, E=pkit@microsoft.com"; using (X509Certificate cert = new X509Certificate(Path.Combine("TestData", "microsoft.cer"))) { Assert.Equal(certSubject, cert.Subject); Assert.Equal(certSubject, cert.Issuer); int snlen = cert.GetSerialNumber().Length; Assert.Equal(16, snlen); byte[] serialNumber = new byte[snlen]; Buffer.BlockCopy(cert.GetSerialNumber(), 0, serialNumber, 0, snlen); Assert.Equal(0xF6, serialNumber[0]); Assert.Equal(0xB3, serialNumber[snlen / 2]); Assert.Equal(0x2A, serialNumber[snlen - 1]); Assert.Equal("1.2.840.113549.1.1.1", cert.GetKeyAlgorithm()); int pklen = cert.GetPublicKey().Length; Assert.Equal(270, pklen); byte[] publicKey = new byte[pklen]; Buffer.BlockCopy(cert.GetPublicKey(), 0, publicKey, 0, pklen); Assert.Equal(0x30, publicKey[0]); Assert.Equal(0xB6, publicKey[9]); Assert.Equal(1, publicKey[pklen - 1]); } } [Fact] public static void X509Cert2Test() { string certName = @"E=admin@digsigtrust.com, CN=ABA.ECOM Root CA, O=""ABA.ECOM, INC."", L=Washington, S=DC, C=US"; DateTime notBefore = new DateTime(1999, 7, 12, 17, 33, 53, DateTimeKind.Utc).ToLocalTime(); DateTime notAfter = new DateTime(2009, 7, 9, 17, 33, 53, DateTimeKind.Utc).ToLocalTime(); using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.cer"))) { Assert.Equal(certName, cert2.IssuerName.Name); Assert.Equal(certName, cert2.SubjectName.Name); Assert.Equal("ABA.ECOM Root CA", cert2.GetNameInfo(X509NameType.DnsName, true)); PublicKey pubKey = cert2.PublicKey; Assert.Equal("RSA", pubKey.Oid.FriendlyName); Assert.Equal(notAfter, cert2.NotAfter); Assert.Equal(notBefore, cert2.NotBefore); Assert.Equal(notAfter.ToString(), cert2.GetExpirationDateString()); Assert.Equal(notBefore.ToString(), cert2.GetEffectiveDateString()); Assert.Equal("00D01E4090000046520000000100000004", cert2.SerialNumber); Assert.Equal("1.2.840.113549.1.1.5", cert2.SignatureAlgorithm.Value); Assert.Equal("7A74410FB0CD5C972A364B71BF031D88A6510E9E", cert2.Thumbprint); Assert.Equal(3, cert2.Version); } } [Fact] [OuterLoop("May require using the network, to download CRLs and intermediates")] public void TestVerify() { bool success; using (var microsoftDotCom = new X509Certificate2(TestData.MicrosoftDotComSslCertBytes)) { // Fails because expired (NotAfter = 10/16/2016) Assert.False(microsoftDotCom.Verify(), "MicrosoftDotComSslCertBytes"); } using (var microsoftDotComIssuer = new X509Certificate2(TestData.MicrosoftDotComIssuerBytes)) { // NotAfter=10/31/2023 success = microsoftDotComIssuer.Verify(); if (!success) { LogVerifyErrors(microsoftDotComIssuer, "MicrosoftDotComIssuerBytes"); } Assert.True(success, "MicrosoftDotComIssuerBytes"); } using (var microsoftDotComRoot = new X509Certificate2(TestData.MicrosoftDotComRootBytes)) { // NotAfter=7/17/2036 success = microsoftDotComRoot.Verify(); if (!success) { LogVerifyErrors(microsoftDotComRoot, "MicrosoftDotComRootBytes"); } Assert.True(success, "MicrosoftDotComRootBytes"); } } private void LogVerifyErrors(X509Certificate2 cert, string testName) { // Emulate cert.Verify() implementation in order to capture and log errors. try { using (var chain = new X509Chain()) { if (!chain.Build(cert)) { foreach (X509ChainStatus chainStatus in chain.ChainStatus) { _log.WriteLine(string.Format($"X509Certificate2.Verify error: {testName}, {chainStatus.Status}, {chainStatus.StatusInformation}")); } } else { _log.WriteLine(string.Format($"X509Certificate2.Verify expected error; received none: {testName}")); } } } catch (Exception e) { _log.WriteLine($"X509Certificate2.Verify exception: {testName}, {e}"); } } [Fact] public static void X509CertEmptyToString() { using (var c = new X509Certificate()) { string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate"; Assert.Equal(expectedResult, c.ToString()); Assert.Equal(expectedResult, c.ToString(false)); Assert.Equal(expectedResult, c.ToString(true)); } } [Fact] public static void X509Cert2EmptyToString() { using (var c2 = new X509Certificate2()) { string expectedResult = "System.Security.Cryptography.X509Certificates.X509Certificate2"; Assert.Equal(expectedResult, c2.ToString()); Assert.Equal(expectedResult, c2.ToString(false)); Assert.Equal(expectedResult, c2.ToString(true)); } } [Fact] public static void X509Cert2ToStringVerbose() { using (X509Store store = new X509Store("My", StoreLocation.CurrentUser)) { store.Open(OpenFlags.ReadOnly); foreach (X509Certificate2 c in store.Certificates) { Assert.False(string.IsNullOrWhiteSpace(c.ToString(true))); c.Dispose(); } } } [Fact] public static void X509Cert2CreateFromEmptyPfx() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.EmptyPfx)); } [Fact] public static void X509Cert2CreateFromPfxFile() { using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "DummyTcpServer.pfx"))) { // OID=RSA Encryption Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm()); } } [Fact] public static void X509Cert2CreateFromPfxWithPassword() { using (X509Certificate2 cert2 = new X509Certificate2(Path.Combine("TestData", "test.pfx"), "test")) { // OID=RSA Encryption Assert.Equal("1.2.840.113549.1.1.1", cert2.GetKeyAlgorithm()); } } [Fact] public static void X509Certificate2FromPkcs7DerFile() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7b"))); } [Fact] public static void X509Certificate2FromPkcs7PemFile() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(Path.Combine("TestData", "singlecert.p7c"))); } [Fact] public static void X509Certificate2FromPkcs7DerBlob() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SingleDerBytes)); } [Fact] public static void X509Certificate2FromPkcs7PemBlob() { Assert.ThrowsAny<CryptographicException>(() => new X509Certificate2(TestData.Pkcs7SinglePemBytes)); } [Fact] public static void UseAfterDispose() { using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate)) { IntPtr h = c.Handle; // Do a couple of things that would only be true on a valid certificate, as a precondition. Assert.NotEqual(IntPtr.Zero, h); byte[] actualThumbprint = c.GetCertHash(); c.Dispose(); // For compat reasons, Dispose() acts like the now-defunct Reset() method rather than // causing ObjectDisposedExceptions. h = c.Handle; Assert.Equal(IntPtr.Zero, h); // State held on X509Certificate Assert.ThrowsAny<CryptographicException>(() => c.GetCertHash()); Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithm()); Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParameters()); Assert.ThrowsAny<CryptographicException>(() => c.GetKeyAlgorithmParametersString()); Assert.ThrowsAny<CryptographicException>(() => c.GetPublicKey()); Assert.ThrowsAny<CryptographicException>(() => c.GetSerialNumber()); Assert.ThrowsAny<CryptographicException>(() => c.Issuer); Assert.ThrowsAny<CryptographicException>(() => c.Subject); Assert.ThrowsAny<CryptographicException>(() => c.NotBefore); Assert.ThrowsAny<CryptographicException>(() => c.NotAfter); // State held on X509Certificate2 Assert.ThrowsAny<CryptographicException>(() => c.RawData); Assert.ThrowsAny<CryptographicException>(() => c.SignatureAlgorithm); Assert.ThrowsAny<CryptographicException>(() => c.Version); Assert.ThrowsAny<CryptographicException>(() => c.SubjectName); Assert.ThrowsAny<CryptographicException>(() => c.IssuerName); Assert.ThrowsAny<CryptographicException>(() => c.PublicKey); Assert.ThrowsAny<CryptographicException>(() => c.Extensions); Assert.ThrowsAny<CryptographicException>(() => c.PrivateKey); } } [Fact] public static void ExportPublicKeyAsPkcs12() { using (X509Certificate2 publicOnly = new X509Certificate2(TestData.MsCertificate)) { // Pre-condition: There's no private key Assert.False(publicOnly.HasPrivateKey); // This won't throw. byte[] pkcs12Bytes = publicOnly.Export(X509ContentType.Pkcs12); // Read it back as a collection, there should be only one cert, and it should // be equal to the one we started with. using (ImportedCollection ic = Cert.Import(pkcs12Bytes)) { X509Certificate2Collection fromPfx = ic.Collection; Assert.Equal(1, fromPfx.Count); Assert.Equal(publicOnly, fromPfx[0]); } } } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using System; using System.Collections.Generic; using System.Linq; using System.Text; using Encog.Util; using Encog.Util.CSV; namespace Encog.ML.Bayesian.Parse { /// <summary> /// Parse a probability string. /// </summary> public class ParseProbability { /// <summary> /// The network used. /// </summary> private readonly BayesianNetwork network; /// <summary> /// Parse the probability for the specified network. /// </summary> /// <param name="theNetwork">The network to parse for.</param> public ParseProbability(BayesianNetwork theNetwork) { this.network = theNetwork; } /// <summary> /// Add events, as they are pased. /// </summary> /// <param name="parser">The parser.</param> /// <param name="results">The events found.</param> /// <param name="delim">The delimiter to use.</param> private void AddEvents(SimpleParser parser, IList<ParsedEvent> results, String delim) { bool done = false; StringBuilder l = new StringBuilder(); while (!done && !parser.EOL()) { char ch = parser.Peek(); if (delim.IndexOf(ch) != -1) { if (ch == ')' || ch == '|') done = true; ParsedEvent parsedEvent; // deal with a value specified by + or - if (l.Length > 0 && l[0] == '+') { String l2 = l.ToString().Substring(1); parsedEvent = new ParsedEvent(l2.Trim()); parsedEvent.Value = "true"; } else if (l.Length > 0 && l[0] == '-') { String l2 = l.ToString().Substring(1); parsedEvent = new ParsedEvent(l2.Trim()); parsedEvent.Value = "false"; } else { String l2 = l.ToString(); parsedEvent = new ParsedEvent(l2.Trim()); } // parse choices if (ch == '[') { parser.Advance(); int index = 0; while (ch != ']' && !parser.EOL()) { String labelName = parser.ReadToChars(":,]"); if (parser.Peek() == ':') { parser.Advance(); parser.EatWhiteSpace(); double min = double.Parse(parser.ReadToWhiteSpace()); parser.EatWhiteSpace(); if (!parser.LookAhead("to", true)) { throw new BayesianError("Expected \"to\" in probability choice range."); } parser.Advance(2); double max = CSVFormat.EgFormat.Parse(parser.ReadToChars(",]")); parsedEvent.ChoiceList.Add(new ParsedChoice(labelName, min, max)); } else { parsedEvent.ChoiceList.Add(new ParsedChoice(labelName, index++)); } parser.EatWhiteSpace(); ch = parser.Peek(); if (ch == ',') { parser.Advance(); } } } // deal with a value specified by = if (parser.Peek() == '=') { parser.ReadChar(); String value = parser.ReadToChars(delim); // BayesianEvent evt = this.network.getEvent(parsedEvent.getLabel()); parsedEvent.Value = value; } if (ch == ',') { parser.Advance(); } if (ch == ']') { parser.Advance(); } if (parsedEvent.Label.Length > 0) { results.Add(parsedEvent); } l.Length = 0; } else { parser.Advance(); l.Append(ch); } } } /// <summary> /// Parse the given line. /// </summary> /// <param name="line">The line to parse.</param> /// <returns>The parsed probability.</returns> public ParsedProbability Parse(String line) { ParsedProbability result = new ParsedProbability(); SimpleParser parser = new SimpleParser(line); parser.EatWhiteSpace(); if (!parser.LookAhead("P(", true)) { throw new EncogError("Bayes table lines must start with P("); } parser.Advance(2); // handle base AddEvents(parser, result.BaseEvents, "|,)=[]"); // handle conditions if (parser.Peek() == '|') { parser.Advance(); AddEvents(parser, result.GivenEvents, ",)=[]"); } if (parser.Peek() != ')') { throw new BayesianError("Probability not properly terminated."); } return result; } /// <summary> /// Parse a probability list. /// </summary> /// <param name="network">The network to parse for.</param> /// <param name="line">The line to parse.</param> /// <returns>The parsed list.</returns> public static IList<ParsedProbability> ParseProbabilityList(BayesianNetwork network, String line) { IList<ParsedProbability> result = new List<ParsedProbability>(); StringBuilder prob = new StringBuilder(); for (int i = 0; i < line.Length; i++) { char ch = line[i]; if (ch == ')') { prob.Append(ch); ParseProbability parse = new ParseProbability(network); ParsedProbability parsedProbability = parse.Parse(prob.ToString()); result.Add(parsedProbability); prob.Length = 0; } else { prob.Append(ch); } } return result; } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | 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.ComponentModel; using ESRI.ArcLogistics.Utility; namespace ESRI.ArcLogistics.DomainObjects { /// <summary> /// Class that contains information about a physical address. /// </summary> public class Address : ICloneable, INotifyPropertyChanged { #region public static properties public static string PropertyNameUnit { get { return PROP_NAME_UNIT; } } public static string PropertyNameFullAddress { get { return PROP_NAME_FULLADDRESS; } } public static string PropertyNameAddressLine { get { return PROP_NAME_ADDRESSLINE; } } public static string PropertyNameLocality1 { get { return PROP_NAME_LOCALITY1; } } public static string PropertyNameLocality2 { get { return PROP_NAME_LOCALITY2; } } public static string PropertyNameLocality3 { get { return PROP_NAME_LOCALITY3; } } public static string PropertyNameCountryPrefecture { get { return PROP_NAME_COUNTYPREFECTURE; } } public static string PropertyNamePostalCode1 { get { return PROP_NAME_POSTALCODE1; } } public static string PropertyNamePostalCode2 { get { return PROP_NAME_POSTALCODE2; } } public static string PropertyNameStateProvince { get { return PROP_NAME_STATEPROVINCE; } } public static string PropertyNameCountry { get { return PROP_NAME_COUNTRY; } } public static string PropertyNameMatchMethod { get { return PROP_NAME_MATCHMETHOD; } } #endregion #region public static methods /// <summary> /// Checks if the parameter is the name of any property of the <c>Address</c> class. /// </summary> /// <param name="propName">Property name to check.</param> public static bool IsAddressPropertyName(string propName) { return ((PROP_NAME_FULLADDRESS == propName) || (PROP_NAME_ADDRESSLINE == propName) || (PROP_NAME_LOCALITY1 == propName) || (PROP_NAME_LOCALITY2 == propName) || (PROP_NAME_LOCALITY3 == propName) || (PROP_NAME_COUNTYPREFECTURE == propName) || (PROP_NAME_POSTALCODE1 == propName) || (PROP_NAME_POSTALCODE2 == propName) || (PROP_NAME_STATEPROVINCE == propName) || (PROP_NAME_COUNTRY == propName) || (PROP_NAME_UNIT == propName)); } /// <summary> /// Compares specified objects for the equality. /// </summary> /// <param name="left">The <see cref="ESRI.ArcLogistics.DomainObjects.Address"/> /// instance to compare with the <paramref name="right"/>.</param> /// <param name="right">The <see cref="ESRI.ArcLogistics.DomainObjects.Address"/> /// instance to compare with the <paramref name="left"/>.</param> /// <returns>True if and only if specified objects are equal.</returns> public static bool operator ==(Address left, Address right) { if (object.ReferenceEquals(left, right)) { return true; } if (object.ReferenceEquals(left, null)) { return false; } return left.Equals(right); } /// <summary> /// Compares specified objects for the inequality. /// </summary> /// <param name="left">The <see cref="ESRI.ArcLogistics.DomainObjects.Address"/> /// instance to compare with the <paramref name="right"/>.</param> /// <param name="right">The <see cref="ESRI.ArcLogistics.DomainObjects.Address"/> /// instance to compare with the <paramref name="left"/>.</param> /// <returns>True if and only if specified objects are not equal.</returns> public static bool operator !=(Address left, Address right) { return !(left == right); } #endregion #region public events /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Event which is fired if a property's value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #endregion public events #region public properties /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Unit name. /// </summary> public string Unit { get { return _unit; } set { _unit = value; _NotifyPropertyChanged(PROP_NAME_UNIT); } } /// <summary> /// Full address string. /// </summary> public string FullAddress { get { return _fullAddress; } set { _fullAddress = value; _NotifyPropertyChanged(PROP_NAME_FULLADDRESS); } } /// <summary> /// Street address. /// </summary> public string AddressLine { get { return _addressLine; } set { _addressLine = value; _NotifyPropertyChanged(PROP_NAME_ADDRESSLINE); } } /// <summary> /// Can represent either area in a neighborhood, district, block, or double dependent locality. /// </summary> public string Locality1 { get { return _locality1; } set { _locality1 = value; _NotifyPropertyChanged(PROP_NAME_LOCALITY1); } } /// <summary> /// Can represent community, place name, municipality, settlement, or dependent locality. /// </summary> public string Locality2 { get { return _locality2; } set { _locality2 = value; _NotifyPropertyChanged(PROP_NAME_LOCALITY2); } } /// <summary> /// Can represent city, town ,post town or village. /// </summary> public string Locality3 { get { return _locality3; } set { _locality3 = value; _NotifyPropertyChanged(PROP_NAME_LOCALITY3); } } /// <summary> /// Can represent either county or prefecture. /// </summary> public string CountyPrefecture { get { return _countyPrefecture; } set { _countyPrefecture = value; _NotifyPropertyChanged(PROP_NAME_COUNTYPREFECTURE); } } /// <summary> /// Can represent ZIP code, Postal code or FSA. /// </summary> public string PostalCode1 { get { return _postalCode1; } set { _postalCode1 = value; _NotifyPropertyChanged(PROP_NAME_POSTALCODE1); } } /// <summary> /// Can represent either ZIP+4 code or LDU code. /// </summary> public string PostalCode2 { get { return _postalCode2; } set { _postalCode2 = value; _NotifyPropertyChanged(PROP_NAME_POSTALCODE2); } } /// <summary> /// Can represent either state or province. /// </summary> public string StateProvince { get { return _stateProvince; } set { _stateProvince = value; _NotifyPropertyChanged(PROP_NAME_STATEPROVINCE); } } /// <summary> /// Country name. /// </summary> public string Country { get { return _country; } set { _country = value; _NotifyPropertyChanged(PROP_NAME_COUNTRY); } } /// <summary> /// Describes the match method used to get this address. /// </summary> /// <remarks> /// Typically match method contains the name of the locator that returned the adderess. But it can /// be also one of the predefined values. /// <para>Match method is set to "Edited X/Y" when user manually specified or edited order/location point.</para> /// <para>Match method is set to "Imported X/Y" when order/location wasn't geocoded but both address and point came from import database.</para> /// </remarks> public string MatchMethod { get { return _matchMethod; } set { _matchMethod = value; _NotifyPropertyChanged(PROP_NAME_MATCHMETHOD); } } /// <summary> /// Returns value of specififed address part. /// </summary> /// <param name="addressPart"></param> /// <returns></returns> public string this[AddressPart addressPart] { get { return _GetAddressPart(addressPart); } set { _SetAddressPart(addressPart, value); } } #endregion public properties #region public methods /// <summary> /// Returns the contents of the FullAddress property. /// </summary> /// <returns></returns> public override string ToString() { return FullAddress; } /// <summary> /// Copies address parts to the target address. /// </summary> /// <param name="address">Target address.</param> public void CopyTo(Address address) { address.Unit = _unit; address.FullAddress = _fullAddress; address.AddressLine = _addressLine; address.Locality1 = _locality1; address.Locality2 = _locality2; address.Locality3 = _locality3; address.CountyPrefecture = _countyPrefecture; address.PostalCode1 = _postalCode1; address.PostalCode2 = _postalCode2; address.StateProvince = _stateProvince; address.Country = _country; address.MatchMethod = _matchMethod; } /// <summary> /// clones the current Address instance. /// </summary> /// <returns>A new <see cref="T:ESRI.ArcLogistics.DomainObjects.Address"/> object equal to /// this one.</returns> public Address Clone() { Address obj = new Address(); this.CopyTo(obj); return obj; } #endregion #region Object Members /// <summary> /// Check is the same address values. /// </summary> /// <param name="obj">Address to compare.</param> /// <returns>Is the same address values.</returns> public override bool Equals(object obj) { Address address = obj as Address; if (object.ReferenceEquals(address, null)) { return false; } foreach (var addressPart in EnumHelpers.GetValues<AddressPart>()) { string addressPartValue = this[addressPart]; string addressPartToCompareValue = address[addressPart]; if (!PART_COMPARER.Equals(addressPartValue, addressPartToCompareValue)) { return false; } } return true; } /// <summary> /// Returns hash code for the address object. /// </summary> /// <returns>A hash code for the address object.</returns> public override int GetHashCode() { unchecked { var hashCode = 1173891413; foreach (var addressPart in EnumHelpers.GetValues<AddressPart>()) { string addressPartValue = this[addressPart]; var partHash = addressPartValue == null ? 1873891399 : PART_COMPARER.GetHashCode(addressPartValue); hashCode = 873891391 * hashCode + partHash; } return hashCode; } } #endregion #region ICloneable Members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// clones the current Address instance. /// </summary> /// <returns></returns> object ICloneable.Clone() { return this.Clone(); } #endregion #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private string _GetAddressPart(AddressPart addressPart) { string result = string.Empty; switch(addressPart) { case AddressPart.Unit: { result = Unit; break; } case AddressPart.FullAddress : { result = FullAddress; break; } case AddressPart.AddressLine : { result = AddressLine; break; } case AddressPart.Locality1 : { result = Locality1; break; } case AddressPart.Locality2 : { result = Locality2; break; } case AddressPart.Locality3 : { result = Locality3; break; } case AddressPart.CountyPrefecture : { result = CountyPrefecture; break; } case AddressPart.PostalCode1 : { result = PostalCode1; break; } case AddressPart.PostalCode2 : { result = PostalCode2; break; } case AddressPart.StateProvince : { result = StateProvince; break; } case AddressPart.Country : { result = Country; break; } default: throw new NotSupportedException(); } return result; } private void _SetAddressPart(AddressPart addressPart, string value) { switch(addressPart) { case AddressPart.Unit: { Unit = value; break; } case AddressPart.FullAddress : { FullAddress = value; break; } case AddressPart.AddressLine : { AddressLine = value; break; } case AddressPart.Locality1 : { Locality1 = value; break; } case AddressPart.Locality2 : { Locality2 = value; break; } case AddressPart.Locality3 : { Locality3 = value; break; } case AddressPart.CountyPrefecture : { CountyPrefecture = value; break; } case AddressPart.PostalCode1 : { PostalCode1 = value; break; } case AddressPart.PostalCode2 : { PostalCode2 = value; break; } case AddressPart.StateProvince : { StateProvince = value; break; } case AddressPart.Country : { Country = value; break; } default: throw new NotSupportedException(); } } /// <summary> /// Notify parent about changes /// </summary> /// <param name="info">Param name</param> private void _NotifyPropertyChanged(String info) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(info)); } #endregion private methods #region private constants /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// // property names private const string PROP_NAME_UNIT = "Unit"; private const string PROP_NAME_FULLADDRESS = "FullAddress"; private const string PROP_NAME_ADDRESSLINE = "AddressLine"; private const string PROP_NAME_LOCALITY1 = "Locality1"; private const string PROP_NAME_LOCALITY2 = "Locality2"; private const string PROP_NAME_LOCALITY3 = "Locality3"; private const string PROP_NAME_COUNTYPREFECTURE = "CountyPrefecture"; private const string PROP_NAME_POSTALCODE1 = "PostalCode1"; private const string PROP_NAME_POSTALCODE2 = "PostalCode2"; private const string PROP_NAME_STATEPROVINCE = "StateProvince"; private const string PROP_NAME_COUNTRY = "Country"; private const string PROP_NAME_MATCHMETHOD = "MatchMethod"; /// <summary> /// The reference to the equality comparer object to be used for comparing address parts. /// </summary> private static readonly IEqualityComparer<string> PART_COMPARER = StringComparer.OrdinalIgnoreCase; #endregion #region private members /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private string _unit; private string _fullAddress; private string _addressLine; private string _locality1; private string _locality2; private string _locality3; private string _countyPrefecture; private string _postalCode1; private string _postalCode2; private string _stateProvince; private string _country; private string _matchMethod; #endregion private members } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Don't entity encode high chars (160 to 256) #define ENTITY_ENCODE_HIGH_ASCII_CHARS using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Text; namespace System.Net { public static class WebUtility { // some consts copied from Char / CharUnicodeInfo since we don't have friend access to those types private const char HIGH_SURROGATE_START = '\uD800'; private const char LOW_SURROGATE_START = '\uDC00'; private const char LOW_SURROGATE_END = '\uDFFF'; private const int UNICODE_PLANE00_END = 0x00FFFF; private const int UNICODE_PLANE01_START = 0x10000; private const int UNICODE_PLANE16_END = 0x10FFFF; private const int UnicodeReplacementChar = '\uFFFD'; #region HtmlEncode / HtmlDecode methods private static readonly char[] s_htmlEntityEndingChars = new char[] { ';', '&' }; public static string HtmlEncode(string value) { if (String.IsNullOrEmpty(value)) { return value; } // Don't create StringBuilder if we don't have anything to encode int index = IndexOfHtmlEncodingChars(value, 0); if (index == -1) { return value; } StringBuilder sb = StringBuilderCache.Acquire(value.Length); HtmlEncode(value, index, sb); return StringBuilderCache.GetStringAndRelease(sb); } private static unsafe void HtmlEncode(string value, int index, StringBuilder output) { Debug.Assert(output != null); Debug.Assert(0 <= index && index <= value.Length, "0 <= index && index <= value.Length"); int cch = value.Length - index; fixed (char* str = value) { char* pch = str; while (index-- > 0) { output.Append(*pch++); } for (; cch > 0; cch--, pch++) { char ch = *pch; if (ch <= '>') { switch (ch) { case '<': output.Append("&lt;"); break; case '>': output.Append("&gt;"); break; case '"': output.Append("&quot;"); break; case '\'': output.Append("&#39;"); break; case '&': output.Append("&amp;"); break; default: output.Append(ch); break; } } else { int valueToEncode = -1; // set to >= 0 if needs to be encoded #if ENTITY_ENCODE_HIGH_ASCII_CHARS if (ch >= 160 && ch < 256) { // The seemingly arbitrary 160 comes from RFC valueToEncode = ch; } else #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS if (Char.IsSurrogate(ch)) { int scalarValue = GetNextUnicodeScalarValueFromUtf16Surrogate(ref pch, ref cch); if (scalarValue >= UNICODE_PLANE01_START) { valueToEncode = scalarValue; } else { // Don't encode BMP characters (like U+FFFD) since they wouldn't have // been encoded if explicitly present in the string anyway. ch = (char)scalarValue; } } if (valueToEncode >= 0) { // value needs to be encoded output.Append("&#"); output.Append(valueToEncode.ToString(CultureInfo.InvariantCulture)); output.Append(';'); } else { // write out the character directly output.Append(ch); } } } } } public static string HtmlDecode(string value) { if (String.IsNullOrEmpty(value)) { return value; } // Don't create StringBuilder if we don't have anything to encode if (!StringRequiresHtmlDecoding(value)) { return value; } StringBuilder sb = StringBuilderCache.Acquire(value.Length); HtmlDecode(value, sb); return StringBuilderCache.GetStringAndRelease(sb); } [SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "System.UInt16.TryParse(System.String,System.Globalization.NumberStyles,System.IFormatProvider,System.UInt16@)", Justification = "UInt16.TryParse guarantees that result is zero if the parse fails.")] private static void HtmlDecode(string value, StringBuilder output) { Debug.Assert(output != null); int l = value.Length; for (int i = 0; i < l; i++) { char ch = value[i]; if (ch == '&') { // We found a '&'. Now look for the next ';' or '&'. The idea is that // if we find another '&' before finding a ';', then this is not an entity, // and the next '&' might start a real entity (VSWhidbey 275184) int index = value.IndexOfAny(s_htmlEntityEndingChars, i + 1); if (index > 0 && value[index] == ';') { string entity = value.Substring(i + 1, index - i - 1); if (entity.Length > 1 && entity[0] == '#') { // The # syntax can be in decimal or hex, e.g. // &#229; --> decimal // &#xE5; --> same char in hex // See http://www.w3.org/TR/REC-html40/charset.html#entities bool parsedSuccessfully; uint parsedValue; if (entity[1] == 'x' || entity[1] == 'X') { parsedSuccessfully = UInt32.TryParse(entity.Substring(2), NumberStyles.AllowHexSpecifier, CultureInfo.InvariantCulture, out parsedValue); } else { parsedSuccessfully = UInt32.TryParse(entity.Substring(1), NumberStyles.Integer, CultureInfo.InvariantCulture, out parsedValue); } if (parsedSuccessfully) { // decoded character must be U+0000 .. U+10FFFF, excluding surrogates parsedSuccessfully = ((parsedValue < HIGH_SURROGATE_START) || (LOW_SURROGATE_END < parsedValue && parsedValue <= UNICODE_PLANE16_END)); } if (parsedSuccessfully) { if (parsedValue <= UNICODE_PLANE00_END) { // single character output.Append((char)parsedValue); } else { // multi-character char leadingSurrogate, trailingSurrogate; ConvertSmpToUtf16(parsedValue, out leadingSurrogate, out trailingSurrogate); output.Append(leadingSurrogate); output.Append(trailingSurrogate); } i = index; // already looked at everything until semicolon continue; } } else { i = index; // already looked at everything until semicolon char entityChar = HtmlEntities.Lookup(entity); if (entityChar != (char)0) { ch = entityChar; } else { output.Append('&'); output.Append(entity); output.Append(';'); continue; } } } } output.Append(ch); } } private static unsafe int IndexOfHtmlEncodingChars(string s, int startPos) { Debug.Assert(0 <= startPos && startPos <= s.Length, "0 <= startPos && startPos <= s.Length"); int cch = s.Length - startPos; fixed (char* str = s) { for (char* pch = &str[startPos]; cch > 0; pch++, cch--) { char ch = *pch; if (ch <= '>') { switch (ch) { case '<': case '>': case '"': case '\'': case '&': return s.Length - cch; } } #if ENTITY_ENCODE_HIGH_ASCII_CHARS else if (ch >= 160 && ch < 256) { return s.Length - cch; } #endif // ENTITY_ENCODE_HIGH_ASCII_CHARS else if (Char.IsSurrogate(ch)) { return s.Length - cch; } } } return -1; } #endregion #region UrlEncode implementation // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. private static byte[] UrlEncode(byte[] bytes, int offset, int count, bool alwaysCreateNewReturnValue) { byte[] encoded = UrlEncode(bytes, offset, count); return (alwaysCreateNewReturnValue && (encoded != null) && (encoded == bytes)) ? (byte[])encoded.Clone() : encoded; } private static byte[] UrlEncode(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int cSpaces = 0; int cUnsafe = 0; // count them first for (int i = 0; i < count; i++) { char ch = (char)bytes[offset + i]; if (ch == ' ') cSpaces++; else if (!IsUrlSafeChar(ch)) cUnsafe++; } // nothing to expand? if (cSpaces == 0 && cUnsafe == 0) return bytes; // expand not 'safe' characters into %XX, spaces to +s byte[] expandedBytes = new byte[count + cUnsafe * 2]; int pos = 0; for (int i = 0; i < count; i++) { byte b = bytes[offset + i]; char ch = (char)b; if (IsUrlSafeChar(ch)) { expandedBytes[pos++] = b; } else if (ch == ' ') { expandedBytes[pos++] = (byte)'+'; } else { expandedBytes[pos++] = (byte)'%'; expandedBytes[pos++] = (byte)IntToHex((b >> 4) & 0xf); expandedBytes[pos++] = (byte)IntToHex(b & 0x0f); } } return expandedBytes; } #endregion #region UrlEncode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")] public static string UrlEncode(string value) { if (value == null) return null; byte[] bytes = Encoding.UTF8.GetBytes(value); byte[] encodedBytes = UrlEncode(bytes, 0, bytes.Length, false /* alwaysCreateNewReturnValue */); return Encoding.UTF8.GetString(encodedBytes, 0, encodedBytes.Length); } public static byte[] UrlEncodeToBytes(byte[] value, int offset, int count) { return UrlEncode(value, offset, count, true /* alwaysCreateNewReturnValue */); } #endregion #region UrlDecode implementation // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. // Changes done - Removed the logic to handle %Uxxxx as it is not standards compliant. private static string UrlDecodeInternal(string value, Encoding encoding) { if (value == null) { return null; } int count = value.Length; UrlDecoder helper = new UrlDecoder(count, encoding); // go through the string's chars collapsing %XX and // appending each char as char, with exception of %XX constructs // that are appended as bytes for (int pos = 0; pos < count; pos++) { char ch = value[pos]; if (ch == '+') { ch = ' '; } else if (ch == '%' && pos < count - 2) { int h1 = HexToInt(value[pos + 1]); int h2 = HexToInt(value[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars byte b = (byte)((h1 << 4) | h2); pos += 2; // don't add as char helper.AddByte(b); continue; } } if ((ch & 0xFF80) == 0) helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode else helper.AddChar(ch); } return helper.GetString(); } private static byte[] UrlDecodeInternal(byte[] bytes, int offset, int count) { if (!ValidateUrlEncodingParameters(bytes, offset, count)) { return null; } int decodedBytesCount = 0; byte[] decodedBytes = new byte[count]; for (int i = 0; i < count; i++) { int pos = offset + i; byte b = bytes[pos]; if (b == '+') { b = (byte)' '; } else if (b == '%' && i < count - 2) { int h1 = HexToInt((char)bytes[pos + 1]); int h2 = HexToInt((char)bytes[pos + 2]); if (h1 >= 0 && h2 >= 0) { // valid 2 hex chars b = (byte)((h1 << 4) | h2); i += 2; } } decodedBytes[decodedBytesCount++] = b; } if (decodedBytesCount < decodedBytes.Length) { Array.Resize(ref decodedBytes, decodedBytesCount); } return decodedBytes; } #endregion #region UrlDecode public methods [SuppressMessage("Microsoft.Design", "CA1055:UriReturnValuesShouldNotBeStrings", Justification = "Already shipped public API; code moved here as part of API consolidation")] public static string UrlDecode(string encodedValue) { if (encodedValue == null) return null; return UrlDecodeInternal(encodedValue, Encoding.UTF8); } public static byte[] UrlDecodeToBytes(byte[] encodedValue, int offset, int count) { return UrlDecodeInternal(encodedValue, offset, count); } #endregion #region Helper methods // similar to Char.ConvertFromUtf32, but doesn't check arguments or generate strings // input is assumed to be an SMP character private static void ConvertSmpToUtf16(uint smpChar, out char leadingSurrogate, out char trailingSurrogate) { Debug.Assert(UNICODE_PLANE01_START <= smpChar && smpChar <= UNICODE_PLANE16_END); int utf32 = (int)(smpChar - UNICODE_PLANE01_START); leadingSurrogate = (char)((utf32 / 0x400) + HIGH_SURROGATE_START); trailingSurrogate = (char)((utf32 % 0x400) + LOW_SURROGATE_START); } private static unsafe int GetNextUnicodeScalarValueFromUtf16Surrogate(ref char* pch, ref int charsRemaining) { // invariants Debug.Assert(charsRemaining >= 1); Debug.Assert(Char.IsSurrogate(*pch)); if (charsRemaining <= 1) { // not enough characters remaining to resurrect the original scalar value return UnicodeReplacementChar; } char leadingSurrogate = pch[0]; char trailingSurrogate = pch[1]; if (Char.IsSurrogatePair(leadingSurrogate, trailingSurrogate)) { // we're going to consume an extra char pch++; charsRemaining--; // below code is from Char.ConvertToUtf32, but without the checks (since we just performed them) return (((leadingSurrogate - HIGH_SURROGATE_START) * 0x400) + (trailingSurrogate - LOW_SURROGATE_START) + UNICODE_PLANE01_START); } else { // unmatched surrogate return UnicodeReplacementChar; } } private static int HexToInt(char h) { return (h >= '0' && h <= '9') ? h - '0' : (h >= 'a' && h <= 'f') ? h - 'a' + 10 : (h >= 'A' && h <= 'F') ? h - 'A' + 10 : -1; } private static char IntToHex(int n) { Debug.Assert(n < 0x10); if (n <= 9) return (char)(n + (int)'0'); else return (char)(n - 10 + (int)'A'); } // Set of safe chars, from RFC 1738.4 minus '+' private static bool IsUrlSafeChar(char ch) { if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') return true; switch (ch) { case '-': case '_': case '.': case '!': case '*': case '(': case ')': return true; } return false; } private static bool ValidateUrlEncodingParameters(byte[] bytes, int offset, int count) { if (bytes == null && count == 0) return false; if (bytes == null) { throw new ArgumentNullException("bytes"); } if (offset < 0 || offset > bytes.Length) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0 || offset + count > bytes.Length) { throw new ArgumentOutOfRangeException("count"); } return true; } private static bool StringRequiresHtmlDecoding(string s) { // this string requires html decoding if it contains '&' or a surrogate character for (int i = 0; i < s.Length; i++) { char c = s[i]; if (c == '&' || Char.IsSurrogate(c)) { return true; } } return false; } #endregion #region UrlDecoder nested class // *** Source: alm/tfs_core/Framework/Common/UriUtility/HttpUtility.cs // This specific code was copied from above ASP.NET codebase. // Internal class to facilitate URL decoding -- keeps char buffer and byte buffer, allows appending of either chars or bytes private class UrlDecoder { private int _bufferSize; // Accumulate characters in a special array private int _numChars; private char[] _charBuffer; // Accumulate bytes for decoding into characters in a special array private int _numBytes; private byte[] _byteBuffer; // Encoding to convert chars to bytes private Encoding _encoding; private void FlushBytes() { if (_numBytes > 0) { _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } internal UrlDecoder(int bufferSize, Encoding encoding) { _bufferSize = bufferSize; _encoding = encoding; _charBuffer = new char[bufferSize]; // byte buffer created on demand } internal void AddChar(char ch) { if (_numBytes > 0) FlushBytes(); _charBuffer[_numChars++] = ch; } internal void AddByte(byte b) { if (_byteBuffer == null) _byteBuffer = new byte[_bufferSize]; _byteBuffer[_numBytes++] = b; } internal String GetString() { if (_numBytes > 0) FlushBytes(); if (_numChars > 0) return new String(_charBuffer, 0, _numChars); else return String.Empty; } } #endregion #region HtmlEntities nested class // helper class for lookup of HTML encoding entities private static class HtmlEntities { // The list is from http://www.w3.org/TR/REC-html40/sgml/entities.html, except for &apos;, which // is defined in http://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent. private static String[] s_entitiesList = new String[] { "\x0022-quot", "\x0026-amp", "\x0027-apos", "\x003c-lt", "\x003e-gt", "\x00a0-nbsp", "\x00a1-iexcl", "\x00a2-cent", "\x00a3-pound", "\x00a4-curren", "\x00a5-yen", "\x00a6-brvbar", "\x00a7-sect", "\x00a8-uml", "\x00a9-copy", "\x00aa-ordf", "\x00ab-laquo", "\x00ac-not", "\x00ad-shy", "\x00ae-reg", "\x00af-macr", "\x00b0-deg", "\x00b1-plusmn", "\x00b2-sup2", "\x00b3-sup3", "\x00b4-acute", "\x00b5-micro", "\x00b6-para", "\x00b7-middot", "\x00b8-cedil", "\x00b9-sup1", "\x00ba-ordm", "\x00bb-raquo", "\x00bc-frac14", "\x00bd-frac12", "\x00be-frac34", "\x00bf-iquest", "\x00c0-Agrave", "\x00c1-Aacute", "\x00c2-Acirc", "\x00c3-Atilde", "\x00c4-Auml", "\x00c5-Aring", "\x00c6-AElig", "\x00c7-Ccedil", "\x00c8-Egrave", "\x00c9-Eacute", "\x00ca-Ecirc", "\x00cb-Euml", "\x00cc-Igrave", "\x00cd-Iacute", "\x00ce-Icirc", "\x00cf-Iuml", "\x00d0-ETH", "\x00d1-Ntilde", "\x00d2-Ograve", "\x00d3-Oacute", "\x00d4-Ocirc", "\x00d5-Otilde", "\x00d6-Ouml", "\x00d7-times", "\x00d8-Oslash", "\x00d9-Ugrave", "\x00da-Uacute", "\x00db-Ucirc", "\x00dc-Uuml", "\x00dd-Yacute", "\x00de-THORN", "\x00df-szlig", "\x00e0-agrave", "\x00e1-aacute", "\x00e2-acirc", "\x00e3-atilde", "\x00e4-auml", "\x00e5-aring", "\x00e6-aelig", "\x00e7-ccedil", "\x00e8-egrave", "\x00e9-eacute", "\x00ea-ecirc", "\x00eb-euml", "\x00ec-igrave", "\x00ed-iacute", "\x00ee-icirc", "\x00ef-iuml", "\x00f0-eth", "\x00f1-ntilde", "\x00f2-ograve", "\x00f3-oacute", "\x00f4-ocirc", "\x00f5-otilde", "\x00f6-ouml", "\x00f7-divide", "\x00f8-oslash", "\x00f9-ugrave", "\x00fa-uacute", "\x00fb-ucirc", "\x00fc-uuml", "\x00fd-yacute", "\x00fe-thorn", "\x00ff-yuml", "\x0152-OElig", "\x0153-oelig", "\x0160-Scaron", "\x0161-scaron", "\x0178-Yuml", "\x0192-fnof", "\x02c6-circ", "\x02dc-tilde", "\x0391-Alpha", "\x0392-Beta", "\x0393-Gamma", "\x0394-Delta", "\x0395-Epsilon", "\x0396-Zeta", "\x0397-Eta", "\x0398-Theta", "\x0399-Iota", "\x039a-Kappa", "\x039b-Lambda", "\x039c-Mu", "\x039d-Nu", "\x039e-Xi", "\x039f-Omicron", "\x03a0-Pi", "\x03a1-Rho", "\x03a3-Sigma", "\x03a4-Tau", "\x03a5-Upsilon", "\x03a6-Phi", "\x03a7-Chi", "\x03a8-Psi", "\x03a9-Omega", "\x03b1-alpha", "\x03b2-beta", "\x03b3-gamma", "\x03b4-delta", "\x03b5-epsilon", "\x03b6-zeta", "\x03b7-eta", "\x03b8-theta", "\x03b9-iota", "\x03ba-kappa", "\x03bb-lambda", "\x03bc-mu", "\x03bd-nu", "\x03be-xi", "\x03bf-omicron", "\x03c0-pi", "\x03c1-rho", "\x03c2-sigmaf", "\x03c3-sigma", "\x03c4-tau", "\x03c5-upsilon", "\x03c6-phi", "\x03c7-chi", "\x03c8-psi", "\x03c9-omega", "\x03d1-thetasym", "\x03d2-upsih", "\x03d6-piv", "\x2002-ensp", "\x2003-emsp", "\x2009-thinsp", "\x200c-zwnj", "\x200d-zwj", "\x200e-lrm", "\x200f-rlm", "\x2013-ndash", "\x2014-mdash", "\x2018-lsquo", "\x2019-rsquo", "\x201a-sbquo", "\x201c-ldquo", "\x201d-rdquo", "\x201e-bdquo", "\x2020-dagger", "\x2021-Dagger", "\x2022-bull", "\x2026-hellip", "\x2030-permil", "\x2032-prime", "\x2033-Prime", "\x2039-lsaquo", "\x203a-rsaquo", "\x203e-oline", "\x2044-frasl", "\x20ac-euro", "\x2111-image", "\x2118-weierp", "\x211c-real", "\x2122-trade", "\x2135-alefsym", "\x2190-larr", "\x2191-uarr", "\x2192-rarr", "\x2193-darr", "\x2194-harr", "\x21b5-crarr", "\x21d0-lArr", "\x21d1-uArr", "\x21d2-rArr", "\x21d3-dArr", "\x21d4-hArr", "\x2200-forall", "\x2202-part", "\x2203-exist", "\x2205-empty", "\x2207-nabla", "\x2208-isin", "\x2209-notin", "\x220b-ni", "\x220f-prod", "\x2211-sum", "\x2212-minus", "\x2217-lowast", "\x221a-radic", "\x221d-prop", "\x221e-infin", "\x2220-ang", "\x2227-and", "\x2228-or", "\x2229-cap", "\x222a-cup", "\x222b-int", "\x2234-there4", "\x223c-sim", "\x2245-cong", "\x2248-asymp", "\x2260-ne", "\x2261-equiv", "\x2264-le", "\x2265-ge", "\x2282-sub", "\x2283-sup", "\x2284-nsub", "\x2286-sube", "\x2287-supe", "\x2295-oplus", "\x2297-otimes", "\x22a5-perp", "\x22c5-sdot", "\x2308-lceil", "\x2309-rceil", "\x230a-lfloor", "\x230b-rfloor", "\x2329-lang", "\x232a-rang", "\x25ca-loz", "\x2660-spades", "\x2663-clubs", "\x2665-hearts", "\x2666-diams", }; private static LowLevelDictionary<string, char> s_lookupTable = GenerateLookupTable(); private static LowLevelDictionary<string, char> GenerateLookupTable() { // e[0] is unicode char, e[1] is '-', e[2+] is entity string LowLevelDictionary<string, char> lookupTable = new LowLevelDictionary<string, char>(StringComparer.Ordinal); foreach (string e in s_entitiesList) { lookupTable.Add(e.Substring(2), e[0]); } return lookupTable; } public static char Lookup(string entity) { char theChar; s_lookupTable.TryGetValue(entity, out theChar); return theChar; } } #endregion } }
using J2N.Collections; using System.Diagnostics; using System.Reflection; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Util.Fst { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using PackedInt32s = Lucene.Net.Util.Packed.PackedInt32s; using PagedGrowableWriter = Lucene.Net.Util.Packed.PagedGrowableWriter; /// <summary> /// Used to dedup states (lookup already-frozen states) /// </summary> internal sealed class NodeHash<T> { private PagedGrowableWriter table; private long count; private long mask; private readonly FST<T> fst; private readonly FST.Arc<T> scratchArc = new FST.Arc<T>(); private readonly FST.BytesReader input; // LUCENENET specific - optimize the Hash methods // by only calling StructuralEqualityComparer.GetHashCode() if the value is a reference type private readonly static bool tIsValueType = typeof(T).IsValueType; public NodeHash(FST<T> fst, FST.BytesReader input) { table = new PagedGrowableWriter(16, 1 << 30, 8, PackedInt32s.COMPACT); mask = 15; this.fst = fst; this.input = input; } private bool NodesEqual(Builder.UnCompiledNode<T> node, long address) { fst.ReadFirstRealTargetArc(address, scratchArc, input); if (scratchArc.BytesPerArc != 0 && node.NumArcs != scratchArc.NumArcs) { return false; } for (int arcUpto = 0; arcUpto < node.NumArcs; arcUpto++) { Builder.Arc<T> arc = node.Arcs[arcUpto]; if (arc.IsFinal != scratchArc.IsFinal || arc.Label != scratchArc.Label || ((Builder.CompiledNode)arc.Target).Node != scratchArc.Target || !(tIsValueType ? JCG.EqualityComparer<T>.Default.Equals(arc.Output, scratchArc.Output) : StructuralEqualityComparer.Default.Equals(arc.Output, scratchArc.Output)) || !(tIsValueType ? JCG.EqualityComparer<T>.Default.Equals(arc.NextFinalOutput, scratchArc.NextFinalOutput) : StructuralEqualityComparer.Default.Equals(arc.NextFinalOutput, scratchArc.NextFinalOutput)) ) { return false; } if (scratchArc.IsLast) { if (arcUpto == node.NumArcs - 1) { return true; } else { return false; } } fst.ReadNextRealArc(scratchArc, input); } return false; } /// <summary> /// hash code for an unfrozen node. this must be identical /// to the frozen case (below)!! /// </summary> private long Hash(Builder.UnCompiledNode<T> node) { const int PRIME = 31; //System.out.println("hash unfrozen"); long h = 0; // TODO: maybe if number of arcs is high we can safely subsample? for (int arcIdx = 0; arcIdx < node.NumArcs; arcIdx++) { Builder.Arc<T> arc = node.Arcs[arcIdx]; h = PRIME * h + arc.Label; long n = ((Builder.CompiledNode)arc.Target).Node; h = PRIME * h + (int)(n ^ (n >> 32)); // LUCENENET specific - optimize the Hash methods // by only calling StructuralEqualityComparer.GetHashCode() if the value is a reference type h = PRIME * h + (tIsValueType ? JCG.EqualityComparer<T>.Default.GetHashCode(arc.Output) : StructuralEqualityComparer.Default.GetHashCode(arc.Output)); h = PRIME * h + (tIsValueType ? JCG.EqualityComparer<T>.Default.GetHashCode(arc.NextFinalOutput) : StructuralEqualityComparer.Default.GetHashCode(arc.NextFinalOutput)); if (arc.IsFinal) { h += 17; } } //System.out.println(" ret " + (h&Integer.MAX_VALUE)); return h & long.MaxValue; } /// <summary> /// hash code for a frozen node /// </summary> private long Hash(long node) { const int PRIME = 31; //System.out.println("hash frozen node=" + node); long h = 0; fst.ReadFirstRealTargetArc(node, scratchArc, input); while (true) { //System.out.println(" label=" + scratchArc.label + " target=" + scratchArc.target + " h=" + h + " output=" + fst.outputs.outputToString(scratchArc.output) + " next?=" + scratchArc.flag(4) + " final?=" + scratchArc.isFinal() + " pos=" + in.getPosition()); h = PRIME * h + scratchArc.Label; h = PRIME * h + (int)(scratchArc.Target ^ (scratchArc.Target >> 32)); // LUCENENET specific - optimize the Hash methods // by only calling StructuralEqualityComparer.Default.GetHashCode() if the value is a reference type h = PRIME * h + (tIsValueType ? JCG.EqualityComparer<T>.Default.GetHashCode(scratchArc.Output) : StructuralEqualityComparer.Default.GetHashCode(scratchArc.Output)); h = PRIME * h + (tIsValueType ? JCG.EqualityComparer<T>.Default.GetHashCode(scratchArc.NextFinalOutput) : StructuralEqualityComparer.Default.GetHashCode(scratchArc.NextFinalOutput)); if (scratchArc.IsFinal) { h += 17; } if (scratchArc.IsLast) { break; } fst.ReadNextRealArc(scratchArc, input); } //System.out.println(" ret " + (h&Integer.MAX_VALUE)); return h & long.MaxValue; } public long Add(Builder.UnCompiledNode<T> nodeIn) { //System.out.println("hash: add count=" + count + " vs " + table.size() + " mask=" + mask); long h = Hash(nodeIn); long pos = h & mask; int c = 0; while (true) { long v = table.Get(pos); if (v == 0) { // freeze & add long node = fst.AddNode(nodeIn); //System.out.println(" now freeze node=" + node); long hashNode = Hash(node); Debug.Assert(hashNode == h, "frozenHash=" + hashNode + " vs h=" + h); count++; table.Set(pos, node); // Rehash at 2/3 occupancy: if (count > 2 * table.Count / 3) { Rehash(); } return node; } else if (NodesEqual(nodeIn, v)) { // same node is already here return v; } // quadratic probe pos = (pos + (++c)) & mask; } } /// <summary> /// called only by rehash /// </summary> private void AddNew(long address) { long pos = Hash(address) & mask; int c = 0; while (true) { if (table.Get(pos) == 0) { table.Set(pos, address); break; } // quadratic probe pos = (pos + (++c)) & mask; } } private void Rehash() { PagedGrowableWriter oldTable = table; table = new PagedGrowableWriter(2 * oldTable.Count, 1 << 30, PackedInt32s.BitsRequired(count), PackedInt32s.COMPACT); mask = table.Count - 1; for (long idx = 0; idx < oldTable.Count; idx++) { long address = oldTable.Get(idx); if (address != 0) { AddNew(address); } } } } }
// 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 global::System; using global::System.Reflection; using global::System.Collections.Generic; using global::Internal.Runtime.Augments; using global::Internal.Reflection.Core; using global::Internal.Reflection.Core.Execution; using global::Internal.Reflection.Execution.MethodInvokers; using global::Internal.Metadata.NativeFormat; using global::System.Runtime.CompilerServices; using global::System.Runtime.InteropServices; using global::Internal.Runtime; using Debug = System.Diagnostics.Debug; using TargetException = System.ArgumentException; namespace Internal.Reflection.Execution { internal sealed partial class ExecutionEnvironmentImplementation : ExecutionEnvironment { internal unsafe struct MetadataTable : IEnumerable<IntPtr> { public readonly uint ElementCount; int _elementSize; byte* _blob; public struct Enumerator : IEnumerator<IntPtr> { byte* _base; byte* _current; byte* _limit; int _elementSize; internal Enumerator(ref MetadataTable table) { _base = table._blob; _elementSize = table._elementSize; _current = _base - _elementSize; _limit = _base + (_elementSize * table.ElementCount); } public IntPtr Current { get { return (IntPtr)_current; } } public void Dispose() { } object System.Collections.IEnumerator.Current { get { return Current; } } public bool MoveNext() { _current += _elementSize; if (_current < _limit) { return true; } _current = _limit; return false; } public void Reset() { _current = _base - _elementSize; } } public MetadataTable(IntPtr moduleHandle, ReflectionMapBlob blobId, int elementSize) { Debug.Assert(elementSize != 0); _elementSize = elementSize; byte* pBlob; uint cbBlob; if (!RuntimeAugments.FindBlob(moduleHandle, (int)blobId, new IntPtr(&pBlob), new IntPtr(&cbBlob))) { pBlob = null; cbBlob = 0; } Debug.Assert(cbBlob % elementSize == 0); _blob = pBlob; ElementCount = cbBlob / (uint)elementSize; } public IntPtr this[uint index] { get { Debug.Assert(index < ElementCount); return (IntPtr)(_blob + (index * _elementSize)); } } public Enumerator GetEnumerator() { return new Enumerator(ref this); } IEnumerator<IntPtr> IEnumerable<IntPtr>.GetEnumerator() { return GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } } struct ExternalReferencesTable { unsafe uint* _base; uint _count; IntPtr _moduleHandle; unsafe public ExternalReferencesTable(IntPtr moduleHandle, ReflectionMapBlob blobId) { _moduleHandle = moduleHandle; uint* pBlob; uint cbBlob; if (RuntimeAugments.FindBlob(moduleHandle, (int)blobId, (IntPtr)(&pBlob), (IntPtr)(&cbBlob))) { _count = cbBlob / sizeof(uint); _base = pBlob; } else { _count = 0; _base = null; } } unsafe public uint GetRvaFromIndex(uint index) { Debug.Assert(_moduleHandle != IntPtr.Zero); if (index >= _count) throw new BadImageFormatException(); return _base[index]; } unsafe public IntPtr GetIntPtrFromIndex(uint index) { uint rva = GetRvaFromIndex(index); if ((rva & 0x80000000) != 0) { // indirect through IAT return *(IntPtr*)((byte*)_moduleHandle + (rva & ~0x80000000)); } else { return (IntPtr)((byte*)_moduleHandle + rva); } } public RuntimeTypeHandle GetRuntimeTypeHandleFromIndex(uint index) { return RuntimeAugments.CreateRuntimeTypeHandle(GetIntPtrFromIndex(index)); } } [StructLayout(LayoutKind.Sequential)] struct TypeMapEntry { public IntPtr EEType; public int TypeDefinitionHandle; } [StructLayout(LayoutKind.Sequential)] struct BlockReflectionTypeMapEntry { public uint EETypeRva; } [StructLayout(LayoutKind.Sequential)] struct ArrayMapEntry { public uint ElementEETypeRva; public uint ArrayEETypeRva; } [StructLayout(LayoutKind.Sequential)] struct GenericInstanceMapEntry { public uint TypeSpecEETypeRva; public uint TypeDefEETypeRva; public uint ArgumentIndex; } struct DynamicInvokeMapEntry { public const uint IsImportMethodFlag = 0x40000000; public const uint InstantiationDetailIndexMask = 0x3FFFFFFF; } [Flags] enum InvokeTableFlags : uint { HasVirtualInvoke = 0x00000001, IsGenericMethod = 0x00000002, HasMetadataHandle = 0x00000004, IsDefaultConstructor = 0x00000008, RequiresInstArg = 0x00000010, HasEntrypoint = 0x00000020, IsUniversalCanonicalEntry = 0x00000040, HasDefaultParameters = 0x00000080, } struct VirtualInvokeTableEntry { public const int GenericVirtualMethod = 1; public const int FlagsMask = 1; } static class FieldAccessFlags { public const int RemoteStaticFieldRVA = unchecked((int)0x80000000); } [Flags] enum FieldTableFlags : uint { Instance = 0x00, Static = 0x01, ThreadStatic = 0x02, StorageClass = 0x03, IsUniversalCanonicalEntry = 0x04, HasMetadataHandle = 0x08, IsGcSection = 0x10, } /// <summary> /// This structure describes one static field in an external module. It is represented /// by an indirection cell pointer and an offset within the cell - the final address /// of the static field is essentially *IndirectionCell + Offset. /// </summary> [StructLayout(LayoutKind.Sequential)] struct RemoteStaticFieldDescriptor { public unsafe IntPtr* IndirectionCell; public int Offset; } [StructLayout(LayoutKind.Sequential)] struct CctorContextEntry { public uint EETypeRva; public uint CctorContextRva; } [StructLayout(LayoutKind.Sequential)] struct PointerTypeMapEntry { public uint PointerTypeEETypeRva; public uint ElementTypeEETypeRva; } private const uint s_NotActuallyAMetadataHandle = 0x80000000; } }
// ============================================================================ // FileName: StatelessProxyScriptHelper.cs // // Description: // A class that contains helper methods for use in a stateless proxy runtime script. // // Author(s): // Aaron Clauson // // License: // This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php // // Copyright (c) 2006-2015 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery Ltd, Australia (www.sipsorcery.com) // 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 SIP Sorcery Ltd. // 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.Data; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Xml; using SIPSorcery.Net; using SIPSorcery.SIP; using SIPSorcery.SIP.App; using SIPSorcery.Sys; using log4net; #if UNITTEST using NUnit.Framework; #endif namespace SIPSorcery.Servers { public class SIPProxyScriptFacade { private static ILog logger = log4net.LogManager.GetLogger("sipproxy"); private SIPMonitorLogDelegate m_proxyLogger; private SIPTransport m_sipTransport; private SIPProxyDispatcher m_dispatcher; private GetAppServerDelegate GetAppServer_External; public SIPProxyScriptFacade( SIPMonitorLogDelegate proxyLogger, SIPTransport sipTransport, SIPProxyDispatcher dispatcher, GetAppServerDelegate getAppServer) { m_proxyLogger = proxyLogger; m_sipTransport = sipTransport; m_dispatcher = dispatcher; GetAppServer_External = getAppServer; } public void Log(string message) { m_proxyLogger(new SIPMonitorConsoleEvent(SIPMonitorServerTypesEnum.SIPProxy, SIPMonitorEventTypesEnum.DialPlan, message, null)); } /// <summary> /// Used to send a SIP request received from an external user agent to an internal SIP server agent. /// </summary> /// <param name="receivedFromEP">The SIP end point the proxy received the request from.</param> /// <param name="receivedOnEP">The SIP end point the proxy received the request on.</param> /// <param name="dstSocket">The internal socket to send the request to.</param> /// <param name="sipRequest">The SIP request to send.</param> /// <param name="proxyBranch">The branch to set on the Via header when sending the request. The branch should be calculated /// by the proxy core so that looped requests can be detected.</param> /// <param name="sendFromSocket">The proxy socket to send the request from.</param> public void SendInternal(SIPEndPoint receivedFromEP, SIPEndPoint receivedOnEP, string dstSocket, SIPRequest sipRequest, string proxyBranch, string sendFromSocket) { try { if (!IsDestinationValid(sipRequest, dstSocket)) { logger.Debug("SendInternal failed destination check."); return; } sipRequest.Header.ProxyReceivedFrom = receivedFromEP.ToString(); sipRequest.Header.ProxyReceivedOn = receivedOnEP.ToString(); SIPEndPoint dstSIPEndPoint = SIPEndPoint.ParseSIPEndPoint(dstSocket); SIPEndPoint localSIPEndPoint = SIPEndPoint.ParseSIPEndPoint(sendFromSocket); if (receivedOnEP != localSIPEndPoint) { // The proxy is being requested to send the request on a different socket to the one it was received on. // A second Via header is added to ensure the response can navigate back the same path. The calculated branch // parameter needs to go on the top Via header so that whichever internal socket the request is being sent to can // determine re-transmits. SIPViaHeader via = new SIPViaHeader(receivedOnEP, CallProperties.CreateBranchId()); sipRequest.Header.Vias.PushViaHeader(via); SIPViaHeader topVia = new SIPViaHeader(localSIPEndPoint, proxyBranch); sipRequest.Header.Vias.PushViaHeader(topVia); } else { // Only a single Via header is required as any response to this request will be sent from the same socket it gets received on. SIPViaHeader via = new SIPViaHeader(localSIPEndPoint, proxyBranch); sipRequest.Header.Vias.PushViaHeader(via); } sipRequest.LocalSIPEndPoint = localSIPEndPoint; m_sipTransport.SendRequest(dstSIPEndPoint, sipRequest); } catch (Exception excp) { logger.Error("Exception SIPRequest SendInternal. " + excp.Message); logger.Error(sipRequest.ToString()); throw; } } /// <summary> /// Used to send a request from an internal server agent to an external SIP user agent. The difference between this method and /// the SendTransparent method is that this one will set Via headers in accordance with RFC3261. /// </summary> /// <param name="receivedOnEP">The proxy SIP end point the request was received on.</param> /// <param name="dstSocket">The SIP end point the request is being sent to.</param> /// <param name="sipRequest">The SIP request to send.</param> /// <param name="proxyBranch">The branch parameter for the top Via header that has been pre-calculated by the proxy core.</param> /// <param name="sendFromSocket">The proxy SIP end point to send this request from. If the SIP request has its ProxySendFrom header /// value set that will overrule this parameter.</param> public void SendExternal(SIPEndPoint receivedOnEP, SIPEndPoint dstSIPEndPoint, SIPRequest sipRequest, string proxyBranch, IPAddress publicIPAddress) { try { if (!IsDestinationValid(sipRequest, dstSIPEndPoint)) { logger.Debug("SendExternal failed destination check."); return; } // Determine the external SIP endpoint that the proxy will use to send this request. SIPEndPoint localSIPEndPoint = m_sipTransport.GetDefaultSIPEndPoint(dstSIPEndPoint); if (!sipRequest.Header.ProxySendFrom.IsNullOrBlank()) { SIPChannel proxyChannel = m_sipTransport.FindSIPChannel(SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxySendFrom)); if (proxyChannel == null) { logger.Warn("No SIP channel could be found for\n" + sipRequest.ToString()); } localSIPEndPoint = (proxyChannel != null) ? proxyChannel.SIPChannelEndPoint : localSIPEndPoint; } if (receivedOnEP != localSIPEndPoint) { // The proxy is being requested to send the request on a different socket to the one it was received on. // A second Via header is added to ensure the response can navigate back the same path. The calculated branch // parameter needs to go on the top Via header so that whichever internal socket the request is being sent to can // determine re-transmits. SIPViaHeader via = new SIPViaHeader(receivedOnEP, CallProperties.CreateBranchId()); sipRequest.Header.Vias.PushViaHeader(via); SIPViaHeader externalVia = new SIPViaHeader(localSIPEndPoint, proxyBranch); sipRequest.Header.Vias.PushViaHeader(externalVia); } else { // Only a single Via header is required as any response to this request will be sent from the same socket it gets received on. SIPViaHeader via = new SIPViaHeader(localSIPEndPoint, proxyBranch); sipRequest.Header.Vias.PushViaHeader(via); } if (sipRequest.Method != SIPMethodsEnum.REGISTER) { AdjustContactHeader(sipRequest.Header, localSIPEndPoint, publicIPAddress); } sipRequest.LocalSIPEndPoint = localSIPEndPoint; // Proxy sepecific headers that don't need to be seen by external UAs. sipRequest.Header.ProxyReceivedOn = null; sipRequest.Header.ProxyReceivedFrom = null; sipRequest.Header.ProxySendFrom = null; m_sipTransport.SendRequest(dstSIPEndPoint, sipRequest); } catch (Exception excp) { logger.Error("Exception SIPRequest SendExternal. " + excp.Message); logger.Error(sipRequest.ToString()); throw; } } /// <summary> /// Forwards a SIP request through the Proxy. This method differs from the standard Send in that irrespective of whether the Proxy is /// receiving and sending on different sockets only a single Via header will ever be allowed on the request. It is then up to the /// response processing logic to determine from which Proxy socket to forward the request and to add back on the Via header for the /// end agent. This method is only ever used for requests destined for EXTERNAL SIP end points. /// </summary> /// <param name="dstSIPEndPoint">The destination SIP socket to send the request to.</param> /// <param name="sipRequest">The SIP request to send.</param> /// default channel that matches the destination end point should be used.</param> public void SendTransparent(SIPEndPoint dstSIPEndPoint, SIPRequest sipRequest, IPAddress publicIPAddress) { try { if (!IsDestinationValid(sipRequest, dstSIPEndPoint)) { logger.Debug("SendTransparent failed destination check."); return; } // Determine the external SIP endpoint that the proxy will use to send this request. SIPEndPoint localSIPEndPoint = null; if (!sipRequest.Header.ProxySendFrom.IsNullOrBlank()) { SIPChannel proxyChannel = m_sipTransport.FindSIPChannel(SIPEndPoint.ParseSIPEndPoint(sipRequest.Header.ProxySendFrom)); localSIPEndPoint = (proxyChannel != null) ? proxyChannel.SIPChannelEndPoint : null; } localSIPEndPoint = localSIPEndPoint ?? m_sipTransport.GetDefaultSIPEndPoint(dstSIPEndPoint); // Create the single Via header for the outgoing request. It uses the passed in branchid which has been taken from the // request that's being forwarded. If this proxy is behind a NAT and the public IP is known that's also set on the Via. string proxyBranch = sipRequest.Header.Vias.PopTopViaHeader().Branch; sipRequest.Header.Vias = new SIPViaSet(); SIPViaHeader via = new SIPViaHeader(localSIPEndPoint, proxyBranch); if (publicIPAddress != null) { via.Host = publicIPAddress.ToString(); } sipRequest.Header.Vias.PushViaHeader(via); if (sipRequest.Method != SIPMethodsEnum.REGISTER) { AdjustContactHeader(sipRequest.Header, localSIPEndPoint, publicIPAddress); } // If dispatcher is being used record the transaction so responses are sent to the correct internal socket. if (m_dispatcher != null && sipRequest.Method != SIPMethodsEnum.REGISTER && sipRequest.Method != SIPMethodsEnum.ACK && sipRequest.Method != SIPMethodsEnum.NOTIFY) { //Log("RecordDispatch for " + sipRequest.Method + " " + sipRequest.URI.ToString() + " to " + sipRequest.RemoteSIPEndPoint.ToString() + "."); m_dispatcher.RecordDispatch(sipRequest, sipRequest.RemoteSIPEndPoint); } // Proxy sepecific headers that don't need to be seen by external UAs. sipRequest.Header.ProxyReceivedOn = null; sipRequest.Header.ProxyReceivedFrom = null; sipRequest.Header.ProxySendFrom = null; sipRequest.LocalSIPEndPoint = localSIPEndPoint; m_sipTransport.SendRequest(dstSIPEndPoint, sipRequest); } catch (Exception excp) { logger.Error("Exception SendTransparent. " + excp.Message); logger.Error(sipRequest.ToString()); throw; } } public void SendInternal(SIPEndPoint receivedFromEP, SIPEndPoint receivedOnEP, SIPResponse sipResponse, SIPEndPoint localSIPEndPoint) { try { sipResponse.Header.ProxyReceivedFrom = receivedFromEP.ToString(); sipResponse.Header.ProxyReceivedOn = receivedOnEP.ToString(); sipResponse.LocalSIPEndPoint = localSIPEndPoint; m_sipTransport.SendResponse(sipResponse); } catch (Exception excp) { logger.Error("Exception SIPResponse SendInternal. " + excp.Message); logger.Error(sipResponse.ToString()); throw; } } public void SendTransparent(SIPEndPoint receivedFromEP, SIPEndPoint receivedOnEP, SIPResponse sipResponse, SIPEndPoint localSIPEndPoint, string dstSIPEndPoint, string proxyBranch) { SendTransparent(receivedFromEP, receivedOnEP, sipResponse, localSIPEndPoint, SIPEndPoint.ParseSIPEndPoint(dstSIPEndPoint), proxyBranch); } /// <summary> /// This method is the equivalent to the same named method for sending SIP requests. The two methods are used to allow the Proxy to /// deliver requests to external SIP agents with only a SINGLE Via header due to a small number of providers rejecting requests with /// more than one Via header. /// </summary> /// <param name="receivedFromEP">The socket the response was received from.</param> /// <param name="receivedOnEP">The proxy socket the response was received on.</param> /// <param name="sipResponse">The response being forwarded.</param> /// <param name="localSIPEndPoint">The proxy socket to forward the request from.</param> /// <param name="dstSIPEndPoint">The internal destination socket to forward the response to.</param> /// <param name="proxyBranch">The branch parameter from the top Via header that needs to be reused when forwarding the response.</param> public void SendTransparent(SIPEndPoint receivedFromEP, SIPEndPoint receivedOnEP, SIPResponse sipResponse, SIPEndPoint localSIPEndPoint, SIPEndPoint dstSIPEndPoint, string proxyBranch) { try { sipResponse.Header.ProxyReceivedFrom = receivedFromEP.ToString(); sipResponse.Header.ProxyReceivedOn = receivedOnEP.ToString(); sipResponse.Header.Vias.PushViaHeader(new SIPViaHeader(dstSIPEndPoint, proxyBranch)); sipResponse.LocalSIPEndPoint = localSIPEndPoint; m_sipTransport.SendResponse(sipResponse); } catch (Exception excp) { logger.Error("Exception SIPResponse SendInternal. " + excp.Message); logger.Error(sipResponse.ToString()); throw; } } public void SendExternal(SIPResponse sipResponse, SIPEndPoint localSIPEndPoint) { try { sipResponse.Header.ProxyReceivedOn = null; sipResponse.Header.ProxyReceivedFrom = null; sipResponse.Header.ProxySendFrom = null; sipResponse.LocalSIPEndPoint = localSIPEndPoint; m_sipTransport.SendResponse(sipResponse); } catch (Exception excp) { logger.Error("Exception SIPResponse SendExternal. " + excp.Message); logger.Error(sipResponse.ToString()); throw; } } public void SendExternal(SIPResponse sipResponse, SIPEndPoint localSIPEndPoint, IPAddress publicIPAddress) { AdjustContactHeader(sipResponse.Header, localSIPEndPoint, publicIPAddress); SendExternal(sipResponse, localSIPEndPoint); } private bool IsDestinationValid(SIPRequest sipRequest, string dstSIPEndPoint) { if (dstSIPEndPoint.IsNullOrBlank()) { Log("Request with URI " + sipRequest.URI.ToString() + " from " + sipRequest.RemoteSIPEndPoint + " was unresolvable."); Respond(sipRequest, SIPResponseStatusCodesEnum.DoesNotExistAnywhere, "Destination unresolvable"); return false; } else { return IsDestinationValid(sipRequest, SIPEndPoint.ParseSIPEndPoint(dstSIPEndPoint)); } } private bool IsDestinationValid(SIPRequest sipRequest, SIPEndPoint dstSIPEndPoint) { if (dstSIPEndPoint == null) { Log("Request with URI " + sipRequest.URI.ToString() + " from " + sipRequest.RemoteSIPEndPoint + " was unresolvable."); Respond(sipRequest, SIPResponseStatusCodesEnum.DoesNotExistAnywhere, "Destination unresolvable"); return false; } else if (SIPTransport.BlackholeAddress.Equals(dstSIPEndPoint.Address)) { Log("Request with URI " + sipRequest.URI.ToString() + " from " + sipRequest.RemoteSIPEndPoint + " resolved to a blackhole IP address."); Respond(sipRequest, SIPResponseStatusCodesEnum.BadRequest, "Resolved to blackhole"); return false; } return true; } private void AdjustContactHeader(SIPHeader sipHeader, SIPEndPoint localSIPEndPoint, IPAddress publicIPAddress) { try { // Set the Contact URI on the outgoing requests depending on which SIP socket the request is being sent on and whether // the request is going to an external network. if (sipHeader.Contact != null && sipHeader.Contact.Count == 1) { SIPEndPoint proxyContact = localSIPEndPoint.CopyOf(); if (publicIPAddress != null) { proxyContact = new SIPEndPoint(proxyContact.Protocol, publicIPAddress, proxyContact.Port); } sipHeader.Contact[0].ContactURI.Host = proxyContact.GetIPEndPoint().ToString(); sipHeader.Contact[0].ContactURI.Protocol = proxyContact.Protocol; } } catch (Exception excp) { logger.Error("Exception AdjustContactHeader. " + excp.Message); throw; } } /// <summary> /// Helper method for dynamic proxy runtime script. /// </summary> /// <param name="responseCode"></param> /// <param name="localEndPoint"></param> /// <param name="remoteEndPoint"></param> /// <param name="sipRequest"></param> public void Respond(SIPRequest sipRequest, SIPResponseStatusCodesEnum responseCode, string reasonPhrase) { SIPResponse response = SIPTransport.GetResponse(sipRequest, responseCode, reasonPhrase); m_sipTransport.SendResponse(response); } public SIPDNSLookupResult Resolve(SIPRequest sipRequest) { if (sipRequest.Header.Routes != null && sipRequest.Header.Routes.Length > 0 && !sipRequest.Header.Routes.TopRoute.IsStrictRouter) { return SIPDNSManager.ResolveSIPService(sipRequest.Header.Routes.TopRoute.URI, true); } else { return SIPDNSManager.ResolveSIPService(sipRequest.URI, true); } } public SIPDNSLookupResult Resolve(SIPURI sipURI) { return SIPDNSManager.ResolveSIPService(sipURI, true); } public SIPEndPoint Resolve(SIPResponse sipResponse) { SIPViaHeader topVia = sipResponse.Header.Vias.TopViaHeader; SIPEndPoint dstEndPoint = new SIPEndPoint(topVia.Transport, m_sipTransport.GetHostEndPoint(topVia.ReceivedFromAddress, true).GetSIPEndPoint().GetIPEndPoint()); return dstEndPoint; } public SIPEndPoint GetDefaultSIPEndPoint(SIPProtocolsEnum protocol) { return m_sipTransport.GetDefaultSIPEndPoint(protocol); } public SIPEndPoint DispatcherLookup(SIPRequest sipRequest) { if (m_dispatcher != null && (sipRequest.Method == SIPMethodsEnum.ACK || sipRequest.Method == SIPMethodsEnum.CANCEL || sipRequest.Method == SIPMethodsEnum.INVITE)) { return m_dispatcher.LookupTransactionID(sipRequest); } return null; } public SIPEndPoint DispatcherLookup(SIPResponse sipResponse) { if (m_dispatcher != null && (sipResponse.Header.CSeqMethod == SIPMethodsEnum.ACK || sipResponse.Header.CSeqMethod == SIPMethodsEnum.CANCEL || sipResponse.Header.CSeqMethod == SIPMethodsEnum.INVITE)) { return m_dispatcher.LookupTransactionID(sipResponse); } return null; } public SIPEndPoint GetAppServer() { return GetAppServer_External(); } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2012 FUJIWARA, Yusuke // // 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. // #endregion -- License Terms -- #if UNITY_IOS using System; using System.Diagnostics.Contracts; using System.Linq; #if NETFX_CORE using System.Reflection; #endif using System.Runtime.Serialization; namespace MsgPack.Serialization { /// <summary> /// <see cref="MessagePackSerializer{T}"/> based on reflection, opt-out based. /// </summary> /// <typeparam name="T"></typeparam> internal class AutoMessagePackSerializer : MessagePackSerializer { private readonly IMessagePackSingleObjectSerializer _underlying; /// <summary> /// Initializes a new instance of the <see cref="AutoMessagePackSerializer&lt;T&gt;"/> class. /// </summary> public AutoMessagePackSerializer(Type type, SerializationContext context, Func<SerializationContext, ISerializerBuilder> builderProvider) : base(type, context.CompatibilityOptions.PackerCompatibilityOptions) { Contract.Assert(context != null); var serializer = context.Serializers.Get(type, context); if (serializer != null) { this._underlying = serializer; return; } var traits = type.GetCollectionTraits(); switch (traits.CollectionType) { case CollectionKind.Array: { serializer = builderProvider(context).CreateArraySerializer(); break; } case CollectionKind.Map: { serializer = builderProvider(context).CreateMapSerializer(); break; } case CollectionKind.NotCollection: { serializer = builderProvider(context).CreateSerializer(); break; } } if (serializer != null) { if (!context.Serializers.Register(type, serializer)) { serializer = context.Serializers.Get(type, context); Contract.Assert(serializer != null); } this._underlying = serializer; return; } throw SerializationExceptions.NewTypeCannotSerialize(type); } /// <summary> /// Serialize specified object with specified <see cref="Packer"/>. /// </summary> /// <param name="packer"><see cref="Packer"/> which packs values in <paramref name="objectTree"/>. This value will not be <c>null</c>.</param> /// <param name="objectTree">Object to be serialized.</param> protected internal sealed override void PackToCore(Packer packer, object objectTree) { this._underlying.PackTo(packer, objectTree); } /// <summary> /// Deserialize object with specified <see cref="Unpacker"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <returns>Deserialized object.</returns> protected internal sealed override object UnpackFromCore(Unpacker unpacker) { return this._underlying.UnpackFrom(unpacker); } /// <summary> /// Deserialize collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param> /// <exception cref="SerializationException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="NotSupportedException"> /// <typeparamref name="T"/> is not collection. /// </exception> protected internal sealed override void UnpackToCore(Unpacker unpacker, object collection) { this._underlying.UnpackTo(unpacker, collection); } public override string ToString() { return this._underlying.ToString(); } } } #else //UNITY_IOS using System; using System.Diagnostics.Contracts; using System.Linq; #if NETFX_CORE using System.Reflection; #endif using System.Runtime.Serialization; namespace MsgPack.Serialization { /// <summary> /// <see cref="MessagePackSerializer{T}"/> based on reflection, opt-out based. /// </summary> /// <typeparam name="T"></typeparam> internal class AutoMessagePackSerializer<T> : MessagePackSerializer<T> { private readonly MessagePackSerializer<T> _underlying; /// <summary> /// Initializes a new instance of the <see cref="AutoMessagePackSerializer&lt;T&gt;"/> class. /// </summary> public AutoMessagePackSerializer( SerializationContext context, Func<SerializationContext, SerializerBuilder<T>> builderProvider ) :base( context.CompatibilityOptions.PackerCompatibilityOptions ) { Contract.Assert( context != null ); var serializer = context.Serializers.Get<T>( context ); if ( serializer != null ) { this._underlying = serializer; return; } var traits = typeof( T ).GetCollectionTraits(); switch ( traits.CollectionType ) { case CollectionKind.Array: { serializer = builderProvider( context ).CreateArraySerializer(); break; } case CollectionKind.Map: { serializer = builderProvider( context ).CreateMapSerializer(); break; } case CollectionKind.NotCollection: { if ( ( typeof( T ).GetAssembly().Equals( typeof( object ).GetAssembly() ) || typeof( T ).GetAssembly().Equals( typeof( Enumerable ).GetAssembly() ) ) && typeof( T ).GetIsPublic() && typeof( T ).Name.StartsWith( "Tuple`", StringComparison.Ordinal ) ) { serializer = builderProvider( context ).CreateTupleSerializer(); } else { serializer = builderProvider( context ).CreateSerializer(); } break; } } if ( serializer != null ) { if ( !context.Serializers.Register<T>( serializer ) ) { serializer = context.Serializers.Get<T>( context ); Contract.Assert( serializer != null ); } this._underlying = serializer; return; } throw SerializationExceptions.NewTypeCannotSerialize( typeof( T ) ); } /// <summary> /// Serialize specified object with specified <see cref="Packer"/>. /// </summary> /// <param name="packer"><see cref="Packer"/> which packs values in <paramref name="objectTree"/>. This value will not be <c>null</c>.</param> /// <param name="objectTree">Object to be serialized.</param> protected internal sealed override void PackToCore( Packer packer, T objectTree ) { this._underlying.PackTo( packer, objectTree ); } /// <summary> /// Deserialize object with specified <see cref="Unpacker"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <returns>Deserialized object.</returns> protected internal sealed override T UnpackFromCore( Unpacker unpacker ) { return this._underlying.UnpackFrom( unpacker ); } /// <summary> /// Deserialize collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>. /// </summary> /// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param> /// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param> /// <exception cref="SerializationException"> /// Failed to deserialize object due to invalid unpacker state, stream content, or so. /// </exception> /// <exception cref="NotSupportedException"> /// <typeparamref name="T"/> is not collection. /// </exception> protected internal sealed override void UnpackToCore( Unpacker unpacker, T collection ) { this._underlying.UnpackTo( unpacker, collection ); } public override string ToString() { return this._underlying.ToString(); } } } #endif
using System; using System.Diagnostics; using System.Linq; using NUnit.Framework; using StructureMap.Testing.Configuration.DSL; using StructureMap.Testing.GenericWidgets; using StructureMap.Testing.Graph; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget2; namespace StructureMap.Testing.Query { [TestFixture] public class ModelIntegrationTester { #region Setup/Teardown [SetUp] public void SetUp() { container = new Container(x => { x.For(typeof (IService<>)).Add(typeof (Service<>)); x.For(typeof (IService<>)).Add(typeof (Service2<>)); x.For<IWidget>().Singleton().Use<AWidget>(); x.For<Rule>().AddInstances(o => { o.Type<DefaultRule>(); o.Type<ARule>(); o.Type<ColorRule>().Ctor<string>("color").Is("red"); }); x.For<IEngine>().Use<PushrodEngine>(); x.For<Startable1>().Singleton().Use<Startable1>(); x.For<Startable2>().Use<Startable2>(); x.For<Startable3>().Use<Startable3>(); }); } #endregion private Container container; [Test] public void can_iterate_through_families_including_both_generics_and_normal() { // +1 for "IContainer" itself + Func container.Model.PluginTypes.Count().ShouldEqual(9); container.Model.PluginTypes.Each(x => Debug.WriteLine(x.PluginType.FullName)); } [Test] public void can_iterate_through_instances_of_pipeline_graph_for_closed_type_from_model() { container.Model.InstancesOf<Rule>().Count().ShouldEqual(3); } [Test] public void can_iterate_through_instances_of_pipeline_graph_for_closed_type_that_is_not_registered() { container.Model.InstancesOf<IServiceProvider>().Count().ShouldEqual(0); } [Test] public void can_iterate_through_instances_of_pipeline_graph_for_generics() { container.Model.For(typeof (IService<>)).Instances.Count().ShouldEqual(2); } [Test] public void can_iterate_through_instances_of_pipeline_graph_for_generics_from_model() { container.Model.InstancesOf(typeof (IService<>)).Count().ShouldEqual(2); } [Test] public void default_type_for_from_the_top() { container.Model.DefaultTypeFor<IWidget>().ShouldEqual(typeof (AWidget)); container.Model.DefaultTypeFor<Rule>().ShouldBeNull(); } [Test] public void get_all_instances_from_the_top() { container.Model.AllInstances.Count().ShouldEqual(12); } [Test] public void get_all_possibles() { // Startable1 is a singleton var startable1 = container.GetInstance<Startable1>(); startable1.WasStarted.ShouldBeFalse(); container.Model.GetAllPossible<IStartable>() .ToArray() .Each(x => x.Start()) .Each(x => x.WasStarted.ShouldBeTrue()); startable1.WasStarted.ShouldBeTrue(); } [Test] public void has_default_implementation_from_the_top() { container.Model.HasDefaultImplementationFor<IWidget>().ShouldBeTrue(); container.Model.HasDefaultImplementationFor<Rule>().ShouldBeFalse(); container.Model.HasDefaultImplementationFor<IServiceProvider>().ShouldBeFalse(); } [Test] public void has_implementation_from_the_top() { container.Model.HasDefaultImplementationFor<IServiceProvider>().ShouldBeFalse(); container.Model.HasDefaultImplementationFor<IWidget>().ShouldBeTrue(); } [Test] public void has_implementations_should_be_false_for_a_type_that_is_not_registered() { container.Model.For<ISomething>().HasImplementations().ShouldBeFalse(); } [Test] public void remove_an_entire_closed_type() { container.GetAllInstances<Rule>().Count().ShouldEqual(3); container.Model.EjectAndRemove(typeof (Rule)); container.Model.HasImplementationsFor<Rule>().ShouldBeFalse(); container.TryGetInstance<Rule>().ShouldBeNull(); container.GetAllInstances<Rule>().Count().ShouldEqual(0); } [Test] public void remove_an_entire_closed_type_with_the_filter() { container.Model.EjectAndRemovePluginTypes(t => t == typeof (Rule) || t == typeof (IWidget)); container.Model.HasImplementationsFor<IWidget>().ShouldBeFalse(); container.Model.HasImplementationsFor<Rule>().ShouldBeFalse(); container.Model.HasImplementationsFor<IEngine>().ShouldBeTrue(); } [Test] public void remove_an_open_type() { container.Model.EjectAndRemove(typeof (IService<>)); container.Model.HasImplementationsFor(typeof (IService<>)); container.TryGetInstance<IService<string>>().ShouldBeNull(); } [Test] public void remove_an_open_type_with_a_filter() { container.Model.EjectAndRemovePluginTypes(t => t == typeof (IService<>)); container.Model.HasImplementationsFor(typeof (IService<>)); container.TryGetInstance<IService<string>>().ShouldBeNull(); } [Test] public void remove_types_based_on_a_filter() { container.GetAllInstances<Rule>().Any(x => x is ARule).ShouldBeTrue(); container.Model.HasImplementationsFor<IWidget>().ShouldBeTrue(); container.Model.EjectAndRemoveTypes(t => t == typeof (IWidget) || t == typeof (ARule)); container.GetAllInstances<Rule>().Any(x => x is ARule).ShouldBeFalse(); container.Model.HasImplementationsFor<IWidget>().ShouldBeFalse(); } } public interface IStartable { bool WasStarted { get; } void Start(); } public class Startable : IStartable { public void Start() { WasStarted = true; } public bool WasStarted { get; private set; } } public class Startable1 : Startable { } public class Startable2 : Startable { } public class Startable3 : Startable { } }
// 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. // /// <summary>Generic chaos types</summary> /// <remarks>CommandLine: ///<code>GenericChaos.exe /mtc:5 /mtcc:1 /mic:10 /ol:Cs /ol:Vb /mtpc:1 /mmtpc:1 ///</code> ///Data: ///<code>Help: False /// MaxGenerationDepth: 2 /// MaxTypeParameterCount: 1 /// MaxMethodTypeParameterCount: 1 /// MaxTypeCount: 5 /// MaxMethodCallDepth: 1000 /// MaxTypeInheranceCount: 1 /// MaxStaticFieldCount: 2 /// MaxInterfaceCount: 10 /// GenerateInterfaces: True /// GenerateVirtualMethods: True /// GenerateMethods: True /// GenerateGenericMethods: True /// GenerateNonInlinableMethods: True /// GenerateStaticMethods: True /// GenerateInstanceMethods: True /// GenerateRecursiveMethods: True /// GenerateStaticFields: True /// GenerateInstanceFields: True /// IntermediateTypeRealization: True /// GenerateConstructorConstraints: True /// GenerateTypeParameterConstraints: True /// GenerateMethodParameterConstraints: True /// OutputPath: chaos /// OutputLanguages: /// Cs /// Vb /// OutputNamespace: Chaos /// ShowOutputInConsole: False /// CompileAndRun: False /// </code></remarks> namespace Chaos { using System; public class A0A0 : A0, IA1 { private IA1 _fA0A01; private static A0A1<A0A0> _sfA0A00; [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void VerifyA0A0NotInlinedGenericStatic<T>() where T : new() { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(A0A0)); T t2 = new T(); A0A0._sfA0A00 = new A0A1<A0A0>(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void VerifyA0A0NotInlinedStatic() { System.Console.WriteLine(typeof(A0A0)); A0A0._sfA0A00 = new A0A1<A0A0>(); } public static void VerifyA0A0GenericStatic<T>() where T : new() { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(A0A0)); T t2 = new T(); A0A0._sfA0A00 = new A0A1<A0A0>(); } public static void VerifyA0A0Static() { System.Console.WriteLine(typeof(A0A0)); A0A0._sfA0A00 = new A0A1<A0A0>(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public void VerifyA0A0NotInlinedGeneric<T>() where T : new() { System.Console.WriteLine(this); System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(A0A0)); T t3 = new T(); A0A0._sfA0A00 = new A0A1<A0A0>(); this._fA0A01 = new A0A0(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public void VerifyA0A0NotInlined() { System.Console.WriteLine(this); System.Console.WriteLine(typeof(A0A0)); A0A0._sfA0A00 = new A0A1<A0A0>(); this._fA0A01 = new A0A0(); } public override void VirtualVerifyGeneric<T>() { base.VirtualVerifyGeneric<T>(); System.Console.WriteLine(this); System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(A0A0)); A0A0._sfA0A00 = new A0A1<A0A0>(); this._fA0A01 = new A0A0(); } public override void VirtualVerify() { base.VirtualVerify(); System.Console.WriteLine(this); System.Console.WriteLine(typeof(A0A0)); A0A0._sfA0A00 = new A0A1<A0A0>(); this._fA0A01 = new A0A0(); } public void RecurseA0A0(int depth) { if ((depth < 0)) { return; } System.Console.Write("."); A0 next = new A0(); next.RecurseA0((depth - 1)); } public void CreateAllTypesA0A0() { A0 v0 = new A0(); v0.VerifyInterfaceIA1(); A0 v1 = new A0(); v1.VerifyInterfaceGenericIA1<A0A1<A0>>(); A0.VerifyA0NotInlinedGenericStatic<A0>(); A0.VerifyA0NotInlinedStatic(); A0.VerifyA0GenericStatic<A0A0>(); A0.VerifyA0Static(); A0 v2 = new A0(); v2.VerifyA0NotInlinedGeneric<A0>(); A0 v3 = new A0(); v3.VerifyA0NotInlined(); A0 v4 = new A0(); v4.VirtualVerifyGeneric<IA1>(); A0 v5 = new A0(); v5.VirtualVerify(); A0 v6 = new A0(); v6.DeepRecursion(); IA1 i7 = ((IA1)(new A0())); i7.VerifyInterfaceIA1(); IA1 i8 = ((IA1)(new A0())); i8.VerifyInterfaceGenericIA1<A0A0A0<A0A0>>(); A0A0.VerifyA0A0NotInlinedGenericStatic<A0A0A0<A0A0>>(); A0A0.VerifyA0A0NotInlinedStatic(); A0A0.VerifyA0A0GenericStatic<A0A0>(); A0A0.VerifyA0A0Static(); A0A0 v9 = new A0A0(); v9.VerifyA0A0NotInlinedGeneric<A0A0A0<A0A0>>(); A0A0 v10 = new A0A0(); v10.VerifyA0A0NotInlined(); A0A0 v11 = new A0A0(); v11.VirtualVerifyGeneric<A0A1<A0>>(); A0A0 v12 = new A0A0(); v12.VirtualVerify(); IA1 i13 = ((IA1)(new A0A0())); i13.VerifyInterfaceIA1(); IA1 i14 = ((IA1)(new A0A0())); i14.VerifyInterfaceGenericIA1<A0>(); A0A1<A0>.VerifyA0A1NotInlinedGenericStatic<A0>(); A0A1<A0>.VerifyA0A1NotInlinedStatic(); A0A1<A0>.VerifyA0A1GenericStatic<A0A0>(); A0A1<A0>.VerifyA0A1Static(); A0A1<A0A0> v15 = new A0A1<A0A0>(); v15.VerifyA0A1NotInlinedGeneric<A0A1<A0A0>>(); A0A1<A0A0> v16 = new A0A1<A0A0>(); v16.VerifyA0A1NotInlined(); A0A0A0<A0>.VerifyA0A0A0NotInlinedGenericStatic<A0A0A0<A0>>(); A0A0A0<A0A0A0<A0>>.VerifyA0A0A0NotInlinedStatic(); A0A0A0<A0A0A0<A0A0A0<A0>>>.VerifyA0A0A0GenericStatic<A0A0A0<A0A0A0<A0A0A0<A0>>>>(); A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>.VerifyA0A0A0Static(); A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>> v17 = new A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>(); v17.VerifyA0A0A0NotInlinedGeneric<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>(); A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>> v18 = new A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>(); v18.VerifyA0A0A0NotInlined(); } } public class A0A1<T0> : A0 where T0 : new() { [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void VerifyA0A1NotInlinedGenericStatic<T>() where T : new() { System.Console.WriteLine(typeof(T)); T0 t1 = new T0(); T t2 = new T(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void VerifyA0A1NotInlinedStatic() { T0 t0 = new T0(); } public static void VerifyA0A1GenericStatic<T>() where T : new() { System.Console.WriteLine(typeof(T)); T0 t1 = new T0(); T t2 = new T(); } public static void VerifyA0A1Static() { T0 t0 = new T0(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public void VerifyA0A1NotInlinedGeneric<T>() where T : new() { System.Console.WriteLine(this); System.Console.WriteLine(typeof(T)); T0 t2 = new T0(); T t3 = new T(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public void VerifyA0A1NotInlined() { System.Console.WriteLine(this); T0 t1 = new T0(); } public void RecurseA0A1(int depth) { if ((depth < 0)) { return; } System.Console.Write("."); A0A0 next = new A0A0(); next.RecurseA0A0((depth - 1)); } public void CreateAllTypesA0A1() { A0 v0 = new A0(); v0.VerifyInterfaceIA1(); A0 v1 = new A0(); v1.VerifyInterfaceGenericIA1<A0A1<A0A0>>(); A0.VerifyA0NotInlinedGenericStatic<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>(); A0.VerifyA0NotInlinedStatic(); A0.VerifyA0GenericStatic<A0A1<A0A0>>(); A0.VerifyA0Static(); A0 v2 = new A0(); v2.VerifyA0NotInlinedGeneric<A0>(); A0 v3 = new A0(); v3.VerifyA0NotInlined(); A0 v4 = new A0(); v4.VirtualVerifyGeneric<A0A0>(); A0 v5 = new A0(); v5.VirtualVerify(); A0 v6 = new A0(); v6.DeepRecursion(); IA1 i7 = ((IA1)(new A0())); i7.VerifyInterfaceIA1(); IA1 i8 = ((IA1)(new A0())); i8.VerifyInterfaceGenericIA1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>(); A0A0.VerifyA0A0NotInlinedGenericStatic<A0A1<A0A0>>(); A0A0.VerifyA0A0NotInlinedStatic(); A0A0.VerifyA0A0GenericStatic<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>(); A0A0.VerifyA0A0Static(); A0A0 v9 = new A0A0(); v9.VerifyA0A0NotInlinedGeneric<A0A0>(); A0A0 v10 = new A0A0(); v10.VerifyA0A0NotInlined(); A0A0 v11 = new A0A0(); v11.VirtualVerifyGeneric<A0>(); A0A0 v12 = new A0A0(); v12.VirtualVerify(); IA1 i13 = ((IA1)(new A0A0())); i13.VerifyInterfaceIA1(); IA1 i14 = ((IA1)(new A0A0())); i14.VerifyInterfaceGenericIA1<A0A1<A0A0>>(); A0A1<A0>.VerifyA0A1NotInlinedGenericStatic<A0>(); A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>.VerifyA0A1NotInlinedStatic(); A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>.VerifyA0A1GenericStatic<A0A0>(); A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>.VerifyA0A1Static(); A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>> v15 = new A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>(); v15.VerifyA0A1NotInlinedGeneric<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>(); A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>> v16 = new A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>(); v16.VerifyA0A1NotInlined(); A0A0A0<A0A0>.VerifyA0A0A0NotInlinedGenericStatic<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>(); A0A0A0<A0>.VerifyA0A0A0NotInlinedStatic(); A0A0A0<A0A0A0<A0>>.VerifyA0A0A0GenericStatic<A0>(); A0A0A0<A0A0>.VerifyA0A0A0Static(); A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>> v17 = new A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>(); v17.VerifyA0A0A0NotInlinedGeneric<A0>(); A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>> v18 = new A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>(); v18.VerifyA0A0A0NotInlined(); } } public class Program { public static int Main(string[] args) { A0 v0 = new A0(); v0.CreateAllTypesA0(); A0A0 v1 = new A0A0(); v1.CreateAllTypesA0A0(); A0A1<A0A0A0<A0A0A0<A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>>>> v2 = new A0A1<A0A0A0<A0A0A0<A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>>>>(); v2.CreateAllTypesA0A1(); A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>>>> v3 = new A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>>>>(); v3.CreateAllTypesA0A0A0(); System.Console.WriteLine("Test SUCCESS"); return 100; } } public interface IA1A2<T0> where T0 : new() { } public class A0A0A0<T0> : A0A0 where T0 : new() { [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void VerifyA0A0A0NotInlinedGenericStatic<T>() where T : new() { System.Console.WriteLine(typeof(T)); T0 t1 = new T0(); T t2 = new T(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void VerifyA0A0A0NotInlinedStatic() { T0 t0 = new T0(); } public static void VerifyA0A0A0GenericStatic<T>() where T : new() { System.Console.WriteLine(typeof(T)); T0 t1 = new T0(); T t2 = new T(); } public static void VerifyA0A0A0Static() { T0 t0 = new T0(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public void VerifyA0A0A0NotInlinedGeneric<T>() where T : new() { System.Console.WriteLine(this); System.Console.WriteLine(typeof(T)); T0 t2 = new T0(); T t3 = new T(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public void VerifyA0A0A0NotInlined() { System.Console.WriteLine(this); T0 t1 = new T0(); } public void RecurseA0A0A0(int depth) { if ((depth < 0)) { return; } System.Console.Write("."); A0A1<A0A0A0<A0>> next = new A0A1<A0A0A0<A0>>(); next.RecurseA0A1((depth - 1)); } public void CreateAllTypesA0A0A0() { A0 v0 = new A0(); v0.VerifyInterfaceIA1(); A0 v1 = new A0(); v1.VerifyInterfaceGenericIA1<A0>(); A0.VerifyA0NotInlinedGenericStatic<A0A0>(); A0.VerifyA0NotInlinedStatic(); A0.VerifyA0GenericStatic<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>(); A0.VerifyA0Static(); A0 v2 = new A0(); v2.VerifyA0NotInlinedGeneric<A0>(); A0 v3 = new A0(); v3.VerifyA0NotInlined(); A0 v4 = new A0(); v4.VirtualVerifyGeneric<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>(); A0 v5 = new A0(); v5.VirtualVerify(); A0 v6 = new A0(); v6.DeepRecursion(); IA1 i7 = ((IA1)(new A0())); i7.VerifyInterfaceIA1(); IA1 i8 = ((IA1)(new A0())); i8.VerifyInterfaceGenericIA1<A0A0>(); A0A0.VerifyA0A0NotInlinedGenericStatic<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>(); A0A0.VerifyA0A0NotInlinedStatic(); A0A0.VerifyA0A0GenericStatic<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>(); A0A0.VerifyA0A0Static(); A0A0 v9 = new A0A0(); v9.VerifyA0A0NotInlinedGeneric<A0>(); A0A0 v10 = new A0A0(); v10.VerifyA0A0NotInlined(); A0A0 v11 = new A0A0(); v11.VirtualVerifyGeneric<IA1A2<A0A0A0<A0>>>(); A0A0 v12 = new A0A0(); v12.VirtualVerify(); IA1 i13 = ((IA1)(new A0A0())); i13.VerifyInterfaceIA1(); IA1 i14 = ((IA1)(new A0A0())); i14.VerifyInterfaceGenericIA1<A0>(); A0A1<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>.VerifyA0A1NotInlinedGenericStatic<A0A1<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>(); A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>.VerifyA0A1NotInlinedStatic(); A0A1<A0A0>.VerifyA0A1GenericStatic<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>(); A0A1<A0>.VerifyA0A1Static(); A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>> v15 = new A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>(); v15.VerifyA0A1NotInlinedGeneric<A0>(); A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>> v16 = new A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>(); v16.VerifyA0A1NotInlined(); A0A0A0<A0A0>.VerifyA0A0A0NotInlinedGenericStatic<A0>(); A0A0A0<A0>.VerifyA0A0A0NotInlinedStatic(); A0A0A0<A0>.VerifyA0A0A0GenericStatic<A0A0A0<A0>>(); A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>.VerifyA0A0A0Static(); A0A0A0<A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>> v17 = new A0A0A0<A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>>(); v17.VerifyA0A0A0NotInlinedGeneric<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>(); A0A0A0<A0A0A0<A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>>> v18 = new A0A0A0<A0A0A0<A0A0A0<A0A1<A0A0A0<A0A1<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0A0A0<A0>>>>>>>>>>>>(); v18.VerifyA0A0A0NotInlined(); } } public interface IA1 { void VerifyInterfaceIA1(); void VerifyInterfaceGenericIA1<K>() where K : new(); } public class A0 : object, IA1 { public void VerifyInterfaceIA1() { System.Console.WriteLine(typeof(A0)); } public void VerifyInterfaceGenericIA1<K>() where K : new() { System.Console.WriteLine(typeof(A0)); K t1 = new K(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void VerifyA0NotInlinedGenericStatic<T>() where T : new() { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(A0)); T t2 = new T(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public static void VerifyA0NotInlinedStatic() { System.Console.WriteLine(typeof(A0)); } public static void VerifyA0GenericStatic<T>() where T : new() { System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(A0)); T t2 = new T(); } public static void VerifyA0Static() { System.Console.WriteLine(typeof(A0)); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public void VerifyA0NotInlinedGeneric<T>() where T : new() { System.Console.WriteLine(this); System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(A0)); T t3 = new T(); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] public void VerifyA0NotInlined() { System.Console.WriteLine(this); System.Console.WriteLine(typeof(A0)); } public virtual void VirtualVerifyGeneric<T>() { System.Console.WriteLine(this); System.Console.WriteLine(typeof(T)); System.Console.WriteLine(typeof(A0)); } public virtual void VirtualVerify() { System.Console.WriteLine(this); System.Console.WriteLine(typeof(A0)); } public void RecurseA0(int depth) { if ((depth < 0)) { return; } System.Console.Write("."); A0A0A0<A0A0A0<A0>> next = new A0A0A0<A0A0A0<A0>>(); next.RecurseA0A0A0((depth - 1)); } public void DeepRecursion() { this.RecurseA0(1000); System.Console.WriteLine(); } public void CreateAllTypesA0() { A0 v0 = new A0(); v0.VerifyInterfaceIA1(); A0 v1 = new A0(); v1.VerifyInterfaceGenericIA1<A0A0A0<A0A0A0<A0>>>(); A0.VerifyA0NotInlinedGenericStatic<A0A0A0<A0A0A0<A0>>>(); A0.VerifyA0NotInlinedStatic(); A0.VerifyA0GenericStatic<A0A1<A0A0A0<A0>>>(); A0.VerifyA0Static(); A0 v2 = new A0(); v2.VerifyA0NotInlinedGeneric<A0A0>(); A0 v3 = new A0(); v3.VerifyA0NotInlined(); A0 v4 = new A0(); v4.VirtualVerifyGeneric<A0A1<A0A0A0<A0>>>(); A0 v5 = new A0(); v5.VirtualVerify(); A0 v6 = new A0(); v6.DeepRecursion(); IA1 i7 = ((IA1)(new A0())); i7.VerifyInterfaceIA1(); IA1 i8 = ((IA1)(new A0())); i8.VerifyInterfaceGenericIA1<A0>(); A0A0.VerifyA0A0NotInlinedGenericStatic<A0A1<A0A0A0<A0>>>(); A0A0.VerifyA0A0NotInlinedStatic(); A0A0.VerifyA0A0GenericStatic<A0A1<A0A0A0<A0>>>(); A0A0.VerifyA0A0Static(); A0A0 v9 = new A0A0(); v9.VerifyA0A0NotInlinedGeneric<A0A1<A0A0A0<A0>>>(); A0A0 v10 = new A0A0(); v10.VerifyA0A0NotInlined(); A0A0 v11 = new A0A0(); v11.VirtualVerifyGeneric<A0A0A0<A0A0A0<A0>>>(); A0A0 v12 = new A0A0(); v12.VirtualVerify(); IA1 i13 = ((IA1)(new A0A0())); i13.VerifyInterfaceIA1(); IA1 i14 = ((IA1)(new A0A0())); i14.VerifyInterfaceGenericIA1<A0A0>(); A0A1<A0A0>.VerifyA0A1NotInlinedGenericStatic<A0A1<A0A0>>(); A0A1<A0A1<A0A0>>.VerifyA0A1NotInlinedStatic(); A0A1<A0>.VerifyA0A1GenericStatic<A0A1<A0>>(); A0A1<A0A1<A0>>.VerifyA0A1Static(); A0A1<A0A1<A0A1<A0>>> v15 = new A0A1<A0A1<A0A1<A0>>>(); v15.VerifyA0A1NotInlinedGeneric<A0A1<A0A1<A0A1<A0>>>>(); A0A1<A0> v16 = new A0A1<A0>(); v16.VerifyA0A1NotInlined(); A0A0A0<A0A0A0<A0A0A0<A0>>>.VerifyA0A0A0NotInlinedGenericStatic<A0A0A0<A0A0A0<A0A0A0<A0>>>>(); A0A0A0<A0>.VerifyA0A0A0NotInlinedStatic(); A0A0A0<A0A0A0<A0>>.VerifyA0A0A0GenericStatic<A0A0A0<A0A0A0<A0>>>(); A0A0A0<A0A1<A0>>.VerifyA0A0A0Static(); A0A0A0<A0A0> v17 = new A0A0A0<A0A0>(); v17.VerifyA0A0A0NotInlinedGeneric<A0A1<A0>>(); A0A0A0<A0A0> v18 = new A0A0A0<A0A0>(); v18.VerifyA0A0A0NotInlined(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Xml.Schema { using System; using System.Diagnostics; using System.Text; /// <summary> /// This structure holds components of an Xsd Duration. It is used internally to support Xsd durations without loss /// of fidelity. XsdDuration structures are immutable once they've been created. /// </summary> #if SILVERLIGHT [System.Runtime.CompilerServices.FriendAccessAllowed] // used by System.Runtime.Serialization.dll #endif internal struct XsdDuration { private int _years; private int _months; private int _days; private int _hours; private int _minutes; private int _seconds; private uint _nanoseconds; // High bit is used to indicate whether duration is negative private const uint NegativeBit = 0x80000000; private enum Parts { HasNone = 0, HasYears = 1, HasMonths = 2, HasDays = 4, HasHours = 8, HasMinutes = 16, HasSeconds = 32, } public enum DurationType { Duration, YearMonthDuration, DayTimeDuration, }; /// <summary> /// Construct an XsdDuration from component parts. /// </summary> public XsdDuration(bool isNegative, int years, int months, int days, int hours, int minutes, int seconds, int nanoseconds) { if (years < 0) throw new ArgumentOutOfRangeException(nameof(years)); if (months < 0) throw new ArgumentOutOfRangeException(nameof(months)); if (days < 0) throw new ArgumentOutOfRangeException(nameof(days)); if (hours < 0) throw new ArgumentOutOfRangeException(nameof(hours)); if (minutes < 0) throw new ArgumentOutOfRangeException(nameof(minutes)); if (seconds < 0) throw new ArgumentOutOfRangeException(nameof(seconds)); if (nanoseconds < 0 || nanoseconds > 999999999) throw new ArgumentOutOfRangeException(nameof(nanoseconds)); _years = years; _months = months; _days = days; _hours = hours; _minutes = minutes; _seconds = seconds; _nanoseconds = (uint)nanoseconds; if (isNegative) _nanoseconds |= NegativeBit; } /// <summary> /// Construct an XsdDuration from a TimeSpan value. /// </summary> public XsdDuration(TimeSpan timeSpan) : this(timeSpan, DurationType.Duration) { } /// <summary> /// Construct an XsdDuration from a TimeSpan value that represents an xsd:duration, an xdt:dayTimeDuration, or /// an xdt:yearMonthDuration. /// </summary> public XsdDuration(TimeSpan timeSpan, DurationType durationType) { long ticks = timeSpan.Ticks; ulong ticksPos; bool isNegative; if (ticks < 0) { // Note that (ulong) -Int64.MinValue = Int64.MaxValue + 1, which is what we want for that special case isNegative = true; ticksPos = unchecked((ulong)-ticks); } else { isNegative = false; ticksPos = (ulong)ticks; } if (durationType == DurationType.YearMonthDuration) { int years = (int)(ticksPos / ((ulong)TimeSpan.TicksPerDay * 365)); int months = (int)((ticksPos % ((ulong)TimeSpan.TicksPerDay * 365)) / ((ulong)TimeSpan.TicksPerDay * 30)); if (months == 12) { // If remaining days >= 360 and < 365, then round off to year years++; months = 0; } this = new XsdDuration(isNegative, years, months, 0, 0, 0, 0, 0); } else { Debug.Assert(durationType == DurationType.Duration || durationType == DurationType.DayTimeDuration); // Tick count is expressed in 100 nanosecond intervals _nanoseconds = (uint)(ticksPos % 10000000) * 100; if (isNegative) _nanoseconds |= NegativeBit; _years = 0; _months = 0; _days = (int)(ticksPos / (ulong)TimeSpan.TicksPerDay); _hours = (int)((ticksPos / (ulong)TimeSpan.TicksPerHour) % 24); _minutes = (int)((ticksPos / (ulong)TimeSpan.TicksPerMinute) % 60); _seconds = (int)((ticksPos / (ulong)TimeSpan.TicksPerSecond) % 60); } } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored with loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s) : this(s, DurationType.Duration) { } /// <summary> /// Constructs an XsdDuration from a string in the xsd:duration format. Components are stored without loss /// of fidelity (except in the case of overflow). /// </summary> public XsdDuration(string s, DurationType durationType) { XsdDuration result; Exception exception = TryParse(s, durationType, out result); if (exception != null) { throw exception; } _years = result.Years; _months = result.Months; _days = result.Days; _hours = result.Hours; _minutes = result.Minutes; _seconds = result.Seconds; _nanoseconds = (uint)result.Nanoseconds; if (result.IsNegative) { _nanoseconds |= NegativeBit; } return; } /// <summary> /// Return true if this duration is negative. /// </summary> public bool IsNegative { get { return (_nanoseconds & NegativeBit) != 0; } } /// <summary> /// Return number of years in this duration (stored in 31 bits). /// </summary> public int Years { get { return _years; } } /// <summary> /// Return number of months in this duration (stored in 31 bits). /// </summary> public int Months { get { return _months; } } /// <summary> /// Return number of days in this duration (stored in 31 bits). /// </summary> public int Days { get { return _days; } } /// <summary> /// Return number of hours in this duration (stored in 31 bits). /// </summary> public int Hours { get { return _hours; } } /// <summary> /// Return number of minutes in this duration (stored in 31 bits). /// </summary> public int Minutes { get { return _minutes; } } /// <summary> /// Return number of seconds in this duration (stored in 31 bits). /// </summary> public int Seconds { get { return _seconds; } } /// <summary> /// Return number of nanoseconds in this duration. /// </summary> public int Nanoseconds { get { return (int)(_nanoseconds & ~NegativeBit); } } #if !SILVERLIGHT /// <summary> /// Return number of microseconds in this duration. /// </summary> public int Microseconds { get { return Nanoseconds / 1000; } } /// <summary> /// Return number of milliseconds in this duration. /// </summary> public int Milliseconds { get { return Nanoseconds / 1000000; } } /// <summary> /// Normalize year-month part and day-time part so that month < 12, hour < 24, minute < 60, and second < 60. /// </summary> public XsdDuration Normalize() { int years = Years; int months = Months; int days = Days; int hours = Hours; int minutes = Minutes; int seconds = Seconds; try { checked { if (months >= 12) { years += months / 12; months %= 12; } if (seconds >= 60) { minutes += seconds / 60; seconds %= 60; } if (minutes >= 60) { hours += minutes / 60; minutes %= 60; } if (hours >= 24) { days += hours / 24; hours %= 24; } } } catch (OverflowException) { throw new OverflowException(SR.Format(SR.XmlConvert_Overflow, ToString(), "Duration")); } return new XsdDuration(IsNegative, years, months, days, hours, minutes, seconds, Nanoseconds); } #endif /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan() { return ToTimeSpan(DurationType.Duration); } /// <summary> /// Internal helper method that converts an Xsd duration to a TimeSpan value. This code uses the estimate /// that there are 365 days in the year and 30 days in a month. /// </summary> public TimeSpan ToTimeSpan(DurationType durationType) { TimeSpan result; Exception exception = TryToTimeSpan(durationType, out result); if (exception != null) { throw exception; } return result; } #if !SILVERLIGHT internal Exception TryToTimeSpan(out TimeSpan result) { return TryToTimeSpan(DurationType.Duration, out result); } #endif internal Exception TryToTimeSpan(DurationType durationType, out TimeSpan result) { Exception exception = null; ulong ticks = 0; // Throw error if result cannot fit into a long try { checked { // Discard year and month parts if constructing TimeSpan for DayTimeDuration if (durationType != DurationType.DayTimeDuration) { ticks += ((ulong)_years + (ulong)_months / 12) * 365; ticks += ((ulong)_months % 12) * 30; } // Discard day and time parts if constructing TimeSpan for YearMonthDuration if (durationType != DurationType.YearMonthDuration) { ticks += (ulong)_days; ticks *= 24; ticks += (ulong)_hours; ticks *= 60; ticks += (ulong)_minutes; ticks *= 60; ticks += (ulong)_seconds; // Tick count interval is in 100 nanosecond intervals (7 digits) ticks *= (ulong)TimeSpan.TicksPerSecond; ticks += (ulong)Nanoseconds / 100; } else { // Multiply YearMonth duration by number of ticks per day ticks *= (ulong)TimeSpan.TicksPerDay; } if (IsNegative) { // Handle special case of Int64.MaxValue + 1 before negation, since it would otherwise overflow if (ticks == (ulong)Int64.MaxValue + 1) { result = new TimeSpan(Int64.MinValue); } else { result = new TimeSpan(-((long)ticks)); } } else { result = new TimeSpan((long)ticks); } return null; } } catch (OverflowException) { result = TimeSpan.MinValue; exception = new OverflowException(SR.Format(SR.XmlConvert_Overflow, durationType, "TimeSpan")); } return exception; } /// <summary> /// Return the string representation of this Xsd duration. /// </summary> public override string ToString() { return ToString(DurationType.Duration); } /// <summary> /// Return the string representation according to xsd:duration rules, xdt:dayTimeDuration rules, or /// xdt:yearMonthDuration rules. /// </summary> internal string ToString(DurationType durationType) { StringBuilder sb = new StringBuilder(20); int nanoseconds, digit, zeroIdx, len; if (IsNegative) sb.Append('-'); sb.Append('P'); if (durationType != DurationType.DayTimeDuration) { if (_years != 0) { sb.Append(XmlConvert.ToString(_years)); sb.Append('Y'); } if (_months != 0) { sb.Append(XmlConvert.ToString(_months)); sb.Append('M'); } } if (durationType != DurationType.YearMonthDuration) { if (_days != 0) { sb.Append(XmlConvert.ToString(_days)); sb.Append('D'); } if (_hours != 0 || _minutes != 0 || _seconds != 0 || Nanoseconds != 0) { sb.Append('T'); if (_hours != 0) { sb.Append(XmlConvert.ToString(_hours)); sb.Append('H'); } if (_minutes != 0) { sb.Append(XmlConvert.ToString(_minutes)); sb.Append('M'); } nanoseconds = Nanoseconds; if (_seconds != 0 || nanoseconds != 0) { sb.Append(XmlConvert.ToString(_seconds)); if (nanoseconds != 0) { sb.Append('.'); len = sb.Length; sb.Length += 9; zeroIdx = sb.Length - 1; for (int idx = zeroIdx; idx >= len; idx--) { digit = nanoseconds % 10; sb[idx] = (char)(digit + '0'); if (zeroIdx == idx && digit == 0) zeroIdx--; nanoseconds /= 10; } sb.Length = zeroIdx + 1; } sb.Append('S'); } } // Zero is represented as "PT0S" if (sb[sb.Length - 1] == 'P') sb.Append("T0S"); } else { // Zero is represented as "T0M" if (sb[sb.Length - 1] == 'P') sb.Append("0M"); } return sb.ToString(); } #if !SILVERLIGHT internal static Exception TryParse(string s, out XsdDuration result) { return TryParse(s, DurationType.Duration, out result); } #endif internal static Exception TryParse(string s, DurationType durationType, out XsdDuration result) { string errorCode; int length; int value, pos, numDigits; Parts parts = Parts.HasNone; result = new XsdDuration(); s = s.Trim(); length = s.Length; pos = 0; numDigits = 0; if (pos >= length) goto InvalidFormat; if (s[pos] == '-') { pos++; result._nanoseconds = NegativeBit; } else { result._nanoseconds = 0; } if (pos >= length) goto InvalidFormat; if (s[pos++] != 'P') goto InvalidFormat; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'Y') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasYears; result._years = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMonths; result._months = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'D') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasDays; result._days = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'T') { if (numDigits != 0) goto InvalidFormat; pos++; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; if (s[pos] == 'H') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasHours; result._hours = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == 'M') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasMinutes; result._minutes = value; if (++pos == length) goto Done; errorCode = TryParseDigits(s, ref pos, false, out value, out numDigits); if (errorCode != null) goto Error; if (pos >= length) goto InvalidFormat; } if (s[pos] == '.') { pos++; parts |= Parts.HasSeconds; result._seconds = value; errorCode = TryParseDigits(s, ref pos, true, out value, out numDigits); if (errorCode != null) goto Error; if (numDigits == 0) { //If there are no digits after the decimal point, assume 0 value = 0; } // Normalize to nanosecond intervals for (; numDigits > 9; numDigits--) value /= 10; for (; numDigits < 9; numDigits++) value *= 10; result._nanoseconds |= (uint)value; if (pos >= length) goto InvalidFormat; if (s[pos] != 'S') goto InvalidFormat; if (++pos == length) goto Done; } else if (s[pos] == 'S') { if (numDigits == 0) goto InvalidFormat; parts |= Parts.HasSeconds; result._seconds = value; if (++pos == length) goto Done; } } // Duration cannot end with digits if (numDigits != 0) goto InvalidFormat; // No further characters are allowed if (pos != length) goto InvalidFormat; Done: // At least one part must be defined if (parts == Parts.HasNone) goto InvalidFormat; if (durationType == DurationType.DayTimeDuration) { if ((parts & (Parts.HasYears | Parts.HasMonths)) != 0) goto InvalidFormat; } else if (durationType == DurationType.YearMonthDuration) { if ((parts & ~(XsdDuration.Parts.HasYears | XsdDuration.Parts.HasMonths)) != 0) goto InvalidFormat; } return null; InvalidFormat: return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, durationType)); Error: return new OverflowException(SR.Format(SR.XmlConvert_Overflow, s, durationType)); } /// Helper method that constructs an integer from leading digits starting at s[offset]. "offset" is /// updated to contain an offset just beyond the last digit. The number of digits consumed is returned in /// cntDigits. The integer is returned (0 if no digits). If the digits cannot fit into an Int32: /// 1. If eatDigits is true, then additional digits will be silently discarded (don't count towards numDigits) /// 2. If eatDigits is false, an overflow exception is thrown private static string TryParseDigits(string s, ref int offset, bool eatDigits, out int result, out int numDigits) { int offsetStart = offset; int offsetEnd = s.Length; int digit; result = 0; numDigits = 0; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { digit = s[offset] - '0'; if (result > (Int32.MaxValue - digit) / 10) { if (!eatDigits) { return SR.XmlConvert_Overflow; } // Skip past any remaining digits numDigits = offset - offsetStart; while (offset < offsetEnd && s[offset] >= '0' && s[offset] <= '9') { offset++; } return null; } result = result * 10 + digit; offset++; } numDigits = offset - offsetStart; return null; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Reflection; using Microsoft.FSharp.Core.CompilerServices; namespace TypeProviderInCSharp { public class ArtificialType : Type { string _Namespace; string _Name; bool _IsGenericType; bool _IsValueType; // value type = not class / not interface bool _IsByRef; // is the value passed by reference? bool _IsEnum; bool _IsPointer; Type _BaseType; MethodInfo _Method1; PropertyInfo _Property1; EventInfo _Event1; FieldInfo _Field1; ConstructorInfo _Ctor1; public ArtificialType(string @namespace, string name, bool isGenericType, Type basetype, bool isValueType, bool isByRef, bool isEnum, bool IsPointer) { _Name = name; _Namespace = @namespace; _IsGenericType = isGenericType; _BaseType = basetype; _IsValueType = isValueType; _IsByRef = isByRef; _IsEnum = isEnum; _IsPointer = IsPointer; _Method1 = new ArtificialMethodInfo("M", this, typeof(int[]), MethodAttributes.Public | MethodAttributes.Static); _Property1 = new ArtificialPropertyInfo("StaticProp", this, typeof(decimal), true, false); _Event1 = new ArtificalEventInfo("Event1", this, typeof(EventHandler)); _Ctor1 = new ArtificialConstructorInfo(this, new ParameterInfo[] {} ); // parameter-less ctor } public override System.Reflection.Assembly Assembly { get { return Assembly.GetExecutingAssembly(); } } public override string Name { get { return _Name; } } public override Type BaseType { get { return _BaseType; } } public override string Namespace { get { return _Namespace; } } public override string FullName { get { return string.Format("{0}.{1}", _Namespace, _Name); } } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { Debug.Assert(false, "Why are we calling into GetCustomAttributes()?"); return null; } public override object[] GetCustomAttributes(bool inherit) { Debug.Assert(false, "Why are we calling into GetCustomAttributes()?"); return null; } // TODO: what is this? protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Class | TypeAttributes.Public | (TypeAttributes)0x40000000; // add the special flag to indicate an erased type, see TypeProviderTypeAttributes } // This one seems to be invoked when in IDE, I type something like: // let _ = typeof<N. // In this case => no constructors public override System.Reflection.ConstructorInfo[] GetConstructors(System.Reflection.BindingFlags bindingAttr) { // According to the spec, we should only expect these 4, so we guard against that here! Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!"); if (_Ctor1!=null) return new System.Reflection.ConstructorInfo[] { _Ctor1 }; else return new System.Reflection.ConstructorInfo[] { }; } // When you start typing more interesting things like... // let a = N.T.M() // this one gets invoked... public override System.Reflection.MethodInfo[] GetMethods(System.Reflection.BindingFlags bindingAttr) { // According to the spec, we should only expect these 4, so we guard against that here! Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!"); return new[] { _Method1 }; } // This method is called when in the source file we have something like: // - N.T.StaticProp // (most likely also when we have an instance prop...) // name -> "StaticProp" protected override System.Reflection.PropertyInfo GetPropertyImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Type returnType, Type[] types, System.Reflection.ParameterModifier[] modifiers) { // According to the spec, we should only expect these 4, so we guard against that here! Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!"); Debug.Assert(binder == null && returnType == null && types == null && modifiers == null, "One of binder, returnType, types, or modifiers was not null"); if (name == _Property1.Name) return _Property1; else return null; } // Advertise our property... // I think that is this one returns an empty array => you don't get intellisense/autocomplete in IDE/FSI public override System.Reflection.PropertyInfo[] GetProperties(System.Reflection.BindingFlags bindingAttr) { // According to the spec, we should only expect these 4, so we guard against that here! Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!"); return new PropertyInfo[] { _Property1 }; } // No fields... public override System.Reflection.FieldInfo GetField(string name, System.Reflection.BindingFlags bindingAttr) { // According to the spec, we should only expect these 4, so we guard against that here! Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!"); return null; } public override System.Reflection.FieldInfo[] GetFields(System.Reflection.BindingFlags bindingAttr) { // According to the spec, we should only expect these 4, so we guard against that here! Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!"); return new System.Reflection.FieldInfo[] { }; } // Events public override System.Reflection.EventInfo GetEvent(string name, System.Reflection.BindingFlags bindingAttr) { // According to the spec, we should only expect these 4, so we guard against that here! Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!"); if (_Event1 != null && _Event1.Name == name) return _Event1; else return null; } // Events... public override System.Reflection.EventInfo[] GetEvents(System.Reflection.BindingFlags bindingAttr) { return _Event1 != null ? new [] { _Event1 } : new System.Reflection.EventInfo[] { }; } // TODO: according to the spec, this should not be invoked... instead it seems like it may be invoked... // ?? I have no idea what this is used for... ?? public override Type UnderlyingSystemType { get { return null; } } // According to the spec, this should always be 'false' protected override bool IsArrayImpl() { return false; } // No interfaces... public override Type[] GetInterfaces() { return new Type[] { }; } // No nested type // This method is invoked on the type 'T', e.g.: // let _ = N.T.M // to figure out if M is a nested type. public override Type GetNestedType(string name, System.Reflection.BindingFlags bindingAttr) { return null; } public override Type[] GetNestedTypes(System.Reflection.BindingFlags bindingAttr) { // According to the spec, we should only expect these 4, so we guard against that here! Debug.Assert(bindingAttr == (BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly), "bindingAttr has value not according to the spec!"); return new Type[] { }; } // This one is invoked when the type has a .ctor // and the code looks like // let _ = new N.T() // for example. // It was observed that the // TODO: cover both cases! public override bool IsGenericType { get { return _IsGenericType; } } // This is invoked if the IsGenericType is true public override Type[] GetGenericArguments() { if (_IsGenericType) return new Type[] { typeof(int), typeof(decimal), typeof(System.Guid) }; // This is currently triggering an ICE... else { Debug.Assert(false, "Why are we here?"); throw new NotImplementedException(); } } // This one seems to be invoked when compiling something like // let a = new N.T() // Let's just stay away from generics... public override bool IsGenericTypeDefinition { get { return _IsGenericType; } } // This one seems to be invoked when compiling something like // let a = new N.T() // Let's just stay away from generics... public override bool ContainsGenericParameters { get { return _IsGenericType; } } // This one seems to be checked when in IDE. // let b = N.T( protected override bool IsValueTypeImpl() { return _IsValueType; } // This one seems to be checked when in IDE. // let b = N.T( protected override bool IsByRefImpl() { return _IsByRef; } // This one seems to be checked when in IDE. // let b = N.T( public override bool IsEnum { get { return _IsEnum; } } // This one seems to be checked when in IDE. // let b = N.T( protected override bool IsPointerImpl() { return _IsPointer; } public override string AssemblyQualifiedName { get { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } } public override Guid GUID { get { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } } protected override System.Reflection.ConstructorInfo GetConstructorImpl(System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers) { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } public override Type GetElementType() { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } public override Type GetInterface(string name, bool ignoreCase) { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } public override System.Reflection.MemberInfo[] GetMembers(System.Reflection.BindingFlags bindingAttr) { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } protected override System.Reflection.MethodInfo GetMethodImpl(string name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, System.Reflection.ParameterModifier[] modifiers) { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } protected override bool HasElementTypeImpl() { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } public override object InvokeMember(string name, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, object target, object[] args, System.Reflection.ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } protected override bool IsCOMObjectImpl() { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } protected override bool IsPrimitiveImpl() { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } public override System.Reflection.Module Module { get { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } } public override bool IsDefined(Type attributeType, bool inherit) { Debug.Assert(false, "NYI"); throw new NotImplementedException(); } public override MethodBase DeclaringMethod { get { Debug.Assert(false, "NYI"); return base.DeclaringMethod; } } // This one is invoked by the F# compiler! public override Type DeclaringType { get { return null; // base.DeclaringType; } } public override Type[] FindInterfaces(TypeFilter filter, object filterCriteria) { Debug.Assert(false, "NYI"); return base.FindInterfaces(filter, filterCriteria); } public override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria) { Debug.Assert(false, "NYI"); return base.FindMembers(memberType, bindingAttr, filter, filterCriteria); } public override GenericParameterAttributes GenericParameterAttributes { get { Debug.Assert(false, "NYI"); return base.GenericParameterAttributes; } } public override int GenericParameterPosition { get { Debug.Assert(false, "NYI"); return base.GenericParameterPosition; } } public override int GetArrayRank() { Debug.Assert(false, "NYI"); return base.GetArrayRank(); } public override MemberInfo[] GetDefaultMembers() { Debug.Assert(false, "NYI"); return base.GetDefaultMembers(); } public override string GetEnumName(object value) { Debug.Assert(false, "NYI"); return base.GetEnumName(value); } public override string[] GetEnumNames() { Debug.Assert(false, "NYI"); return base.GetEnumNames(); } public override Type GetEnumUnderlyingType() { Debug.Assert(false, "NYI"); return base.GetEnumUnderlyingType(); } public override Array GetEnumValues() { Debug.Assert(false, "NYI"); return base.GetEnumValues(); } public override EventInfo[] GetEvents() { Debug.Assert(false, "NYI"); return base.GetEvents(); } public override Type[] GetGenericParameterConstraints() { Debug.Assert(false, "NYI"); return base.GetGenericParameterConstraints(); } public override Type GetGenericTypeDefinition() { Debug.Assert(false, "NYI"); return base.GetGenericTypeDefinition(); } public override InterfaceMapping GetInterfaceMap(Type interfaceType) { Debug.Assert(false, "NYI"); return base.GetInterfaceMap(interfaceType); } public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { Debug.Assert(false, "NYI"); return base.GetMember(name, bindingAttr); } public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { Debug.Assert(false, "NYI"); return base.GetMember(name, type, bindingAttr); } protected override TypeCode GetTypeCodeImpl() { Debug.Assert(false, "NYI"); return base.GetTypeCodeImpl(); } public override bool IsAssignableFrom(Type c) { Debug.Assert(false, "NYI"); return base.IsAssignableFrom(c); } protected override bool IsContextfulImpl() { Debug.Assert(false, "NYI"); return base.IsContextfulImpl(); } public override bool IsEnumDefined(object value) { Debug.Assert(false, "NYI"); return base.IsEnumDefined(value); } public override bool IsEquivalentTo(Type other) { Debug.Assert(false, "NYI"); return base.IsEquivalentTo(other); } public override bool IsGenericParameter { get { Debug.Assert(false, "NYI"); return base.IsGenericParameter; } } public override bool IsInstanceOfType(object o) { Debug.Assert(false, "NYI"); return base.IsInstanceOfType(o); } protected override bool IsMarshalByRefImpl() { Debug.Assert(false, "NYI"); return base.IsMarshalByRefImpl(); } public override bool IsSecurityCritical { get { Debug.Assert(false, "NYI"); return base.IsSecurityCritical; } } public override bool IsSecuritySafeCritical { get { Debug.Assert(false, "NYI"); return base.IsSecuritySafeCritical; } } public override bool IsSecurityTransparent { get { Debug.Assert(false, "NYI"); return base.IsSecurityTransparent; } } public override bool IsSerializable { get { Debug.Assert(false, "NYI"); return base.IsSerializable; } } public override bool IsSubclassOf(Type c) { Debug.Assert(false, "NYI"); return base.IsSubclassOf(c); } public override Type MakeArrayType() { Debug.Assert(false, "NYI"); return base.MakeArrayType(); } public override Type MakeArrayType(int rank) { Debug.Assert(false, "NYI"); return base.MakeArrayType(rank); } public override Type MakeByRefType() { return base.MakeByRefType(); } public override Type MakeGenericType(params Type[] typeArguments) { Debug.Assert(false, "NYI"); return base.MakeGenericType(typeArguments); } public override Type MakePointerType() { Debug.Assert(false, "NYI"); return base.MakePointerType(); } public override MemberTypes MemberType { get { Debug.Assert(false, "NYI"); return base.MemberType; } } public override int MetadataToken { get { Debug.Assert(false, "NYI"); return base.MetadataToken; } } public override Type ReflectedType { get { Debug.Assert(false, "NYI"); return base.ReflectedType; } } public override System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute { get { Debug.Assert(false, "NYI"); return base.StructLayoutAttribute; } } public override RuntimeTypeHandle TypeHandle { get { Debug.Assert(false, "NYI"); return base.TypeHandle; } } public override string ToString() { Debug.Assert(false, "NYI"); return base.ToString(); } public override IList<CustomAttributeData> GetCustomAttributesData() { var attrs = new List<CustomAttributeData>(); attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderXmlDocAttribute("This is a synthetic type created by me!"))); attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderDefinitionLocationAttribute() { Column = 21, FilePath = "File.fs", Line = 50 })); attrs.Add(new Helpers.TypeProviderCustomAttributeData(new TypeProviderEditorHideMethodsAttribute())); return attrs; } } }
namespace StockSharp.Algo.Storages.Binary.Snapshot { using System; using System.Runtime.InteropServices; using Ecng.Common; using Ecng.Interop; using StockSharp.Messages; /// <summary> /// Implementation of <see cref="ISnapshotSerializer{TKey,TMessage}"/> in binary format for <see cref="Level1ChangeMessage"/>. /// </summary> public class Level1BinarySnapshotSerializer : ISnapshotSerializer<SecurityId, Level1ChangeMessage> { [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] private struct Level1Snapshot { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string SecurityId; public long LastChangeServerTime; public long LastChangeLocalTime; public BlittableDecimal? OpenPrice; public BlittableDecimal? HighPrice; public BlittableDecimal? LowPrice; public BlittableDecimal? ClosePrice; public BlittableDecimal? StepPrice; public BlittableDecimal? IV; public BlittableDecimal? TheorPrice; public BlittableDecimal? OI; public BlittableDecimal? MinPrice; public BlittableDecimal? MaxPrice; public BlittableDecimal? BidsVolume; public int? BidsCount; public BlittableDecimal? AsksVolume; public int? AsksCount; public BlittableDecimal? HV; public BlittableDecimal? Delta; public BlittableDecimal? Gamma; public BlittableDecimal? Vega; public BlittableDecimal? Theta; public BlittableDecimal? MarginBuy; public BlittableDecimal? MarginSell; public BlittableDecimal? PriceStep; public BlittableDecimal? VolumeStep; public byte? State; public BlittableDecimal? LastTradePrice; public BlittableDecimal? LastTradeVolume; public BlittableDecimal? Volume; public BlittableDecimal? AveragePrice; public BlittableDecimal? SettlementPrice; public BlittableDecimal? Change; public BlittableDecimal? BestBidPrice; public BlittableDecimal? BestBidVolume; public BlittableDecimal? BestAskPrice; public BlittableDecimal? BestAskVolume; public BlittableDecimal? Rho; public BlittableDecimal? AccruedCouponIncome; public BlittableDecimal? HighBidPrice; public BlittableDecimal? LowAskPrice; public BlittableDecimal? Yield; public long? LastTradeTime; public int? TradesCount; public BlittableDecimal? VWAP; public long? LastTradeId; public long? BestBidTime; public long? BestAskTime; public byte? LastTradeUpDown; public byte? LastTradeOrigin; public BlittableDecimal? Multiplier; public BlittableDecimal? PriceEarnings; public BlittableDecimal? ForwardPriceEarnings; public BlittableDecimal? PriceEarningsGrowth; public BlittableDecimal? PriceSales; public BlittableDecimal? PriceBook; public BlittableDecimal? PriceCash; public BlittableDecimal? PriceFreeCash; public BlittableDecimal? Payout; public BlittableDecimal? SharesOutstanding; public BlittableDecimal? SharesFloat; public BlittableDecimal? FloatShort; public BlittableDecimal? ShortRatio; public BlittableDecimal? ReturnOnAssets; public BlittableDecimal? ReturnOnEquity; public BlittableDecimal? ReturnOnInvestment; public BlittableDecimal? CurrentRatio; public BlittableDecimal? QuickRatio; public BlittableDecimal? LongTermDebtEquity; public BlittableDecimal? TotalDebtEquity; public BlittableDecimal? GrossMargin; public BlittableDecimal? OperatingMargin; public BlittableDecimal? ProfitMargin; public BlittableDecimal? Beta; public BlittableDecimal? AverageTrueRange; public BlittableDecimal? HistoricalVolatilityWeek; public BlittableDecimal? HistoricalVolatilityMonth; public byte? IsSystem; public int? Decimals; public BlittableDecimal? Duration; public BlittableDecimal? IssueSize; public long? BuyBackDate; public BlittableDecimal? BuyBackPrice; public BlittableDecimal? Turnover; public BlittableDecimal? SpreadMiddle; public BlittableDecimal? Dividend; public BlittableDecimal? AfterSplit; public BlittableDecimal? BeforeSplit; public BlittableDecimal? CommissionTaker; public BlittableDecimal? CommissionMaker; public BlittableDecimal? MinVolume; public BlittableDecimal? UnderlyingMinVolume; public BlittableDecimal? CouponValue; public long? CouponDate; public BlittableDecimal? CouponPeriod; public BlittableDecimal? MarketPriceYesterday; public BlittableDecimal? MarketPriceToday; public BlittableDecimal? VWAPPrev; public BlittableDecimal? YieldVWAP; public BlittableDecimal? YieldVWAPPrev; public BlittableDecimal? Index; public BlittableDecimal? Imbalance; public BlittableDecimal? UnderlyingPrice; public BlittableDecimal? MaxVolume; public BlittableDecimal? LowBidPrice; public BlittableDecimal? HighAskPrice; public BlittableDecimal? LastTradeVolumeLow; public BlittableDecimal? LastTradeVolumeHigh; public BlittableDecimal? OptionMargin; public BlittableDecimal? OptionSyntheticMargin; public long SeqNum; public SnapshotDataType? BuildFrom; public BlittableDecimal? LowBidVolume; public BlittableDecimal? HighAskVolume; public BlittableDecimal? UnderlyingBestBidPrice; public BlittableDecimal? UnderlyingBestAskPrice; public BlittableDecimal? MedianPrice; public BlittableDecimal? HighPrice52Week; public BlittableDecimal? LowPrice52Week; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = Sizes.S100)] public string LastTradeStringId; } Version ISnapshotSerializer<SecurityId, Level1ChangeMessage>.Version { get; } = SnapshotVersions.V23; string ISnapshotSerializer<SecurityId, Level1ChangeMessage>.Name => "Level1"; byte[] ISnapshotSerializer<SecurityId, Level1ChangeMessage>.Serialize(Version version, Level1ChangeMessage message) { if (version == null) throw new ArgumentNullException(nameof(version)); if (message == null) throw new ArgumentNullException(nameof(message)); var snapshot = new Level1Snapshot { SecurityId = message.SecurityId.ToStringId().VerifySize(Sizes.S100), LastChangeServerTime = message.ServerTime.To<long>(), LastChangeLocalTime = message.LocalTime.To<long>(), BuildFrom = message.BuildFrom == null ? default(SnapshotDataType?) : (SnapshotDataType)message.BuildFrom, SeqNum = message.SeqNum, }; foreach (var change in message.Changes) { switch (change.Key) { case Level1Fields.OpenPrice: snapshot.OpenPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.HighPrice: snapshot.HighPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LowPrice: snapshot.LowPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.ClosePrice: snapshot.ClosePrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.StepPrice: snapshot.StepPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.ImpliedVolatility: snapshot.IV = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.TheorPrice: snapshot.TheorPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.OpenInterest: snapshot.OI = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MinPrice: snapshot.MinPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MaxPrice: snapshot.MaxPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BidsVolume: snapshot.BidsVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BidsCount: snapshot.BidsCount = (int)change.Value; break; case Level1Fields.AsksVolume: snapshot.AsksVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.AsksCount: snapshot.AsksCount = (int)change.Value; break; case Level1Fields.HistoricalVolatility: snapshot.HV = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Delta: snapshot.Delta = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Gamma: snapshot.Gamma = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Vega: snapshot.Vega = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Theta: snapshot.Theta = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MarginBuy: snapshot.MarginBuy = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MarginSell: snapshot.MarginSell = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.State: snapshot.State = (byte)(SecurityStates)change.Value; break; case Level1Fields.LastTradePrice: snapshot.LastTradePrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LastTradeVolume: snapshot.LastTradeVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Volume: snapshot.Volume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.AveragePrice: snapshot.AveragePrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.SettlementPrice: snapshot.SettlementPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Change: snapshot.Change = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BestBidPrice: snapshot.BestBidPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BestBidVolume: snapshot.BestBidVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BestAskPrice: snapshot.BestAskPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BestAskVolume: snapshot.BestAskVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Rho: snapshot.Rho = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.AccruedCouponIncome: snapshot.AccruedCouponIncome = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.HighBidPrice: snapshot.HighBidPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LowAskPrice: snapshot.LowAskPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Yield: snapshot.Yield = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LastTradeTime: snapshot.LastTradeTime = change.Value.To<long>(); break; case Level1Fields.TradesCount: snapshot.TradesCount = (int)change.Value; break; case Level1Fields.VWAP: snapshot.VWAP = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LastTradeId: snapshot.LastTradeId = (long)change.Value; break; case Level1Fields.LastTradeUpDown: snapshot.LastTradeUpDown = (bool)change.Value ? (byte?)1 : 0; break; case Level1Fields.LastTradeOrigin: snapshot.LastTradeOrigin = (byte)(Sides)change.Value; break; case Level1Fields.Beta: snapshot.Beta = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.AverageTrueRange: snapshot.AverageTrueRange = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Duration: snapshot.Duration = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Turnover: snapshot.Turnover = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.SpreadMiddle: snapshot.SpreadMiddle = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.PriceEarnings: snapshot.PriceEarnings = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.ForwardPriceEarnings: snapshot.ForwardPriceEarnings = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.PriceEarningsGrowth: snapshot.PriceEarningsGrowth = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.PriceSales: snapshot.PriceSales = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.PriceBook: snapshot.PriceBook = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.PriceCash: snapshot.PriceCash = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.PriceFreeCash: snapshot.PriceFreeCash = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Payout: snapshot.Payout = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.SharesOutstanding: snapshot.SharesOutstanding = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.SharesFloat: snapshot.SharesFloat = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.FloatShort: snapshot.FloatShort = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.ShortRatio: snapshot.ShortRatio = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.ReturnOnAssets: snapshot.ReturnOnAssets = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.ReturnOnEquity: snapshot.ReturnOnEquity = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.ReturnOnInvestment: snapshot.ReturnOnInvestment = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.CurrentRatio: snapshot.CurrentRatio = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.QuickRatio: snapshot.QuickRatio = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.HistoricalVolatilityWeek: snapshot.HistoricalVolatilityWeek = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.HistoricalVolatilityMonth: snapshot.HistoricalVolatilityMonth = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.IssueSize: snapshot.IssueSize = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BuyBackPrice: snapshot.BuyBackPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BuyBackDate: snapshot.BuyBackDate = change.Value.To<long>(); break; case Level1Fields.Dividend: snapshot.Dividend = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.AfterSplit: snapshot.AfterSplit = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BeforeSplit: snapshot.BeforeSplit = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.CommissionTaker: snapshot.CommissionTaker = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.CommissionMaker: snapshot.CommissionMaker = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MinVolume: snapshot.MinVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.UnderlyingMinVolume: snapshot.UnderlyingMinVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.CouponValue: snapshot.CouponValue = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.CouponDate: snapshot.CouponDate = ((DateTimeOffset)change.Value).To<long>(); break; case Level1Fields.CouponPeriod: snapshot.CouponPeriod = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MarketPriceYesterday: snapshot.MarketPriceYesterday = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MarketPriceToday: snapshot.MarketPriceToday = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.VWAPPrev: snapshot.VWAPPrev = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.YieldVWAP: snapshot.YieldVWAP = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.YieldVWAPPrev: snapshot.YieldVWAPPrev = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Index: snapshot.Index = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.Imbalance: snapshot.Imbalance = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.UnderlyingPrice: snapshot.UnderlyingPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MaxVolume: snapshot.MaxVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LowBidPrice: snapshot.LowBidPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.HighAskPrice: snapshot.HighAskPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LastTradeVolumeLow: snapshot.LastTradeVolumeLow = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LastTradeVolumeHigh: snapshot.LastTradeVolumeHigh = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.OptionMargin: snapshot.OptionMargin = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.OptionSyntheticMargin: snapshot.OptionSyntheticMargin = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.PriceStep: snapshot.PriceStep = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.VolumeStep: snapshot.VolumeStep = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.BestBidTime: snapshot.BestBidTime = ((DateTimeOffset)change.Value).To<long>(); break; case Level1Fields.BestAskTime: snapshot.BestAskTime = ((DateTimeOffset)change.Value).To<long>(); break; case Level1Fields.Multiplier: snapshot.Multiplier = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LongTermDebtEquity: snapshot.LongTermDebtEquity = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.TotalDebtEquity: snapshot.TotalDebtEquity = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.GrossMargin: snapshot.GrossMargin = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.OperatingMargin: snapshot.OperatingMargin = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.ProfitMargin: snapshot.ProfitMargin = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.IsSystem: snapshot.IsSystem = ((bool)change.Value).ToByte(); break; case Level1Fields.Decimals: snapshot.Decimals = (int)change.Value; break; case Level1Fields.LowBidVolume: snapshot.LowBidVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.HighAskVolume: snapshot.HighAskVolume = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.UnderlyingBestBidPrice: snapshot.UnderlyingBestBidPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.UnderlyingBestAskPrice: snapshot.UnderlyingBestAskPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.MedianPrice: snapshot.MedianPrice = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.HighPrice52Week: snapshot.HighPrice52Week = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LowPrice52Week: snapshot.LowPrice52Week = (BlittableDecimal)(decimal)change.Value; break; case Level1Fields.LastTradeStringId: snapshot.LastTradeStringId = (string)change.Value; break; } } var buffer = new byte[typeof(Level1Snapshot).SizeOf()]; var ptr = snapshot.StructToPtr(); ptr.CopyTo(buffer); ptr.FreeHGlobal(); return buffer; } Level1ChangeMessage ISnapshotSerializer<SecurityId, Level1ChangeMessage>.Deserialize(Version version, byte[] buffer) { if (version == null) throw new ArgumentNullException(nameof(version)); using (var handle = new GCHandle<byte[]>(buffer)) { var snapshot = handle.CreatePointer().ToStruct<Level1Snapshot>(true); var level1Msg = new Level1ChangeMessage { SecurityId = snapshot.SecurityId.ToSecurityId(), ServerTime = snapshot.LastChangeServerTime.To<DateTimeOffset>(), LocalTime = snapshot.LastChangeLocalTime.To<DateTimeOffset>(), BuildFrom = snapshot.BuildFrom, SeqNum = snapshot.SeqNum, }; level1Msg .TryAdd(Level1Fields.LastTradePrice, snapshot.LastTradePrice) .TryAdd(Level1Fields.LastTradeVolume, snapshot.LastTradeVolume) .TryAdd(Level1Fields.LastTradeId, snapshot.LastTradeId) .TryAdd(Level1Fields.BestBidPrice, snapshot.BestBidPrice) .TryAdd(Level1Fields.BestAskPrice, snapshot.BestAskPrice) .TryAdd(Level1Fields.BestBidVolume, snapshot.BestBidVolume) .TryAdd(Level1Fields.BestAskVolume, snapshot.BestAskVolume) .TryAdd(Level1Fields.BidsVolume, snapshot.BidsVolume) .TryAdd(Level1Fields.AsksVolume, snapshot.AsksVolume) .TryAdd(Level1Fields.BidsCount, snapshot.BidsCount) .TryAdd(Level1Fields.AsksCount, snapshot.AsksCount) .TryAdd(Level1Fields.HighBidPrice, snapshot.HighBidPrice) .TryAdd(Level1Fields.LowAskPrice, snapshot.LowAskPrice) .TryAdd(Level1Fields.OpenPrice, snapshot.OpenPrice) .TryAdd(Level1Fields.HighPrice, snapshot.HighPrice) .TryAdd(Level1Fields.LowPrice, snapshot.LowPrice) .TryAdd(Level1Fields.ClosePrice, snapshot.ClosePrice) .TryAdd(Level1Fields.Volume, snapshot.Volume) .TryAdd(Level1Fields.StepPrice, snapshot.StepPrice) .TryAdd(Level1Fields.OpenInterest, snapshot.OI) .TryAdd(Level1Fields.MinPrice, snapshot.MinPrice) .TryAdd(Level1Fields.MaxPrice, snapshot.MaxPrice) .TryAdd(Level1Fields.MarginBuy, snapshot.MarginBuy) .TryAdd(Level1Fields.MarginSell, snapshot.MarginSell) .TryAdd(Level1Fields.ImpliedVolatility, snapshot.IV) .TryAdd(Level1Fields.HistoricalVolatility, snapshot.HV) .TryAdd(Level1Fields.TheorPrice, snapshot.TheorPrice) .TryAdd(Level1Fields.Delta, snapshot.Delta) .TryAdd(Level1Fields.Gamma, snapshot.Gamma) .TryAdd(Level1Fields.Vega, snapshot.Vega) .TryAdd(Level1Fields.Theta, snapshot.Theta) .TryAdd(Level1Fields.Rho, snapshot.Rho) .TryAdd(Level1Fields.AveragePrice, snapshot.AveragePrice) .TryAdd(Level1Fields.SettlementPrice, snapshot.SettlementPrice) .TryAdd(Level1Fields.Change, snapshot.Change) .TryAdd(Level1Fields.AccruedCouponIncome, snapshot.AccruedCouponIncome) .TryAdd(Level1Fields.Yield, snapshot.Yield) .TryAdd(Level1Fields.VWAP, snapshot.VWAP) .TryAdd(Level1Fields.TradesCount, snapshot.TradesCount) .TryAdd(Level1Fields.Beta, snapshot.Beta) .TryAdd(Level1Fields.AverageTrueRange, snapshot.AverageTrueRange) .TryAdd(Level1Fields.Duration, snapshot.Duration) .TryAdd(Level1Fields.Turnover, snapshot.Turnover) .TryAdd(Level1Fields.SpreadMiddle, snapshot.SpreadMiddle) .TryAdd(Level1Fields.PriceEarnings, snapshot.PriceEarnings) .TryAdd(Level1Fields.ForwardPriceEarnings, snapshot.ForwardPriceEarnings) .TryAdd(Level1Fields.PriceEarningsGrowth, snapshot.PriceEarningsGrowth) .TryAdd(Level1Fields.PriceSales, snapshot.PriceSales) .TryAdd(Level1Fields.PriceBook, snapshot.PriceBook) .TryAdd(Level1Fields.PriceCash, snapshot.PriceCash) .TryAdd(Level1Fields.PriceFreeCash, snapshot.PriceFreeCash) .TryAdd(Level1Fields.Payout, snapshot.Payout) .TryAdd(Level1Fields.SharesOutstanding, snapshot.SharesOutstanding) .TryAdd(Level1Fields.SharesFloat, snapshot.SharesFloat) .TryAdd(Level1Fields.FloatShort, snapshot.FloatShort) .TryAdd(Level1Fields.ShortRatio, snapshot.ShortRatio) .TryAdd(Level1Fields.ReturnOnAssets, snapshot.ReturnOnAssets) .TryAdd(Level1Fields.ReturnOnEquity, snapshot.ReturnOnEquity) .TryAdd(Level1Fields.ReturnOnInvestment, snapshot.ReturnOnInvestment) .TryAdd(Level1Fields.CurrentRatio, snapshot.CurrentRatio) .TryAdd(Level1Fields.QuickRatio, snapshot.QuickRatio) .TryAdd(Level1Fields.HistoricalVolatilityWeek, snapshot.HistoricalVolatilityWeek) .TryAdd(Level1Fields.HistoricalVolatilityMonth, snapshot.HistoricalVolatilityMonth) .TryAdd(Level1Fields.IssueSize, snapshot.IssueSize) .TryAdd(Level1Fields.BuyBackPrice, snapshot.BuyBackPrice) .TryAdd(Level1Fields.Dividend, snapshot.Dividend) .TryAdd(Level1Fields.AfterSplit, snapshot.AfterSplit) .TryAdd(Level1Fields.BeforeSplit, snapshot.BeforeSplit) .TryAdd(Level1Fields.CommissionTaker, snapshot.CommissionTaker) .TryAdd(Level1Fields.CommissionMaker, snapshot.CommissionMaker) .TryAdd(Level1Fields.MinVolume, snapshot.MinVolume) .TryAdd(Level1Fields.UnderlyingMinVolume, snapshot.UnderlyingMinVolume) .TryAdd(Level1Fields.CouponValue, snapshot.CouponValue) .TryAdd(Level1Fields.CouponDate, snapshot.CouponDate?.To<DateTimeOffset>()) .TryAdd(Level1Fields.CouponPeriod, snapshot.CouponPeriod) .TryAdd(Level1Fields.MarketPriceYesterday, snapshot.MarketPriceYesterday) .TryAdd(Level1Fields.MarketPriceToday, snapshot.MarketPriceToday) .TryAdd(Level1Fields.VWAPPrev, snapshot.VWAPPrev) .TryAdd(Level1Fields.YieldVWAP, snapshot.YieldVWAP) .TryAdd(Level1Fields.YieldVWAPPrev, snapshot.YieldVWAPPrev) .TryAdd(Level1Fields.Index, snapshot.Index) .TryAdd(Level1Fields.Imbalance, snapshot.Imbalance) .TryAdd(Level1Fields.UnderlyingPrice, snapshot.UnderlyingPrice) .TryAdd(Level1Fields.MaxVolume, snapshot.MaxVolume) .TryAdd(Level1Fields.LowBidPrice, snapshot.LowBidPrice) .TryAdd(Level1Fields.HighAskPrice, snapshot.HighAskPrice) .TryAdd(Level1Fields.LastTradeVolumeLow, snapshot.LastTradeVolumeLow) .TryAdd(Level1Fields.LastTradeVolumeHigh, snapshot.LastTradeVolumeHigh) .TryAdd(Level1Fields.OptionMargin, snapshot.OptionMargin) .TryAdd(Level1Fields.OptionSyntheticMargin, snapshot.OptionSyntheticMargin) .TryAdd(Level1Fields.PriceStep, snapshot.PriceStep) .TryAdd(Level1Fields.VolumeStep, snapshot.VolumeStep) .TryAdd(Level1Fields.BestBidTime, snapshot.BestBidTime?.To<DateTimeOffset>()) .TryAdd(Level1Fields.BestAskTime, snapshot.BestAskTime?.To<DateTimeOffset>()) .TryAdd(Level1Fields.Multiplier, snapshot.Multiplier) .TryAdd(Level1Fields.LongTermDebtEquity, snapshot.LongTermDebtEquity) .TryAdd(Level1Fields.TotalDebtEquity, snapshot.TotalDebtEquity) .TryAdd(Level1Fields.GrossMargin, snapshot.GrossMargin) .TryAdd(Level1Fields.OperatingMargin, snapshot.OperatingMargin) .TryAdd(Level1Fields.ProfitMargin, snapshot.ProfitMargin) .TryAdd(Level1Fields.IsSystem, snapshot.IsSystem?.ToBool()) .TryAdd(Level1Fields.Decimals, snapshot.Decimals, true) .TryAdd(Level1Fields.LowBidVolume, snapshot.LowBidVolume) .TryAdd(Level1Fields.HighAskVolume, snapshot.HighAskVolume) .TryAdd(Level1Fields.UnderlyingBestBidPrice, snapshot.UnderlyingBestBidPrice) .TryAdd(Level1Fields.UnderlyingBestAskPrice, snapshot.UnderlyingBestAskPrice) .TryAdd(Level1Fields.MedianPrice, snapshot.MedianPrice) .TryAdd(Level1Fields.HighPrice52Week, snapshot.HighPrice52Week) .TryAdd(Level1Fields.LowPrice52Week, snapshot.LowPrice52Week) .TryAdd(Level1Fields.LastTradeStringId, snapshot.LastTradeStringId) ; if (snapshot.LastTradeTime != null) level1Msg.Add(Level1Fields.LastTradeTime, snapshot.LastTradeTime.Value.To<DateTimeOffset>()); if (snapshot.LastTradeUpDown != null) level1Msg.Add(Level1Fields.LastTradeUpDown, snapshot.LastTradeUpDown.Value == 1); if (snapshot.LastTradeOrigin != null) level1Msg.Add(Level1Fields.LastTradeOrigin, (Sides)snapshot.LastTradeOrigin.Value); if (snapshot.State != null) level1Msg.Add(Level1Fields.State, (SecurityStates)snapshot.State.Value); if (snapshot.BuyBackDate != null) level1Msg.Add(Level1Fields.BuyBackDate, snapshot.BuyBackDate.Value.To<DateTimeOffset>()); return level1Msg; } } SecurityId ISnapshotSerializer<SecurityId, Level1ChangeMessage>.GetKey(Level1ChangeMessage message) { return message.SecurityId; } void ISnapshotSerializer<SecurityId, Level1ChangeMessage>.Update(Level1ChangeMessage message, Level1ChangeMessage changes) { var lastTradeFound = false; var bestBidFound = false; var bestAskFound = false; foreach (var pair in changes.Changes) { var field = pair.Key; if (!lastTradeFound) { if (field.IsLastTradeField()) { message.Changes.Remove(Level1Fields.LastTradeUpDown); message.Changes.Remove(Level1Fields.LastTradeTime); message.Changes.Remove(Level1Fields.LastTradeId); message.Changes.Remove(Level1Fields.LastTradeOrigin); message.Changes.Remove(Level1Fields.LastTradePrice); message.Changes.Remove(Level1Fields.LastTradeVolume); lastTradeFound = true; } } if (!bestBidFound) { if (field.IsBestBidField()) { message.Changes.Remove(Level1Fields.BestBidPrice); message.Changes.Remove(Level1Fields.BestBidTime); message.Changes.Remove(Level1Fields.BestBidVolume); bestBidFound = true; } } if (!bestAskFound) { if (field.IsBestAskField()) { message.Changes.Remove(Level1Fields.BestAskPrice); message.Changes.Remove(Level1Fields.BestAskTime); message.Changes.Remove(Level1Fields.BestAskVolume); bestAskFound = true; } } message.Changes[pair.Key] = pair.Value; } message.LocalTime = changes.LocalTime; message.ServerTime = changes.ServerTime; if (changes.BuildFrom != default) message.BuildFrom = changes.BuildFrom; if (changes.SeqNum != default) message.SeqNum = changes.SeqNum; } DataType ISnapshotSerializer<SecurityId, Level1ChangeMessage>.DataType => DataType.Level1; } }
using System; using System.Drawing; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Net; using DeOps.Implementation; using DeOps.Implementation.Dht; using DeOps.Implementation.Transport; using DeOps.Implementation.Protocol.Net; using DeOps.Services; using DeOps.Services.Assist; using DeOps.Services.Board; using DeOps.Services.Chat; using DeOps.Services.IM; using DeOps.Services.Location; using DeOps.Services.Mail; using DeOps.Services.Profile; using DeOps.Services.Transfer; using DeOps.Services.Trust; namespace DeOps.Interface.Tools { public delegate void ShowDelegate(object pass); /// <summary> /// Summary description for InternalsForm. /// </summary> public class InternalsForm : DeOps.Interface.CustomIconForm { CoreUI UI; OpCore Core; BoardService Boards; MailService Mail; ProfileService Profiles; private System.Windows.Forms.Splitter splitter1; private System.Windows.Forms.TreeView treeStructure; private System.Windows.Forms.ListView listValues; private System.Windows.Forms.Button buttonRefresh; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public static void Show(CoreUI ui) { if (ui.GuiInternal == null) ui.GuiInternal = new InternalsForm(ui); ui.GuiInternal.Show(); ui.GuiInternal.Activate(); } public InternalsForm(CoreUI ui) { // // Required for Windows Form Designer support // InitializeComponent(); UI = ui; Core = ui.Core; Boards = Core.GetService(ServiceIDs.Board) as BoardService; Mail = Core.GetService(ServiceIDs.Mail) as MailService; Profiles = Core.GetService(ServiceIDs.Profile) as ProfileService; Text = "Internals (" + Core.Network.GetLabel() + ")"; treeStructure.Nodes.Add( new StructureNode("", new ShowDelegate(ShowNone), null)); // core // identity // networks (global/operation) // cache // logs // routing // search // store // tcp // Components // Link // Location // ... // rudp // sessions[] // core StructureNode coreNode = new StructureNode("Core", new ShowDelegate(ShowCore), null); // identity coreNode.Nodes.Add( new StructureNode(".Identity", new ShowDelegate(ShowIdentity), null)); // networks if(Core.Context.Lookup != null) LoadNetwork(coreNode.Nodes, "Lookup", Core.Context.Lookup.Network); LoadNetwork(coreNode.Nodes, "Organization", Core.Network); // components StructureNode componentsNode = new StructureNode("Components", new ShowDelegate(ShowNone), null); LoadComponents(componentsNode); coreNode.Nodes.Add(componentsNode); treeStructure.Nodes.Add(coreNode); coreNode.Expand(); } private void LoadComponents(StructureNode componentsNode) { foreach (ushort id in Core.ServiceMap.Keys) { switch (id) { case 1://ServiceID.Trust: StructureNode linkNode = new StructureNode("Links", new ShowDelegate(ShowLinks), null); linkNode.Nodes.Add(new StructureNode("Index", new ShowDelegate(ShowLinkMap), null)); linkNode.Nodes.Add(new StructureNode("Roots", new ShowDelegate(ShowLinkRoots), null)); linkNode.Nodes.Add(new StructureNode("Projects", new ShowDelegate(ShowLinkProjects), null)); componentsNode.Nodes.Add(linkNode); break; case 2://ServiceID.Location: StructureNode locNode = new StructureNode("Locations", new ShowDelegate(ShowLocations), null); locNode.Nodes.Add(new StructureNode("Lookup", new ShowDelegate(ShowLocGlobal), null)); locNode.Nodes.Add(new StructureNode("Organization", new ShowDelegate(ShowLocOperation), null)); componentsNode.Nodes.Add(locNode); break; case 3://ServiceID.Transfer: StructureNode transNode = new StructureNode("Transfers", new ShowDelegate(ShowTransfers), null); transNode.Nodes.Add(new StructureNode("Uploads", new ShowDelegate(ShowUploads), null)); transNode.Nodes.Add(new StructureNode("Downloads", new ShowDelegate(ShowDownloads), null)); componentsNode.Nodes.Add(transNode); break; case 4://ServiceID.Profile: StructureNode profileNode = new StructureNode("Profiles", new ShowDelegate(ShowProfiles), null); componentsNode.Nodes.Add(profileNode); break; case 7://ServiceID.Mail: StructureNode mailNode = new StructureNode("Mail", new ShowDelegate(ShowMail), null); mailNode.Nodes.Add(new StructureNode("Mail", new ShowDelegate(ShowMailMap), null)); mailNode.Nodes.Add(new StructureNode("Acks", new ShowDelegate(ShowAckMap), null)); mailNode.Nodes.Add(new StructureNode("Pending", new ShowDelegate(ShowPendingMap), null)); mailNode.Nodes.Add(new StructureNode("My Pending Mail", new ShowDelegate(ShowPendingMail), null)); mailNode.Nodes.Add(new StructureNode("My Pending Acks", new ShowDelegate(ShowPendingAcks), null)); componentsNode.Nodes.Add(mailNode); break; case 8://ServiceID.Board: StructureNode boardNode = new StructureNode("Board", new ShowDelegate(ShowBoard), null); componentsNode.Nodes.Add(boardNode); break; case 11: // ServiceID.LocalSync StructureNode syncNode = new StructureNode("LocalSync", new ShowDelegate(ShowLocalSync), null); componentsNode.Nodes.Add(syncNode); break; } } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(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.treeStructure = new System.Windows.Forms.TreeView(); this.splitter1 = new System.Windows.Forms.Splitter(); this.listValues = new System.Windows.Forms.ListView(); this.buttonRefresh = new System.Windows.Forms.Button(); this.SuspendLayout(); // // treeStructure // this.treeStructure.BackColor = System.Drawing.Color.WhiteSmoke; this.treeStructure.BorderStyle = System.Windows.Forms.BorderStyle.None; this.treeStructure.Dock = System.Windows.Forms.DockStyle.Left; this.treeStructure.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.treeStructure.FullRowSelect = true; this.treeStructure.HideSelection = false; this.treeStructure.Location = new System.Drawing.Point(0, 0); this.treeStructure.Name = "treeStructure"; this.treeStructure.ShowLines = false; this.treeStructure.Size = new System.Drawing.Size(160, 414); this.treeStructure.Sorted = true; this.treeStructure.TabIndex = 0; this.treeStructure.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeStructure_AfterSelect); // // splitter1 // this.splitter1.Location = new System.Drawing.Point(160, 0); this.splitter1.Name = "splitter1"; this.splitter1.Size = new System.Drawing.Size(3, 414); this.splitter1.TabIndex = 1; this.splitter1.TabStop = false; // // listValues // this.listValues.AllowColumnReorder = true; this.listValues.BorderStyle = System.Windows.Forms.BorderStyle.None; this.listValues.Dock = System.Windows.Forms.DockStyle.Fill; this.listValues.FullRowSelect = true; this.listValues.Location = new System.Drawing.Point(163, 0); this.listValues.Name = "listValues"; this.listValues.Size = new System.Drawing.Size(301, 414); this.listValues.TabIndex = 2; this.listValues.UseCompatibleStateImageBehavior = false; this.listValues.View = System.Windows.Forms.View.Details; this.listValues.MouseClick += new System.Windows.Forms.MouseEventHandler(this.listValues_MouseClick); // // buttonRefresh // this.buttonRefresh.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.buttonRefresh.Location = new System.Drawing.Point(368, 368); this.buttonRefresh.Name = "buttonRefresh"; this.buttonRefresh.Size = new System.Drawing.Size(75, 23); this.buttonRefresh.TabIndex = 3; this.buttonRefresh.Text = "Refresh"; this.buttonRefresh.Click += new System.EventHandler(this.buttonRefresh_Click); // // InternalsForm // this.AcceptButton = this.buttonRefresh; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(464, 414); this.Controls.Add(this.buttonRefresh); this.Controls.Add(this.listValues); this.Controls.Add(this.splitter1); this.Controls.Add(this.treeStructure); this.Name = "InternalsForm"; this.Text = "Internals"; this.Closing += new System.ComponentModel.CancelEventHandler(this.InternalsForm_Closing); this.ResumeLayout(false); } #endregion private void treeStructure_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e) { RefreshView(); } public void ShowNone(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); } public void ShowCore(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 300, HorizontalAlignment.Left); listValues.Items.Add(new ListViewItem(new string[] { "StartTime", xStr(Core.StartTime) })); } public void ShowIdentity(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 300, HorizontalAlignment.Left); listValues.Items.Add(new ListViewItem(new string[] { "ProfilePath", xStr(Core.User.ProfilePath) })); listValues.Items.Add(new ListViewItem(new string[] { "Organization", xStr(Core.User.Settings.Operation) })); listValues.Items.Add(new ListViewItem(new string[] { "ScreenName", xStr(Core.User.Settings.UserName) })); listValues.Items.Add(new ListViewItem(new string[] { "OpPortTcp", xStr(Core.User.Settings.TcpPort) })); listValues.Items.Add(new ListViewItem(new string[] { "OpPortUdp", xStr(Core.User.Settings.UdpPort) })); listValues.Items.Add(new ListViewItem(new string[] { "OpAccess", xStr(Core.User.Settings.OpAccess) })); } public void LoadNetwork(TreeNodeCollection root, string name, DhtNetwork network) { StructureNode netItem = new StructureNode(name, new ShowDelegate(ShowNetwork), network); // cache netItem.Nodes.Add(new StructureNode("Cache", new ShowDelegate(ShowCache), network)); // logs StructureNode logsNode = new StructureNode("Logs", new ShowDelegate(UpdateLogs), network); AddLogs(logsNode, network); netItem.Nodes.Add(logsNode); // routing netItem.Nodes.Add(new StructureNode("Routing", new ShowDelegate(ShowRouting), network)); // search StructureNode searchNode = new StructureNode("Searches", new ShowDelegate(ShowNone), null); StructureNode pendingNode = new StructureNode("Pending", new ShowDelegate(UpdateSearches), network.Searches.Pending); StructureNode activeNode = new StructureNode("Active", new ShowDelegate(UpdateSearches), network.Searches.Active); AddSearchNodes(pendingNode, network.Searches.Pending); AddSearchNodes(activeNode, network.Searches.Active); searchNode.Nodes.Add(pendingNode); searchNode.Nodes.Add(activeNode); netItem.Nodes.Add(searchNode); // store StructureNode storeNode = new StructureNode("Store", new ShowDelegate(ShowStore), network); netItem.Nodes.Add(storeNode); // tcp StructureNode connectionsNode = new StructureNode("Tcp", new ShowDelegate(ShowTcp), network); AddConnectionNodes(connectionsNode, network); netItem.Nodes.Add(connectionsNode); // identity netItem.Nodes.Add(new StructureNode("Rudp", new ShowDelegate(ShowRudp), network)); root.Add(netItem); } public void ShowNetwork(object pass) { DhtNetwork network = pass as DhtNetwork; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 300, HorizontalAlignment.Left); listValues.Items.Add(new ListViewItem(new string[] { "LocalIP", xStr(network.Core.LocalIP) })); listValues.Items.Add(new ListViewItem(new string[] { "Firewall", xStr(network.Core.Firewall) })); listValues.Items.Add(new ListViewItem(new string[] { "LanMode", xStr(network.LanMode) })); listValues.Items.Add(new ListViewItem(new string[] { "LocalDhtID", IDtoStr(network.Local.UserID) })); listValues.Items.Add(new ListViewItem(new string[] { "ClientID", xStr(network.Local.ClientID) })); listValues.Items.Add(new ListViewItem(new string[] { "OpID", IDtoStr(network.OpID) })); listValues.Items.Add(new ListViewItem(new string[] { "Responsive", xStr(network.Responsive) })); listValues.Items.Add(new ListViewItem(new string[] { "Established", xStr(network.Established) })); if (!network.IsLookup) { listValues.Items.Add(new ListViewItem(new string[] { "UseGlobalProxies", xStr(network.UseLookupProxies) })); listValues.Items.Add(new ListViewItem(new string[] { "TunnelID", xStr(network.Core.TunnelID) })); } listValues.Items.Add(new ListViewItem(new string[] { "IPCache", xStr(network.Cache.IPs.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "IPTable", xStr(network.Cache.IPTable.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "Searches Pending", xStr(network.Searches.Pending.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "Searches Active", xStr(network.Searches.Active.Count) })); } public void ShowCache(object pass) { DhtNetwork network = pass as DhtNetwork; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Address", 100, HorizontalAlignment.Left); listValues.Columns.Add("TcpPort", 100, HorizontalAlignment.Left); listValues.Columns.Add("UdpPort", 100, HorizontalAlignment.Left); listValues.Columns.Add("DhtID", 100, HorizontalAlignment.Left); listValues.Columns.Add("NextTry", 150, HorizontalAlignment.Left); listValues.Columns.Add("NextTryTcp",150, HorizontalAlignment.Left); foreach (DhtContact entry in network.Cache.IPs) listValues.Items.Add( new ListViewItem( new string[] { xStr(entry.IP), xStr(entry.TcpPort), xStr(entry.UdpPort), xStr(Utilities.IDtoBin(entry.UserID)), xStr(entry.NextTry), xStr(entry.NextTryProxy) })); } public void UpdateSearches(object pass) { List<DhtSearch> searchList = pass as List<DhtSearch>; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Name", 100, HorizontalAlignment.Left); listValues.Columns.Add("Service", 100, HorizontalAlignment.Left); listValues.Columns.Add("Target", 100, HorizontalAlignment.Left); listValues.Columns.Add("SearchID", 100, HorizontalAlignment.Left); listValues.Columns.Add("LookupList", 100, HorizontalAlignment.Left); listValues.Columns.Add("Finished", 100, HorizontalAlignment.Left); listValues.Columns.Add("FinishReason", 100, HorizontalAlignment.Left); listValues.Columns.Add("FoundProxy", 100, HorizontalAlignment.Left); listValues.Columns.Add("ProxyTcp", 100, HorizontalAlignment.Left); listValues.Columns.Add("FoundContact", 100, HorizontalAlignment.Left); listValues.Columns.Add("FoundValues", 100, HorizontalAlignment.Left); lock(searchList) foreach (DhtSearch search in searchList) listValues.Items.Add( new ListViewItem( new string[] { xStr(search.Name), xStr(Core.GetServiceName(search.Service)), IDtoStr(search.TargetID), xStr(search.SearchID), xStr(search.LookupList.Count), xStr(search.Finished), xStr(search.FinishReason), xStr(search.FoundProxy), xStr(search.ProxyTcp), xStr(search.FoundContact), xStr(search.FoundValues.Count) })); AddSearchNodes((StructureNode)treeStructure.SelectedNode, searchList); } public void AddSearchNodes(StructureNode parentNode, List<DhtSearch> searchList) { parentNode.Nodes.Clear(); foreach(DhtSearch search in searchList) parentNode.Nodes.Add( new StructureNode(search.Name, new ShowDelegate(ShowSearch), search)); } public void ShowSearch(object pass) { DhtSearch search = (DhtSearch) pass; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Satus", 100, HorizontalAlignment.Left); listValues.Columns.Add("Age", 100, HorizontalAlignment.Left); listValues.Columns.Add("DhtID", 100, HorizontalAlignment.Left); listValues.Columns.Add("ClientID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Address", 100, HorizontalAlignment.Left); listValues.Columns.Add("TcpPort", 100, HorizontalAlignment.Left); listValues.Columns.Add("UdpPort", 100, HorizontalAlignment.Left); listValues.Columns.Add("LastSeen", 100, HorizontalAlignment.Left); listValues.Columns.Add("Attempts", 100, HorizontalAlignment.Left); listValues.Columns.Add("NextTryProxy", 100, HorizontalAlignment.Left); foreach (DhtLookup lookup in search.LookupList) listValues.Items.Add(new ListViewItem(new string[] { xStr(lookup.Status), xStr(lookup.Age), IDtoStr(lookup.Contact.UserID), xStr(lookup.Contact.ClientID), xStr(lookup.Contact.IP), xStr(lookup.Contact.TcpPort), xStr(lookup.Contact.UdpPort), xStr(lookup.Contact.LastSeen), xStr(lookup.Contact.Attempts), xStr(lookup.Contact.NextTryProxy) })); } public void ShowLocations(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 300, HorizontalAlignment.Left); listValues.Items.Add(new ListViewItem(new string[] { "LocationVersion", xStr(Core.Locations.LocationVersion) })); listValues.Items.Add(new ListViewItem(new string[] { "LocationMap", xStr(Core.Locations.Clients.SafeCount) })); } public void ShowLocGlobal(object pass) { SetupLocationList(); if (Core.Context.Lookup == null) return; var globalLocs = Core.Context.Lookup.GetService(ServiceIDs.Lookup) as LookupService; foreach (TempData temp in globalLocs.LookupCache.CachedData) { LocationData data = LocationData.Decode(temp.Data); ClientInfo info = new ClientInfo(); info.Data = data; DisplayLoc(temp.TargetID, info); } } public void ShowLocOperation(object pass) { SetupLocationList(); Core.Locations.Clients.LockReading(delegate() { foreach (ClientInfo info in Core.Locations.Clients.Values) DisplayLoc(Core.Network.OpID, info); }); } private void DisplayLoc(ulong opID, ClientInfo info) { listValues.Items.Add(new ListViewItem(new string[] { xStr(opID), "xx", IDtoStr(info.Data.UserID), xStr(info.Data.Source.ClientID), xStr(info.Data.Source.TcpPort), xStr(info.Data.Source.UdpPort), xStr(info.Data.Source.Firewall), xStr(info.Data.IP), xStr(info.Data.Proxies.Count), xStr(info.Data.Place), xStr(0), xStr(info.Data.Version) })); } public void SetupLocationList() { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("OpID", 100, HorizontalAlignment.Left); listValues.Columns.Add("TTL", 100, HorizontalAlignment.Left); listValues.Columns.Add("DhtID", 100, HorizontalAlignment.Left); listValues.Columns.Add("ClientID", 100, HorizontalAlignment.Left); listValues.Columns.Add("TcpPort", 100, HorizontalAlignment.Left); listValues.Columns.Add("UdpPort", 100, HorizontalAlignment.Left); listValues.Columns.Add("Firewall", 100, HorizontalAlignment.Left); listValues.Columns.Add("IP", 100, HorizontalAlignment.Left); listValues.Columns.Add("Proxies", 100, HorizontalAlignment.Left); listValues.Columns.Add("Location", 100, HorizontalAlignment.Left); listValues.Columns.Add("TTL", 100, HorizontalAlignment.Left); listValues.Columns.Add("Version", 100, HorizontalAlignment.Left); } public void ShowTcp(object pass) { DhtNetwork network = pass as DhtNetwork; AddConnectionNodes((StructureNode)treeStructure.SelectedNode, network); ShowNone(null); } public void AddConnectionNodes(StructureNode parentNode, DhtNetwork network) { parentNode.Nodes.Clear(); lock(network.TcpControl.SocketList) foreach (TcpConnect connect in network.TcpControl.SocketList) parentNode.Nodes.Add( new StructureNode(connect.ToString(), new ShowDelegate(ShowTcpConnect), connect)); } public void ShowTcpConnect(object pass) { TcpConnect connect = (TcpConnect) pass; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 300, HorizontalAlignment.Left); listValues.Items.Add( new ListViewItem( new string[]{"Address", xStr(connect.RemoteIP)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"TcpPort", xStr(connect.TcpPort)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"UdpPort", xStr(connect.UdpPort)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"DhtID", IDtoStr(connect.UserID)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"ClientID", xStr(connect.ClientID)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"TcpSocket", xStr(connect.TcpSocket)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"Age", xStr(connect.Age)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"CheckedFirewall", xStr(connect.CheckedFirewall)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"Outbound", xStr(connect.Outbound)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"ByeMessage", xStr(connect.ByeMessage)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"BytesReceivedinSec", xStr(connect.BytesReceivedinSec)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"BytesSentinSec", xStr(connect.BytesSentinSec)} ) ); listValues.Items.Add( new ListViewItem( new string[]{"Proxy", xStr(connect.Proxy)} ) ); } public void ShowStore(object pass) { DhtNetwork network = pass as DhtNetwork; DhtStore store = network.Store; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Key", 100, HorizontalAlignment.Left); listValues.Columns.Add("Mode", 100, HorizontalAlignment.Left); listValues.Columns.Add("Kind", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 100, HorizontalAlignment.Left); listValues.Columns.Add("TTL", 100, HorizontalAlignment.Left); listValues.Columns.Add("LastUpdate", 100, HorizontalAlignment.Left); } public void ShowRouting(object pass) { DhtNetwork network = pass as DhtNetwork; DhtRouting routing = network.Routing; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 200, HorizontalAlignment.Left); listValues.Items.Add(new ListViewItem(new string[] { "LocalRoutingID", Utilities.IDtoBin(routing.LocalRoutingID) })); listValues.Items.Add(new ListViewItem(new string[] { "Buckets", xStr(routing.BucketList.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "NearXor", xStr(routing.NearXor.Contacts.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "NearHigh", xStr(routing.NearHigh.Contacts.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "NearLow", xStr(routing.NearLow.Contacts.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "ContactMap", xStr(routing.ContactMap.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "NextSelfSearch", xStr(routing.NextSelfSearch) })); TreeNodeCollection nodes = treeStructure.SelectedNode.Nodes; nodes.Clear(); foreach (DhtBucket bucket in network.Routing.BucketList) nodes.Add(new StructureNode(bucket.Depth.ToString(), new ShowDelegate(ShowBucket), bucket.ContactList)); nodes.Add(new StructureNode("Near", new ShowDelegate(ShowBucket), network.Routing.NearXor.Contacts)); nodes.Add(new StructureNode("High", new ShowDelegate(ShowBucket), network.Routing.NearHigh.Contacts)); nodes.Add(new StructureNode("Low", new ShowDelegate(ShowBucket), network.Routing.NearLow.Contacts)); } public void ShowBucket(object pass) { List<DhtContact> contactList = pass as List<DhtContact>; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Name", 100, HorizontalAlignment.Left); listValues.Columns.Add("RoutingID", 100, HorizontalAlignment.Left); listValues.Columns.Add("ClientID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Address", 100, HorizontalAlignment.Left); listValues.Columns.Add("TcpPort", 100, HorizontalAlignment.Left); listValues.Columns.Add("UdpPort", 100, HorizontalAlignment.Left); listValues.Columns.Add("LastSeen", 100, HorizontalAlignment.Left); listValues.Columns.Add("Attempts", 100, HorizontalAlignment.Left); listValues.Columns.Add("NextTryProxy", 100, HorizontalAlignment.Left); listValues.Columns.Add("Tunnel Client/Server", 100, HorizontalAlignment.Left); foreach (DhtContact contact in contactList) { listValues.Items.Add(new ListViewItem(new string[] { GetLinkName(contact.UserID), xStr( Utilities.IDtoBin(contact.RoutingID)), xStr(contact.ClientID), xStr(contact.IP), xStr(contact.TcpPort), xStr(contact.UdpPort), xStr(contact.LastSeen), xStr(contact.Attempts), xStr(contact.NextTryProxy), xStr(contact.TunnelClient) + " / " + xStr(contact.TunnelServer) })); } } public void ShowRudp(object pass) { DhtNetwork network = pass as DhtNetwork; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Name", 100, HorizontalAlignment.Left); listValues.Columns.Add("DhtID", 100, HorizontalAlignment.Left); listValues.Columns.Add("ClientID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Status", 100, HorizontalAlignment.Left); listValues.Columns.Add("Startup", 100, HorizontalAlignment.Left); foreach (RudpSession session in network.RudpControl.SessionMap.Values) listValues.Items.Add(new ListViewItem(new string[] { xStr(Core.GetName(session.UserID)), IDtoStr(session.UserID), xStr(session.ClientID), xStr(session.Status), xStr(session.Startup) })); } public void ShowTransfers(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 300, HorizontalAlignment.Left); //listValues.Items.Add(new ListViewItem(new string[] { "TransferMap", xStr(Core.Transfers.DownloadMap.Count) })); //listValues.Items.Add(new ListViewItem(new string[] { "UploadMap", xStr(Core.Transfers.UploadMap.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "Active", xStr(Core.Transfers.Transfers.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "Pending", xStr(Core.Transfers.Pending.Count) })); } public void ShowUploads(object pass) { /*listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Name", 100, HorizontalAlignment.Left); listValues.Columns.Add("DhtID", 100, HorizontalAlignment.Left); listValues.Columns.Add("ClientID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Done", 100, HorizontalAlignment.Left); listValues.Columns.Add("TransferID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Service", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileSize", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileHash", 100, HorizontalAlignment.Left); listValues.Columns.Add("FilePos", 100, HorizontalAlignment.Left); listValues.Columns.Add("Path", 100, HorizontalAlignment.Left); foreach (List<FileUpload> list in Core.Transfers.UploadMap.Values) foreach (FileUpload upload in list) listValues.Items.Add(new ListViewItem(new string[] { xStr(upload.Session.Name), IDtoStr(upload.Session.UserID), xStr(upload.Session.ClientID), xStr(upload.Done), xStr(upload.Request.TransferID), Core.GetServiceName(upload.Details.Service), xStr(upload.Details.Size), Utilities.BytestoHex(upload.Details.Hash), xStr(upload.FilePos), xStr(upload.Path) }));*/ } public void ShowDownloads(object pass) { /*listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Target", 100, HorizontalAlignment.Left); listValues.Columns.Add("Status", 100, HorizontalAlignment.Left); listValues.Columns.Add("TransferID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Service", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileSize", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileHash", 100, HorizontalAlignment.Left); listValues.Columns.Add("FilePos", 100, HorizontalAlignment.Left); listValues.Columns.Add("Path", 100, HorizontalAlignment.Left); listValues.Columns.Add("Searching", 100, HorizontalAlignment.Left); listValues.Columns.Add("Sources", 100, HorizontalAlignment.Left); listValues.Columns.Add("Attempted", 100, HorizontalAlignment.Left); listValues.Columns.Add("Sessions", 100, HorizontalAlignment.Left); foreach (FileDownload download in Core.Transfers.DownloadMap.Values) listValues.Items.Add(new ListViewItem(new string[] { IDtoStr(download.Target), xStr(download.Status), xStr(download.ID), Core.GetServiceName(download.Details.Service), xStr(download.Details.Size), Utilities.BytestoHex(download.Details.Hash), xStr(download.FilePos), xStr(download.Destination), xStr(download.Searching), xStr(download.Sources.Count), xStr(download.Attempted.Count), xStr(download.Sessions.Count) }));*/ } public void ShowLinks(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 300, HorizontalAlignment.Left); listValues.Items.Add(new ListViewItem(new string[] { "LocalLink", xStr(Core.GetName(Core.UserID)) })); listValues.Items.Add(new ListViewItem(new string[] { "ProjectRoots", xStr(Core.Trust.ProjectRoots.SafeCount) })); listValues.Items.Add(new ListViewItem(new string[] { "LinkMap", xStr(Core.Trust.TrustMap.SafeCount) })); listValues.Items.Add(new ListViewItem(new string[] { "ProjectNames", xStr(Core.Trust.ProjectNames.SafeCount) })); listValues.Items.Add(new ListViewItem(new string[] { "LinkPath", xStr(Core.Trust.LinkPath) })); } public void ShowLinkMap(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Name", 100, HorizontalAlignment.Left); listValues.Columns.Add("DhtID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Loaded", 100, HorizontalAlignment.Left); listValues.Columns.Add("Local Link", 100, HorizontalAlignment.Left); listValues.Columns.Add("Searched", 100, HorizontalAlignment.Left); listValues.Columns.Add("Projects", 100, HorizontalAlignment.Left); listValues.Columns.Add("Titles", 100, HorizontalAlignment.Left); listValues.Columns.Add("Uplinks", 100, HorizontalAlignment.Left); listValues.Columns.Add("Downlinks", 100, HorizontalAlignment.Left); listValues.Columns.Add("Confirmed", 100, HorizontalAlignment.Left); listValues.Columns.Add("Requests", 100, HorizontalAlignment.Left); listValues.Columns.Add("Version", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileHash", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileSize", 100, HorizontalAlignment.Left); listValues.Columns.Add("Path", 100, HorizontalAlignment.Left); Core.Trust.TrustMap.LockReading(delegate() { foreach (OpTrust trust in Core.Trust.TrustMap.Values) { string projects = ""; string titles = ""; string uplinks = ""; string downlinks = ""; string confirmed = ""; string requests = ""; foreach (OpLink link in trust.Links.Values) { string projectName = GetProjectName(link.Project); projects += projectName + ", "; titles += projectName + ", "; if (link.Uplink != null) uplinks += projectName + ": " + GetLinkName(link.Uplink.UserID) + ", "; if (link.Confirmed.Count > 0) { confirmed += projectName + ": "; foreach (ulong key in link.Confirmed) confirmed += GetLinkName(key) + ", "; } if (link.Downlinks.Count > 0) { downlinks += GetProjectName(link.Project) + ": "; foreach (OpLink downlink in link.Downlinks) downlinks += GetLinkName(downlink.UserID) + ", "; } if (link.Requests.Count > 0) { requests += GetProjectName(link.Project) + ": "; foreach (UplinkRequest request in link.Requests) requests += GetLinkName(request.KeyID) + ", "; } } ListViewItem item = new ListViewItem(new string[] { xStr(Core.GetName(trust.UserID)), IDtoStr(trust.UserID), xStr(trust.Loaded), xStr(trust.InLocalLinkTree), xStr(trust.Searched), xStr(projects), xStr(titles), xStr(uplinks), xStr(downlinks), xStr(confirmed), xStr(requests), "", "", "", "", "" }); if (trust.File.Header != null) { item.SubItems[12] = new ListViewItem.ListViewSubItem(item, xStr(trust.File.Header.Version)); item.SubItems[13] = new ListViewItem.ListViewSubItem(item, Utilities.BytestoHex(trust.File.Header.FileHash)); item.SubItems[14] = new ListViewItem.ListViewSubItem(item, xStr(trust.File.Header.FileSize)); item.SubItems[15] = new ListViewItem.ListViewSubItem(item, xStr(Core.Trust.Cache.GetFilePath(trust.File.Header))); } listValues.Items.Add(item); } }); } public void ShowMail(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Property", 100, HorizontalAlignment.Left); listValues.Columns.Add("Value", 300, HorizontalAlignment.Left); listValues.Items.Add(new ListViewItem(new string[] { "MailMap", xStr(Mail.MailMap.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "AckMap", xStr(Mail.AckMap.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "PendingMap", xStr(Mail.PendingMap.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "PendingMail", xStr(Mail.PendingMail.Count) })); listValues.Items.Add(new ListViewItem(new string[] { "PendingAcks", xStr(Mail.PendingAcks.Count) })); } public void ShowMailMap(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Source", 100, HorizontalAlignment.Left); listValues.Columns.Add("Target", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileHash", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileSize", 100, HorizontalAlignment.Left); listValues.Columns.Add("TargetVersion", 100, HorizontalAlignment.Left); listValues.Columns.Add("SourceVersion", 100, HorizontalAlignment.Left); listValues.Columns.Add("MailID", 100, HorizontalAlignment.Left); foreach (List<CachedMail> list in Mail.MailMap.Values) foreach (CachedMail mail in list) listValues.Items.Add(new ListViewItem(new string[] { GetLinkName(mail.Header.SourceID), GetLinkName(mail.Header.TargetID), Utilities.BytestoHex(mail.Header.FileHash), mail.Header.FileSize.ToString(), mail.Header.TargetVersion.ToString(), mail.Header.SourceVersion.ToString(), Utilities.BytestoHex(mail.Header.MailID) })); } public void ShowAckMap(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Source", 100, HorizontalAlignment.Left); listValues.Columns.Add("Target", 100, HorizontalAlignment.Left); listValues.Columns.Add("TargetVersion", 100, HorizontalAlignment.Left); listValues.Columns.Add("SourceVersion", 100, HorizontalAlignment.Left); listValues.Columns.Add("MailID", 100, HorizontalAlignment.Left); foreach (List<CachedAck> list in Mail.AckMap.Values) foreach (CachedAck cached in list) listValues.Items.Add(new ListViewItem(new string[] { GetLinkName(cached.Ack.SourceID), GetLinkName(cached.Ack.TargetID), cached.Ack.TargetVersion.ToString(), cached.Ack.SourceVersion.ToString(), Utilities.BytestoHex(cached.Ack.MailID) })); } public void ShowPendingMap(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Key", 100, HorizontalAlignment.Left); listValues.Columns.Add("Version", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileSize", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileHash", 100, HorizontalAlignment.Left); foreach (CachedPending pending in Mail.PendingMap.Values) listValues.Items.Add(new ListViewItem(new string[] { GetLinkName(pending.Header.KeyID), pending.Header.Version.ToString(), pending.Header.FileSize.ToString(), Utilities.BytestoHex(pending.Header.FileHash) })); } public void ShowPendingMail(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Target", 100, HorizontalAlignment.Left); listValues.Columns.Add("HashID", 100, HorizontalAlignment.Left); listValues.Columns.Add("MailID", 100, HorizontalAlignment.Left); foreach(ulong hashID in Mail.PendingMail.Keys) foreach(ulong target in Mail.PendingMail[hashID]) listValues.Items.Add(new ListViewItem(new string[] { GetLinkName(target), Utilities.BytestoHex(BitConverter.GetBytes(hashID)), Utilities.BytestoHex(Mail.GetMailID(hashID, target)) })); } public void ShowPendingAcks(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Target", 100, HorizontalAlignment.Left); listValues.Columns.Add("MailID", 100, HorizontalAlignment.Left); foreach (ulong target in Mail.PendingAcks.Keys) foreach (byte[] mailID in Mail.PendingAcks[target]) listValues.Items.Add(new ListViewItem(new string[] { GetLinkName(target), Utilities.BytestoHex(mailID) })); } public void ShowBoard(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); if (Boards == null) return; // Target, Posts listValues.Columns.Add("Target", 100, HorizontalAlignment.Left); listValues.Columns.Add("Posts", 100, HorizontalAlignment.Left); Boards.BoardMap.LockReading(delegate() { foreach (OpBoard board in Boards.BoardMap.Values) { listValues.Items.Add(new ListViewItem(new string[] { GetLinkName(board.UserID), board.Posts.SafeCount.ToString() })); } }); AddBoardNodes((StructureNode)treeStructure.SelectedNode); } public void AddBoardNodes(StructureNode parentNode) { parentNode.Nodes.Clear(); Boards.BoardMap.LockReading(delegate() { foreach (OpBoard board in Boards.BoardMap.Values) parentNode.Nodes.Add(new StructureNode(GetLinkName(board.UserID), new ShowDelegate(ShowTargetBoard), board)); }); } public void ShowTargetBoard(object pass) { OpBoard board = pass as OpBoard; if (board == null) return; listValues.Columns.Clear(); listValues.Items.Clear(); // Target, Source, Project, Post, Parent, Version, Time, Scope, Hash, Size listValues.Columns.Add("Target", 100, HorizontalAlignment.Left); listValues.Columns.Add("Source", 100, HorizontalAlignment.Left); listValues.Columns.Add("Project", 100, HorizontalAlignment.Left); listValues.Columns.Add("Post", 100, HorizontalAlignment.Left); listValues.Columns.Add("Parent", 100, HorizontalAlignment.Left); listValues.Columns.Add("Version", 100, HorizontalAlignment.Left); listValues.Columns.Add("Time", 100, HorizontalAlignment.Left); listValues.Columns.Add("Scope", 100, HorizontalAlignment.Left); listValues.Columns.Add("Hash", 100, HorizontalAlignment.Left); listValues.Columns.Add("Size", 100, HorizontalAlignment.Left); board.Posts.LockReading(delegate() { foreach (OpPost post in board.Posts.Values) { PostHeader header = post.Header; listValues.Items.Add(new ListViewItem(new string[] { GetLinkName(header.TargetID), GetLinkName(header.SourceID), header.ProjectID.ToString(), header.PostID.ToString(), header.ParentID.ToString(), header.Version.ToString(), header.Time.ToString(), header.Scope.ToString(), Utilities.BytestoHex(header.FileHash), header.FileSize.ToString() })); } }); } private string GetLinkName(ulong key) { return Core.GetName(key);; } private string GetProjectName(uint id) { string name = Core.Trust.GetProjectName(id); return name; } public void ShowLinkRoots(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("ID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Name", 300, HorizontalAlignment.Left); Core.Trust.ProjectRoots.LockReading(delegate() { foreach (uint id in Core.Trust.ProjectRoots.Keys) { string project = Core.Trust.GetProjectName(id); string names = ""; ThreadedList<OpLink> roots = Core.Trust.ProjectRoots[id]; roots.LockReading(delegate() { foreach (OpLink link in roots) names += xStr(Core.GetName(link.UserID)) + ", "; }); listValues.Items.Add(new ListViewItem(new string[] { project, names })); } }); } public void ShowLinkProjects(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("ID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Name", 300, HorizontalAlignment.Left); Core.Trust.ProjectNames.LockReading(delegate() { foreach (uint id in Core.Trust.ProjectNames.Keys) { listValues.Items.Add(new ListViewItem(new string[] { id.ToString(), xStr(Core.Trust.GetProjectName(id)) })); } }); } public void ShowLocalSync(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Name", 100, HorizontalAlignment.Left); listValues.Columns.Add("ID", 100, HorizontalAlignment.Left); listValues.Columns.Add("Version", 100, HorizontalAlignment.Left); listValues.Columns.Add("InCache", 100, HorizontalAlignment.Left); listValues.Columns.Add("Tags", 400, HorizontalAlignment.Left); ShowLocalSyncItems(pass, Core.Sync.InRange, "yes"); ShowLocalSyncItems(pass, Core.Sync.OutofRange, "no"); } public void ShowLocalSyncItems(object pass, Dictionary<ulong, ServiceData> map, string inCache) { foreach (ulong user in map.Keys) { OpVersionedFile file = Core.Sync.Cache.GetFile(user); ServiceData data = map[user]; string tags = ""; foreach(PatchTag tag in data.Tags) if (tag.Tag.Length >= 4) { uint version = BitConverter.ToUInt32(tag.Tag, 0); tags += Core.GetServiceName(tag.Service) + ":" + tag.DataType.ToString() + " v" + version.ToString() + ", "; } tags.Trim(',', ' '); ListViewItem item = new ListViewItem(new string[] { GetLinkName(user), Utilities.IDtoBin(user), file.Header.Version.ToString(), inCache, tags }); listValues.Items.Add(item); } } public void ShowProfiles(object pass) { listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Name", 100, HorizontalAlignment.Left); listValues.Columns.Add("Version", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileHash", 100, HorizontalAlignment.Left); listValues.Columns.Add("FileSize", 100, HorizontalAlignment.Left); listValues.Columns.Add("EmbedStart", 100, HorizontalAlignment.Left); listValues.Columns.Add("Path", 100, HorizontalAlignment.Left); listValues.Columns.Add("Embedded", 100, HorizontalAlignment.Left); Profiles.ProfileMap.LockReading(delegate() { foreach (OpProfile profile in Profiles.ProfileMap.Values) { if (!profile.Loaded) Profiles.LoadProfile(profile.UserID); string embedded = ""; foreach (ProfileAttachment attach in profile.Attached) embedded += attach.Name + ": " + attach.Size.ToString() + "bytes, "; ListViewItem item = new ListViewItem(new string[] { GetLinkName(profile.UserID), "", "", "", "", "", embedded }); if (profile.File.Header != null) { item.SubItems[2] = new ListViewItem.ListViewSubItem(item, xStr(profile.File.Header.Version)); item.SubItems[3] = new ListViewItem.ListViewSubItem(item, Utilities.BytestoHex(profile.File.Header.FileHash)); item.SubItems[4] = new ListViewItem.ListViewSubItem(item, xStr(profile.File.Header.FileSize)); //item.SubItems[5] = new ListViewItem.ListViewSubItem(item, xStr(profile.Header.EmbeddedStart)); item.SubItems[6] = new ListViewItem.ListViewSubItem(item, xStr(Profiles.GetFilePath(profile))); } listValues.Items.Add(item); } }); } public void UpdateLogs(object pass) { DhtNetwork network = pass as DhtNetwork; AddLogs((StructureNode)treeStructure.SelectedNode, network); ShowNone(null); } public void AddLogs(StructureNode parentNode, DhtNetwork network) { parentNode.Nodes.Clear(); lock(network.LogTable) foreach (string name in network.LogTable.Keys) parentNode.Nodes.Add( new StructureNode(name, new ShowDelegate(ShowLog), new LogInfo(name, network))); } public void ShowLog(object pass) { LogInfo info = pass as LogInfo; listValues.Columns.Clear(); listValues.Items.Clear(); listValues.Columns.Add("Entry", 600, HorizontalAlignment.Left); lock(info.Network.LogTable) foreach (string message in info.Network.LogTable[info.Name]) listValues.Items.Add( new ListViewItem( new string[] {message} ) ); listValues.EnsureVisible( listValues.Items.Count - 1); } private void InternalsForm_Closing(object sender, System.ComponentModel.CancelEventArgs e) { UI.GuiInternal = null; } string xStr(object o) { if(o == null) return "null"; return o.ToString(); } string IDtoStr(UInt64 id) { return Utilities.IDtoBin(id); } private void buttonRefresh_Click(object sender, System.EventArgs e) { RefreshView(); } void RefreshView() { if(treeStructure.SelectedNode == null) return; if(treeStructure.SelectedNode.GetType() != typeof(StructureNode)) return; StructureNode node = (StructureNode) treeStructure.SelectedNode; node.RunShow(); } string copytext = ""; private void listValues_MouseClick(object sender, MouseEventArgs e) { if (e.Button != MouseButtons.Right) return; ListViewItem.ListViewSubItem item = GetItemAt(e.Location); if (item == null) return; copytext = item.Text; ContextMenu menu = new ContextMenu(); menu.MenuItems.Add( new MenuItem("Copy", new EventHandler(ItemCopy_Click))); menu.Show(listValues, e.Location); } private void ItemCopy_Click(object sender, EventArgs e) { Clipboard.SetText(copytext); } private ListViewItem.ListViewSubItem GetItemAt(Point point) { ListViewItem item = listValues.GetItemAt(point.X, point.Y); if (item == null) return null; ListViewItem.ListViewSubItem sub = item.GetSubItemAt(point.X, point.Y); return sub; } } public class LogInfo { public string Name; public DhtNetwork Network; public LogInfo(string name, DhtNetwork network) { Name = name; Network = network; } } public class StructureNode : TreeNode { ShowDelegate Show; object Pass; public StructureNode(string text, ShowDelegate show, object pass) : base(text) { Show = show; Pass = pass; } public void RunShow() { if(Show != null) Show(Pass); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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.Globalization; using System.IO; using System.Linq; using QuantConnect.Configuration; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Orders.Fees; using QuantConnect.Util; namespace QuantConnect.Securities.Future { /// <summary> /// Represents a simple margin model for margin futures. Margin file contains Initial and Maintenance margins /// </summary> public class FutureMarginModel : SecurityMarginModel { private static readonly object DataFolderSymbolLock = new object(); // historical database of margin requirements private MarginRequirementsEntry[] _marginRequirementsHistory; private int _marginCurrentIndex; private readonly Security _security; private IDataProvider _dataProvider = Composer.Instance.GetExportedValueByTypeName<IDataProvider>(Config.Get("data-provider", "DefaultDataProvider")); /// <summary> /// True will enable usage of intraday margins. /// </summary> /// <remarks>Disabled by default. Note that intraday margins are less than overnight margins /// and could lead to margin calls</remarks> public bool EnableIntradayMargins { get; set; } /// <summary> /// Initial Overnight margin requirement for the contract effective from the date of change /// </summary> public virtual decimal InitialOvernightMarginRequirement => GetCurrentMarginRequirements(_security)?.InitialOvernight ?? 0m; /// <summary> /// Maintenance Overnight margin requirement for the contract effective from the date of change /// </summary> public virtual decimal MaintenanceOvernightMarginRequirement => GetCurrentMarginRequirements(_security)?.MaintenanceOvernight ?? 0m; /// <summary> /// Initial Intraday margin for the contract effective from the date of change /// </summary> public virtual decimal InitialIntradayMarginRequirement => GetCurrentMarginRequirements(_security)?.InitialIntraday ?? 0m; /// <summary> /// Maintenance Intraday margin requirement for the contract effective from the date of change /// </summary> public virtual decimal MaintenanceIntradayMarginRequirement => GetCurrentMarginRequirements(_security)?.MaintenanceIntraday ?? 0m; /// <summary> /// Initializes a new instance of the <see cref="FutureMarginModel"/> /// </summary> /// <param name="requiredFreeBuyingPowerPercent">The percentage used to determine the required unused buying power for the account.</param> /// <param name="security">The security that this model belongs to</param> public FutureMarginModel(decimal requiredFreeBuyingPowerPercent = 0, Security security = null) { RequiredFreeBuyingPowerPercent = requiredFreeBuyingPowerPercent; _security = security; } /// <summary> /// Gets the current leverage of the security /// </summary> /// <param name="security">The security to get leverage for</param> /// <returns>The current leverage in the security</returns> public override decimal GetLeverage(Security security) { return 1; } /// <summary> /// Sets the leverage for the applicable securities, i.e, futures /// </summary> /// <remarks> /// This is added to maintain backwards compatibility with the old margin/leverage system /// </remarks> /// <param name="security"></param> /// <param name="leverage">The new leverage</param> public override void SetLeverage(Security security, decimal leverage) { // Futures are leveraged products and different leverage cannot be set by user. throw new InvalidOperationException("Futures are leveraged products and different leverage cannot be set by user"); } /// <summary> /// Get the maximum market order quantity to obtain a position with a given buying power percentage. /// Will not take into account free buying power. /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the target signed buying power percentage</param> /// <returns>Returns the maximum allowed market order quantity and if zero, also the reason</returns> public override GetMaximumOrderQuantityResult GetMaximumOrderQuantityForTargetBuyingPower( GetMaximumOrderQuantityForTargetBuyingPowerParameters parameters) { if (Math.Abs(parameters.TargetBuyingPower) > 1) { throw new InvalidOperationException( "Futures do not allow specifying a leveraged target, since they are traded using margin which already is leveraged. " + $"Possible target buying power goes from -1 to 1, target provided is: {parameters.TargetBuyingPower}"); } return base.GetMaximumOrderQuantityForTargetBuyingPower(parameters); } /// <summary> /// Gets the total margin required to execute the specified order in units of the account currency including fees /// </summary> /// <param name="parameters">An object containing the portfolio, the security and the order</param> /// <returns>The total margin in terms of the currency quoted in the order</returns> public override InitialMargin GetInitialMarginRequiredForOrder( InitialMarginRequiredForOrderParameters parameters ) { //Get the order value from the non-abstract order classes (MarketOrder, LimitOrder, StopMarketOrder) //Market order is approximated from the current security price and set in the MarketOrder Method in QCAlgorithm. var fees = parameters.Security.FeeModel.GetOrderFee( new OrderFeeParameters(parameters.Security, parameters.Order)).Value; var feesInAccountCurrency = parameters.CurrencyConverter. ConvertToAccountCurrency(fees).Amount; var orderMargin = this.GetInitialMarginRequirement(parameters.Security, parameters.Order.Quantity); return new InitialMargin(orderMargin + Math.Sign(orderMargin) * feesInAccountCurrency); } /// <summary> /// Gets the margin currently allotted to the specified holding /// </summary> /// <param name="parameters">An object containing the security</param> /// <returns>The maintenance margin required for the </returns> public override MaintenanceMargin GetMaintenanceMargin(MaintenanceMarginParameters parameters) { var security = parameters.Security; if (security?.GetLastData() == null || parameters.Quantity == 0m) { return 0m; } var marginReq = GetCurrentMarginRequirements(security); if (EnableIntradayMargins && security.Exchange.ExchangeOpen && !security.Exchange.ClosingSoon) { return marginReq.MaintenanceIntraday * parameters.AbsoluteQuantity; } // margin is per contract return marginReq.MaintenanceOvernight * parameters.AbsoluteQuantity; } /// <summary> /// The margin that must be held in order to increase the position by the provided quantity /// </summary> public override InitialMargin GetInitialMarginRequirement(InitialMarginParameters parameters) { var security = parameters.Security; var quantity = parameters.Quantity; if (security?.GetLastData() == null || quantity == 0m) return InitialMargin.Zero; var marginReq = GetCurrentMarginRequirements(security); if (EnableIntradayMargins && security.Exchange.ExchangeOpen && !security.Exchange.ClosingSoon) { return new InitialMargin(marginReq.InitialIntraday * quantity); } // margin is per contract return new InitialMargin(marginReq.InitialOvernight * quantity); } private MarginRequirementsEntry GetCurrentMarginRequirements(Security security) { if (security?.GetLastData() == null) return null; if (_marginRequirementsHistory == null) { _marginRequirementsHistory = LoadMarginRequirementsHistory(security.Symbol); _marginCurrentIndex = 0; } var date = security.GetLastData().Time.Date; while (_marginCurrentIndex + 1 < _marginRequirementsHistory.Length && _marginRequirementsHistory[_marginCurrentIndex + 1].Date <= date) { _marginCurrentIndex++; } return _marginRequirementsHistory[_marginCurrentIndex]; } /// <summary> /// Gets the sorted list of historical margin changes produced by reading in the margin requirements /// data found in /Data/symbol-margin/ /// </summary> /// <returns>Sorted list of historical margin changes</returns> private MarginRequirementsEntry[] LoadMarginRequirementsHistory(Symbol symbol) { var directory = Path.Combine(Globals.DataFolder, symbol.SecurityType.ToLower(), symbol.ID.Market.ToLowerInvariant(), "margins"); return FromCsvFile(Path.Combine(directory, symbol.ID.Symbol + ".csv")); } /// <summary> /// Reads margin requirements file and returns a sorted list of historical margin changes /// </summary> /// <param name="file">The csv file to be read</param> /// <returns>Sorted list of historical margin changes</returns> private MarginRequirementsEntry[] FromCsvFile(string file) { lock (DataFolderSymbolLock) { // skip the first header line, also skip #'s as these are comment lines var marginRequirementsEntries = _dataProvider.ReadLines(file) .Where(x => !x.StartsWith("#") && !string.IsNullOrWhiteSpace(x)) .Skip(1) .Select(MarginRequirementsEntry.Create) .OrderBy(x => x.Date) .ToArray(); if(marginRequirementsEntries.Length == 0) { Log.Trace($"Unable to locate future margin requirements file. Defaulting to zero margin for this symbol. File: {file}"); return new[] { new MarginRequirementsEntry { Date = DateTime.MinValue } }; } return marginRequirementsEntries; } } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace HiRezApi.RealmRoyale { using System.Linq; using System.Threading; using System.Threading.Tasks; using HiRezApi.Common.Models; using Models; using MatchDetails = HiRezApi.RealmRoyale.Models.MatchDetails; using MatchIdsByQueue = HiRezApi.RealmRoyale.Models.MatchIdsByQueue; using Player = HiRezApi.RealmRoyale.Models.Player; /// <summary> /// Extension methods for RealmRoyaleApiClient. /// </summary> public static partial class RealmRoyaleApiClientExtensions { /// <summary> /// createsession /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static Session CreateSession(this IRealmRoyaleApiClient operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRealmRoyaleApiClient)s).CreateSessionAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// createsession /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Session> CreateSessionAsync(this IRealmRoyaleApiClient operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateSessionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// getdataused /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static System.Collections.Generic.IList<DataUsed> GetDataUsed(this IRealmRoyaleApiClient operations) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRealmRoyaleApiClient)s).GetDataUsedAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// getdataused /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<DataUsed>> GetDataUsedAsync(this IRealmRoyaleApiClient operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetDataUsedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// getmatchdetails /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='matchId'> /// The matchId /// </param> public static MatchDetails GetMatchDetails(this IRealmRoyaleApiClient operations, string matchId) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRealmRoyaleApiClient)s).GetMatchDetailsAsync(matchId), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// getmatchdetails /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='matchId'> /// The matchId /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<MatchDetails> GetMatchDetailsAsync(this IRealmRoyaleApiClient operations, string matchId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetMatchDetailsWithHttpMessagesAsync(matchId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// getmatchidsbyqueue /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queue'> /// The queue /// </param> /// <param name='date'> /// The date /// </param> /// <param name='hour'> /// The hour /// </param> public static System.Collections.Generic.IList<MatchIdsByQueue> GetMatchIdsByQueue(this IRealmRoyaleApiClient operations, string queue, string date, string hour) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRealmRoyaleApiClient)s).GetMatchIdsByQueueAsync(queue, date, hour), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// getmatchidsbyqueue /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queue'> /// The queue /// </param> /// <param name='date'> /// The date /// </param> /// <param name='hour'> /// The hour /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<System.Collections.Generic.IList<MatchIdsByQueue>> GetMatchIdsByQueueAsync(this IRealmRoyaleApiClient operations, string queue, string date, string hour, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetMatchIdsByQueueWithHttpMessagesAsync(queue, date, hour, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// getleaderboard /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queue'> /// The queue /// </param> /// <param name='tier'> /// The tier /// </param> public static Leaderboard GetLeaderboard(this IRealmRoyaleApiClient operations, string queue, string tier) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRealmRoyaleApiClient)s).GetLeaderboardAsync(queue, tier), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// getleaderboard /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='queue'> /// The queue /// </param> /// <param name='tier'> /// The tier /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Leaderboard> GetLeaderboardAsync(this IRealmRoyaleApiClient operations, string queue, string tier, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetLeaderboardWithHttpMessagesAsync(queue, tier, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// getplayermatchhistory /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='player'> /// The player /// </param> public static PlayerMatchHistory GetPlayerMatchHistory(this IRealmRoyaleApiClient operations, string player) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRealmRoyaleApiClient)s).GetPlayerMatchHistoryAsync(player), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// getplayermatchhistory /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='player'> /// The player /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PlayerMatchHistory> GetPlayerMatchHistoryAsync(this IRealmRoyaleApiClient operations, string player, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetPlayerMatchHistoryWithHttpMessagesAsync(player, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// getplayer /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='player'> /// The player /// </param> /// <param name='platform'> /// The platform /// </param> public static Player GetPlayer(this IRealmRoyaleApiClient operations, string player, string platform) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRealmRoyaleApiClient)s).GetPlayerAsync(player, platform), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// getplayer /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='player'> /// The player /// </param> /// <param name='platform'> /// The platform /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<Player> GetPlayerAsync(this IRealmRoyaleApiClient operations, string player, string platform, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetPlayerWithHttpMessagesAsync(player, platform, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// getplayerstats /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='player'> /// The player /// </param> public static PlayerStats GetPlayerStats(this IRealmRoyaleApiClient operations, string player) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((IRealmRoyaleApiClient)s).GetPlayerStatsAsync(player), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// getplayerstats /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='player'> /// The player /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<PlayerStats> GetPlayerStatsAsync(this IRealmRoyaleApiClient operations, string player, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetPlayerStatsWithHttpMessagesAsync(player, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// getpatchinfo /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static PatchInfo GetPatchInfo(this IRealmRoyaleApiClient operations) { return operations.GetPatchInfoAsync().GetAwaiter().GetResult(); } /// <summary> /// getpatchinfo /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PatchInfo> GetPatchInfoAsync(this IRealmRoyaleApiClient operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetPatchInfoWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// gethirezserverstatus /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static HirezServerStatus GetHirezServerStatus(this IRealmRoyaleApiClient operations) { return operations.GetHirezServerStatusAsync().GetAwaiter().GetResult(); } /// <summary> /// gethirezserverstatus /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<HirezServerStatus> GetHirezServerStatusAsync(this IRealmRoyaleApiClient operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetHirezServerStatusWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body?.FirstOrDefault(); } } /// <summary> /// ping /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static string Ping(this IRealmRoyaleApiClient operations) { return operations.PingAsync().GetAwaiter().GetResult(); } /// <summary> /// ping /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> PingAsync(this IRealmRoyaleApiClient operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PingWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// testsession /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static string TestSession(this IRealmRoyaleApiClient operations) { return operations.TestSessionAsync().GetAwaiter().GetResult(); } /// <summary> /// testsession /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<string> TestSessionAsync(this IRealmRoyaleApiClient operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.TestSessionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// GtkSharp.Generation.Signal.cs - The Signal Generatable. // // Author: Mike Kestner <mkestner@speakeasy.net> // // Copyright (c) 2001-2003 Mike Kestner // Copyright (c) 2003-2005 Novell, Inc. // Copyright (c) 2007 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the GNU General Public // License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GtkSharp.Generation { using System; using System.Collections; using System.IO; using System.Xml; public class Signal { bool marshaled; string name; XmlElement elem; ReturnValue retval; Parameters parms; ClassBase container_type; public Signal (XmlElement elem, ClassBase container_type) { this.elem = elem; name = elem.GetAttribute ("name"); marshaled = elem.GetAttribute ("manual") == "true"; retval = new ReturnValue (elem ["return-type"]); parms = new Parameters (elem["parameters"]); this.container_type = container_type; } bool Marshaled { get { return marshaled; } } public string Name { get { return name; } set { name = value; } } public bool Validate () { if (Name == "") { Console.Write ("Nameless signal "); Statistics.ThrottledCount++; return false; } if (!parms.Validate () || !retval.Validate ()) { Console.Write (" in signal " + Name + " "); Statistics.ThrottledCount++; return false; } return true; } public void GenerateDecl (StreamWriter sw) { if (elem.HasAttribute("new_flag") || (container_type != null && container_type.GetSignalRecursively (Name) != null)) sw.Write("new "); sw.WriteLine ("\t\tevent " + EventHandlerQualifiedName + " " + Name + ";"); } public string CName { get { return "\"" + elem.GetAttribute("cname") + "\""; } } string CallbackSig { get { string result = ""; for (int i = 0; i < parms.Count; i++) { if (i > 0) result += ", "; Parameter p = parms [i]; if (p.PassAs != "" && !(p.Generatable is StructBase)) result += p.PassAs + " "; result += (p.MarshalType + " arg" + i); } return result; } } string CallbackName { get { return Name + "SignalCallback"; } } string DelegateName { get { return Name + "SignalDelegate"; } } private string EventArgsName { get { if (IsEventHandler) return "EventArgs"; else return Name + "Args"; } } private string EventArgsQualifiedName { get { if (IsEventHandler) return "System.EventArgs"; else return container_type.NS + "." + Name + "Args"; } } private string EventHandlerName { get { if (IsEventHandler) return "EventHandler"; else if (SymbolTable.Table [container_type.NS + Name + "Handler"] != null) return Name + "EventHandler"; else return Name + "Handler"; } } private string EventHandlerQualifiedName { get { if (IsEventHandler) return "System.EventHandler"; else return container_type.NS + "." + EventHandlerName; } } string ClassFieldName { get { return elem.HasAttribute ("field_name") ? elem.GetAttribute("field_name") : String.Empty; } } private bool HasOutParams { get { foreach (Parameter p in parms) { if (p.PassAs == "out") return true; } return false; } } private bool IsEventHandler { get { return retval.CSType == "void" && parms.Count == 1 && (parms [0].Generatable is ObjectGen || parms [0].Generatable is InterfaceGen); } } private bool IsVoid { get { return retval.CSType == "void"; } } private string ReturnGType { get { IGeneratable igen = SymbolTable.Table [retval.CType]; if (igen is ObjectGen) return "GLib.GType.Object"; if (igen is BoxedGen) return retval.CSType + ".GType"; if (igen is EnumGen) return retval.CSType + "GType.GType"; switch (retval.CSType) { case "bool": return "GLib.GType.Boolean"; case "string": return "GLib.GType.String"; case "int": return "GLib.GType.Int"; default: throw new Exception (retval.CSType); } } } public string GenArgsInitialization (StreamWriter sw) { if (parms.Count > 1) sw.WriteLine("\t\t\t\targs.Args = new object[" + (parms.Count - 1) + "];"); string finish = ""; for (int idx = 1; idx < parms.Count; idx++) { Parameter p = parms [idx]; IGeneratable igen = p.Generatable; if (p.PassAs != "out") { if (igen is ManualGen) { sw.WriteLine("\t\t\t\tif (arg{0} == IntPtr.Zero)", idx); sw.WriteLine("\t\t\t\t\targs.Args[{0}] = null;", idx - 1); sw.WriteLine("\t\t\t\telse {"); sw.WriteLine("\t\t\t\t\targs.Args[" + (idx - 1) + "] = " + p.FromNative ("arg" + idx) + ";"); sw.WriteLine("\t\t\t\t}"); } else sw.WriteLine("\t\t\t\targs.Args[" + (idx - 1) + "] = " + p.FromNative ("arg" + idx) + ";"); } if (igen is StructBase && p.PassAs == "ref") finish += "\t\t\t\tif (arg" + idx + " != IntPtr.Zero) System.Runtime.InteropServices.Marshal.StructureToPtr (args.Args[" + (idx-1) + "], arg" + idx + ", false);\n"; else if (p.PassAs != "") finish += "\t\t\t\targ" + idx + " = " + igen.ToNativeReturn ("((" + p.CSType + ")args.Args[" + (idx - 1) + "])") + ";\n"; } return finish; } public void GenArgsCleanup (StreamWriter sw, string finish) { if (IsVoid && finish.Length == 0) return; sw.WriteLine("\n\t\t\ttry {"); sw.Write (finish); if (!IsVoid) { if (retval.CSType == "bool") { sw.WriteLine ("\t\t\t\tif (args.RetVal == null)"); sw.WriteLine ("\t\t\t\t\treturn false;"); } sw.WriteLine("\t\t\t\treturn " + SymbolTable.Table.ToNativeReturn (retval.CType, "((" + retval.CSType + ")args.RetVal)") + ";"); } sw.WriteLine("\t\t\t} catch (Exception) {"); sw.WriteLine ("\t\t\t\tException ex = new Exception (\"args.RetVal or 'out' property unset or set to incorrect type in " + EventHandlerQualifiedName + " callback\");"); sw.WriteLine("\t\t\t\tGLib.ExceptionManager.RaiseUnhandledException (ex, true);"); sw.WriteLine ("\t\t\t\t// NOTREACHED: above call doesn't return."); sw.WriteLine ("\t\t\t\tthrow ex;"); sw.WriteLine("\t\t\t}"); } public void GenCallback (StreamWriter sw) { if (IsEventHandler) return; sw.WriteLine ("\t\t[GLib.CDeclCallback]"); sw.WriteLine ("\t\tdelegate " + retval.ToNativeType + " " + DelegateName + " (" + CallbackSig + ", IntPtr gch);"); sw.WriteLine (); sw.WriteLine ("\t\tstatic " + retval.ToNativeType + " " + CallbackName + " (" + CallbackSig + ", IntPtr gch)"); sw.WriteLine("\t\t{"); sw.WriteLine("\t\t\t{0} args = new {0} ();", EventArgsQualifiedName); sw.WriteLine("\t\t\ttry {"); sw.WriteLine("\t\t\t\tGLib.Signal sig = ((GCHandle) gch).Target as GLib.Signal;"); sw.WriteLine("\t\t\t\tif (sig == null)"); sw.WriteLine("\t\t\t\t\tthrow new Exception(\"Unknown signal GC handle received \" + gch);"); sw.WriteLine(); string finish = GenArgsInitialization (sw); sw.WriteLine("\t\t\t\t{0} handler = ({0}) sig.Handler;", EventHandlerQualifiedName); sw.WriteLine("\t\t\t\thandler (GLib.Object.GetObject (arg0), args);"); sw.WriteLine("\t\t\t} catch (Exception e) {"); sw.WriteLine("\t\t\t\tGLib.ExceptionManager.RaiseUnhandledException (e, false);"); sw.WriteLine("\t\t\t}"); GenArgsCleanup (sw, finish); sw.WriteLine("\t\t}"); sw.WriteLine(); } private bool NeedNew (ClassBase implementor) { return elem.HasAttribute ("new_flag") || (container_type != null && container_type.GetSignalRecursively (Name) != null) || (implementor != null && implementor.GetSignalRecursively (Name) != null); } public void GenEventHandler (GenerationInfo gen_info) { if (IsEventHandler) return; string ns = container_type.NS; StreamWriter sw = gen_info.OpenStream (EventHandlerName); sw.WriteLine ("namespace " + ns + " {"); sw.WriteLine (); sw.WriteLine ("\tusing System;"); sw.WriteLine (); sw.WriteLine ("\tpublic delegate void " + EventHandlerName + "(object o, " + EventArgsName + " args);"); sw.WriteLine (); sw.WriteLine ("\tpublic class " + EventArgsName + " : GLib.SignalArgs {"); for (int i = 1; i < parms.Count; i++) { sw.WriteLine ("\t\tpublic " + parms[i].CSType + " " + parms[i].StudlyName + "{"); if (parms[i].PassAs != "out") { sw.WriteLine ("\t\t\tget {"); sw.WriteLine ("\t\t\t\treturn (" + parms[i].CSType + ") Args[" + (i - 1) + "];"); sw.WriteLine ("\t\t\t}"); } if (parms[i].PassAs != "") { sw.WriteLine ("\t\t\tset {"); sw.WriteLine ("\t\t\t\tArgs[" + (i - 1) + "] = (" + parms[i].CSType + ")value;"); sw.WriteLine ("\t\t\t}"); } sw.WriteLine ("\t\t}"); sw.WriteLine (); } sw.WriteLine ("\t}"); sw.WriteLine ("}"); sw.Close (); } private void GenVMDeclaration (StreamWriter sw, ClassBase implementor) { VMSignature vmsig = new VMSignature (parms); sw.WriteLine ("\t\t[GLib.DefaultSignalHandler(Type=typeof(" + (implementor != null ? implementor.QualifiedName : container_type.QualifiedName) + "), ConnectionMethod=\"Override" + Name +"\")]"); sw.Write ("\t\tprotected "); if (NeedNew (implementor)) sw.Write ("new "); sw.WriteLine ("virtual {0} {1} ({2})", retval.CSType, "On" + Name, vmsig.ToString ()); } private string CastFromInt (string type) { return type != "int" ? "(" + type + ") " : ""; } private string GlueCallString { get { string result = "Handle"; for (int i = 1; i < parms.Count; i++) { Parameter p = parms [i]; IGeneratable igen = p.Generatable; if (i > 1 && parms [i - 1].IsString && p.IsLength && p.PassAs == String.Empty) { string string_name = parms [i - 1].Name; result += ", " + igen.CallByName (CastFromInt (p.CSType) + "System.Text.Encoding.UTF8.GetByteCount (" + string_name + ")"); continue; } p.CallName = p.Name; string call_parm = p.CallString; if (p.IsUserData && parms.IsHidden (p) && !parms.HideData && (i == 1 || parms [i - 1].Scope != "notified")) { call_parm = "IntPtr.Zero"; } result += ", " + call_parm; } return result; } } private string GlueSignature { get { string result = String.Empty; for (int i = 0; i < parms.Count; i++) result += parms[i].CType.Replace ("const-", "const ") + " " + parms[i].Name + (i == parms.Count-1 ? "" : ", "); return result; } } private string DefaultGlueValue { get { string val = retval.DefaultValue; switch (val) { case "null": return "NULL"; case "false": return "FALSE"; case "true": return "TRUE"; default: return val; } } } private void GenGlueVirtualMethod (GenerationInfo gen_info) { StreamWriter glue = gen_info.GlueWriter; string glue_name = String.Format ("{0}sharp_{1}_base_{2}", container_type.NS.ToLower ().Replace (".", "_"), container_type.Name.ToLower (), ClassFieldName); glue.WriteLine ("{0} {1} ({2});\n", retval.CType, glue_name, GlueSignature); glue.WriteLine ("{0}\n{1} ({2})", retval.CType, glue_name, GlueSignature); glue.WriteLine ("{"); glue.WriteLine ("\t{0}Class *klass = ({0}Class *) get_threshold_class (G_OBJECT ({1}));", container_type.CName, parms[0].Name); glue.Write ("\tif (klass->{0})\n\t\t", ClassFieldName); if (!IsVoid) glue.Write ("return "); glue.Write ("(* klass->{0}) (", ClassFieldName); for (int i = 0; i < parms.Count; i++) glue.Write (parms[i].Name + (i == parms.Count - 1 ? "" : ", ")); glue.WriteLine (");"); if (!IsVoid) glue.WriteLine ("\treturn " + DefaultGlueValue + ";"); glue.WriteLine ("}"); StreamWriter sw = gen_info.Writer; sw.WriteLine ("\t\t[DllImport (\"{0}\")]", gen_info.GluelibName); sw.WriteLine ("\t\tstatic extern {0} {1} ({2});\n", retval.MarshalType, glue_name, parms.ImportSignature); GenVMDeclaration (sw, null); sw.WriteLine ("\t\t{"); MethodBody body = new MethodBody (parms); body.Initialize (gen_info, false, false, String.Empty); sw.WriteLine ("\t\t\t{0}{1} ({2});", IsVoid ? "" : retval.MarshalType + " __ret = ", glue_name, GlueCallString); body.Finish (sw, ""); if (!IsVoid) sw.WriteLine ("\t\t\treturn {0};", retval.FromNative ("__ret")); sw.WriteLine ("\t\t}\n"); } private void GenChainVirtualMethod (StreamWriter sw, ClassBase implementor) { GenVMDeclaration (sw, implementor); sw.WriteLine ("\t\t{"); if (IsVoid) sw.WriteLine ("\t\t\tGLib.Value ret = GLib.Value.Empty;"); else sw.WriteLine ("\t\t\tGLib.Value ret = new GLib.Value (" + ReturnGType + ");"); sw.WriteLine ("\t\t\tGLib.ValueArray inst_and_params = new GLib.ValueArray (" + parms.Count + ");"); sw.WriteLine ("\t\t\tGLib.Value[] vals = new GLib.Value [" + parms.Count + "];"); sw.WriteLine ("\t\t\tvals [0] = new GLib.Value (this);"); sw.WriteLine ("\t\t\tinst_and_params.Append (vals [0]);"); string cleanup = ""; for (int i = 1; i < parms.Count; i++) { Parameter p = parms [i]; if (p.PassAs != "") { if (SymbolTable.Table.IsBoxed (p.CType)) { if (p.PassAs == "ref") sw.WriteLine ("\t\t\tvals [" + i + "] = new GLib.Value (" + p.Name + ");"); else sw.WriteLine ("\t\t\tvals [" + i + "] = new GLib.Value ((GLib.GType)typeof (" + p.CSType + "));"); cleanup += "\t\t\t" + p.Name + " = (" + p.CSType + ") vals [" + i + "];\n"; } else { if (p.PassAs == "ref") sw.WriteLine ("\t\t\tIntPtr " + p.Name + "_ptr = GLib.Marshaller.StructureToPtrAlloc (" + p.Generatable.CallByName (p.Name) + ");"); else sw.WriteLine ("\t\t\tIntPtr " + p.Name + "_ptr = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (" + p.MarshalType + ")));"); sw.WriteLine ("\t\t\tvals [" + i + "] = new GLib.Value (" + p.Name + "_ptr);"); cleanup += "\t\t\t" + p.Name + " = " + p.FromNative ("(" + p.MarshalType + ") Marshal.PtrToStructure (" + p.Name + "_ptr, typeof (" + p.MarshalType + "))") + ";\n"; cleanup += "\t\t\tMarshal.FreeHGlobal (" + p.Name + "_ptr);\n"; } } else if (p.IsLength && parms [i - 1].IsString) sw.WriteLine ("\t\t\tvals [" + i + "] = new GLib.Value (System.Text.Encoding.UTF8.GetByteCount (" + parms [i-1].Name + "));"); else sw.WriteLine ("\t\t\tvals [" + i + "] = new GLib.Value (" + p.Name + ");"); sw.WriteLine ("\t\t\tinst_and_params.Append (vals [" + i + "]);"); } sw.WriteLine ("\t\t\tg_signal_chain_from_overridden (inst_and_params.ArrayPtr, ref ret);"); if (cleanup != "") sw.WriteLine (cleanup); sw.WriteLine ("\t\t\tforeach (GLib.Value v in vals)"); sw.WriteLine ("\t\t\t\tv.Dispose ();"); if (!IsVoid) { IGeneratable igen = SymbolTable.Table [retval.CType]; sw.WriteLine ("\t\t\t" + retval.CSType + " result = (" + (igen is EnumGen ? retval.CSType + ") (Enum" : retval.CSType) + ") ret;"); sw.WriteLine ("\t\t\tret.Dispose ();"); sw.WriteLine ("\t\t\treturn result;"); } sw.WriteLine ("\t\t}\n"); } private void GenDefaultHandlerDelegate (GenerationInfo gen_info, ClassBase implementor) { StreamWriter sw = gen_info.Writer; StreamWriter glue; bool use_glue = gen_info.GlueEnabled && implementor == null && ClassFieldName.Length > 0; string glue_name = String.Empty; ManagedCallString call = new ManagedCallString (parms, true); sw.WriteLine ("\t\t[GLib.CDeclCallback]"); sw.WriteLine ("\t\tdelegate " + retval.ToNativeType + " " + Name + "VMDelegate (" + parms.ImportSignature + ");\n"); if (use_glue) { glue = gen_info.GlueWriter; glue_name = String.Format ("{0}sharp_{1}_override_{2}", container_type.NS.ToLower ().Replace (".", "_"), container_type.Name.ToLower (), ClassFieldName); sw.WriteLine ("\t\t[DllImport (\"{0}\")]", gen_info.GluelibName); sw.WriteLine ("\t\tstatic extern void {0} (IntPtr gtype, {1}VMDelegate cb);\n", glue_name, Name); glue.WriteLine ("void {0} (GType gtype, gpointer cb);\n", glue_name); glue.WriteLine ("void\n{0} (GType gtype, gpointer cb)", glue_name); glue.WriteLine ("{"); glue.WriteLine ("\tGObjectClass *klass = g_type_class_peek (gtype);"); glue.WriteLine ("\tif (klass == NULL)"); glue.WriteLine ("\t\tklass = g_type_class_ref (gtype);"); glue.WriteLine ("\t(({0} *)klass)->{1} = cb;", container_type.CName + "Class", ClassFieldName); glue.WriteLine ("}\n"); } sw.WriteLine ("\t\tstatic {0} {1};\n", Name + "VMDelegate", Name + "VMCallback"); sw.WriteLine ("\t\tstatic " + retval.ToNativeType + " " + Name.ToLower() + "_cb (" + parms.ImportSignature + ")"); sw.WriteLine ("\t\t{"); string unconditional = call.Unconditional ("\t\t\t"); if (unconditional.Length > 0) sw.WriteLine (unconditional); sw.WriteLine ("\t\t\ttry {"); sw.WriteLine ("\t\t\t\t{0} {1}_managed = GLib.Object.GetObject ({1}, false) as {0};", implementor != null ? implementor.Name : container_type.Name, parms[0].Name); sw.Write (call.Setup ("\t\t\t\t")); sw.Write ("\t\t\t\t{0}", IsVoid ? "" : retval.CSType == retval.ToNativeType ? "return " : retval.CSType + " raw_ret = "); sw.WriteLine ("{2}_managed.{0} ({1});", "On" + Name, call.ToString (), parms[0].Name); sw.Write (call.Finish ("\t\t\t\t")); if (!IsVoid && retval.CSType != retval.ToNativeType) sw.WriteLine ("\t\t\t\treturn {0};", SymbolTable.Table.ToNativeReturn (retval.CType, "raw_ret")); sw.WriteLine ("\t\t\t} catch (Exception e) {"); bool fatal = HasOutParams || !IsVoid; sw.WriteLine ("\t\t\t\tGLib.ExceptionManager.RaiseUnhandledException (e, " + (fatal ? "true" : "false") + ");"); if (fatal) { sw.WriteLine ("\t\t\t\t// NOTREACHED: above call doesn't return"); sw.WriteLine ("\t\t\t\tthrow e;"); } sw.WriteLine ("\t\t\t}"); sw.WriteLine ("\t\t}\n"); sw.WriteLine ("\t\tprivate static void Override" + Name + " (GLib.GType gtype)"); sw.WriteLine ("\t\t{"); sw.WriteLine ("\t\t\tif (" + Name + "VMCallback == null)"); sw.WriteLine ("\t\t\t\t" + Name + "VMCallback = new " + Name + "VMDelegate (" + Name.ToLower() + "_cb);"); if (use_glue) sw.WriteLine ("\t\t\t{0} (gtype.Val, {1}VMCallback);", glue_name, Name); else sw.WriteLine ("\t\t\tOverrideVirtualMethod (gtype, " + CName + ", " + Name + "VMCallback);"); sw.WriteLine ("\t\t}\n"); } public void GenEvent (StreamWriter sw, ClassBase implementor, string target) { string args_type = IsEventHandler ? "" : ", typeof (" + EventArgsQualifiedName + ")"; if (Marshaled) { GenCallback (sw); args_type = ", new " + DelegateName + "(" + CallbackName + ")"; } sw.WriteLine("\t\t[GLib.Signal("+ CName + ")]"); sw.Write("\t\tpublic "); if (NeedNew (implementor)) sw.Write("new "); sw.WriteLine("event " + EventHandlerQualifiedName + " " + Name + " {"); sw.WriteLine("\t\t\tadd {"); sw.WriteLine("\t\t\t\tGLib.Signal sig = GLib.Signal.Lookup (" + target + ", " + CName + args_type + ");"); sw.WriteLine("\t\t\t\tsig.AddDelegate (value);"); sw.WriteLine("\t\t\t}"); sw.WriteLine("\t\t\tremove {"); sw.WriteLine("\t\t\t\tGLib.Signal sig = GLib.Signal.Lookup (" + target + ", " + CName + args_type + ");"); sw.WriteLine("\t\t\t\tsig.RemoveDelegate (value);"); sw.WriteLine("\t\t\t}"); sw.WriteLine("\t\t}"); sw.WriteLine(); } public void Generate (GenerationInfo gen_info, ClassBase implementor) { StreamWriter sw = gen_info.Writer; if (implementor == null) GenEventHandler (gen_info); GenDefaultHandlerDelegate (gen_info, implementor); if (gen_info.GlueEnabled && implementor == null && ClassFieldName.Length > 0) GenGlueVirtualMethod (gen_info); else GenChainVirtualMethod (sw, implementor); GenEvent (sw, implementor, "this"); Statistics.SignalCount++; } } }
namespace Epi.Windows.Analysis.Dialogs { partial class UndeleteRecordsDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UndeleteRecordsDialog)); this.btnHelp = new System.Windows.Forms.Button(); this.btnClear = new System.Windows.Forms.Button(); this.btnFunctions = new System.Windows.Forms.Button(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.cbkRunSilent = new System.Windows.Forms.CheckBox(); this.lblAvailableVar = new System.Windows.Forms.Label(); this.txtRecAffected = new System.Windows.Forms.TextBox(); this.lblRecAffected = new System.Windows.Forms.Label(); this.btnMissing = new System.Windows.Forms.Button(); this.btnNo = new System.Windows.Forms.Button(); this.btnYes = new System.Windows.Forms.Button(); this.btnOr = new System.Windows.Forms.Button(); this.btnAnd = new System.Windows.Forms.Button(); this.btnClosedParen = new System.Windows.Forms.Button(); this.btnOpenParen = new System.Windows.Forms.Button(); this.btnQuote = new System.Windows.Forms.Button(); this.btnAmpersand = new System.Windows.Forms.Button(); this.btnGreaterThan = new System.Windows.Forms.Button(); this.btnLessThan = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.btnMinus = new System.Windows.Forms.Button(); this.btnMultiply = new System.Windows.Forms.Button(); this.btnDivide = new System.Windows.Forms.Button(); this.btnEqual = new System.Windows.Forms.Button(); this.cmbAvailableVar = new System.Windows.Forms.ComboBox(); this.btnSaveOnly = new System.Windows.Forms.Button(); this.btnFunction = new System.Windows.Forms.Button(); this.SuspendLayout(); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); // // btnHelp // resources.ApplyResources(this.btnHelp, "btnHelp"); this.btnHelp.Name = "btnHelp"; this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click); // // btnClear // resources.ApplyResources(this.btnClear, "btnClear"); this.btnClear.Name = "btnClear"; this.btnClear.Click += new System.EventHandler(this.btnClear_Click); // // btnFunctions // resources.ApplyResources(this.btnFunctions, "btnFunctions"); this.btnFunctions.Name = "btnFunctions"; this.btnFunctions.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnFunction_MouseDown); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Name = "btnCancel"; // // btnOK // resources.ApplyResources(this.btnOK, "btnOK"); this.btnOK.Name = "btnOK"; // // cbkRunSilent // resources.ApplyResources(this.cbkRunSilent, "cbkRunSilent"); this.cbkRunSilent.Name = "cbkRunSilent"; // // lblAvailableVar // this.lblAvailableVar.FlatStyle = System.Windows.Forms.FlatStyle.System; resources.ApplyResources(this.lblAvailableVar, "lblAvailableVar"); this.lblAvailableVar.Name = "lblAvailableVar"; // // txtRecAffected // resources.ApplyResources(this.txtRecAffected, "txtRecAffected"); this.txtRecAffected.Name = "txtRecAffected"; this.txtRecAffected.TextChanged += new System.EventHandler(this.txtRecAffected_Leave); this.txtRecAffected.Leave += new System.EventHandler(this.txtRecAffected_Leave); // // lblRecAffected // resources.ApplyResources(this.lblRecAffected, "lblRecAffected"); this.lblRecAffected.FlatStyle = System.Windows.Forms.FlatStyle.System; this.lblRecAffected.Name = "lblRecAffected"; // // btnMissing // resources.ApplyResources(this.btnMissing, "btnMissing"); this.btnMissing.Name = "btnMissing"; this.btnMissing.Tag = "(.)"; this.btnMissing.Click += new System.EventHandler(this.ClickHandler); // // btnNo // resources.ApplyResources(this.btnNo, "btnNo"); this.btnNo.Name = "btnNo"; this.btnNo.Tag = "(-)"; this.btnNo.Click += new System.EventHandler(this.ClickHandler); // // btnYes // resources.ApplyResources(this.btnYes, "btnYes"); this.btnYes.Name = "btnYes"; this.btnYes.Tag = "(+)"; this.btnYes.Click += new System.EventHandler(this.ClickHandler); // // btnOr // resources.ApplyResources(this.btnOr, "btnOr"); this.btnOr.Name = "btnOr"; this.btnOr.Tag = "OR"; this.btnOr.Click += new System.EventHandler(this.ClickHandler); // // btnAnd // resources.ApplyResources(this.btnAnd, "btnAnd"); this.btnAnd.Name = "btnAnd"; this.btnAnd.Tag = "AND"; this.btnAnd.Click += new System.EventHandler(this.ClickHandler); // // btnClosedParen // resources.ApplyResources(this.btnClosedParen, "btnClosedParen"); this.btnClosedParen.Name = "btnClosedParen"; this.btnClosedParen.Click += new System.EventHandler(this.ClickHandler); // // btnOpenParen // resources.ApplyResources(this.btnOpenParen, "btnOpenParen"); this.btnOpenParen.Name = "btnOpenParen"; this.btnOpenParen.Click += new System.EventHandler(this.ClickHandler); // // btnQuote // resources.ApplyResources(this.btnQuote, "btnQuote"); this.btnQuote.Name = "btnQuote"; this.btnQuote.Click += new System.EventHandler(this.ClickHandler); // // btnAmpersand // resources.ApplyResources(this.btnAmpersand, "btnAmpersand"); this.btnAmpersand.Name = "btnAmpersand"; this.btnAmpersand.Tag = " & "; this.btnAmpersand.Click += new System.EventHandler(this.ClickHandler); // // btnGreaterThan // resources.ApplyResources(this.btnGreaterThan, "btnGreaterThan"); this.btnGreaterThan.Name = "btnGreaterThan"; this.btnGreaterThan.Click += new System.EventHandler(this.ClickHandler); // // btnLessThan // resources.ApplyResources(this.btnLessThan, "btnLessThan"); this.btnLessThan.Name = "btnLessThan"; this.btnLessThan.Click += new System.EventHandler(this.ClickHandler); // // btnAdd // resources.ApplyResources(this.btnAdd, "btnAdd"); this.btnAdd.Name = "btnAdd"; this.btnAdd.Click += new System.EventHandler(this.ClickHandler); // // btnMinus // resources.ApplyResources(this.btnMinus, "btnMinus"); this.btnMinus.Name = "btnMinus"; this.btnMinus.Click += new System.EventHandler(this.ClickHandler); // // btnMultiply // resources.ApplyResources(this.btnMultiply, "btnMultiply"); this.btnMultiply.Name = "btnMultiply"; this.btnMultiply.Click += new System.EventHandler(this.ClickHandler); // // btnDivide // resources.ApplyResources(this.btnDivide, "btnDivide"); this.btnDivide.Name = "btnDivide"; this.btnDivide.Click += new System.EventHandler(this.ClickHandler); // // btnEqual // resources.ApplyResources(this.btnEqual, "btnEqual"); this.btnEqual.Name = "btnEqual"; this.btnEqual.Click += new System.EventHandler(this.ClickHandler); // // cmbAvailableVar // resources.ApplyResources(this.cmbAvailableVar, "cmbAvailableVar"); this.cmbAvailableVar.Items.AddRange(new object[] { resources.GetString("cmbAvailableVar.Items"), resources.GetString("cmbAvailableVar.Items1"), resources.GetString("cmbAvailableVar.Items2"), resources.GetString("cmbAvailableVar.Items3")}); this.cmbAvailableVar.Name = "cmbAvailableVar"; this.cmbAvailableVar.SelectedValueChanged += new System.EventHandler(this.txtRecAffected_Leave); // // btnSaveOnly // resources.ApplyResources(this.btnSaveOnly, "btnSaveOnly"); this.btnSaveOnly.Name = "btnSaveOnly"; // // btnFunction // resources.ApplyResources(this.btnFunction, "btnFunction"); this.btnFunction.Name = "btnFunction"; this.btnFunction.MouseDown += new System.Windows.Forms.MouseEventHandler(this.btnFunction_MouseDown); // // UndeleteRecordsDialog // this.AcceptButton = this.btnOK; resources.ApplyResources(this, "$this"); this.CancelButton = this.btnCancel; this.Controls.Add(this.btnFunction); this.Controls.Add(this.btnSaveOnly); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnClear); this.Controls.Add(this.btnFunctions); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOK); this.Controls.Add(this.cbkRunSilent); this.Controls.Add(this.lblAvailableVar); this.Controls.Add(this.txtRecAffected); this.Controls.Add(this.lblRecAffected); this.Controls.Add(this.btnMissing); this.Controls.Add(this.btnNo); this.Controls.Add(this.btnYes); this.Controls.Add(this.btnOr); this.Controls.Add(this.btnAnd); this.Controls.Add(this.btnClosedParen); this.Controls.Add(this.btnOpenParen); this.Controls.Add(this.btnQuote); this.Controls.Add(this.btnAmpersand); this.Controls.Add(this.btnGreaterThan); this.Controls.Add(this.btnLessThan); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnMinus); this.Controls.Add(this.btnMultiply); this.Controls.Add(this.btnDivide); this.Controls.Add(this.btnEqual); this.Controls.Add(this.cmbAvailableVar); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "UndeleteRecordsDialog"; this.ShowIcon = false; this.Load += new System.EventHandler(this.UndeleteRecordsDialog_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.CheckBox cbkRunSilent; private System.Windows.Forms.Label lblAvailableVar; private System.Windows.Forms.Button btnMissing; private System.Windows.Forms.Button btnNo; private System.Windows.Forms.Button btnYes; private System.Windows.Forms.Button btnOr; private System.Windows.Forms.Button btnAnd; private System.Windows.Forms.Button btnClosedParen; private System.Windows.Forms.Button btnOpenParen; private System.Windows.Forms.Button btnQuote; private System.Windows.Forms.Button btnAmpersand; private System.Windows.Forms.Button btnGreaterThan; private System.Windows.Forms.Button btnLessThan; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnMinus; private System.Windows.Forms.Button btnMultiply; private System.Windows.Forms.Button btnDivide; private System.Windows.Forms.Button btnEqual; private System.Windows.Forms.ComboBox cmbAvailableVar; private System.Windows.Forms.Button btnFunctions; private System.Windows.Forms.TextBox txtRecAffected; private System.Windows.Forms.Label lblRecAffected; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnClear; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.Button btnSaveOnly; private System.Windows.Forms.Button btnFunction; } }
// // ListView_DragAndDrop.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; namespace Hyena.Data.Gui { public static class ListViewDragDropTarget { public enum TargetType { ModelSelection } public static readonly TargetEntry ModelSelection = new TargetEntry ("application/x-hyena-data-model-selection", TargetFlags.App, (uint)TargetType.ModelSelection); } public partial class ListView<T> : ListViewBase { private static TargetEntry [] drag_drop_dest_entries = new TargetEntry [] { ListViewDragDropTarget.ModelSelection }; protected virtual TargetEntry [] DragDropDestEntries { get { return drag_drop_dest_entries; } } protected virtual TargetEntry [] DragDropSourceEntries { get { return drag_drop_dest_entries; } } private bool is_reorderable = false; public bool IsReorderable { get { return is_reorderable && IsEverReorderable; } set { is_reorderable = value; OnDragSourceSet (); OnDragDestSet (); } } private bool is_ever_reorderable = false; public bool IsEverReorderable { get { return is_ever_reorderable; } set { is_ever_reorderable = value; OnDragSourceSet (); OnDragDestSet (); } } private bool force_drag_source_set = false; protected bool ForceDragSourceSet { get { return force_drag_source_set; } set { force_drag_source_set = true; OnDragSourceSet (); } } private bool force_drag_dest_set = false; protected bool ForceDragDestSet { get { return force_drag_dest_set; } set { force_drag_dest_set = true; OnDragDestSet (); } } protected virtual void OnDragDestSet () { if (ForceDragDestSet || IsReorderable) { Gtk.Drag.DestSet (this, DestDefaults.All, DragDropDestEntries, Gdk.DragAction.Move); } else { Gtk.Drag.DestUnset (this); } } protected virtual void OnDragSourceSet () { if (ForceDragSourceSet || IsReorderable) { Gtk.Drag.SourceSet (this, Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask, DragDropSourceEntries, Gdk.DragAction.Copy | Gdk.DragAction.Move); } else { Gtk.Drag.SourceUnset (this); } } private uint drag_scroll_timeout_id; private uint drag_scroll_timeout_duration = 50; private double drag_scroll_velocity; private double drag_scroll_velocity_max = 100.0; private int drag_reorder_row_index = -1; private int drag_reorder_motion_y = -1; private void StopDragScroll () { drag_scroll_velocity = 0.0; if (drag_scroll_timeout_id > 0) { GLib.Source.Remove (drag_scroll_timeout_id); drag_scroll_timeout_id = 0; } } private void OnDragScroll (GLib.TimeoutHandler handler, double threshold, int total, int position) { if (position < threshold) { drag_scroll_velocity = -1.0 + (position / threshold); } else if (position > total - threshold) { drag_scroll_velocity = 1.0 - ((total - position) / threshold); } else { StopDragScroll (); return; } if (drag_scroll_timeout_id == 0) { drag_scroll_timeout_id = GLib.Timeout.Add (drag_scroll_timeout_duration, handler); } } protected override bool OnDragMotion (Gdk.DragContext context, int x, int y, uint time) { if (!IsReorderable) { StopDragScroll (); drag_reorder_row_index = -1; drag_reorder_motion_y = -1; InvalidateList (); return false; } drag_reorder_motion_y = y; DragReorderUpdateRow (); OnDragScroll (OnDragVScrollTimeout, Allocation.Height * 0.3, Allocation.Height, y); return true; } protected override void OnDragLeave (Gdk.DragContext context, uint time) { StopDragScroll (); } protected override void OnDragEnd (Gdk.DragContext context) { StopDragScroll (); drag_reorder_row_index = -1; drag_reorder_motion_y = -1; InvalidateList (); } private bool OnDragVScrollTimeout () { ScrollTo (VadjustmentValue + (drag_scroll_velocity * drag_scroll_velocity_max)); DragReorderUpdateRow (); return true; } private void DragReorderUpdateRow () { int row = GetDragRow (drag_reorder_motion_y); if (row != drag_reorder_row_index) { drag_reorder_row_index = row; InvalidateList (); } } protected int GetDragRow (int y) { y = TranslateToListY (y); int row = GetRowAtY (y); if (row == -1) { return -1; } if (row != GetRowAtY (y + RowHeight / 2)) { row++; } return row; } } }
// 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.Net.Sockets; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.NetworkInformation.Tests { public class NetworkInterfaceBasicTest { private readonly ITestOutputHelper _log; public NetworkInterfaceBasicTest() { _log = TestLogging.GetInstance(); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 public void BasicTest_GetNetworkInterfaces_AtLeastOne() { Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_AccessInstanceProperties_NoExceptions() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); _log.WriteLine("Description: " + nic.Description); _log.WriteLine("ID: " + nic.Id); _log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); // Validate NIC speed overflow. // We've found that certain WiFi adapters will return speed of -1 when not connected. Assert.InRange(nic.Speed, nic.OperationalStatus != OperationalStatus.Down ? 0 : -1, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_AccessInstanceProperties_NoExceptions_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); try { _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, -1, long.MaxValue); } // We cannot guarantee this works on all devices. catch (PlatformNotSupportedException pnse) { _log.WriteLine(pnse.ToString()); } _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX public void BasicTest_AccessInstanceProperties_NoExceptions_Osx() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, 0, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.Loopback)) { Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index, NetworkInterface.LoopbackInterfaceIndex); return; // Only check IPv4 loopback } } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.IPv6Loopback)) { Assert.Equal<int>( nic.GetIPProperties().GetIPv6Properties().Index, NetworkInterface.IPv6LoopbackInterfaceIndex); return; // Only check IPv6 loopback. } } } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_GetIPInterfaceStatistics_Success() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_GetIPInterfaceStatistics_Success_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX public void BasicTest_GetIPInterfaceStatistics_Success_OSX() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 public void BasicTest_GetIsNetworkAvailable_Success() { Assert.True(NetworkInterface.GetIsNetworkAvailable()); } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308 [PlatformSpecific(~TestPlatforms.OSX)] [InlineData(false)] [InlineData(true)] public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6) { using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp)) using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp)) { server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0)); var serverEndPoint = (IPEndPoint)server.LocalEndPoint; Task<SocketReceiveMessageFromResult> receivedTask = server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint); while (!receivedTask.IsCompleted) { client.SendTo(new byte[] { 42 }, serverEndPoint); await Task.Delay(1); } Assert.Equal( (await receivedTask).PacketInformation.Interface, ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex); } } } }
// <copyright file="TFQMR.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-2013 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// A Transpose Free Quasi-Minimal Residual (TFQMR) iterative matrix solver. /// </summary> /// <remarks> /// <para> /// The TFQMR algorithm was taken from: <br/> /// Iterative methods for sparse linear systems. /// <br/> /// Yousef Saad /// <br/> /// Algorithm is described in Chapter 7, section 7.4.3, page 219 /// </para> /// <para> /// The example code below provides an indication of the possible use of the /// solver. /// </para> /// </remarks> public sealed class TFQMR : IIterativeSolver<Complex> { /// <summary> /// Calculates the <c>true</c> residual of the matrix equation Ax = b according to: residual = b - Ax /// </summary> /// <param name="matrix">Instance of the <see cref="Matrix"/> A.</param> /// <param name="residual">Residual values in <see cref="Vector"/>.</param> /// <param name="x">Instance of the <see cref="Vector"/> x.</param> /// <param name="b">Instance of the <see cref="Vector"/> b.</param> static void CalculateTrueResidual(Matrix<Complex> matrix, Vector<Complex> residual, Vector<Complex> x, Vector<Complex> b) { // -Ax = residual matrix.Multiply(x, residual); residual.Multiply(-1, residual); // residual + b residual.Add(b, residual); } /// <summary> /// Is <paramref name="number"/> even? /// </summary> /// <param name="number">Number to check</param> /// <returns><c>true</c> if <paramref name="number"/> even, otherwise <c>false</c></returns> static bool IsEven(int number) { return number % 2 == 0; } /// <summary> /// Solves the matrix equation Ax = b, where A is the coefficient matrix, b is the /// solution vector and x is the unknown vector. /// </summary> /// <param name="matrix">The coefficient matrix, <c>A</c>.</param> /// <param name="input">The solution vector, <c>b</c></param> /// <param name="result">The result vector, <c>x</c></param> /// <param name="iterator">The iterator to use to control when to stop iterating.</param> /// <param name="preconditioner">The preconditioner to use for approximations.</param> public void Solve(Matrix<Complex> matrix, Vector<Complex> input, Vector<Complex> result, Iterator<Complex> iterator, IPreconditioner<Complex> preconditioner) { if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } if (input.Count != matrix.RowCount || result.Count != input.Count) { throw Matrix.DimensionsDontMatch<ArgumentException>(matrix, input, result); } if (iterator == null) { iterator = new Iterator<Complex>(); } if (preconditioner == null) { preconditioner = new UnitPreconditioner<Complex>(); } preconditioner.Initialize(matrix); var d = new DenseVector(input.Count); var r = DenseVector.OfVector(input); var uodd = new DenseVector(input.Count); var ueven = new DenseVector(input.Count); var v = new DenseVector(input.Count); var pseudoResiduals = DenseVector.OfVector(input); var x = new DenseVector(input.Count); var yodd = new DenseVector(input.Count); var yeven = DenseVector.OfVector(input); // Temp vectors var temp = new DenseVector(input.Count); var temp1 = new DenseVector(input.Count); var temp2 = new DenseVector(input.Count); // Define the scalars Complex alpha = 0; Complex eta = 0; double theta = 0; // Initialize var tau = input.L2Norm(); Complex rho = tau*tau; // Calculate the initial values for v // M temp = yEven preconditioner.Approximate(yeven, temp); // v = A temp matrix.Multiply(temp, v); // Set uOdd v.CopyTo(ueven); // Start the iteration var iterationNumber = 0; while (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) == IterationStatus.Continue) { // First part of the step, the even bit if (IsEven(iterationNumber)) { // sigma = (v, r) var sigma = r.ConjugateDotProduct(v); if (sigma.Real.AlmostEqualNumbersBetween(0, 1) && sigma.Imaginary.AlmostEqualNumbersBetween(0, 1)) { // FAIL HERE iterator.Cancel(); break; } // alpha = rho / sigma alpha = rho/sigma; // yOdd = yEven - alpha * v v.Multiply(-alpha, temp1); yeven.Add(temp1, yodd); // Solve M temp = yOdd preconditioner.Approximate(yodd, temp); // uOdd = A temp matrix.Multiply(temp, uodd); } // The intermediate step which is equal for both even and // odd iteration steps. // Select the correct vector var uinternal = IsEven(iterationNumber) ? ueven : uodd; var yinternal = IsEven(iterationNumber) ? yeven : yodd; // pseudoResiduals = pseudoResiduals - alpha * uOdd uinternal.Multiply(-alpha, temp1); pseudoResiduals.Add(temp1, temp2); temp2.CopyTo(pseudoResiduals); // d = yOdd + theta * theta * eta / alpha * d d.Multiply(theta*theta*eta/alpha, temp); yinternal.Add(temp, d); // theta = ||pseudoResiduals||_2 / tau theta = pseudoResiduals.L2Norm()/tau; var c = 1/Math.Sqrt(1 + (theta*theta)); // tau = tau * theta * c tau *= theta*c; // eta = c^2 * alpha eta = c*c*alpha; // x = x + eta * d d.Multiply(eta, temp1); x.Add(temp1, temp2); temp2.CopyTo(x); // Check convergence and see if we can bail if (iterator.DetermineStatus(iterationNumber, result, input, pseudoResiduals) != IterationStatus.Continue) { // Calculate the real values preconditioner.Approximate(x, result); // Calculate the true residual. Use the temp vector for that // so that we don't pollute the pseudoResidual vector for no // good reason. CalculateTrueResidual(matrix, temp, result, input); // Now recheck the convergence if (iterator.DetermineStatus(iterationNumber, result, input, temp) != IterationStatus.Continue) { // We're all good now. return; } } // The odd step if (!IsEven(iterationNumber)) { if (rho.Real.AlmostEqualNumbersBetween(0, 1) && rho.Imaginary.AlmostEqualNumbersBetween(0, 1)) { // FAIL HERE iterator.Cancel(); break; } var rhoNew = r.ConjugateDotProduct(pseudoResiduals); var beta = rhoNew/rho; // Update rho for the next loop rho = rhoNew; // yOdd = pseudoResiduals + beta * yOdd yodd.Multiply(beta, temp1); pseudoResiduals.Add(temp1, yeven); // Solve M temp = yOdd preconditioner.Approximate(yeven, temp); // uOdd = A temp matrix.Multiply(temp, ueven); // v = uEven + beta * (uOdd + beta * v) v.Multiply(beta, temp1); uodd.Add(temp1, temp); temp.Multiply(beta, temp1); ueven.Add(temp1, v); } // Calculate the real values preconditioner.Approximate(x, result); iterationNumber++; } } } }