context
stringlengths
2.52k
185k
gt
stringclasses
1 value
#if ENABLE_PLAYFABADMIN_API using PlayFab.AdminModels; namespace PlayFab.Events { public partial class PlayFabEvents { public event PlayFabRequestEvent<CreatePlayerSharedSecretRequest> OnAdminCreatePlayerSharedSecretRequestEvent; public event PlayFabResultEvent<CreatePlayerSharedSecretResult> OnAdminCreatePlayerSharedSecretResultEvent; public event PlayFabRequestEvent<DeletePlayerSharedSecretRequest> OnAdminDeletePlayerSharedSecretRequestEvent; public event PlayFabResultEvent<DeletePlayerSharedSecretResult> OnAdminDeletePlayerSharedSecretResultEvent; public event PlayFabRequestEvent<GetPlayerSharedSecretsRequest> OnAdminGetPlayerSharedSecretsRequestEvent; public event PlayFabResultEvent<GetPlayerSharedSecretsResult> OnAdminGetPlayerSharedSecretsResultEvent; public event PlayFabRequestEvent<GetPolicyRequest> OnAdminGetPolicyRequestEvent; public event PlayFabResultEvent<GetPolicyResponse> OnAdminGetPolicyResultEvent; public event PlayFabRequestEvent<SetPlayerSecretRequest> OnAdminSetPlayerSecretRequestEvent; public event PlayFabResultEvent<SetPlayerSecretResult> OnAdminSetPlayerSecretResultEvent; public event PlayFabRequestEvent<UpdatePlayerSharedSecretRequest> OnAdminUpdatePlayerSharedSecretRequestEvent; public event PlayFabResultEvent<UpdatePlayerSharedSecretResult> OnAdminUpdatePlayerSharedSecretResultEvent; public event PlayFabRequestEvent<UpdatePolicyRequest> OnAdminUpdatePolicyRequestEvent; public event PlayFabResultEvent<UpdatePolicyResponse> OnAdminUpdatePolicyResultEvent; public event PlayFabRequestEvent<BanUsersRequest> OnAdminBanUsersRequestEvent; public event PlayFabResultEvent<BanUsersResult> OnAdminBanUsersResultEvent; public event PlayFabRequestEvent<DeletePlayerRequest> OnAdminDeletePlayerRequestEvent; public event PlayFabResultEvent<DeletePlayerResult> OnAdminDeletePlayerResultEvent; public event PlayFabRequestEvent<LookupUserAccountInfoRequest> OnAdminGetUserAccountInfoRequestEvent; public event PlayFabResultEvent<LookupUserAccountInfoResult> OnAdminGetUserAccountInfoResultEvent; public event PlayFabRequestEvent<GetUserBansRequest> OnAdminGetUserBansRequestEvent; public event PlayFabResultEvent<GetUserBansResult> OnAdminGetUserBansResultEvent; public event PlayFabRequestEvent<ResetUsersRequest> OnAdminResetUsersRequestEvent; public event PlayFabResultEvent<BlankResult> OnAdminResetUsersResultEvent; public event PlayFabRequestEvent<RevokeAllBansForUserRequest> OnAdminRevokeAllBansForUserRequestEvent; public event PlayFabResultEvent<RevokeAllBansForUserResult> OnAdminRevokeAllBansForUserResultEvent; public event PlayFabRequestEvent<RevokeBansRequest> OnAdminRevokeBansRequestEvent; public event PlayFabResultEvent<RevokeBansResult> OnAdminRevokeBansResultEvent; public event PlayFabRequestEvent<SendAccountRecoveryEmailRequest> OnAdminSendAccountRecoveryEmailRequestEvent; public event PlayFabResultEvent<SendAccountRecoveryEmailResult> OnAdminSendAccountRecoveryEmailResultEvent; public event PlayFabRequestEvent<UpdateBansRequest> OnAdminUpdateBansRequestEvent; public event PlayFabResultEvent<UpdateBansResult> OnAdminUpdateBansResultEvent; public event PlayFabRequestEvent<UpdateUserTitleDisplayNameRequest> OnAdminUpdateUserTitleDisplayNameRequestEvent; public event PlayFabResultEvent<UpdateUserTitleDisplayNameResult> OnAdminUpdateUserTitleDisplayNameResultEvent; public event PlayFabRequestEvent<CreatePlayerStatisticDefinitionRequest> OnAdminCreatePlayerStatisticDefinitionRequestEvent; public event PlayFabResultEvent<CreatePlayerStatisticDefinitionResult> OnAdminCreatePlayerStatisticDefinitionResultEvent; public event PlayFabRequestEvent<DeleteUsersRequest> OnAdminDeleteUsersRequestEvent; public event PlayFabResultEvent<DeleteUsersResult> OnAdminDeleteUsersResultEvent; public event PlayFabRequestEvent<GetDataReportRequest> OnAdminGetDataReportRequestEvent; public event PlayFabResultEvent<GetDataReportResult> OnAdminGetDataReportResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticDefinitionsRequest> OnAdminGetPlayerStatisticDefinitionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticDefinitionsResult> OnAdminGetPlayerStatisticDefinitionsResultEvent; public event PlayFabRequestEvent<GetPlayerStatisticVersionsRequest> OnAdminGetPlayerStatisticVersionsRequestEvent; public event PlayFabResultEvent<GetPlayerStatisticVersionsResult> OnAdminGetPlayerStatisticVersionsResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserInternalDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserInternalDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserPublisherDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserPublisherDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserPublisherInternalDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserPublisherInternalDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<GetUserDataRequest> OnAdminGetUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<GetUserDataResult> OnAdminGetUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<IncrementPlayerStatisticVersionRequest> OnAdminIncrementPlayerStatisticVersionRequestEvent; public event PlayFabResultEvent<IncrementPlayerStatisticVersionResult> OnAdminIncrementPlayerStatisticVersionResultEvent; public event PlayFabRequestEvent<RefundPurchaseRequest> OnAdminRefundPurchaseRequestEvent; public event PlayFabResultEvent<RefundPurchaseResponse> OnAdminRefundPurchaseResultEvent; public event PlayFabRequestEvent<ResetUserStatisticsRequest> OnAdminResetUserStatisticsRequestEvent; public event PlayFabResultEvent<ResetUserStatisticsResult> OnAdminResetUserStatisticsResultEvent; public event PlayFabRequestEvent<ResolvePurchaseDisputeRequest> OnAdminResolvePurchaseDisputeRequestEvent; public event PlayFabResultEvent<ResolvePurchaseDisputeResponse> OnAdminResolvePurchaseDisputeResultEvent; public event PlayFabRequestEvent<UpdatePlayerStatisticDefinitionRequest> OnAdminUpdatePlayerStatisticDefinitionRequestEvent; public event PlayFabResultEvent<UpdatePlayerStatisticDefinitionResult> OnAdminUpdatePlayerStatisticDefinitionResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnAdminUpdateUserDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserDataResultEvent; public event PlayFabRequestEvent<UpdateUserInternalDataRequest> OnAdminUpdateUserInternalDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserInternalDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnAdminUpdateUserPublisherDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserPublisherDataResultEvent; public event PlayFabRequestEvent<UpdateUserInternalDataRequest> OnAdminUpdateUserPublisherInternalDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserPublisherInternalDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnAdminUpdateUserPublisherReadOnlyDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserPublisherReadOnlyDataResultEvent; public event PlayFabRequestEvent<UpdateUserDataRequest> OnAdminUpdateUserReadOnlyDataRequestEvent; public event PlayFabResultEvent<UpdateUserDataResult> OnAdminUpdateUserReadOnlyDataResultEvent; public event PlayFabRequestEvent<AddNewsRequest> OnAdminAddNewsRequestEvent; public event PlayFabResultEvent<AddNewsResult> OnAdminAddNewsResultEvent; public event PlayFabRequestEvent<AddVirtualCurrencyTypesRequest> OnAdminAddVirtualCurrencyTypesRequestEvent; public event PlayFabResultEvent<BlankResult> OnAdminAddVirtualCurrencyTypesResultEvent; public event PlayFabRequestEvent<DeleteStoreRequest> OnAdminDeleteStoreRequestEvent; public event PlayFabResultEvent<DeleteStoreResult> OnAdminDeleteStoreResultEvent; public event PlayFabRequestEvent<GetCatalogItemsRequest> OnAdminGetCatalogItemsRequestEvent; public event PlayFabResultEvent<GetCatalogItemsResult> OnAdminGetCatalogItemsResultEvent; public event PlayFabRequestEvent<GetPublisherDataRequest> OnAdminGetPublisherDataRequestEvent; public event PlayFabResultEvent<GetPublisherDataResult> OnAdminGetPublisherDataResultEvent; public event PlayFabRequestEvent<GetRandomResultTablesRequest> OnAdminGetRandomResultTablesRequestEvent; public event PlayFabResultEvent<GetRandomResultTablesResult> OnAdminGetRandomResultTablesResultEvent; public event PlayFabRequestEvent<GetStoreItemsRequest> OnAdminGetStoreItemsRequestEvent; public event PlayFabResultEvent<GetStoreItemsResult> OnAdminGetStoreItemsResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnAdminGetTitleDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnAdminGetTitleDataResultEvent; public event PlayFabRequestEvent<GetTitleDataRequest> OnAdminGetTitleInternalDataRequestEvent; public event PlayFabResultEvent<GetTitleDataResult> OnAdminGetTitleInternalDataResultEvent; public event PlayFabRequestEvent<ListVirtualCurrencyTypesRequest> OnAdminListVirtualCurrencyTypesRequestEvent; public event PlayFabResultEvent<ListVirtualCurrencyTypesResult> OnAdminListVirtualCurrencyTypesResultEvent; public event PlayFabRequestEvent<RemoveVirtualCurrencyTypesRequest> OnAdminRemoveVirtualCurrencyTypesRequestEvent; public event PlayFabResultEvent<BlankResult> OnAdminRemoveVirtualCurrencyTypesResultEvent; public event PlayFabRequestEvent<UpdateCatalogItemsRequest> OnAdminSetCatalogItemsRequestEvent; public event PlayFabResultEvent<UpdateCatalogItemsResult> OnAdminSetCatalogItemsResultEvent; public event PlayFabRequestEvent<UpdateStoreItemsRequest> OnAdminSetStoreItemsRequestEvent; public event PlayFabResultEvent<UpdateStoreItemsResult> OnAdminSetStoreItemsResultEvent; public event PlayFabRequestEvent<SetTitleDataRequest> OnAdminSetTitleDataRequestEvent; public event PlayFabResultEvent<SetTitleDataResult> OnAdminSetTitleDataResultEvent; public event PlayFabRequestEvent<SetTitleDataRequest> OnAdminSetTitleInternalDataRequestEvent; public event PlayFabResultEvent<SetTitleDataResult> OnAdminSetTitleInternalDataResultEvent; public event PlayFabRequestEvent<SetupPushNotificationRequest> OnAdminSetupPushNotificationRequestEvent; public event PlayFabResultEvent<SetupPushNotificationResult> OnAdminSetupPushNotificationResultEvent; public event PlayFabRequestEvent<UpdateCatalogItemsRequest> OnAdminUpdateCatalogItemsRequestEvent; public event PlayFabResultEvent<UpdateCatalogItemsResult> OnAdminUpdateCatalogItemsResultEvent; public event PlayFabRequestEvent<UpdateRandomResultTablesRequest> OnAdminUpdateRandomResultTablesRequestEvent; public event PlayFabResultEvent<UpdateRandomResultTablesResult> OnAdminUpdateRandomResultTablesResultEvent; public event PlayFabRequestEvent<UpdateStoreItemsRequest> OnAdminUpdateStoreItemsRequestEvent; public event PlayFabResultEvent<UpdateStoreItemsResult> OnAdminUpdateStoreItemsResultEvent; public event PlayFabRequestEvent<AddUserVirtualCurrencyRequest> OnAdminAddUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAdminAddUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<GetUserInventoryRequest> OnAdminGetUserInventoryRequestEvent; public event PlayFabResultEvent<GetUserInventoryResult> OnAdminGetUserInventoryResultEvent; public event PlayFabRequestEvent<GrantItemsToUsersRequest> OnAdminGrantItemsToUsersRequestEvent; public event PlayFabResultEvent<GrantItemsToUsersResult> OnAdminGrantItemsToUsersResultEvent; public event PlayFabRequestEvent<RevokeInventoryItemRequest> OnAdminRevokeInventoryItemRequestEvent; public event PlayFabResultEvent<RevokeInventoryResult> OnAdminRevokeInventoryItemResultEvent; public event PlayFabRequestEvent<SubtractUserVirtualCurrencyRequest> OnAdminSubtractUserVirtualCurrencyRequestEvent; public event PlayFabResultEvent<ModifyUserVirtualCurrencyResult> OnAdminSubtractUserVirtualCurrencyResultEvent; public event PlayFabRequestEvent<GetMatchmakerGameInfoRequest> OnAdminGetMatchmakerGameInfoRequestEvent; public event PlayFabResultEvent<GetMatchmakerGameInfoResult> OnAdminGetMatchmakerGameInfoResultEvent; public event PlayFabRequestEvent<GetMatchmakerGameModesRequest> OnAdminGetMatchmakerGameModesRequestEvent; public event PlayFabResultEvent<GetMatchmakerGameModesResult> OnAdminGetMatchmakerGameModesResultEvent; public event PlayFabRequestEvent<ModifyMatchmakerGameModesRequest> OnAdminModifyMatchmakerGameModesRequestEvent; public event PlayFabResultEvent<ModifyMatchmakerGameModesResult> OnAdminModifyMatchmakerGameModesResultEvent; public event PlayFabRequestEvent<AddServerBuildRequest> OnAdminAddServerBuildRequestEvent; public event PlayFabResultEvent<AddServerBuildResult> OnAdminAddServerBuildResultEvent; public event PlayFabRequestEvent<GetServerBuildInfoRequest> OnAdminGetServerBuildInfoRequestEvent; public event PlayFabResultEvent<GetServerBuildInfoResult> OnAdminGetServerBuildInfoResultEvent; public event PlayFabRequestEvent<GetServerBuildUploadURLRequest> OnAdminGetServerBuildUploadUrlRequestEvent; public event PlayFabResultEvent<GetServerBuildUploadURLResult> OnAdminGetServerBuildUploadUrlResultEvent; public event PlayFabRequestEvent<ListBuildsRequest> OnAdminListServerBuildsRequestEvent; public event PlayFabResultEvent<ListBuildsResult> OnAdminListServerBuildsResultEvent; public event PlayFabRequestEvent<ModifyServerBuildRequest> OnAdminModifyServerBuildRequestEvent; public event PlayFabResultEvent<ModifyServerBuildResult> OnAdminModifyServerBuildResultEvent; public event PlayFabRequestEvent<RemoveServerBuildRequest> OnAdminRemoveServerBuildRequestEvent; public event PlayFabResultEvent<RemoveServerBuildResult> OnAdminRemoveServerBuildResultEvent; public event PlayFabRequestEvent<SetPublisherDataRequest> OnAdminSetPublisherDataRequestEvent; public event PlayFabResultEvent<SetPublisherDataResult> OnAdminSetPublisherDataResultEvent; public event PlayFabRequestEvent<GetCloudScriptRevisionRequest> OnAdminGetCloudScriptRevisionRequestEvent; public event PlayFabResultEvent<GetCloudScriptRevisionResult> OnAdminGetCloudScriptRevisionResultEvent; public event PlayFabRequestEvent<GetCloudScriptVersionsRequest> OnAdminGetCloudScriptVersionsRequestEvent; public event PlayFabResultEvent<GetCloudScriptVersionsResult> OnAdminGetCloudScriptVersionsResultEvent; public event PlayFabRequestEvent<SetPublishedRevisionRequest> OnAdminSetPublishedRevisionRequestEvent; public event PlayFabResultEvent<SetPublishedRevisionResult> OnAdminSetPublishedRevisionResultEvent; public event PlayFabRequestEvent<UpdateCloudScriptRequest> OnAdminUpdateCloudScriptRequestEvent; public event PlayFabResultEvent<UpdateCloudScriptResult> OnAdminUpdateCloudScriptResultEvent; public event PlayFabRequestEvent<DeleteContentRequest> OnAdminDeleteContentRequestEvent; public event PlayFabResultEvent<BlankResult> OnAdminDeleteContentResultEvent; public event PlayFabRequestEvent<GetContentListRequest> OnAdminGetContentListRequestEvent; public event PlayFabResultEvent<GetContentListResult> OnAdminGetContentListResultEvent; public event PlayFabRequestEvent<GetContentUploadUrlRequest> OnAdminGetContentUploadUrlRequestEvent; public event PlayFabResultEvent<GetContentUploadUrlResult> OnAdminGetContentUploadUrlResultEvent; public event PlayFabRequestEvent<ResetCharacterStatisticsRequest> OnAdminResetCharacterStatisticsRequestEvent; public event PlayFabResultEvent<ResetCharacterStatisticsResult> OnAdminResetCharacterStatisticsResultEvent; public event PlayFabRequestEvent<AddPlayerTagRequest> OnAdminAddPlayerTagRequestEvent; public event PlayFabResultEvent<AddPlayerTagResult> OnAdminAddPlayerTagResultEvent; public event PlayFabRequestEvent<GetAllActionGroupsRequest> OnAdminGetAllActionGroupsRequestEvent; public event PlayFabResultEvent<GetAllActionGroupsResult> OnAdminGetAllActionGroupsResultEvent; public event PlayFabRequestEvent<GetAllSegmentsRequest> OnAdminGetAllSegmentsRequestEvent; public event PlayFabResultEvent<GetAllSegmentsResult> OnAdminGetAllSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayersSegmentsRequest> OnAdminGetPlayerSegmentsRequestEvent; public event PlayFabResultEvent<GetPlayerSegmentsResult> OnAdminGetPlayerSegmentsResultEvent; public event PlayFabRequestEvent<GetPlayersInSegmentRequest> OnAdminGetPlayersInSegmentRequestEvent; public event PlayFabResultEvent<GetPlayersInSegmentResult> OnAdminGetPlayersInSegmentResultEvent; public event PlayFabRequestEvent<GetPlayerTagsRequest> OnAdminGetPlayerTagsRequestEvent; public event PlayFabResultEvent<GetPlayerTagsResult> OnAdminGetPlayerTagsResultEvent; public event PlayFabRequestEvent<RemovePlayerTagRequest> OnAdminRemovePlayerTagRequestEvent; public event PlayFabResultEvent<RemovePlayerTagResult> OnAdminRemovePlayerTagResultEvent; public event PlayFabRequestEvent<AbortTaskInstanceRequest> OnAdminAbortTaskInstanceRequestEvent; public event PlayFabResultEvent<EmptyResult> OnAdminAbortTaskInstanceResultEvent; public event PlayFabRequestEvent<CreateActionsOnPlayerSegmentTaskRequest> OnAdminCreateActionsOnPlayersInSegmentTaskRequestEvent; public event PlayFabResultEvent<CreateTaskResult> OnAdminCreateActionsOnPlayersInSegmentTaskResultEvent; public event PlayFabRequestEvent<CreateCloudScriptTaskRequest> OnAdminCreateCloudScriptTaskRequestEvent; public event PlayFabResultEvent<CreateTaskResult> OnAdminCreateCloudScriptTaskResultEvent; public event PlayFabRequestEvent<DeleteTaskRequest> OnAdminDeleteTaskRequestEvent; public event PlayFabResultEvent<EmptyResult> OnAdminDeleteTaskResultEvent; public event PlayFabRequestEvent<GetTaskInstanceRequest> OnAdminGetActionsOnPlayersInSegmentTaskInstanceRequestEvent; public event PlayFabResultEvent<GetActionsOnPlayersInSegmentTaskInstanceResult> OnAdminGetActionsOnPlayersInSegmentTaskInstanceResultEvent; public event PlayFabRequestEvent<GetTaskInstanceRequest> OnAdminGetCloudScriptTaskInstanceRequestEvent; public event PlayFabResultEvent<GetCloudScriptTaskInstanceResult> OnAdminGetCloudScriptTaskInstanceResultEvent; public event PlayFabRequestEvent<GetTaskInstancesRequest> OnAdminGetTaskInstancesRequestEvent; public event PlayFabResultEvent<GetTaskInstancesResult> OnAdminGetTaskInstancesResultEvent; public event PlayFabRequestEvent<GetTasksRequest> OnAdminGetTasksRequestEvent; public event PlayFabResultEvent<GetTasksResult> OnAdminGetTasksResultEvent; public event PlayFabRequestEvent<RunTaskRequest> OnAdminRunTaskRequestEvent; public event PlayFabResultEvent<RunTaskResult> OnAdminRunTaskResultEvent; public event PlayFabRequestEvent<UpdateTaskRequest> OnAdminUpdateTaskRequestEvent; public event PlayFabResultEvent<EmptyResult> OnAdminUpdateTaskResultEvent; } } #endif
using System; using LinqToTwitter; using Newtonsoft.Json; using Core.Domain; using Core.Data; using Integration.Twitter.Domain; namespace Integration.Twitter { public static class TwDbHelper { public static TwitterContext GetContext() { const string _key = "enterKey"; const string _secret = "enterSecret"; const string _token = "enterToken"; const string _tokenSecret = "enterTokenSecret"; var auth = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = _key, ConsumerSecret = _secret, AccessToken = _token, AccessTokenSecret = _tokenSecret } }; return new TwitterContext(auth); } //Gets tweets and updates azure database public static string GetNewMaxIDandUpdateDB(string twitterAccountToDisplay, ulong sinceID = 544516702412723892) { string currentDate = DateTime.Now.ToString(); string message = ""; var doTask = GetSearchTweetsAsync(twitterAccountToDisplay, sinceID); doTask.Wait(); message = "Please Print/Save this information for future records.\n Now the database is updated for " + twitterAccountToDisplay + " with previous StatusID (" + sinceID.ToString() + ") at " + currentDate + ".\n Now the new StatusID is " + GetNewMaxID(twitterAccountToDisplay).ToString(); return message; } //Gets new maxID public static ulong GetNewMaxID(string twitterAccountToDisplay) { //string newStatusID = "No MaxID found"; //UInt64 ulong newMaxID = 563722001925218304; // 544516702412723892; try { using (var db = new OnlyTweetContext()) { //Get only Status Tweet with New MaxID/StatusID from the database var query = (from t in db.OnlyTweetDB where t.ScreenName == twitterAccountToDisplay orderby t.CreatedAt descending select new { maxID = t.StatusID }).Take(1); //Console.WriteLine("All Status Tweet in the database:"); foreach (var item in query) { //Console.WriteLine("New MaxID is: {0}", item.StatusID); //newStatusID = item.maxID.ToString(); newMaxID = (ulong)item.maxID; break; } } } catch (Exception ex) { string innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : String.Empty; //Console.WriteLine("{0}\n{1}", ex.Message, innerMessage); } return newMaxID; // newStatusID; } //Gets tweets asynchronously public static async Task GetSearchTweetsAsync(string twitterAccountToDisplay, ulong sinceID) { try { var twitterCtx = GetContext(); //string twitterAccountToDisplay = "Linq2Twitr"; int count = 5; int maxStatuses = 30; int lastStatusCount = 0; //last tweet processed on previous query set //ulong sinceID = 544516702412723892; ulong maxID; var statusList = new List<Status>(); //only count var searchResponse = await (from search in twitterCtx.Search where search.Type == SearchType.Search && search.Query == "from:@" + twitterAccountToDisplay + " -retweets" && // -filter:retweets // -RT until:2012-10-26 search.Count == count select search) .SingleOrDefaultAsync(); if (searchResponse != null && searchResponse.Statuses != null) { List<Status> newStatuses = searchResponse.Statuses; // first tweet processed on current query maxID = newStatuses.Min(status => status.StatusID) - 1; statusList.AddRange(newStatuses); //adding if condition to fix Error : LinqToTwitter.TwitterQueryException: Missing or invalid url parameter //as SinceID is greater than MaxID, which is wrong according to the query. if (sinceID < maxID) { do { // now add sinceID and maxID searchResponse = await (from search in twitterCtx.Search where search.Type == SearchType.Search && search.Query == "from:@" + twitterAccountToDisplay + " -retweets" && // -filter:retweets // -RT search.Count == count && //search.Until == new DateTime(2014,12,1) && search.SinceID == sinceID && search.MaxID == maxID select search) .SingleOrDefaultAsync(); //.ToList(); if (searchResponse == null) break; if (searchResponse.Count > 0 && searchResponse.Statuses.Count > 0) { newStatuses = searchResponse.Statuses; // first tweet processed on current query maxID = newStatuses.Min(status => status.StatusID) - 1; statusList.AddRange(newStatuses); lastStatusCount = newStatuses.Count; } if (searchResponse.Count > 0 && searchResponse.Statuses.Count == 0) { lastStatusCount = 0; } } while (lastStatusCount != 0 && statusList.Count < maxStatuses); //(searchResponse.Count != 0 && statusList.Count < 30); } //searchResponse.Statuses.ForEach(tweet => Console.WriteLine( "User: {0}, Tweet: {1}", tweet.User.ScreenNameResponse, tweet.Text)); var tweetsOnlyList = from status in statusList //searchResponse.Statuses //Exclude replies and retweets where status.InReplyToScreenName == null && status.IncludeMyRetweet == false select new Status() { Text = status.Text, ScreenName = status.User.ScreenNameResponse, StatusID = status.StatusID, CreatedAt = status.CreatedAt //ProfileImageUrlHttps = status.ProfileImageUrlHttps }; //To display Tweets //foreach (var tweet in tweetsOnlyList) //{ // Console.WriteLine("User: {0},\n Tweet: {1},\n maxID: {2},\n CreatedAt: {3}\n", // tweet.ScreenNameResponse, // tweet.Text, // tweet.StatusID, // tweet.CreatedAt); //} //Set Tweets to Database SetTweetsOnly(tweetsOnlyList); } } catch (Exception ex) { Console.WriteLine("Error : " + ex); } } //Map tweets to list before writing to database public static List<OnlyTweet> SetTweetsOnly(IEnumerable<Status> statusTweets) //IQueryable { var sTweetsOnlyList = new List<OnlyTweet>(); try { // map to list sTweetsOnlyList = statusTweets .Select(sTweet => new OnlyTweet() { CreatedAt = sTweet.CreatedAt, ScreenName = sTweet.ScreenName, Text = sTweet.Text, StatusID = Convert.ToInt64(sTweet.StatusID) }) .ToList(); //Thread.Sleep(1000); //Write to Database SetTweetsOnlyToDB(sTweetsOnlyList); } catch (Exception ex) { Console.WriteLine("Error : " + ex); } return sTweetsOnlyList; } //Write tweets to azure database public static bool SetTweetsOnlyToDB(List<OnlyTweet> sTweetsOnlyList) { var sTweetExist = false; try { using (var db = new OnlyTweetContext()) { // Create and save a new status tweet //Console.Write("Text for new status tweet : "); int count = 0; foreach (var statusTweet in sTweetsOnlyList) { if (statusTweet != null) { //Console.WriteLine((count + 1) + ". {0}-{1}\n\t{2}", statusTweet.CreatedAt, statusTweet.Text, statusTweet.ScreenName); // Check if Status Tweets already exists in the database var query = from t in db.OnlyTweetDB where t.Text == statusTweet.Text orderby t.Text select t; sTweetExist = false; //Console.WriteLine("Reading all Status Tweets in the database..."); foreach (var item in query) { if (String.Equals(item.Text, statusTweet.Text) && String.Equals(item.CreatedAt, statusTweet.CreatedAt)) { // Status Tweet already exists, do not duplicate Console.WriteLine("Status tweet already exists: \n{0}", statusTweet.Text); sTweetExist = true; } } //Write Status Tweet to database if title doesn't exist in Db if (!sTweetExist) { var sTweet = new OnlyTweet { CreatedAt = statusTweet.CreatedAt, ScreenName = statusTweet.ScreenName, Text = statusTweet.Text, StatusID = statusTweet.StatusID }; db.OnlyTweetDB.Add(sTweet); db.SaveChanges(); count++; sTweetExist = true; } } else { Console.WriteLine("No status tweets found in the database."); } } //Console.WriteLine("Press any key to exit..."); //Console.ReadKey(); } } catch (Exception ex) { string innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : String.Empty; Console.WriteLine("{0}\n{1}", ex.Message, innerMessage); } return sTweetExist; } // Gets Twitter Feed from azure database public static ICollection<StatusTweet> GetTweetsOnlyFeedFromDB(string twitterAccountToDisplay) { var stList = new List<StatusTweet>(); try { using (var dbContext = new OnlyTweetContext()) { dbContext.Database.Connection.Open(); //Get top 20 Status Tweets from the database var query = (from t in dbContext.OnlyTweetDB where t.ScreenName == twitterAccountToDisplay orderby t.CreatedAt descending select t).Take(20); //Console.WriteLine("All Status Tweet in the database:"); foreach (var item in query) { var st = new StatusTweet(); //Console.WriteLine("{0}:\n{1}\n\t{2}\n\t{3}\n\", item.StatusID, item.ScreenName, item.Text, item.CreatedAt); st.Text = item.Text; st.CreatedAt = item.CreatedAt; st.StatusID = item.StatusID; st.ScreenName = item.ScreenName; st.StringStatusID = item.StatusID.ToString(); switch (item.ScreenName) { case "Linq2Twitr": //Sample Username: https://twitter.com/Linq2Twitr st.ProfileImageUrlHttps = "https://pbs.twimg.com/profile_images/378800000625948439/57f4351535721aeedc632745ceaacfea_400x400.png"; break; default: st.ProfileImageUrlHttps = ""; break; } stList.Add(st); } } } catch (Exception ex) { string innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : String.Empty; //Console.WriteLine("{0}\n{1}", ex.Message, innerMessage); } return stList.ToList(); } } }
// <copyright file="DivergenceStopCriterionTest.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex32; using MathNet.Numerics.LinearAlgebra.Solvers; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32.Solvers.StopCriterion { using Numerics; /// <summary> /// Divergence stop criterion test. /// </summary> [TestFixture, Category("LASolver")] public sealed class DivergenceStopCriterionTest { /// <summary> /// Create with negative maximum increase throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void CreateWithNegativeMaximumIncreaseThrowsArgumentOutOfRangeException() { Assert.That(() => new DivergenceStopCriterion<Complex32>(-0.1), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Create with illegal minimum iterations throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void CreateWithIllegalMinimumIterationsThrowsArgumentOutOfRangeException() { Assert.That(() => new DivergenceStopCriterion<Complex32>(minimumIterations: 2), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can create stop criterion. /// </summary> [Test] public void Create() { var criterion = new DivergenceStopCriterion<Complex32>(0.1, 3); Assert.IsNotNull(criterion, "There should be a criterion"); Assert.AreEqual(0.1, criterion.MaximumRelativeIncrease, "Incorrect maximum"); Assert.AreEqual(3, criterion.MinimumNumberOfIterations, "Incorrect iteration count"); } /// <summary> /// Determine status with illegal iteration number throws <c>ArgumentOutOfRangeException</c>. /// </summary> [Test] public void DetermineStatusWithIllegalIterationNumberThrowsArgumentOutOfRangeException() { var criterion = new DivergenceStopCriterion<Complex32>(0.5, 15); Assert.That(() => criterion.DetermineStatus( -1, Vector<Complex32>.Build.Dense(3, 4), Vector<Complex32>.Build.Dense(3, 5), Vector<Complex32>.Build.Dense(3, 6)), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can determine status with too few iterations. /// </summary> [Test] public void DetermineStatusWithTooFewIterations() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<Complex32>(Increase, Iterations); // Add residuals. We should not diverge because we'll have to few iterations for (var i = 0; i < Iterations - 1; i++) { var status = criterion.DetermineStatus( i, new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32((i + 1)*(Increase + 0.1f), 0) })); Assert.AreEqual(IterationStatus.Continue, status, "Status check fail."); } } /// <summary> /// Can determine status with no divergence. /// </summary> [Test] public void DetermineStatusWithNoDivergence() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<Complex32>(Increase, Iterations); // Add residuals. We should not diverge because we won't have enough increase for (var i = 0; i < Iterations*2; i++) { var status = criterion.DetermineStatus( i, new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32((i + 1)*(Increase - 0.01f), 0) })); Assert.AreEqual(IterationStatus.Continue, status, "Status check fail."); } } /// <summary> /// Can determine status with divergence through NaN. /// </summary> [Test] public void DetermineStatusWithDivergenceThroughNaN() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<Complex32>(Increase, Iterations); // Add residuals. We should not diverge because we'll have to few iterations for (var i = 0; i < Iterations - 5; i++) { var status = criterion.DetermineStatus( i, new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32((i + 1)*(Increase - 0.01f), 0) })); Assert.AreEqual(IterationStatus.Continue, status, "Status check fail."); } // Now make it fail by throwing in a NaN var status2 = criterion.DetermineStatus( Iterations, new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(float.NaN, 0) })); Assert.AreEqual(IterationStatus.Diverged, status2, "Status check fail."); } /// <summary> /// Can determine status with divergence. /// </summary> [Test] public void DetermineStatusWithDivergence() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<Complex32>(Increase, Iterations); // Add residuals. We should not diverge because we'll have one to few iterations float previous = 1; for (var i = 0; i < Iterations - 1; i++) { previous *= 1 + Increase + 0.01f; var status = criterion.DetermineStatus( i, new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(previous, 0) })); Assert.AreEqual(IterationStatus.Continue, status, "Status check fail."); } // Add the final residual. Now we should have divergence previous *= 1 + Increase + 0.01f; var status2 = criterion.DetermineStatus( Iterations - 1, new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(previous, 0) })); Assert.AreEqual(IterationStatus.Diverged, status2, "Status check fail."); } /// <summary> /// Can reset calculation state. /// </summary> [Test] public void ResetCalculationState() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<Complex32>(Increase, Iterations); // Add residuals. Blow it up instantly var status = criterion.DetermineStatus( 1, new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(1.0f, 0) }), new DenseVector(new[] { new Complex32(float.NaN, 0) })); Assert.AreEqual(IterationStatus.Diverged, status, "Status check fail."); // Reset the state criterion.Reset(); Assert.AreEqual(Increase, criterion.MaximumRelativeIncrease, "Incorrect maximum"); Assert.AreEqual(Iterations, criterion.MinimumNumberOfIterations, "Incorrect iteration count"); Assert.AreEqual(IterationStatus.Continue, criterion.Status, "Status check fail."); } /// <summary> /// Can clone stop criterion. /// </summary> [Test] public void Clone() { const float Increase = 0.5f; const int Iterations = 10; var criterion = new DivergenceStopCriterion<Complex32>(Increase, Iterations); Assert.IsNotNull(criterion, "There should be a criterion"); var clone = criterion.Clone(); Assert.IsInstanceOf(typeof (DivergenceStopCriterion<Complex32>), clone, "Wrong criterion type"); var clonedCriterion = clone as DivergenceStopCriterion<Complex32>; Assert.IsNotNull(clonedCriterion); Assert.AreEqual(criterion.MaximumRelativeIncrease, clonedCriterion.MaximumRelativeIncrease, "Incorrect maximum"); Assert.AreEqual(criterion.MinimumNumberOfIterations, clonedCriterion.MinimumNumberOfIterations, "Incorrect iteration count"); } } }
using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using System.IO; using System; using Agens.StickersEditor.UnityEditor.iOS.Xcode.PBX; using UnityEngine; namespace Agens.StickersEditor.UnityEditor.iOS.Xcode { using PBXBuildFileSection = KnownSectionBase<PBXBuildFileData>; using PBXFileReferenceSection = KnownSectionBase<PBXFileReferenceData>; using PBXGroupSection = KnownSectionBase<PBXGroupData>; using PBXContainerItemProxySection = KnownSectionBase<PBXContainerItemProxyData>; using PBXReferenceProxySection = KnownSectionBase<PBXReferenceProxyData>; using PBXSourcesBuildPhaseSection = KnownSectionBase<PBXSourcesBuildPhaseData>; using PBXFrameworksBuildPhaseSection= KnownSectionBase<PBXFrameworksBuildPhaseData>; using PBXResourcesBuildPhaseSection = KnownSectionBase<PBXResourcesBuildPhaseData>; using PBXCopyFilesBuildPhaseSection = KnownSectionBase<PBXCopyFilesBuildPhaseData>; using PBXShellScriptBuildPhaseSection = KnownSectionBase<PBXShellScriptBuildPhaseData>; using PBXVariantGroupSection = KnownSectionBase<PBXVariantGroupData>; using PBXNativeTargetSection = KnownSectionBase<PBXNativeTargetData>; using PBXTargetDependencySection = KnownSectionBase<PBXTargetDependencyData>; using XCBuildConfigurationSection = KnownSectionBase<XCBuildConfigurationData>; using XCConfigurationListSection = KnownSectionBase<XCConfigurationListData>; using UnknownSection = KnownSectionBase<PBXObjectData>; // Determines the tree the given path is relative to public enum PBXSourceTree { Absolute, // The path is absolute Source, // The path is relative to the source folder Group, // The path is relative to the folder it's in. This enum is used only internally, // do not use it as function parameter Build, // The path is relative to the build products folder Developer, // The path is relative to the developer folder Sdk // The path is relative to the sdk folder }; public class PBXProject { PBXProjectData m_Data = new PBXProjectData(); // convenience accessors for public members of data. This is temporary; will be fixed by an interface change // of PBXProjectData PBXContainerItemProxySection containerItems { get { return m_Data.containerItems; } } PBXReferenceProxySection references { get { return m_Data.references; } } PBXSourcesBuildPhaseSection sources { get { return m_Data.sources; } } PBXFrameworksBuildPhaseSection frameworks { get { return m_Data.frameworks; } } PBXResourcesBuildPhaseSection resources { get { return m_Data.resources; } } PBXCopyFilesBuildPhaseSection copyFiles { get { return m_Data.copyFiles; } } PBXShellScriptBuildPhaseSection shellScripts { get { return m_Data.shellScripts; } } PBXNativeTargetSection nativeTargets { get { return m_Data.nativeTargets; } } PBXTargetDependencySection targetDependencies { get { return m_Data.targetDependencies; } } PBXVariantGroupSection variantGroups { get { return m_Data.variantGroups; } } XCBuildConfigurationSection buildConfigs { get { return m_Data.buildConfigs; } } XCConfigurationListSection configs { get { return m_Data.configs; } } PBXProjectSection projectSection { get { return m_Data.project; } } PBXBuildFileData BuildFilesGet(string guid) { return m_Data.BuildFilesGet(guid); } void BuildFilesAdd(string targetGuid, PBXBuildFileData buildFile) { m_Data.BuildFilesAdd(targetGuid, buildFile); } void BuildFilesRemove(string targetGuid, string fileGuid) { m_Data.BuildFilesRemove(targetGuid, fileGuid); } PBXBuildFileData BuildFilesGetForSourceFile(string targetGuid, string fileGuid) { return m_Data.BuildFilesGetForSourceFile(targetGuid, fileGuid); } IEnumerable<PBXBuildFileData> BuildFilesGetAll() { return m_Data.BuildFilesGetAll(); } void FileRefsAdd(string realPath, string projectPath, PBXGroupData parent, PBXFileReferenceData fileRef) { m_Data.FileRefsAdd(realPath, projectPath, parent, fileRef); } PBXFileReferenceData FileRefsGet(string guid) { return m_Data.FileRefsGet(guid); } PBXFileReferenceData FileRefsGetByRealPath(string path, PBXSourceTree sourceTree) { return m_Data.FileRefsGetByRealPath(path, sourceTree); } PBXFileReferenceData FileRefsGetByProjectPath(string path) { return m_Data.FileRefsGetByProjectPath(path); } void FileRefsRemove(string guid) { m_Data.FileRefsRemove(guid); } PBXGroupData GroupsGet(string guid) { return m_Data.GroupsGet(guid); } PBXGroupData GroupsGetByChild(string childGuid) { return m_Data.GroupsGetByChild(childGuid); } PBXGroupData GroupsGetMainGroup() { return m_Data.GroupsGetMainGroup(); } PBXGroupData GroupsGetByProjectPath(string sourceGroup) { return m_Data.GroupsGetByProjectPath(sourceGroup); } void GroupsAdd(string projectPath, PBXGroupData parent, PBXGroupData gr) { m_Data.GroupsAdd(projectPath, parent, gr); } void GroupsAddDuplicate(PBXGroupData gr) { m_Data.GroupsAddDuplicate(gr); } void GroupsRemove(string guid) { m_Data.GroupsRemove(guid); } FileGUIDListBase BuildSectionAny(PBXNativeTargetData target, string path, bool isFolderRef) { return m_Data.BuildSectionAny(target, path, isFolderRef); } public static string GetPBXProjectPath(string buildPath) { return PBX.Utils.CombinePaths(buildPath, "Unity-iPhone.xcodeproj/project.pbxproj"); } public static string GetUnityTargetName() { return "Unity-iPhone"; } public static string GetUnityTestTargetName() { return "Unity-iPhone Tests"; } internal string ProjectGuid() { return projectSection.project.guid; } /// Returns a guid identifying native target with name @a name public string TargetGuidByName(string name) { foreach (var entry in nativeTargets.GetEntries()) if (entry.Value.name == name) return entry.Key; return null; } /// Returns the name of the native target identified with guid @a guid public string TargetNameByGuid(string guid) { var target = nativeTargets[guid]; if (target == null) return null; else return target.name; } public static bool IsKnownExtension(string ext) { return FileTypeUtils.IsKnownExtension(ext); } public static bool IsBuildable(string ext) { return FileTypeUtils.IsBuildableFile(ext); } // The same file can be referred to by more than one project path. private string AddFileImpl(string path, string projectPath, PBXSourceTree tree, bool isFolderReference) { path = PBX.Utils.FixSlashesInPath(path); projectPath = PBX.Utils.FixSlashesInPath(projectPath); if (!isFolderReference && Path.GetExtension(path) != Path.GetExtension(projectPath)) throw new Exception("Project and real path extensions do not match"); string guid = FindFileGuidByProjectPath(projectPath); if (guid == null) guid = FindFileGuidByRealPath(path); if (guid == null) { PBXFileReferenceData fileRef; if (isFolderReference) fileRef = PBXFileReferenceData.CreateFromFolderReference(path, PBX.Utils.GetFilenameFromPath(projectPath), tree); else fileRef = PBXFileReferenceData.CreateFromFile(path, PBX.Utils.GetFilenameFromPath(projectPath), tree); PBXGroupData parent = CreateSourceGroup(PBX.Utils.GetDirectoryFromPath(projectPath)); parent.children.AddGUID(fileRef.guid); FileRefsAdd(path, projectPath, parent, fileRef); guid = fileRef.guid; } return guid; } // The extension of the files identified by path and projectPath must be the same. public string AddFile(string path, string projectPath) { return AddFileImpl(path, projectPath, PBXSourceTree.Source, false); } // sourceTree must not be PBXSourceTree.Group public string AddFile(string path, string projectPath, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception("sourceTree must not be PBXSourceTree.Group"); return AddFileImpl(path, projectPath, sourceTree, false); } public string AddFolderReference(string path, string projectPath) { return AddFileImpl(path, projectPath, PBXSourceTree.Source, true); } // sourceTree must not be PBXSourceTree.Group public string AddFolderReference(string path, string projectPath, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception("sourceTree must not be PBXSourceTree.Group"); return AddFileImpl(path, projectPath, sourceTree, true); } private void AddBuildFileImpl(string targetGuid, string fileGuid, bool weak, string compileFlags) { PBXNativeTargetData target = nativeTargets[targetGuid]; PBXFileReferenceData fileRef = FileRefsGet(fileGuid); string ext = Path.GetExtension(fileRef.path); if (FileTypeUtils.IsBuildable(ext, fileRef.isFolderReference) && BuildFilesGetForSourceFile(targetGuid, fileGuid) == null) { PBXBuildFileData buildFile = PBXBuildFileData.CreateFromFile(fileGuid, weak, compileFlags); BuildFilesAdd(targetGuid, buildFile); BuildSectionAny(target, ext, fileRef.isFolderReference).files.AddGUID(buildFile.guid); } } public void AddFileToBuild(string targetGuid, string fileGuid) { AddBuildFileImpl(targetGuid, fileGuid, false, null); } public void AddFileToBuildWithFlags(string targetGuid, string fileGuid, string compileFlags) { AddBuildFileImpl(targetGuid, fileGuid, false, compileFlags); } // returns null on error // FIXME: at the moment returns all flags as the first element of the array public List<string> GetCompileFlagsForFile(string targetGuid, string fileGuid) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return null; if (buildFile.compileFlags == null) return new List<string>(); return new List<string> {buildFile.compileFlags}; } public void SetCompileFlagsForFile(string targetGuid, string fileGuid, List<string> compileFlags) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return; if (compileFlags == null) buildFile.compileFlags = null; else buildFile.compileFlags = string.Join(" ", compileFlags.ToArray()); } public void AddAssetTagForFile(string targetGuid, string fileGuid, string tag) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return; if (!buildFile.assetTags.Contains(tag)) buildFile.assetTags.Add(tag); if (!projectSection.project.knownAssetTags.Contains(tag)) projectSection.project.knownAssetTags.Add(tag); } public void RemoveAssetTagForFile(string targetGuid, string fileGuid, string tag) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return; buildFile.assetTags.Remove(tag); // remove from known tags if this was the last one foreach (var buildFile2 in BuildFilesGetAll()) { if (buildFile2.assetTags.Contains(tag)) return; } projectSection.project.knownAssetTags.Remove(tag); } public void AddAssetTagToDefaultInstall(string targetGuid, string tag) { if (!projectSection.project.knownAssetTags.Contains(tag)) return; AddBuildProperty(targetGuid, "ON_DEMAND_RESOURCES_INITIAL_INSTALL_TAGS", tag); } public void RemoveAssetTagFromDefaultInstall(string targetGuid, string tag) { UpdateBuildProperty(targetGuid, "ON_DEMAND_RESOURCES_INITIAL_INSTALL_TAGS", null, new string[] {tag}); } public void RemoveAssetTag(string tag) { foreach (var buildFile in BuildFilesGetAll()) buildFile.assetTags.Remove(tag); foreach (var targetGuid in nativeTargets.GetGuids()) RemoveAssetTagFromDefaultInstall(targetGuid, tag); projectSection.project.knownAssetTags.Remove(tag); } public bool ContainsFileByRealPath(string path) { return FindFileGuidByRealPath(path) != null; } // sourceTree must not be PBXSourceTree.Group public bool ContainsFileByRealPath(string path, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception("sourceTree must not be PBXSourceTree.Group"); return FindFileGuidByRealPath(path, sourceTree) != null; } public bool ContainsFileByProjectPath(string path) { return FindFileGuidByProjectPath(path) != null; } public bool HasFramework(string framework) { return ContainsFileByRealPath("System/Library/Frameworks/" + framework); } /// The framework must be specified with the '.framework' extension public void AddFrameworkToProject(string targetGuid, string framework, bool weak) { string fileGuid = AddFile("System/Library/Frameworks/" + framework, "Frameworks/" + framework, PBXSourceTree.Sdk); AddBuildFileImpl(targetGuid, fileGuid, weak, null); } /// The framework must be specified with the '.framework' extension // FIXME: targetGuid is ignored at the moment public void RemoveFrameworkFromProject(string targetGuid, string framework) { string fileGuid = FindFileGuidByRealPath("System/Library/Frameworks/" + framework); if (fileGuid != null) RemoveFile(fileGuid); } // sourceTree must not be PBXSourceTree.Group public string FindFileGuidByRealPath(string path, PBXSourceTree sourceTree) { //if (sourceTree == PBXSourceTree.Group) // throw new Exception("sourceTree must not be PBXSourceTree.Group"); path = PBX.Utils.FixSlashesInPath(path); var fileRef = FileRefsGetByRealPath(path, sourceTree); if (fileRef != null) return fileRef.guid; return null; } public string FindFileGuidByRealPath(string path) { path = PBX.Utils.FixSlashesInPath(path); foreach (var tree in FileTypeUtils.AllAbsoluteSourceTrees()) { string res = FindFileGuidByRealPath(path, tree); if (res != null) return res; } return null; } public string FindFileGuidByProjectPath(string path) { path = PBX.Utils.FixSlashesInPath(path); var fileRef = FileRefsGetByProjectPath(path); if (fileRef != null) return fileRef.guid; return null; } public void RemoveFileFromBuild(string targetGuid, string fileGuid) { var buildFile = BuildFilesGetForSourceFile(targetGuid, fileGuid); if (buildFile == null) return; BuildFilesRemove(targetGuid, fileGuid); string buildGuid = buildFile.guid; if (buildGuid != null) { foreach (var section in sources.GetEntries()) section.Value.files.RemoveGUID(buildGuid); foreach (var section in resources.GetEntries()) section.Value.files.RemoveGUID(buildGuid); foreach (var section in copyFiles.GetEntries()) section.Value.files.RemoveGUID(buildGuid); foreach (var section in frameworks.GetEntries()) section.Value.files.RemoveGUID(buildGuid); } } public void RemoveFile(string fileGuid) { if (fileGuid == null) return; // remove from parent PBXGroupData parent = GroupsGetByChild(fileGuid); if (parent != null) parent.children.RemoveGUID(fileGuid); RemoveGroupIfEmpty(parent); // remove actual file foreach (var target in nativeTargets.GetEntries()) RemoveFileFromBuild(target.Value.guid, fileGuid); FileRefsRemove(fileGuid); } void RemoveGroupIfEmpty(PBXGroupData gr) { if (gr.children.Count == 0 && gr != GroupsGetMainGroup()) { // remove from parent PBXGroupData parent = GroupsGetByChild(gr.guid); parent.children.RemoveGUID(gr.guid); RemoveGroupIfEmpty(parent); // remove actual group GroupsRemove(gr.guid); } } private void RemoveGroupChildrenRecursive(PBXGroupData parent) { List<string> children = new List<string>(parent.children); parent.children.Clear(); foreach (string guid in children) { PBXFileReferenceData file = FileRefsGet(guid); if (file != null) { foreach (var target in nativeTargets.GetEntries()) RemoveFileFromBuild(target.Value.guid, guid); FileRefsRemove(guid); continue; } PBXGroupData gr = GroupsGet(guid); if (gr != null) { RemoveGroupChildrenRecursive(gr); GroupsRemove(gr.guid); continue; } } } internal void RemoveFilesByProjectPathRecursive(string projectPath) { projectPath = PBX.Utils.FixSlashesInPath(projectPath); PBXGroupData gr = GroupsGetByProjectPath(projectPath); if (gr == null) return; RemoveGroupChildrenRecursive(gr); RemoveGroupIfEmpty(gr); } // Returns null on error internal List<string> GetGroupChildrenFiles(string projectPath) { projectPath = PBX.Utils.FixSlashesInPath(projectPath); PBXGroupData gr = GroupsGetByProjectPath(projectPath); if (gr == null) return null; var res = new List<string>(); foreach (var guid in gr.children) { var fileRef = FileRefsGet(guid); if (fileRef != null) res.Add(fileRef.name); } return res; } private PBXGroupData GetPBXGroupChildByName(PBXGroupData group, string name) { foreach (string guid in group.children) { var gr = GroupsGet(guid); if (gr != null && gr.name == name) return gr; } return null; } /// Creates source group identified by sourceGroup, if needed, and returns it. /// If sourceGroup is empty or null, root group is returned private PBXGroupData CreateSourceGroup(string sourceGroup) { sourceGroup = PBX.Utils.FixSlashesInPath(sourceGroup); if (sourceGroup == null || sourceGroup == "") return GroupsGetMainGroup(); PBXGroupData gr = GroupsGetByProjectPath(sourceGroup); if (gr != null) return gr; // the group does not exist -- create new gr = GroupsGetMainGroup(); var elements = PBX.Utils.SplitPath(sourceGroup); string projectPath = null; foreach (string pathEl in elements) { if (projectPath == null) projectPath = pathEl; else projectPath += "/" + pathEl; PBXGroupData child = GetPBXGroupChildByName(gr, pathEl); if (child != null) gr = child; else { PBXGroupData newGroup = PBXGroupData.Create(pathEl, pathEl, PBXSourceTree.Group); gr.children.AddGUID(newGroup.guid); GroupsAdd(projectPath, gr, newGroup); gr = newGroup; } } return gr; } // sourceTree must not be PBXSourceTree.Group public void AddExternalProjectDependency(string path, string projectPath, PBXSourceTree sourceTree) { if (sourceTree == PBXSourceTree.Group) throw new Exception("sourceTree must not be PBXSourceTree.Group"); path = PBX.Utils.FixSlashesInPath(path); projectPath = PBX.Utils.FixSlashesInPath(projectPath); // note: we are duplicating products group for the project reference. Otherwise Xcode crashes. PBXGroupData productGroup = PBXGroupData.CreateRelative("Products"); GroupsAddDuplicate(productGroup); // don't use GroupsAdd here PBXFileReferenceData fileRef = PBXFileReferenceData.CreateFromFile(path, Path.GetFileName(projectPath), sourceTree); FileRefsAdd(path, projectPath, null, fileRef); CreateSourceGroup(PBX.Utils.GetDirectoryFromPath(projectPath)).children.AddGUID(fileRef.guid); projectSection.project.AddReference(productGroup.guid, fileRef.guid); } /** This function must be called only after the project the library is in has been added as a dependency via AddExternalProjectDependency. projectPath must be the same as the 'path' parameter passed to the AddExternalProjectDependency. remoteFileGuid must be the guid of the referenced file as specified in PBXFileReference section of the external project TODO: what. is remoteInfo entry in PBXContainerItemProxy? Is in referenced project name or referenced library name without extension? */ public void AddExternalLibraryDependency(string targetGuid, string filename, string remoteFileGuid, string projectPath, string remoteInfo) { PBXNativeTargetData target = nativeTargets[targetGuid]; filename = PBX.Utils.FixSlashesInPath(filename); projectPath = PBX.Utils.FixSlashesInPath(projectPath); // find the products group to put the new library in string projectGuid = FindFileGuidByRealPath(projectPath); if (projectGuid == null) throw new Exception("No such project"); string productsGroupGuid = null; foreach (var proj in projectSection.project.projectReferences) { if (proj.projectRef == projectGuid) { productsGroupGuid = proj.group; break; } } if (productsGroupGuid == null) throw new Exception("Malformed project: no project in project references"); PBXGroupData productGroup = GroupsGet(productsGroupGuid); // verify file extension string ext = Path.GetExtension(filename); if (!FileTypeUtils.IsBuildableFile(ext)) throw new Exception("Wrong file extension"); // create ContainerItemProxy object var container = PBXContainerItemProxyData.Create(projectGuid, "2", remoteFileGuid, remoteInfo); containerItems.AddEntry(container); // create a reference and build file for the library string typeName = FileTypeUtils.GetTypeName(ext); var libRef = PBXReferenceProxyData.Create(filename, typeName, container.guid, "BUILT_PRODUCTS_DIR"); references.AddEntry(libRef); PBXBuildFileData libBuildFile = PBXBuildFileData.CreateFromFile(libRef.guid, false, null); BuildFilesAdd(targetGuid, libBuildFile); BuildSectionAny(target, ext, false).files.AddGUID(libBuildFile.guid); // add to products folder productGroup.children.AddGUID(libRef.guid); } private void SetDefaultAppExtensionReleaseBuildFlags(XCBuildConfigurationData config, string infoPlistPath) { config.AddProperty("ALWAYS_SEARCH_USER_PATHS", "NO"); config.AddProperty("CLANG_CXX_LANGUAGE_STANDARD", "gnu++0x"); config.AddProperty("CLANG_CXX_LIBRARY", "libc++"); config.AddProperty("CLANG_ENABLE_MODULES", "YES"); config.AddProperty("CLANG_ENABLE_OBJC_ARC", "YES"); config.AddProperty("CLANG_WARN_BOOL_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_CONSTANT_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "YES_ERROR"); config.AddProperty("CLANG_WARN_EMPTY_BODY", "YES"); config.AddProperty("CLANG_WARN_ENUM_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_INT_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_OBJC_ROOT_CLASS", "YES_ERROR"); config.AddProperty("CLANG_WARN_UNREACHABLE_CODE", "YES"); config.AddProperty("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES"); config.AddProperty("COPY_PHASE_STRIP", "YES"); config.AddProperty("DEVELOPMENT_TEAM", ""); config.AddProperty("ENABLE_NS_ASSERTIONS", "NO"); config.AddProperty("ENABLE_STRICT_OBJC_MSGSEND", "YES"); config.AddProperty("GCC_C_LANGUAGE_STANDARD", "gnu99"); config.AddProperty("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES"); config.AddProperty("GCC_WARN_ABOUT_RETURN_TYPE", "YES_ERROR"); config.AddProperty("GCC_WARN_UNDECLARED_SELECTOR", "YES"); config.AddProperty("GCC_WARN_UNINITIALIZED_AUTOS", "YES_AGGRESSIVE"); config.AddProperty("GCC_WARN_UNUSED_FUNCTION", "YES"); config.AddProperty("INFOPLIST_FILE", infoPlistPath); config.AddProperty("IPHONEOS_DEPLOYMENT_TARGET", "8.0"); config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "$(inherited)"); config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks"); config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "@executable_path/../../Frameworks"); config.AddProperty("MTL_ENABLE_DEBUG_INFO", "NO"); config.AddProperty("PRODUCT_NAME", "$(TARGET_NAME)"); config.AddProperty("SKIP_INSTALL", "YES"); config.AddProperty("VALIDATE_PRODUCT", "YES"); } private void SetDefaultAppExtensionDebugBuildFlags(XCBuildConfigurationData config, string infoPlistPath) { config.AddProperty("ALWAYS_SEARCH_USER_PATHS", "NO"); config.AddProperty("CLANG_CXX_LANGUAGE_STANDARD", "gnu++0x"); config.AddProperty("CLANG_CXX_LIBRARY", "libc++"); config.AddProperty("CLANG_ENABLE_MODULES", "YES"); config.AddProperty("CLANG_ENABLE_OBJC_ARC", "YES"); config.AddProperty("CLANG_WARN_BOOL_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_CONSTANT_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "YES_ERROR"); config.AddProperty("CLANG_WARN_EMPTY_BODY", "YES"); config.AddProperty("CLANG_WARN_ENUM_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_INT_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_OBJC_ROOT_CLASS", "YES_ERROR"); config.AddProperty("CLANG_WARN_UNREACHABLE_CODE", "YES"); config.AddProperty("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES"); config.AddProperty("COPY_PHASE_STRIP", "NO"); config.AddProperty("DEVELOPMENT_TEAM", ""); config.AddProperty("ENABLE_STRICT_OBJC_MSGSEND", "YES"); config.AddProperty("GCC_C_LANGUAGE_STANDARD", "gnu99"); config.AddProperty("GCC_DYNAMIC_NO_PIC", "NO"); config.AddProperty("GCC_OPTIMIZATION_LEVEL", "0"); config.AddProperty("GCC_PREPROCESSOR_DEFINITIONS", "DEBUG=1"); config.AddProperty("GCC_PREPROCESSOR_DEFINITIONS", "$(inherited)"); config.AddProperty("GCC_SYMBOLS_PRIVATE_EXTERN", "NO"); config.AddProperty("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES"); config.AddProperty("GCC_WARN_ABOUT_RETURN_TYPE", "YES_ERROR"); config.AddProperty("GCC_WARN_UNDECLARED_SELECTOR", "YES"); config.AddProperty("GCC_WARN_UNINITIALIZED_AUTOS", "YES_AGGRESSIVE"); config.AddProperty("GCC_WARN_UNUSED_FUNCTION", "YES"); config.AddProperty("INFOPLIST_FILE", infoPlistPath); config.AddProperty("IPHONEOS_DEPLOYMENT_TARGET", "8.0"); config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "$(inherited)"); config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "@executable_path/Frameworks"); config.AddProperty("LD_RUNPATH_SEARCH_PATHS", "@executable_path/../../Frameworks"); config.AddProperty("MTL_ENABLE_DEBUG_INFO", "YES"); config.AddProperty("ONLY_ACTIVE_ARCH", "YES"); config.AddProperty("PRODUCT_NAME", "$(TARGET_NAME)"); config.AddProperty("SKIP_INSTALL", "YES"); } // Returns the guid of the new target public string CreateNewTarget(string name, string ext, string type) { // create build configurations var releaseBuildConfig = XCBuildConfigurationData.Create("Release"); buildConfigs.AddEntry(releaseBuildConfig); var debugBuildConfig = XCBuildConfigurationData.Create("Debug"); buildConfigs.AddEntry(debugBuildConfig); var buildConfigList = XCConfigurationListData.Create(); configs.AddEntry(buildConfigList); buildConfigList.buildConfigs.AddGUID(releaseBuildConfig.guid); buildConfigList.buildConfigs.AddGUID(debugBuildConfig.guid); // create build file reference string fullName = name + ext; var productFileRef = AddFile(fullName, "Products/" + fullName, PBXSourceTree.Build); var newTarget = PBXNativeTargetData.Create(name, productFileRef, type, buildConfigList.guid); nativeTargets.AddEntry(newTarget); projectSection.project.targets.Add(newTarget.guid); return newTarget.guid; } // Returns the guid of the new target public string AddAppExtension(string mainTarget, string name, string type, string infoPlistPath) { string ext = ".appex"; string newTargetGuid = CreateNewTarget(name, ext, type); var newTarget = nativeTargets[newTargetGuid]; SetDefaultAppExtensionReleaseBuildFlags(buildConfigs[BuildConfigByName(newTarget.guid, "Release")], infoPlistPath); SetDefaultAppExtensionDebugBuildFlags(buildConfigs[BuildConfigByName(newTarget.guid, "Debug")], infoPlistPath); var sourcesBuildPhase = PBXSourcesBuildPhaseData.Create(); sources.AddEntry(sourcesBuildPhase); newTarget.phases.AddGUID(sourcesBuildPhase.guid); var resourcesBuildPhase = PBXResourcesBuildPhaseData.Create(); resources.AddEntry(resourcesBuildPhase); newTarget.phases.AddGUID(resourcesBuildPhase.guid); var frameworksBuildPhase = PBXFrameworksBuildPhaseData.Create(); frameworks.AddEntry(frameworksBuildPhase); newTarget.phases.AddGUID(frameworksBuildPhase.guid); var copyFilesBuildPhase = PBXCopyFilesBuildPhaseData.Create("Embed App Extensions", "13"); copyFiles.AddEntry(copyFilesBuildPhase); nativeTargets[mainTarget].phases.AddGUID(copyFilesBuildPhase.guid); var containerProxy = PBXContainerItemProxyData.Create(projectSection.project.guid, "1", newTarget.guid, name); containerItems.AddEntry(containerProxy); var targetDependency = PBXTargetDependencyData.Create(newTarget.guid, containerProxy.guid); targetDependencies.AddEntry(targetDependency); nativeTargets[mainTarget].dependencies.AddGUID(targetDependency.guid); var buildAppCopy = PBXBuildFileData.CreateFromFile(FindFileGuidByProjectPath("Products/" + name + ext), false, ""); BuildFilesAdd(mainTarget, buildAppCopy); copyFilesBuildPhase.files.AddGUID(buildAppCopy.guid); AddFile(infoPlistPath, infoPlistPath, PBXSourceTree.Source); return newTarget.guid; } public string BuildConfigByName(string targetGuid, string name) { PBXNativeTargetData target = nativeTargets[targetGuid]; foreach (string guid in configs[target.buildConfigList].buildConfigs) { var buildConfig = buildConfigs[guid]; if (buildConfig != null && buildConfig.name == name) return buildConfig.guid; } return null; } public void AddFileToResourcesForTarget(string targetGuid, string filePath) { var target = nativeTargets[targetGuid]; if (target == null) throw new Exception("Invalid target guid"); Dictionary<string, PBXResourcesBuildPhaseData> resourcesDictionary = (Dictionary<string, PBXResourcesBuildPhaseData>) resources.GetEntries(); PBXResourcesBuildPhaseData resource = null; foreach (var section in target.phases) { if (resourcesDictionary.ContainsKey(section)) { resource = resourcesDictionary[section]; } } if (resource == null) throw new Exception("No PBXResourcesBuildPhaseData for target"); var buildFileData = PBXBuildFileData.CreateFromFile(FindFileGuidByProjectPath(filePath), false, ""); BuildFilesAdd(targetGuid, buildFileData); resource.files.AddGUID(buildFileData.guid); } string GetConfigListForTarget(string targetGuid) { if (targetGuid == projectSection.project.guid) return projectSection.project.buildConfigList; else return nativeTargets[targetGuid].buildConfigList; } // Adds an item to a build property that contains a value list. Duplicate build properties // are ignored. Values for name "LIBRARY_SEARCH_PATHS" are quoted if they contain spaces. // targetGuid may refer to PBXProject object public void AddBuildProperty(string targetGuid, string name, string value) { foreach (string guid in configs[GetConfigListForTarget(targetGuid)].buildConfigs) AddBuildPropertyForConfig(guid, name, value); } public void AddBuildProperty(IEnumerable<string> targetGuids, string name, string value) { foreach (string t in targetGuids) AddBuildProperty(t, name, value); } public void AddBuildPropertyForConfig(string configGuid, string name, string value) { buildConfigs[configGuid].AddProperty(name, value); } public void AddBuildPropertyForConfig(IEnumerable<string> configGuids, string name, string value) { foreach (string guid in configGuids) AddBuildPropertyForConfig(guid, name, value); } // targetGuid may refer to PBXProject object public void SetBuildProperty(string targetGuid, string name, string value) { foreach (string guid in configs[GetConfigListForTarget(targetGuid)].buildConfigs) SetBuildPropertyForConfig(guid, name, value); } public void SetBuildProperty(IEnumerable<string> targetGuids, string name, string value) { foreach (string t in targetGuids) SetBuildProperty(t, name, value); } public void SetBuildPropertyForConfig(string configGuid, string name, string value) { buildConfigs[configGuid].SetProperty(name, value); } public void SetBuildPropertyForConfig(IEnumerable<string> configGuids, string name, string value) { foreach (string guid in configGuids) SetBuildPropertyForConfig(guid, name, value); } internal void RemoveBuildProperty(string targetGuid, string name) { foreach (string guid in configs[GetConfigListForTarget(targetGuid)].buildConfigs) RemoveBuildPropertyForConfig(guid, name); } internal void RemoveBuildProperty(IEnumerable<string> targetGuids, string name) { foreach (string t in targetGuids) RemoveBuildProperty(t, name); } internal void RemoveBuildPropertyForConfig(string configGuid, string name) { buildConfigs[configGuid].RemoveProperty(name); } internal void RemoveBuildPropertyForConfig(IEnumerable<string> configGuids, string name) { foreach (string guid in configGuids) RemoveBuildPropertyForConfig(guid, name); } /// Interprets the value of the given property as a set of space-delimited strings, then /// removes strings equal to items to removeValues and adds strings in addValues. public void UpdateBuildProperty(string targetGuid, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string guid in configs[GetConfigListForTarget(targetGuid)].buildConfigs) UpdateBuildPropertyForConfig(guid, name, addValues, removeValues); } public void UpdateBuildProperty(IEnumerable<string> targetGuids, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string t in targetGuids) UpdateBuildProperty(t, name, addValues, removeValues); } public void UpdateBuildPropertyForConfig(string configGuid, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { var config = buildConfigs[configGuid]; if (config != null) { if (removeValues != null) foreach (var v in removeValues) config.RemovePropertyValue(name, v); if (addValues != null) foreach (var v in addValues) config.AddProperty(name, v); } } public void UpdateBuildPropertyForConfig(IEnumerable<string> configGuids, string name, IEnumerable<string> addValues, IEnumerable<string> removeValues) { foreach (string guid in configGuids) UpdateBuildProperty(guid, name, addValues, removeValues); } public void ReadFromFile(string path) { ReadFromString(File.ReadAllText(path)); } public void ReadFromString(string src) { TextReader sr = new StringReader(src); ReadFromStream(sr); } public void ReadFromStream(TextReader sr) { m_Data.ReadFromStream(sr); } public void WriteToFile(string path) { File.WriteAllText(path, WriteToString()); } public void WriteToStream(TextWriter sw) { sw.Write(WriteToString()); } public string WriteToString() { return m_Data.WriteToString(); } public static void AddStickerExtensionToXcodeProject(string extensionSourcePath, string pathToBuiltProject, string extensionGroupName, string extensionBundleId, string teamId, string bundleVersion, string buildNumber, string targetDevice, bool auomaticSigning, string provisioningProfile = null, string provisioningProfileSpecifier = null) { string projPath = PBXProject.GetPBXProjectPath(pathToBuiltProject); PBXProject proj = new PBXProject(); proj.ReadFromString(File.ReadAllText(projPath)); var unityIphone = proj.TargetGuidByName(PBXProject.GetUnityTargetName()); CopyDirectory(extensionSourcePath, pathToBuiltProject + extensionGroupName + "/", false); if (proj.HasFramework("Messages.framework")) { Debug.LogWarning("Xcode already contains a messages framework."); } proj.AddFrameworkToProject(unityIphone, "Messages.framework", true); var stickerExtensionName = "Unity-iPhone-Stickers"; string ext = ".appex"; string infoPlistPath = extensionGroupName + "/Info.plist"; if (proj.ContainsExtensionTarget(stickerExtensionName)) { Debug.LogWarning("Sticker extension already added"); } else { var unityiPhoneStickers = proj.CreateExtensionTarget(stickerExtensionName, ext, "com.apple.product-type.app-extension.messages-sticker-pack"); proj.SetStickerExtensionReleaseBuildFlags( proj.buildConfigs[proj.BuildConfigByName(unityiPhoneStickers.guid, "Release")], infoPlistPath, extensionBundleId, teamId, targetDevice, auomaticSigning, provisioningProfile, provisioningProfileSpecifier ); proj.SetStickerExtensionDebugBuildFlags( proj.buildConfigs[proj.BuildConfigByName(unityiPhoneStickers.guid, "Debug")], infoPlistPath, extensionBundleId, teamId, targetDevice, auomaticSigning, provisioningProfile, provisioningProfileSpecifier ); #if UNITY_5_5_OR_NEWER proj.SetStickerExtensionReleaseBuildFlags( proj.buildConfigs[proj.BuildConfigByName(unityiPhoneStickers.guid, "ReleaseForProfiling")], infoPlistPath, extensionBundleId, teamId, targetDevice, auomaticSigning, provisioningProfile, provisioningProfileSpecifier ); proj.SetStickerExtensionReleaseBuildFlags( proj.buildConfigs[proj.BuildConfigByName(unityiPhoneStickers.guid, "ReleaseForRunning")], infoPlistPath, extensionBundleId, teamId, targetDevice, auomaticSigning, provisioningProfile, provisioningProfileSpecifier ); #endif proj.projectSection.project.teamIDs.Add(unityiPhoneStickers.guid, teamId); var resourcesBuildPhase = PBXResourcesBuildPhaseData.Create(); proj.resources.AddEntry(resourcesBuildPhase); unityiPhoneStickers.phases.AddGUID(resourcesBuildPhase.guid); proj.AddFileToBuild(unityiPhoneStickers.guid, proj.AddFileCustom(extensionSourcePath + "Stickers.xcassets", extensionGroupName + "/Stickers.xcassets", PBXSourceTree.Group, false)); proj.AddFileCustom(extensionSourcePath + "Info.plist", extensionGroupName + "/Info.plist", PBXSourceTree.Group, false); var copyFilesBuildPhase = PBXCopyFilesBuildPhaseData.Create("Embed App Extensions", "13"); proj.copyFiles.AddEntry(copyFilesBuildPhase); proj.nativeTargets[unityIphone].phases.AddGUID(copyFilesBuildPhase.guid); var containerProxy = PBXContainerItemProxyData.Create(proj.projectSection.project.guid, "1", unityiPhoneStickers.guid, stickerExtensionName); proj.containerItems.AddEntry(containerProxy); var targetDependency = PBXTargetDependencyData.Create(unityiPhoneStickers.guid, containerProxy.guid); proj.targetDependencies.AddEntry(targetDependency); proj.nativeTargets[unityIphone].dependencies.AddGUID(targetDependency.guid); var buildAppCopy = PBXBuildFileData.CreateFromFile(proj.FindFileGuidByProjectPath("Products/" + stickerExtensionName + ext), false, ""); proj.BuildFilesAdd(unityIphone, buildAppCopy); copyFilesBuildPhase.files.AddGUID(buildAppCopy.guid); File.WriteAllText(projPath, proj.WriteToString()); } // need to set the version numbers to match the main app PlistDocument plist = new PlistDocument(); string stickerPlistPath = projPath.Substring(0, projPath.LastIndexOf("/")) + "/../" + extensionGroupName + "/Info.plist"; plist.ReadFromString(File.ReadAllText(stickerPlistPath)); PlistElementDict rootDict = plist.root; rootDict.SetString("CFBundleShortVersionString", bundleVersion); rootDict.SetString("CFBundleVersion", buildNumber); File.WriteAllText(stickerPlistPath, plist.WriteToString()); } private PBXNativeTargetData CreateExtensionTarget(string name, string ext, string type) { // create build configurations var releaseBuildConfig = XCBuildConfigurationData.Create("Release"); buildConfigs.AddEntry(releaseBuildConfig); var debugBuildConfig = XCBuildConfigurationData.Create("Debug"); buildConfigs.AddEntry(debugBuildConfig); #if UNITY_5_5_OR_NEWER var releaseForRunning = XCBuildConfigurationData.Create("ReleaseForRunning"); buildConfigs.AddEntry(releaseForRunning); var releaseForProfiling = XCBuildConfigurationData.Create("ReleaseForProfiling"); buildConfigs.AddEntry(releaseForProfiling); #endif var buildConfigList = XCConfigurationListData.Create(); configs.AddEntry(buildConfigList); buildConfigList.buildConfigs.AddGUID(releaseBuildConfig.guid); buildConfigList.buildConfigs.AddGUID(debugBuildConfig.guid); #if UNITY_5_5_OR_NEWER buildConfigList.buildConfigs.AddGUID(releaseForRunning.guid); buildConfigList.buildConfigs.AddGUID(releaseForProfiling.guid); #endif // create build file reference string fullName = name + ext; var productFileRef = AddFileCustom(fullName, "Products/" + fullName, PBXSourceTree.Build, false, false); var newTarget = PBXNativeTargetData.Create(name, productFileRef, type, buildConfigList.guid); nativeTargets.AddEntry(newTarget); projectSection.project.targets.Add(newTarget.guid); return newTarget; } private bool ContainsExtensionTarget(string name) { foreach (var entry in nativeTargets.GetEntries()) { if (entry.Value.name == name) { return true; } } return false; } private void SetStickerExtensionBuildFlags(XCBuildConfigurationData config, string infoPlistPath, string bundleId, string teamId, string targetDevice, bool automaticSigning, string provisioningProfile = "", string provisioningProfileSpecifier = "") { config.AddProperty("ALWAYS_SEARCH_USER_PATHS", "NO"); config.AddProperty("ASSETCATALOG_COMPILER_APPICON_NAME", "iMessage App Icon"); config.AddProperty("CLANG_ANALYZER_NONNULL", "YES"); config.AddProperty("CLANG_CXX_LANGUAGE_STANDARD", "gnu++0x"); config.AddProperty("CLANG_CXX_LIBRARY", "libc++"); config.AddProperty("CLANG_ENABLE_MODULES", "YES"); config.AddProperty("CLANG_ENABLE_OBJC_ARC", "YES"); config.AddProperty("CLANG_WARN_BOOL_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_CONSTANT_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_DIRECT_OBJC_ISA_USAGE", "YES_ERROR"); config.AddProperty("CLANG_WARN_DOCUMENTATION_COMMENTS", "YES"); config.AddProperty("CLANG_WARN_EMPTY_BODY", "YES"); config.AddProperty("CLANG_WARN_ENUM_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_INFINITE_RECURSION", "YES"); config.AddProperty("CLANG_WARN_INT_CONVERSION", "YES"); config.AddProperty("CLANG_WARN_OBJC_ROOT_CLASS", "YES_ERROR"); config.AddProperty("CLANG_WARN_SUSPICIOUS_MOVES", "YES"); config.AddProperty("CLANG_WARN_UNREACHABLE_CODE", "YES"); config.AddProperty("CLANG_WARN__DUPLICATE_METHOD_MATCH", "YES"); config.AddProperty("COPY_PHASE_STRIP", "NO"); config.AddProperty("GCC_WARN_64_TO_32_BIT_CONVERSION", "YES"); config.AddProperty("GCC_WARN_ABOUT_RETURN_TYPE", "YES_ERROR"); config.AddProperty("GCC_WARN_UNDECLARED_SELECTOR", "YES"); config.AddProperty("GCC_WARN_UNINITIALIZED_AUTOS", "YES_AGGRESSIVE"); config.AddProperty("GCC_WARN_UNUSED_FUNCTION", "YES"); config.AddProperty("IPHONEOS_DEPLOYMENT_TARGET", "10.0"); // stickers introduced in 10.0 config.AddProperty("PRODUCT_NAME", "$(TARGET_NAME)"); config.AddProperty("SKIP_INSTALL", "YES"); if (automaticSigning) { config.AddProperty("CODE_SIGN_IDENTITY[sdk=iphoneos*]", Debug.isDebugBuild ? "iPhone Developer" : "iPhone Distribution"); } config.AddProperty("INFOPLIST_FILE", infoPlistPath); // e.g. relative to source root "Stickers/Info.plist" config.AddProperty("PRODUCT_BUNDLE_IDENTIFIER", bundleId); config.AddProperty("TARGETED_DEVICE_FAMILY", targetDevice); // e.g. 1,2 universal config.AddProperty("DEVELOPMENT_TEAM", teamId); config.AddProperty("CODE_SIGN_STYLE", automaticSigning ? "Automatic" : "Manual"); if (!automaticSigning && !string.IsNullOrEmpty(provisioningProfile)) { config.AddProperty("PROVISIONING_PROFILE", provisioningProfile); } if (!automaticSigning && !string.IsNullOrEmpty(provisioningProfileSpecifier)) { config.AddProperty("PROVISIONING_PROFILE_SPECIFIER", provisioningProfileSpecifier); } } private void SetStickerExtensionReleaseBuildFlags(XCBuildConfigurationData config, string infoPlistPath, string bundleId, string teamId, string targetDevice, bool automaticSigning, string provisioningProfile = "", string provisioningProfileSpecifier = "") { SetStickerExtensionBuildFlags(config, infoPlistPath, bundleId, teamId, targetDevice, automaticSigning, provisioningProfile, provisioningProfileSpecifier); config.AddProperty("DEBUG_INFORMATION_FORMAT", "dwarf-with-dsym"); config.AddProperty("ENABLE_NS_ASSERTIONS", "NO"); config.AddProperty("ENABLE_STRICT_OBJC_MSGSEND", "YES"); config.AddProperty("GCC_C_LANGUAGE_STANDARD", "gnu99"); config.AddProperty("GCC_NO_COMMON_BLOCKS", "YES"); config.AddProperty("MTL_ENABLE_DEBUG_INFO", "NO"); config.AddProperty("VALIDATE_PRODUCT", "YES"); } private void SetStickerExtensionDebugBuildFlags(XCBuildConfigurationData config, string infoPlistPath, string bundleId, string teamId, string targetDevice, bool automaticSigning, string provisioningProfile = "", string provisioningProfileSpecifier = "") { SetStickerExtensionBuildFlags(config, infoPlistPath, bundleId, teamId, targetDevice, automaticSigning, provisioningProfile, provisioningProfileSpecifier); config.AddProperty("ENABLE_STRICT_OBJC_MSGSEND", "YES"); config.AddProperty("ENABLE_TESTABILITY", "YES"); config.AddProperty("GCC_C_LANGUAGE_STANDARD", "gnu99"); config.AddProperty("GCC_DYNAMIC_NO_PIC", "NO"); config.AddProperty("GCC_NO_COMMON_BLOCKS", "YES"); config.AddProperty("GCC_OPTIMIZATION_LEVEL", "0"); config.AddProperty("GCC_PREPROCESSOR_DEFINITIONS", "DEBUG=1"); config.AddProperty("GCC_PREPROCESSOR_DEFINITIONS", "$(inherited)"); config.AddProperty("MTL_ENABLE_DEBUG_INFO", "YES"); config.AddProperty("ONLY_ACTIVE_ARCH", "YES"); config.AddProperty("SKIP_INSTALL", "YES"); } // JASON: this is a modified copy of the AddFileImpl method public string AddFileCustom(string path, string projectPath, PBXSourceTree tree, bool isFolderReference, bool includeInIndex = true) { path = PBX.Utils.FixSlashesInPath(path); projectPath = PBX.Utils.FixSlashesInPath(projectPath); if (!isFolderReference && Path.GetExtension(path) != Path.GetExtension(projectPath)) throw new Exception("Project and real path extensions do not match"); string guid = FindFileGuidByProjectPath(projectPath); if (guid == null) guid = FindFileGuidByRealPath(path); if (guid == null) { PBXFileReferenceData fileRef; if (isFolderReference) { fileRef = PBXFileReferenceData.CreateFromFolderReference(path, PBX.Utils.GetFilenameFromPath(projectPath), tree); } else { // JASON: the main difference of this AddFileCustom to AddFileImpl is this next part that strips the full path back to the file name to be relative to the group if (tree == PBXSourceTree.Group) { fileRef = PBXFileReferenceData.CreateFromFile(PBX.Utils.GetFilenameFromPath(projectPath), PBX.Utils.GetFilenameFromPath(projectPath), tree); } else { fileRef = PBXFileReferenceData.CreateFromFile(path, PBX.Utils.GetFilenameFromPath(projectPath), tree); } // JASON: also added a little hack to exclude a file from being indexed if (!includeInIndex) { fileRef.ExcludeFromIndex(); } } PBXGroupData parent = CreateSourceGroup(PBX.Utils.GetDirectoryFromPath(projectPath)); parent.children.AddGUID(fileRef.guid); FileRefsAdd(path, projectPath, parent, fileRef); guid = fileRef.guid; } return guid; } // ------ UTILS public static void CopyDirectory(string fromFolder, string toFolder, bool overwriteFiles) { fromFolder = Path.GetFullPath(fromFolder); toFolder = Path.GetFullPath(toFolder); foreach (var fromSubFolder in Directory.GetDirectories(fromFolder, "*", SearchOption.AllDirectories)) Directory.CreateDirectory(fromSubFolder.Replace(fromFolder, toFolder)); foreach (var fromFilePath in Directory.GetFiles(fromFolder, "*", SearchOption.AllDirectories)) { var toFilePath = fromFilePath.Replace(fromFolder, toFolder); if (overwriteFiles) File.Copy(fromFilePath, toFilePath, true); else if (!File.Exists(toFilePath)) File.Copy(fromFilePath, toFilePath); } } public static void CreateFolderPath(string path) { // creates the folder path if it doesnt exist path = FixSlashes(path); //Debug.Log ("* test: "+path+", "+Directory.Exists( path )); if (!Directory.Exists(path) && (path != "") && (path != "/")) { //Debug.Log ("* doesnt exist: "+path); System.IO.Directory.CreateDirectory(path); } } public static string FixSlashes(string s) { const string forwardSlash = "/"; const string backSlash = "\\"; return s.Replace(backSlash, forwardSlash); } } } // namespace UnityEditor.iOS.Xcode
using System; using System.Linq; using System.Collections.Generic; using Blueprint41; using Blueprint41.Core; using Blueprint41.Query; using Blueprint41.DatastoreTemplates; using q = Domain.Data.Query; namespace Domain.Data.Manipulation { public interface IProductModelOriginalData : ISchemaBaseOriginalData { string Name { get; } string CatalogDescription { get; } string Instructions { get; } string rowguid { get; } Illustration Illustration { get; } ProductDescription ProductDescription { get; } Culture Culture { get; } } public partial class ProductModel : OGM<ProductModel, ProductModel.ProductModelData, System.String>, ISchemaBase, INeo4jBase, IProductModelOriginalData { #region Initialize static ProductModel() { Register.Types(); } protected override void RegisterGeneratedStoredQueries() { #region LoadByKeys RegisterQuery(nameof(LoadByKeys), (query, alias) => query. Where(alias.Uid.In(Parameter.New<System.String>(Param0)))); #endregion AdditionalGeneratedStoredQueries(); } partial void AdditionalGeneratedStoredQueries(); public static Dictionary<System.String, ProductModel> LoadByKeys(IEnumerable<System.String> uids) { return FromQuery(nameof(LoadByKeys), new Parameter(Param0, uids.ToArray(), typeof(System.String))).ToDictionary(item=> item.Uid, item => item); } protected static void RegisterQuery(string name, Func<IMatchQuery, q.ProductModelAlias, IWhereQuery> query) { q.ProductModelAlias alias; IMatchQuery matchQuery = Blueprint41.Transaction.CompiledQuery.Match(q.Node.ProductModel.Alias(out alias)); IWhereQuery partial = query.Invoke(matchQuery, alias); ICompiled compiled = partial.Return(alias).Compile(); RegisterQuery(name, compiled); } public override string ToString() { return $"ProductModel => Name : {this.Name}, CatalogDescription : {this.CatalogDescription?.ToString() ?? "null"}, Instructions : {this.Instructions?.ToString() ?? "null"}, rowguid : {this.rowguid}, ModifiedDate : {this.ModifiedDate}, Uid : {this.Uid}"; } public override int GetHashCode() { return base.GetHashCode(); } protected override void LazySet() { base.LazySet(); if (PersistenceState == PersistenceState.NewAndChanged || PersistenceState == PersistenceState.LoadedAndChanged) { if ((object)InnerData == (object)OriginalData) OriginalData = new ProductModelData(InnerData); } } #endregion #region Validations protected override void ValidateSave() { bool isUpdate = (PersistenceState != PersistenceState.New && PersistenceState != PersistenceState.NewAndChanged); #pragma warning disable CS0472 if (InnerData.Name == null) throw new PersistenceException(string.Format("Cannot save ProductModel with key '{0}' because the Name cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.rowguid == null) throw new PersistenceException(string.Format("Cannot save ProductModel with key '{0}' because the rowguid cannot be null.", this.Uid?.ToString() ?? "<null>")); if (InnerData.ModifiedDate == null) throw new PersistenceException(string.Format("Cannot save ProductModel with key '{0}' because the ModifiedDate cannot be null.", this.Uid?.ToString() ?? "<null>")); #pragma warning restore CS0472 } protected override void ValidateDelete() { } #endregion #region Inner Data public class ProductModelData : Data<System.String> { public ProductModelData() { } public ProductModelData(ProductModelData data) { Name = data.Name; CatalogDescription = data.CatalogDescription; Instructions = data.Instructions; rowguid = data.rowguid; Illustration = data.Illustration; ProductDescription = data.ProductDescription; Culture = data.Culture; ModifiedDate = data.ModifiedDate; Uid = data.Uid; } #region Initialize Collections protected override void InitializeCollections() { NodeType = "ProductModel"; Illustration = new EntityCollection<Illustration>(Wrapper, Members.Illustration); ProductDescription = new EntityCollection<ProductDescription>(Wrapper, Members.ProductDescription); Culture = new EntityCollection<Culture>(Wrapper, Members.Culture); } public string NodeType { get; private set; } sealed public override System.String GetKey() { return Entity.Parent.PersistenceProvider.ConvertFromStoredType<System.String>(Uid); } sealed protected override void SetKey(System.String key) { Uid = (string)Entity.Parent.PersistenceProvider.ConvertToStoredType<System.String>(key); base.SetKey(Uid); } #endregion #region Map Data sealed public override IDictionary<string, object> MapTo() { IDictionary<string, object> dictionary = new Dictionary<string, object>(); dictionary.Add("Name", Name); dictionary.Add("CatalogDescription", CatalogDescription); dictionary.Add("Instructions", Instructions); dictionary.Add("rowguid", rowguid); dictionary.Add("ModifiedDate", Conversion<System.DateTime, long>.Convert(ModifiedDate)); dictionary.Add("Uid", Uid); return dictionary; } sealed public override void MapFrom(IReadOnlyDictionary<string, object> properties) { object value; if (properties.TryGetValue("Name", out value)) Name = (string)value; if (properties.TryGetValue("CatalogDescription", out value)) CatalogDescription = (string)value; if (properties.TryGetValue("Instructions", out value)) Instructions = (string)value; if (properties.TryGetValue("rowguid", out value)) rowguid = (string)value; if (properties.TryGetValue("ModifiedDate", out value)) ModifiedDate = Conversion<long, System.DateTime>.Convert((long)value); if (properties.TryGetValue("Uid", out value)) Uid = (string)value; } #endregion #region Members for interface IProductModel public string Name { get; set; } public string CatalogDescription { get; set; } public string Instructions { get; set; } public string rowguid { get; set; } public EntityCollection<Illustration> Illustration { get; private set; } public EntityCollection<ProductDescription> ProductDescription { get; private set; } public EntityCollection<Culture> Culture { get; private set; } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get; set; } #endregion #region Members for interface INeo4jBase public string Uid { get; set; } #endregion } #endregion #region Outer Data #region Members for interface IProductModel public string Name { get { LazyGet(); return InnerData.Name; } set { if (LazySet(Members.Name, InnerData.Name, value)) InnerData.Name = value; } } public string CatalogDescription { get { LazyGet(); return InnerData.CatalogDescription; } set { if (LazySet(Members.CatalogDescription, InnerData.CatalogDescription, value)) InnerData.CatalogDescription = value; } } public string Instructions { get { LazyGet(); return InnerData.Instructions; } set { if (LazySet(Members.Instructions, InnerData.Instructions, value)) InnerData.Instructions = value; } } public string rowguid { get { LazyGet(); return InnerData.rowguid; } set { if (LazySet(Members.rowguid, InnerData.rowguid, value)) InnerData.rowguid = value; } } public Illustration Illustration { get { return ((ILookupHelper<Illustration>)InnerData.Illustration).GetItem(null); } set { if (LazySet(Members.Illustration, ((ILookupHelper<Illustration>)InnerData.Illustration).GetItem(null), value)) ((ILookupHelper<Illustration>)InnerData.Illustration).SetItem(value, null); } } public ProductDescription ProductDescription { get { return ((ILookupHelper<ProductDescription>)InnerData.ProductDescription).GetItem(null); } set { if (LazySet(Members.ProductDescription, ((ILookupHelper<ProductDescription>)InnerData.ProductDescription).GetItem(null), value)) ((ILookupHelper<ProductDescription>)InnerData.ProductDescription).SetItem(value, null); } } public Culture Culture { get { return ((ILookupHelper<Culture>)InnerData.Culture).GetItem(null); } set { if (LazySet(Members.Culture, ((ILookupHelper<Culture>)InnerData.Culture).GetItem(null), value)) ((ILookupHelper<Culture>)InnerData.Culture).SetItem(value, null); } } #endregion #region Members for interface ISchemaBase public System.DateTime ModifiedDate { get { LazyGet(); return InnerData.ModifiedDate; } set { if (LazySet(Members.ModifiedDate, InnerData.ModifiedDate, value)) InnerData.ModifiedDate = value; } } #endregion #region Members for interface INeo4jBase public string Uid { get { return InnerData.Uid; } set { KeySet(() => InnerData.Uid = value); } } #endregion #region Virtual Node Type public string NodeType { get { return InnerData.NodeType; } } #endregion #endregion #region Reflection private static ProductModelMembers members = null; public static ProductModelMembers Members { get { if (members == null) { lock (typeof(ProductModel)) { if (members == null) members = new ProductModelMembers(); } } return members; } } public class ProductModelMembers { internal ProductModelMembers() { } #region Members for interface IProductModel public Property Name { get; } = Datastore.AdventureWorks.Model.Entities["ProductModel"].Properties["Name"]; public Property CatalogDescription { get; } = Datastore.AdventureWorks.Model.Entities["ProductModel"].Properties["CatalogDescription"]; public Property Instructions { get; } = Datastore.AdventureWorks.Model.Entities["ProductModel"].Properties["Instructions"]; public Property rowguid { get; } = Datastore.AdventureWorks.Model.Entities["ProductModel"].Properties["rowguid"]; public Property Illustration { get; } = Datastore.AdventureWorks.Model.Entities["ProductModel"].Properties["Illustration"]; public Property ProductDescription { get; } = Datastore.AdventureWorks.Model.Entities["ProductModel"].Properties["ProductDescription"]; public Property Culture { get; } = Datastore.AdventureWorks.Model.Entities["ProductModel"].Properties["Culture"]; #endregion #region Members for interface ISchemaBase public Property ModifiedDate { get; } = Datastore.AdventureWorks.Model.Entities["SchemaBase"].Properties["ModifiedDate"]; #endregion #region Members for interface INeo4jBase public Property Uid { get; } = Datastore.AdventureWorks.Model.Entities["Neo4jBase"].Properties["Uid"]; #endregion } private static ProductModelFullTextMembers fullTextMembers = null; public static ProductModelFullTextMembers FullTextMembers { get { if (fullTextMembers == null) { lock (typeof(ProductModel)) { if (fullTextMembers == null) fullTextMembers = new ProductModelFullTextMembers(); } } return fullTextMembers; } } public class ProductModelFullTextMembers { internal ProductModelFullTextMembers() { } } sealed public override Entity GetEntity() { if (entity == null) { lock (typeof(ProductModel)) { if (entity == null) entity = Datastore.AdventureWorks.Model.Entities["ProductModel"]; } } return entity; } private static ProductModelEvents events = null; public static ProductModelEvents Events { get { if (events == null) { lock (typeof(ProductModel)) { if (events == null) events = new ProductModelEvents(); } } return events; } } public class ProductModelEvents { #region OnNew private bool onNewIsRegistered = false; private EventHandler<ProductModel, EntityEventArgs> onNew; public event EventHandler<ProductModel, EntityEventArgs> OnNew { add { lock (this) { if (!onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; Entity.Events.OnNew += onNewProxy; onNewIsRegistered = true; } onNew += value; } } remove { lock (this) { onNew -= value; if (onNew == null && onNewIsRegistered) { Entity.Events.OnNew -= onNewProxy; onNewIsRegistered = false; } } } } private void onNewProxy(object sender, EntityEventArgs args) { EventHandler<ProductModel, EntityEventArgs> handler = onNew; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnDelete private bool onDeleteIsRegistered = false; private EventHandler<ProductModel, EntityEventArgs> onDelete; public event EventHandler<ProductModel, EntityEventArgs> OnDelete { add { lock (this) { if (!onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; Entity.Events.OnDelete += onDeleteProxy; onDeleteIsRegistered = true; } onDelete += value; } } remove { lock (this) { onDelete -= value; if (onDelete == null && onDeleteIsRegistered) { Entity.Events.OnDelete -= onDeleteProxy; onDeleteIsRegistered = false; } } } } private void onDeleteProxy(object sender, EntityEventArgs args) { EventHandler<ProductModel, EntityEventArgs> handler = onDelete; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnSave private bool onSaveIsRegistered = false; private EventHandler<ProductModel, EntityEventArgs> onSave; public event EventHandler<ProductModel, EntityEventArgs> OnSave { add { lock (this) { if (!onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; Entity.Events.OnSave += onSaveProxy; onSaveIsRegistered = true; } onSave += value; } } remove { lock (this) { onSave -= value; if (onSave == null && onSaveIsRegistered) { Entity.Events.OnSave -= onSaveProxy; onSaveIsRegistered = false; } } } } private void onSaveProxy(object sender, EntityEventArgs args) { EventHandler<ProductModel, EntityEventArgs> handler = onSave; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnPropertyChange public static class OnPropertyChange { #region OnName private static bool onNameIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onName; public static event EventHandler<ProductModel, PropertyEventArgs> OnName { add { lock (typeof(OnPropertyChange)) { if (!onNameIsRegistered) { Members.Name.Events.OnChange -= onNameProxy; Members.Name.Events.OnChange += onNameProxy; onNameIsRegistered = true; } onName += value; } } remove { lock (typeof(OnPropertyChange)) { onName -= value; if (onName == null && onNameIsRegistered) { Members.Name.Events.OnChange -= onNameProxy; onNameIsRegistered = false; } } } } private static void onNameProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onName; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnCatalogDescription private static bool onCatalogDescriptionIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onCatalogDescription; public static event EventHandler<ProductModel, PropertyEventArgs> OnCatalogDescription { add { lock (typeof(OnPropertyChange)) { if (!onCatalogDescriptionIsRegistered) { Members.CatalogDescription.Events.OnChange -= onCatalogDescriptionProxy; Members.CatalogDescription.Events.OnChange += onCatalogDescriptionProxy; onCatalogDescriptionIsRegistered = true; } onCatalogDescription += value; } } remove { lock (typeof(OnPropertyChange)) { onCatalogDescription -= value; if (onCatalogDescription == null && onCatalogDescriptionIsRegistered) { Members.CatalogDescription.Events.OnChange -= onCatalogDescriptionProxy; onCatalogDescriptionIsRegistered = false; } } } } private static void onCatalogDescriptionProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onCatalogDescription; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnInstructions private static bool onInstructionsIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onInstructions; public static event EventHandler<ProductModel, PropertyEventArgs> OnInstructions { add { lock (typeof(OnPropertyChange)) { if (!onInstructionsIsRegistered) { Members.Instructions.Events.OnChange -= onInstructionsProxy; Members.Instructions.Events.OnChange += onInstructionsProxy; onInstructionsIsRegistered = true; } onInstructions += value; } } remove { lock (typeof(OnPropertyChange)) { onInstructions -= value; if (onInstructions == null && onInstructionsIsRegistered) { Members.Instructions.Events.OnChange -= onInstructionsProxy; onInstructionsIsRegistered = false; } } } } private static void onInstructionsProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onInstructions; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region Onrowguid private static bool onrowguidIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onrowguid; public static event EventHandler<ProductModel, PropertyEventArgs> Onrowguid { add { lock (typeof(OnPropertyChange)) { if (!onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; Members.rowguid.Events.OnChange += onrowguidProxy; onrowguidIsRegistered = true; } onrowguid += value; } } remove { lock (typeof(OnPropertyChange)) { onrowguid -= value; if (onrowguid == null && onrowguidIsRegistered) { Members.rowguid.Events.OnChange -= onrowguidProxy; onrowguidIsRegistered = false; } } } } private static void onrowguidProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onrowguid; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnIllustration private static bool onIllustrationIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onIllustration; public static event EventHandler<ProductModel, PropertyEventArgs> OnIllustration { add { lock (typeof(OnPropertyChange)) { if (!onIllustrationIsRegistered) { Members.Illustration.Events.OnChange -= onIllustrationProxy; Members.Illustration.Events.OnChange += onIllustrationProxy; onIllustrationIsRegistered = true; } onIllustration += value; } } remove { lock (typeof(OnPropertyChange)) { onIllustration -= value; if (onIllustration == null && onIllustrationIsRegistered) { Members.Illustration.Events.OnChange -= onIllustrationProxy; onIllustrationIsRegistered = false; } } } } private static void onIllustrationProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onIllustration; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnProductDescription private static bool onProductDescriptionIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onProductDescription; public static event EventHandler<ProductModel, PropertyEventArgs> OnProductDescription { add { lock (typeof(OnPropertyChange)) { if (!onProductDescriptionIsRegistered) { Members.ProductDescription.Events.OnChange -= onProductDescriptionProxy; Members.ProductDescription.Events.OnChange += onProductDescriptionProxy; onProductDescriptionIsRegistered = true; } onProductDescription += value; } } remove { lock (typeof(OnPropertyChange)) { onProductDescription -= value; if (onProductDescription == null && onProductDescriptionIsRegistered) { Members.ProductDescription.Events.OnChange -= onProductDescriptionProxy; onProductDescriptionIsRegistered = false; } } } } private static void onProductDescriptionProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onProductDescription; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnCulture private static bool onCultureIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onCulture; public static event EventHandler<ProductModel, PropertyEventArgs> OnCulture { add { lock (typeof(OnPropertyChange)) { if (!onCultureIsRegistered) { Members.Culture.Events.OnChange -= onCultureProxy; Members.Culture.Events.OnChange += onCultureProxy; onCultureIsRegistered = true; } onCulture += value; } } remove { lock (typeof(OnPropertyChange)) { onCulture -= value; if (onCulture == null && onCultureIsRegistered) { Members.Culture.Events.OnChange -= onCultureProxy; onCultureIsRegistered = false; } } } } private static void onCultureProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onCulture; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnModifiedDate private static bool onModifiedDateIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onModifiedDate; public static event EventHandler<ProductModel, PropertyEventArgs> OnModifiedDate { add { lock (typeof(OnPropertyChange)) { if (!onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; Members.ModifiedDate.Events.OnChange += onModifiedDateProxy; onModifiedDateIsRegistered = true; } onModifiedDate += value; } } remove { lock (typeof(OnPropertyChange)) { onModifiedDate -= value; if (onModifiedDate == null && onModifiedDateIsRegistered) { Members.ModifiedDate.Events.OnChange -= onModifiedDateProxy; onModifiedDateIsRegistered = false; } } } } private static void onModifiedDateProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onModifiedDate; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion #region OnUid private static bool onUidIsRegistered = false; private static EventHandler<ProductModel, PropertyEventArgs> onUid; public static event EventHandler<ProductModel, PropertyEventArgs> OnUid { add { lock (typeof(OnPropertyChange)) { if (!onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; Members.Uid.Events.OnChange += onUidProxy; onUidIsRegistered = true; } onUid += value; } } remove { lock (typeof(OnPropertyChange)) { onUid -= value; if (onUid == null && onUidIsRegistered) { Members.Uid.Events.OnChange -= onUidProxy; onUidIsRegistered = false; } } } } private static void onUidProxy(object sender, PropertyEventArgs args) { EventHandler<ProductModel, PropertyEventArgs> handler = onUid; if ((object)handler != null) handler.Invoke((ProductModel)sender, args); } #endregion } #endregion } #endregion #region IProductModelOriginalData public IProductModelOriginalData OriginalVersion { get { return this; } } #region Members for interface IProductModel string IProductModelOriginalData.Name { get { return OriginalData.Name; } } string IProductModelOriginalData.CatalogDescription { get { return OriginalData.CatalogDescription; } } string IProductModelOriginalData.Instructions { get { return OriginalData.Instructions; } } string IProductModelOriginalData.rowguid { get { return OriginalData.rowguid; } } Illustration IProductModelOriginalData.Illustration { get { return ((ILookupHelper<Illustration>)OriginalData.Illustration).GetOriginalItem(null); } } ProductDescription IProductModelOriginalData.ProductDescription { get { return ((ILookupHelper<ProductDescription>)OriginalData.ProductDescription).GetOriginalItem(null); } } Culture IProductModelOriginalData.Culture { get { return ((ILookupHelper<Culture>)OriginalData.Culture).GetOriginalItem(null); } } #endregion #region Members for interface ISchemaBase ISchemaBaseOriginalData ISchemaBase.OriginalVersion { get { return this; } } System.DateTime ISchemaBaseOriginalData.ModifiedDate { get { return OriginalData.ModifiedDate; } } #endregion #region Members for interface INeo4jBase INeo4jBaseOriginalData INeo4jBase.OriginalVersion { get { return this; } } string INeo4jBaseOriginalData.Uid { get { return OriginalData.Uid; } } #endregion #endregion } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Screens; using osu.Framework.Testing; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Cursor; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play; using osuTK; using osuTK.Input; namespace osu.Game.Tests.Visual.Gameplay { public class TestScenePause : PlayerTestScene { protected new PausePlayer Player => (PausePlayer)base.Player; private readonly Container content; protected override Container<Drawable> Content => content; public TestScenePause() : base(new OsuRuleset()) { base.Content.Add(content = new MenuCursorContainer { RelativeSizeAxes = Axes.Both }); } [SetUpSteps] public override void SetUpSteps() { base.SetUpSteps(); AddStep("resume player", () => Player.GameplayClockContainer.Start()); confirmClockRunning(true); } [Test] public void TestPauseResume() { AddStep("move cursor outside", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.TopLeft - new Vector2(10))); pauseAndConfirm(); resumeAndConfirm(); } [Test] public void TestResumeWithResumeOverlay() { AddStep("move cursor to center", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.Centre)); AddUntilStep("wait for hitobjects", () => Player.HealthProcessor.Health.Value < 1); pauseAndConfirm(); resume(); confirmClockRunning(false); confirmPauseOverlayShown(false); AddStep("click to resume", () => { InputManager.PressButton(MouseButton.Left); InputManager.ReleaseButton(MouseButton.Left); }); confirmClockRunning(true); } [Test] public void TestPauseWithResumeOverlay() { AddStep("move cursor to center", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.Centre)); AddUntilStep("wait for hitobjects", () => Player.HealthProcessor.Health.Value < 1); pauseAndConfirm(); resume(); confirmClockRunning(false); confirmPauseOverlayShown(false); pauseAndConfirm(); AddUntilStep("resume overlay is not active", () => Player.DrawableRuleset.ResumeOverlay.State.Value == Visibility.Hidden); confirmPaused(); } [Test] public void TestResumeWithResumeOverlaySkipped() { AddStep("move cursor to button", () => InputManager.MoveMouseTo(Player.HUDOverlay.HoldToQuit.Children.OfType<HoldToConfirmContainer>().First().ScreenSpaceDrawQuad.Centre)); AddUntilStep("wait for hitobjects", () => Player.HealthProcessor.Health.Value < 1); pauseAndConfirm(); resumeAndConfirm(); } [Test] public void TestPauseTooSoon() { AddStep("move cursor outside", () => InputManager.MoveMouseTo(Player.ScreenSpaceDrawQuad.TopLeft - new Vector2(10))); pauseAndConfirm(); resume(); pause(); confirmClockRunning(true); confirmPauseOverlayShown(false); } [Test] public void TestExitTooSoon() { AddStep("seek before gameplay", () => Player.GameplayClockContainer.Seek(-5000)); pauseAndConfirm(); resume(); AddStep("exit too soon", () => Player.Exit()); confirmClockRunning(true); confirmPauseOverlayShown(false); AddAssert("not exited", () => Player.IsCurrentScreen()); } [Test] public void TestPauseAfterFail() { AddUntilStep("wait for fail", () => Player.HasFailed); AddUntilStep("fail overlay shown", () => Player.FailOverlayVisible); confirmClockRunning(false); pause(); confirmClockRunning(false); confirmPauseOverlayShown(false); AddAssert("fail overlay still shown", () => Player.FailOverlayVisible); exitAndConfirm(); } [Test] public void TestExitFromFailedGameplay() { AddUntilStep("wait for fail", () => Player.HasFailed); AddStep("exit", () => Player.Exit()); confirmExited(); } [Test] public void TestQuickRetryFromFailedGameplay() { AddUntilStep("wait for fail", () => Player.HasFailed); AddStep("quick retry", () => Player.GameplayClockContainer.OfType<HotkeyRetryOverlay>().First().Action?.Invoke()); confirmExited(); } [Test] public void TestQuickExitFromFailedGameplay() { AddUntilStep("wait for fail", () => Player.HasFailed); AddStep("quick exit", () => Player.GameplayClockContainer.OfType<HotkeyExitOverlay>().First().Action?.Invoke()); confirmExited(); } [Test] public void TestExitFromGameplay() { AddStep("exit", () => Player.Exit()); confirmPaused(); AddStep("exit", () => Player.Exit()); confirmExited(); } [Test] public void TestQuickExitFromGameplay() { AddStep("quick exit", () => Player.GameplayClockContainer.OfType<HotkeyExitOverlay>().First().Action?.Invoke()); confirmExited(); } [Test] public void TestExitViaHoldToExit() { AddStep("exit", () => { InputManager.MoveMouseTo(Player.HUDOverlay.HoldToQuit.First(c => c is HoldToConfirmContainer)); InputManager.PressButton(MouseButton.Left); }); confirmPaused(); AddStep("release", () => InputManager.ReleaseButton(MouseButton.Left)); exitAndConfirm(); } [Test] public void TestExitFromPause() { pauseAndConfirm(); exitAndConfirm(); } [Test] public void TestRestartAfterResume() { AddStep("seek before gameplay", () => Player.GameplayClockContainer.Seek(-5000)); pauseAndConfirm(); resumeAndConfirm(); restart(); confirmExited(); } private void pauseAndConfirm() { pause(); confirmPaused(); } private void resumeAndConfirm() { resume(); confirmResumed(); } private void exitAndConfirm() { AddUntilStep("player not exited", () => Player.IsCurrentScreen()); AddStep("exit", () => Player.Exit()); confirmExited(); confirmNoTrackAdjustments(); } private void confirmPaused() { confirmClockRunning(false); AddAssert("player not exited", () => Player.IsCurrentScreen()); AddAssert("player not failed", () => !Player.HasFailed); AddAssert("pause overlay shown", () => Player.PauseOverlayVisible); } private void confirmResumed() { confirmClockRunning(true); confirmPauseOverlayShown(false); } private void confirmExited() { AddUntilStep("player exited", () => !Player.IsCurrentScreen()); } private void confirmNoTrackAdjustments() { AddAssert("track has no adjustments", () => Beatmap.Value.Track.AggregateFrequency.Value == 1); } private void restart() => AddStep("restart", () => Player.Restart()); private void pause() => AddStep("pause", () => Player.Pause()); private void resume() => AddStep("resume", () => Player.Resume()); private void confirmPauseOverlayShown(bool isShown) => AddAssert("pause overlay " + (isShown ? "shown" : "hidden"), () => Player.PauseOverlayVisible == isShown); private void confirmClockRunning(bool isRunning) => AddUntilStep("clock " + (isRunning ? "running" : "stopped"), () => Player.GameplayClockContainer.GameplayClock.IsRunning == isRunning); protected override bool AllowFail => true; protected override TestPlayer CreatePlayer(Ruleset ruleset) => new PausePlayer(); protected class PausePlayer : TestPlayer { public bool FailOverlayVisible => FailOverlay.State.Value == Visibility.Visible; public bool PauseOverlayVisible => PauseOverlay.State.Value == Visibility.Visible; public override void OnEntering(IScreen last) { base.OnEntering(last); GameplayClockContainer.Stop(); } } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2005AutoHideStrip : AutoHideStripBase { private class TabVS2005 : Tab { internal TabVS2005(IDockContent content) : base(content) { } private int m_tabX = 0; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth = 0; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } } private const int _ImageHeight = 16; private const int _ImageWidth = 16; private const int _ImageGapTop = 2; private const int _ImageGapLeft = 4; private const int _ImageGapRight = 2; private const int _ImageGapBottom = 2; private const int _TextGapLeft = 0; private const int _TextGapRight = 0; private const int _TabGapTop = 3; private const int _TabGapLeft = 4; private const int _TabGapBetween = 10; #region Customizable Properties private static Font TextFont { get { return SystemInformation.MenuFont; } } private static StringFormat _stringFormatTabHorizontal; private StringFormat StringFormatTabHorizontal { get { if (_stringFormatTabHorizontal == null) { _stringFormatTabHorizontal = new StringFormat(); _stringFormatTabHorizontal.Alignment = StringAlignment.Near; _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabHorizontal; } } private static StringFormat _stringFormatTabVertical; private StringFormat StringFormatTabVertical { get { if (_stringFormatTabVertical == null) { _stringFormatTabVertical = new StringFormat(); _stringFormatTabVertical.Alignment = StringAlignment.Near; _stringFormatTabVertical.LineAlignment = StringAlignment.Center; _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabVertical; } } private static int ImageHeight { get { return _ImageHeight; } } private static int ImageWidth { get { return _ImageWidth; } } private static int ImageGapTop { get { return _ImageGapTop; } } private static int ImageGapLeft { get { return _ImageGapLeft; } } private static int ImageGapRight { get { return _ImageGapRight; } } private static int ImageGapBottom { get { return _ImageGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int TabGapTop { get { return _TabGapTop; } } private static int TabGapLeft { get { return _TabGapLeft; } } private static int TabGapBetween { get { return _TabGapBetween; } } private static Brush BrushTabBackground { get { return SystemBrushes.Control; } } private static Pen PenTabBorder { get { return SystemPens.GrayText; } } private static Brush BrushTabText { get { return SystemBrushes.FromSystemColor(SystemColors.ControlDarkDark); } } #endregion private static Matrix _matrixIdentity = new Matrix(); private static Matrix MatrixIdentity { get { return _matrixIdentity; } } private static DockState[] _dockStates; private static DockState[] DockStates { get { if (_dockStates == null) { _dockStates = new DockState[4]; _dockStates[0] = DockState.DockLeftAutoHide; _dockStates[1] = DockState.DockRightAutoHide; _dockStates[2] = DockState.DockTopAutoHide; _dockStates[3] = DockState.DockBottomAutoHide; } return _dockStates; } } private static GraphicsPath _graphicsPath; internal static GraphicsPath GraphicsPath { get { if (_graphicsPath == null) _graphicsPath = new GraphicsPath(); return _graphicsPath; } } public VS2005AutoHideStrip(DockPanel panel) : base(panel) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); BackColor = SystemColors.ControlLight; } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; DrawTabStrip(g); } protected override void OnLayout(LayoutEventArgs levent) { CalculateTabs(); base.OnLayout (levent); } private void DrawTabStrip(Graphics g) { DrawTabStrip(g, DockState.DockTopAutoHide); DrawTabStrip(g, DockState.DockBottomAutoHide); DrawTabStrip(g, DockState.DockLeftAutoHide); DrawTabStrip(g, DockState.DockRightAutoHide); } private void DrawTabStrip(Graphics g, DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return; Matrix matrixIdentity = g.Transform; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { Matrix matrixRotated = new Matrix(); matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); g.Transform = matrixRotated; } foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2005 tab in pane.AutoHideTabs) DrawTab(g, tab); } g.Transform = matrixIdentity; } private void CalculateTabs() { CalculateTabs(DockState.DockTopAutoHide); CalculateTabs(DockState.DockBottomAutoHide); CalculateTabs(DockState.DockLeftAutoHide); CalculateTabs(DockState.DockRightAutoHide); } private void CalculateTabs(DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); int x = TabGapLeft + rectTabStrip.X; foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2005 tab in pane.AutoHideTabs) { int width = imageWidth + ImageGapLeft + ImageGapRight + TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + TextGapLeft + TextGapRight; tab.TabX = x; tab.TabWidth = width; x += width; } x += TabGapBetween; } } private Rectangle RtlTransform(Rectangle rect, DockState dockState) { Rectangle rectTransformed; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) rectTransformed = rect; else rectTransformed = DrawHelper.RtlTransform(this, rect); return rectTransformed; } private GraphicsPath GetTabOutline(TabVS2005 tab, bool transformed, bool rtlTransform) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTab = GetTabRectangle(tab, transformed); if (rtlTransform) rectTab = RtlTransform(rectTab, dockState); bool upTab = (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide); DrawHelper.GetRoundedCornerTab(GraphicsPath, rectTab, upTab); return GraphicsPath; } private void DrawTab(Graphics g, TabVS2005 tab) { Rectangle rectTabOrigin = GetTabRectangle(tab); if (rectTabOrigin.IsEmpty) return; DockState dockState = tab.Content.DockHandler.DockState; IDockContent content = tab.Content; GraphicsPath path = GetTabOutline(tab, false, true); g.FillPath(BrushTabBackground, path); g.DrawPath(PenTabBorder, path); // Set no rotate for drawing icon and text Matrix matrixRotate = g.Transform; g.Transform = MatrixIdentity; // Draw the icon Rectangle rectImage = rectTabOrigin; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight/ImageHeight); rectImage.Height = imageHeight; rectImage.Width = imageWidth; rectImage = GetTransformedRectangle(dockState, rectImage); g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState)); // Draw the text Rectangle rectText = rectTabOrigin; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState); if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) g.DrawString(content.DockHandler.TabText, TextFont, BrushTabText, rectText, StringFormatTabVertical); else g.DrawString(content.DockHandler.TabText, TextFont, BrushTabText, rectText, StringFormatTabHorizontal); // Set rotate back g.Transform = matrixRotate; } private Rectangle GetLogicalTabStripRectangle(DockState dockState) { return GetLogicalTabStripRectangle(dockState, false); } private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) { if (!DockHelper.IsDockStateAutoHide(dockState)) return Rectangle.Empty; int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; int topPanes = GetPanes(DockState.DockTopAutoHide).Count; int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; int x, y, width, height; height = MeasureHeight(); if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) { x = 0; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height); } else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) { x = Width - height; if (leftPanes != 0 && x < height) x = height; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 :height); } else if (dockState == DockState.DockTopAutoHide && topPanes > 0) { x = leftPanes == 0 ? 0 : height; y = 0; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) { x = leftPanes == 0 ? 0 : height; y = Height - height; if (topPanes != 0 && y < height) y = height; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else return Rectangle.Empty; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTabRectangle(TabVS2005 tab) { return GetTabRectangle(tab, false); } private Rectangle GetTabRectangle(TabVS2005 tab, bool transformed) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return Rectangle.Empty; int x = tab.TabX; int y = rectTabStrip.Y + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ? 0 : TabGapTop); int width = tab.TabWidth; int height = rectTabStrip.Height - TabGapTop; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) { if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) return rect; PointF[] pts = new PointF[1]; // the center of the rectangle pts[0].X = (float)rect.X + (float)rect.Width / 2; pts[0].Y = (float)rect.Y + (float)rect.Height / 2; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); Matrix matrix = new Matrix(); matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); matrix.TransformPoints(pts); return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F), (int)(pts[0].Y - (float)rect.Width / 2 + .5F), rect.Height, rect.Width); } protected override IDockContent HitTest(Point ptMouse) { foreach(DockState state in DockStates) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (!rectTabStrip.Contains(ptMouse)) continue; foreach(Pane pane in GetPanes(state)) { DockState dockState = pane.DockPane.DockState; foreach(TabVS2005 tab in pane.AutoHideTabs) { GraphicsPath path = GetTabOutline(tab, true, true); if (path.IsVisible(ptMouse)) return tab.Content; } } } return null; } protected internal override int MeasureHeight() { return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, TextFont.Height) + TabGapTop; } protected override void OnRefreshChanges() { CalculateTabs(); Invalidate(); } protected override AutoHideStripBase.Tab CreateTab(IDockContent content) { return new TabVS2005(content); } } }
// Code generated by a Template using System; using System.Linq.Expressions; using DNX.Helpers.Maths; using DNX.Helpers.Maths.BuiltInTypes; using DNX.Helpers.Reflection; namespace DNX.Helpers.Validation { /// <summary> /// Guard Extensions. /// </summary> public static partial class Guard { /// <summary> /// Ensures the expression evaluates to greater than the specified minimum /// </summary> /// <param name="exp">The exp.</param> /// <param name="min">The minimum.</param> public static void IsGreaterThan(Expression<Func<ulong>> exp, ulong min) { IsGreaterThan(exp, exp.Compile().Invoke(), min); } /// <summary> /// Ensures the expression and corresponding value evaluates to greater than the specified minimum /// </summary> /// <param name="exp">The exp.</param> /// <param name="val">The value.</param> /// <param name="min">The minimum.</param> /// <exception cref="System.ArgumentOutOfRangeException"></exception> public static void IsGreaterThan(Expression<Func<ulong>> exp, ulong val, ulong min) { if (val > min) { return; } var memberName = ExpressionExtensions.GetMemberName(exp); throw new ArgumentOutOfRangeException( memberName, val, string.Format("{0} must be greater than {1}", memberName, min ) ); } /// <summary> /// Ensures the expression evaluates to greater than or equal to the specified minimum /// </summary> /// <param name="exp">The exp.</param> /// <param name="min">The minimum.</param> public static void IsGreaterThanOrEqualTo(Expression<Func<ulong>> exp, ulong min) { IsGreaterThanOrEqualTo(exp, exp.Compile().Invoke(), min); } /// <summary> /// Ensures the expression and corresponding value evaluates to greater than or equal to the specified minimum /// </summary> /// <param name="exp">The exp.</param> /// <param name="val">The value.</param> /// <param name="min">The minimum.</param> /// <exception cref="System.ArgumentOutOfRangeException"></exception> public static void IsGreaterThanOrEqualTo(Expression<Func<ulong>> exp, ulong val, ulong min) { if (val >= min) { return; } var memberName = ExpressionExtensions.GetMemberName(exp); throw new ArgumentOutOfRangeException( memberName, val, string.Format("{0} must be greater than or equal to {1}", memberName, min ) ); } /// <summary> /// Ensures the expression evaluates to less than the specified minimum /// </summary> /// <param name="exp">The exp.</param> /// <param name="max">The maximum.</param> public static void IsLessThan(Expression<Func<ulong>> exp, ulong max) { IsLessThan(exp, exp.Compile().Invoke(), max); } /// <summary> /// Ensures the expression and corresponding value evaluates to less than the specified minimum /// </summary> /// <param name="exp">The exp.</param> /// <param name="val">The value.</param> /// <param name="max">The minimum.</param> /// <exception cref="System.ArgumentOutOfRangeException"></exception> public static void IsLessThan(Expression<Func<ulong>> exp, ulong val, ulong max) { if (val < max) { return; } var memberName = ExpressionExtensions.GetMemberName(exp); throw new ArgumentOutOfRangeException( memberName, val, string.Format("{0} must be less than {1}", memberName, max ) ); } /// <summary> /// Ensures the expression evaluates to less than or equal to the specified minimum /// </summary> /// <param name="exp">The exp.</param> /// <param name="max">The maximum.</param> public static void IsLessThanOrEqualTo(Expression<Func<ulong>> exp, ulong max) { IsLessThanOrEqualTo(exp, exp.Compile().Invoke(), max); } /// <summary> /// Ensures the expression and corresponding value evaluates to less than or equal to the specified minimum /// </summary> /// <param name="exp">The exp.</param> /// <param name="val">The value.</param> /// <param name="max">The maximum.</param> /// <exception cref="System.ArgumentOutOfRangeException"></exception> public static void IsLessThanOrEqualTo(Expression<Func<ulong>> exp, ulong val, ulong max) { if (val <= max) { return; } var memberName = ExpressionExtensions.GetMemberName(exp); throw new ArgumentOutOfRangeException( memberName, val, string.Format("{0} must be less than or equal to {1}", memberName, max ) ); } /// <summary> /// Ensures the expression evaluates to between the specified values /// </summary> /// <param name="exp">The linq expression of the argument to check</param> /// <param name="min">minimum allowed value</param> /// <param name="max">maximum allowed value</param> public static void IsBetween(Expression<Func<ulong>> exp, ulong min, ulong max) { IsBetween(exp, min, max, IsBetweenBoundsType.Inclusive); } /// <summary> /// Ensures the expression and corresponding value evaluates to between the specified values /// </summary> /// <param name="exp">The exp.</param> /// <param name="min">The minimum.</param> /// <param name="max">The maximum.</param> /// <param name="boundsType">Type of the bounds.</param> public static void IsBetween(Expression<Func<ulong>> exp, ulong min, ulong max, IsBetweenBoundsType boundsType) { IsBetween(exp, min, max, false, boundsType); } /// <summary> /// Ensures the expression evaluates to between the specified values /// </summary> /// <param name="exp">The exp.</param> /// <param name="bound1">The bound1.</param> /// <param name="bound2">The bound2.</param> /// <param name="allowEitherOrder">if set to <c>true</c> [allow either order].</param> /// <param name="boundsType">Type of the bounds.</param> public static void IsBetween(Expression<Func<ulong>> exp, ulong bound1, ulong bound2, bool allowEitherOrder, IsBetweenBoundsType boundsType) { IsBetween(exp, exp.Compile().Invoke(), bound1, bound2, allowEitherOrder, boundsType); } /// <summary> /// Ensures the expression and corresponding value evaluates to between the specified values /// </summary> /// <param name="exp">The exp.</param> /// <param name="val">The value.</param> /// <param name="bound1">The bound1.</param> /// <param name="bound2">The bound2.</param> /// <param name="allowEitherOrder">if set to <c>true</c> [allow either order].</param> /// <param name="boundsType">Type of the bounds.</param> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <exception cref="System.ArgumentOutOfRangeException"></exception> public static void IsBetween(Expression<Func<ulong>> exp, ulong val, ulong bound1, ulong bound2, bool allowEitherOrder, IsBetweenBoundsType boundsType) { if (val.IsBetween(bound1, bound2, allowEitherOrder, boundsType)) { return; } var memberName = ExpressionExtensions.GetMemberName(exp); throw new ArgumentOutOfRangeException( memberName, val, string.Format("{0} must be {1}", memberName, string.Format(boundsType.GetLimitDescriptionFormat(), MathsUInt64Extensions.GetLowerBound(bound1, bound2, allowEitherOrder), MathsUInt64Extensions.GetUpperBound(bound1, bound2, allowEitherOrder) ) ) ); } } }
/* * Copyright 2014, Gregg Tavares. * 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 Gregg Tavares. 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 HappyFunTimes; using UnityEngine; using System; using System.Collections; public class HFTGamepad : MonoBehaviour { public const int AXIS_DPAD0_X = 0; public const int AXIS_DPAD0_Y = 1; public const int AXIS_DPAD1_X = 0; public const int AXIS_DPAD1_Y = 1; public const int AXIS_ORIENTATION_ALPHA = 4; public const int AXIS_ORIENTATION_BETA = 5; public const int AXIS_ORIENTATION_GAMMA = 6; public const int AXIS_ACCELERATION_X = 7; public const int AXIS_ACCELERATION_Y = 8; public const int AXIS_ACCELERATION_Z = 9; public const int AXIS_ROTATION_RATE_ALPHA = 10; public const int AXIS_ROTATION_RATE_BETA = 11; public const int AXIS_ROTATION_RATE_GAMMA = 12; public const int AXIS_TOUCH_X = 13; public const int AXIS_TOUCH_Y = 14; public const int AXIS_TOUCH0_X = 13; public const int AXIS_TOUCH0_Y = 14; public const int AXIS_TOUCH1_X = 15; public const int AXIS_TOUCH1_Y = 16; public const int AXIS_TOUCH2_X = 17; public const int AXIS_TOUCH2_Y = 18; public const int AXIS_TOUCH3_X = 19; public const int AXIS_TOUCH3_Y = 20; public const int AXIS_TOUCH4_X = 21; public const int AXIS_TOUCH4_Y = 22; public const int AXIS_TOUCH5_X = 23; public const int AXIS_TOUCH5_Y = 24; public const int AXIS_TOUCH6_X = 25; public const int AXIS_TOUCH6_Y = 26; public const int AXIS_TOUCH7_X = 27; public const int AXIS_TOUCH7_Y = 28; public const int AXIS_TOUCH8_X = 29; public const int AXIS_TOUCH8_Y = 30; public const int AXIS_TOUCH9_X = 31; public const int AXIS_TOUCH9_Y = 32; public const int BUTTON_DPAD0_LEFT = 14; public const int BUTTON_DPAD0_RIGHT = 15; public const int BUTTON_DPAD0_TOP = 12; public const int BUTTON_DPAD0_BOTTOM = 13; public const int BUTTON_DPAD1_LEFT = 18; public const int BUTTON_DPAD1_RIGHT = 19; public const int BUTTON_DPAD1_TOP = 16; public const int BUTTON_DPAD1_BOTTOM = 17; public const int BUTTON_TOUCH = 18; public const int BUTTON_TOUCH0 = 18; public const int BUTTON_TOUCH1 = 19; public const int BUTTON_TOUCH2 = 20; public const int BUTTON_TOUCH3 = 21; public const int BUTTON_TOUCH4 = 22; public const int BUTTON_TOUCH5 = 23; public const int BUTTON_TOUCH6 = 24; public const int BUTTON_TOUCH7 = 25; public const int BUTTON_TOUCH8 = 26; public const int BUTTON_TOUCH9 = 27; public class Button { public bool pressed = false; public float value = 0.0f; } public enum ControllerType { c_1button, c_2button, c_1dpad_1button, c_1dpad_2button, c_1dpad, c_2dpad, c_1lrpad_1button, c_1lrpad_2button, c_1lrpad, c_touch, c_orient, } [System.Serializable] public class ControllerOptions { public ControllerOptions() { } public ControllerOptions(ControllerOptions src) { controllerType = src.controllerType; provideOrientation = src.provideOrientation; provideAcceleration = src.provideAcceleration; provideRotationRate = src.provideRotationRate; askForName = src.askForName; showMenu = src.showMenu; } // Because I don't understand the whole Equals, GetHashCode C# mess // I named this SameValues public bool SameValues(ControllerOptions other) { return controllerType == other.controllerType && provideOrientation == other.provideOrientation && provideAcceleration == other.provideAcceleration && provideRotationRate == other.provideRotationRate && askForName == other.askForName && showMenu == other.showMenu; } public ControllerType controllerType = ControllerType.c_1dpad_2button; public bool provideOrientation = false; public bool provideAcceleration = false; public bool provideRotationRate = false; public bool askForName = true; public bool showMenu = true; // NOTE: If you add a field you need to add to the constructor and SameValues above! } public string playerName; public bool autoChooseColor = true; public Color color = new Color(0.0f, 1.0f, 0.0f); public ControllerOptions controllerOptions; HFTGamepad() { axes = new float[33]; buttons = new Button[28]; for (int ii = 0; ii < buttons.Length; ++ii) { buttons[ii] = new Button(); } } // For backward compatibility // use gamepad.color instead public Color Color { get { return color; } set { color = value; } } // For backward compatibility // use gamepad.playerName instead public string Name { get { return playerName; } set { playerName = value; } } public NetPlayer NetPlayer { get { return m_netPlayer; } } public event System.EventHandler<System.EventArgs> OnNameChange; public event Action OnDisconnect; [System.NonSerialized] public float[] axes; [System.NonSerialized] public Button[] buttons; // Manages the connection between this object and the phone. private NetPlayer m_netPlayer; private HFTPlayerNameManager m_playerNameManager; private static int s_colorCount = 0; private Color m_oldColor; private ControllerOptions m_oldControllerOptions = new ControllerOptions(); private class MessageOptions { public MessageOptions(ControllerOptions _controllerOptions) { controllerOptions = _controllerOptions; } public ControllerOptions controllerOptions; } private class MessageButton { public int id = 0; public bool pressed = false; } private class MessageColor { public MessageColor(Color _color) { color = _color; } public Color color; } private class MessageDPad { public int pad = 0; public int dir = -1; } private class MessageTouch { public int id = 0; public int x = 0; public int y = 0; } private class MessageOrient { public float a = 0.0f; public float b = 0.0f; public float g = 0.0f; public bool abs = false; } private class MessageAccel { public float x = 0.0f; public float y = 0.0f; public float z = 0.0f; } private class MessageRot { public float a = 0.0f; public float b = 0.0f; public float g = 0.0f; } void InitializeNetPlayer(SpawnInfo spawnInfo) { m_netPlayer = spawnInfo.netPlayer; m_netPlayer.OnDisconnect += HandleDisconnect; // Setup events for the different messages. m_netPlayer.RegisterCmdHandler<MessageButton>("button", HandleButton); m_netPlayer.RegisterCmdHandler<MessageDPad>("dpad", HandleDPad); m_netPlayer.RegisterCmdHandler<MessageOrient>("orient", HandleOrient); m_netPlayer.RegisterCmdHandler<MessageAccel>("accel", HandleAccel); m_netPlayer.RegisterCmdHandler<MessageRot>("rot", HandleRot); m_netPlayer.RegisterCmdHandler<MessageTouch>("touch", HandleTouch); m_playerNameManager = new HFTPlayerNameManager(m_netPlayer); m_playerNameManager.OnNameChange += HandleNameChange; // If the controller is showing the player "game full" // then tell it can play. m_netPlayer.SendCmd("play"); SendControllerOptions(); SendColor(); } void Awake() { if (autoChooseColor) { SetDefaultColor(); } } void OnDestroy() { Cleanup(); } void Cleanup() { m_netPlayer.OnDisconnect -= HandleDisconnect; if (m_playerNameManager != null) { m_playerNameManager.Close(); m_playerNameManager = null; } } void HandleDisconnect(object sender, System.EventArgs e) { Action handler = OnDisconnect; if (handler != null) { handler(); } } void SendColor() { if (m_netPlayer != null) { m_netPlayer.SendCmd("color", new MessageColor(color)); } } void SetDefaultColor() { int colorNdx = s_colorCount++; // Pick a color float hue = (((colorNdx & 0x01) << 5) | ((colorNdx & 0x02) << 3) | ((colorNdx & 0x04) << 1) | ((colorNdx & 0x08) >> 1) | ((colorNdx & 0x10) >> 3) | ((colorNdx & 0x20) >> 5)) / 64.0f; float sat = (colorNdx & 0x10) != 0 ? 0.5f : 1.0f; float value = (colorNdx & 0x20) != 0 ? 0.5f : 1.0f; float alpha = 1.0f; Vector4 hsva = new Vector4(hue, sat, value, alpha); color = HFTColorUtils.HSVAToColor(hsva); } public void ReturnPlayer() { if (m_netPlayer != null) { HFTGamepadHelper.helper.playerSpawner.ReturnPlayer(m_netPlayer); } } void Update() { // Seems kind of dumb to do it this way but it's easier for users if (!m_oldControllerOptions.SameValues(controllerOptions)) { m_oldControllerOptions = new ControllerOptions(controllerOptions); SendControllerOptions(); } if (m_oldColor != color) { m_oldColor = color; SendColor(); } } void SendControllerOptions() { if (m_netPlayer != null) { m_netPlayer.SendCmd("options", new MessageOptions(controllerOptions)); } } void UpdateButton(int ndx, bool pressed) { Button button = buttons[ndx]; button.pressed = pressed; button.value = pressed ? 1.0f : 0.0f; } void HandleButton(MessageButton data) { UpdateButton(data.id, data.pressed); } static int[][] axisButtonMap = new int[][] { new int[] { 14, 15, 12, 13, }, new int[] { 18, 19, 16, 17, }, }; void HandleDPad(MessageDPad data) { int axisOffset = data.pad * 2; int[] buttonIndices = axisButtonMap[data.pad]; DirInfo dirInfo = Direction.GetDirectionInfo(data.dir); UpdateButton(buttonIndices[0], (dirInfo.bits & 0x2) != 0); UpdateButton(buttonIndices[1], (dirInfo.bits & 0x1) != 0); UpdateButton(buttonIndices[2], (dirInfo.bits & 0x4) != 0); UpdateButton(buttonIndices[3], (dirInfo.bits & 0x8) != 0); axes[axisOffset + 0] = dirInfo.dx; axes[axisOffset + 1] = -dirInfo.dy; } void HandleOrient(MessageOrient data) { axes[AXIS_ORIENTATION_ALPHA] = data.a; // data.a / 180 - 1; // range is suspposed to be 0 to 359 axes[AXIS_ORIENTATION_BETA] = data.b; // data.b / 180; // range is suspposed to be -180 to 180 axes[AXIS_ORIENTATION_GAMMA] = data.g; // data.g / 90; // range is suspposed to be -90 to 90 } void HandleAccel(MessageAccel data) { // These values are supposed to be in meters per second squared but I need to convert them to 0 to 1 values. // A quick test seems to make them go to +/- around 50 at least on my iPhone5s but different on my android. // Maybe I should keep track of max values and reset over time with some threshold? // actually I'm just going to pass them through as is. axes[AXIS_ACCELERATION_X] = data.x; //clamp(data.x / maxAcceleration, -1, 1); axes[AXIS_ACCELERATION_Y] = data.y; //clamp(data.y / maxAcceleration, -1, 1); axes[AXIS_ACCELERATION_Z] = data.z; //clamp(data.z / maxAcceleration, -1, 1); } void HandleRot(MessageRot data) { axes[AXIS_ROTATION_RATE_ALPHA] = data.a; axes[AXIS_ROTATION_RATE_BETA] = data.b; axes[AXIS_ROTATION_RATE_GAMMA] = data.g; } void HandleTouch(MessageTouch data) { int index = data.id * 2; axes[AXIS_TOUCH_X + index] = (float)data.x / 500.0f - 1.0f; axes[AXIS_TOUCH_Y + index] = (float)data.y / 500.0f - 1.0f; } void HandleNameChange(string name) { playerName = name; System.EventHandler<System.EventArgs> handler = OnNameChange; if (handler != null) { handler(this, new System.EventArgs()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; namespace System.Xml { internal class Base64Decoder : IncrementalReadDecoder { // // Fields // private byte[] _buffer; private int _startIndex; private int _curIndex; private int _endIndex; private int _bits; private int _bitsFilled; private static readonly String s_charsBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static readonly byte[] s_mapBase64 = ConstructMapBase64(); private const int MaxValidChar = (int)'z'; private const byte Invalid = unchecked((byte)-1); // // IncrementalReadDecoder interface // internal override int DecodedCount { get { return _curIndex - _startIndex; } } internal override bool IsFull { get { return _curIndex == _endIndex; } } internal override unsafe int Decode(char[] chars, int startPos, int len) { if (chars == null) { throw new ArgumentNullException(nameof(chars)); } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); } if (startPos < 0) { throw new ArgumentOutOfRangeException(nameof(startPos)); } if (chars.Length - startPos < len) { throw new ArgumentOutOfRangeException(nameof(len)); } if (len == 0) { return 0; } int bytesDecoded, charsDecoded; fixed (char* pChars = &chars[startPos]) { fixed (byte* pBytes = &_buffer[_curIndex]) { Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded); } } _curIndex += bytesDecoded; return charsDecoded; } internal override unsafe int Decode(string str, int startPos, int len) { if (str == null) { throw new ArgumentNullException(nameof(str)); } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); } if (startPos < 0) { throw new ArgumentOutOfRangeException(nameof(startPos)); } if (str.Length - startPos < len) { throw new ArgumentOutOfRangeException(nameof(len)); } if (len == 0) { return 0; } int bytesDecoded, charsDecoded; fixed (char* pChars = str) { fixed (byte* pBytes = &_buffer[_curIndex]) { Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded); } } _curIndex += bytesDecoded; return charsDecoded; } internal override void Reset() { _bitsFilled = 0; _bits = 0; } internal override void SetNextOutputBuffer(Array buffer, int index, int count) { Debug.Assert(buffer != null); Debug.Assert(count >= 0); Debug.Assert(index >= 0); Debug.Assert(buffer.Length - index >= count); Debug.Assert((buffer as byte[]) != null); _buffer = (byte[])buffer; _startIndex = index; _curIndex = index; _endIndex = index + count; } // // Private methods // private static byte[] ConstructMapBase64() { byte[] mapBase64 = new byte[MaxValidChar + 1]; for (int i = 0; i < mapBase64.Length; i++) { mapBase64[i] = Invalid; } for (int i = 0; i < s_charsBase64.Length; i++) { mapBase64[(int)s_charsBase64[i]] = (byte)i; } return mapBase64; } private unsafe void Decode(char* pChars, char* pCharsEndPos, byte* pBytes, byte* pBytesEndPos, out int charsDecoded, out int bytesDecoded) { #if DEBUG Debug.Assert(pCharsEndPos - pChars >= 0); Debug.Assert(pBytesEndPos - pBytes >= 0); #endif // walk hex digits pairing them up and shoving the value of each pair into a byte byte* pByte = pBytes; char* pChar = pChars; int b = _bits; int bFilled = _bitsFilled; XmlCharType xmlCharType = XmlCharType.Instance; while (pChar < pCharsEndPos && pByte < pBytesEndPos) { char ch = *pChar; // end? if (ch == '=') { break; } pChar++; // ignore whitespace if (xmlCharType.IsWhiteSpace(ch)) { continue; } int digit; if (ch > 122 || (digit = s_mapBase64[ch]) == Invalid) { throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars))); } b = (b << 6) | digit; bFilled += 6; if (bFilled >= 8) { // get top eight valid bits *pByte++ = (byte)((b >> (bFilled - 8)) & 0xFF); bFilled -= 8; if (pByte == pBytesEndPos) { goto Return; } } } if (pChar < pCharsEndPos && *pChar == '=') { bFilled = 0; // ignore padding chars do { pChar++; } while (pChar < pCharsEndPos && *pChar == '='); // ignore whitespace after the padding chars if (pChar < pCharsEndPos) { do { if (!(xmlCharType.IsWhiteSpace(*pChar++))) { throw new XmlException(SR.Xml_InvalidBase64Value, new string(pChars, 0, (int)(pCharsEndPos - pChars))); } } while (pChar < pCharsEndPos); } } Return: _bits = b; _bitsFilled = bFilled; bytesDecoded = (int)(pByte - pBytes); charsDecoded = (int)(pChar - pChars); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.CustomerInsights.Models { using Azure; using Management; using CustomerInsights; using Rest; using Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// The relationship link resource format. /// </summary> [JsonTransformation] public partial class RelationshipLinkResourceFormat : ProxyResource { /// <summary> /// Initializes a new instance of the RelationshipLinkResourceFormat /// class. /// </summary> public RelationshipLinkResourceFormat() { } /// <summary> /// Initializes a new instance of the RelationshipLinkResourceFormat /// class. /// </summary> /// <param name="interactionType">The InteractionType associated with /// the Relationship Link.</param> /// <param name="profilePropertyReferences">The property references for /// the Profile of the Relationship.</param> /// <param name="relatedProfilePropertyReferences">The property /// references for the Related Profile of the Relationship.</param> /// <param name="relationshipName">The Relationship associated with the /// Link.</param> /// <param name="id">Resource ID.</param> /// <param name="name">Resource name.</param> /// <param name="type">Resource type.</param> /// <param name="displayName">Localized display name for the /// Relationship Link.</param> /// <param name="description">Localized descriptions for the /// Relationship Link.</param> /// <param name="linkName">The name of the Relationship Link.</param> /// <param name="mappings">The mappings between Interaction and /// Relationship fields.</param> /// <param name="provisioningState">Provisioning state. Possible values /// include: 'Provisioning', 'Succeeded', 'Expiring', 'Deleting', /// 'HumanIntervention', 'Failed'</param> /// <param name="relationshipGuidId">The relationship guid id.</param> /// <param name="tenantId">The hub name.</param> public RelationshipLinkResourceFormat(string interactionType, IList<ParticipantPropertyReference> profilePropertyReferences, IList<ParticipantPropertyReference> relatedProfilePropertyReferences, string relationshipName, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> displayName = default(IDictionary<string, string>), IDictionary<string, string> description = default(IDictionary<string, string>), string linkName = default(string), IList<RelationshipLinkFieldMapping> mappings = default(IList<RelationshipLinkFieldMapping>), string provisioningState = default(string), string relationshipGuidId = default(string), string tenantId = default(string)) : base(id, name, type) { DisplayName = displayName; Description = description; InteractionType = interactionType; LinkName = linkName; Mappings = mappings; ProfilePropertyReferences = profilePropertyReferences; ProvisioningState = provisioningState; RelatedProfilePropertyReferences = relatedProfilePropertyReferences; RelationshipName = relationshipName; RelationshipGuidId = relationshipGuidId; TenantId = tenantId; } /// <summary> /// Gets or sets localized display name for the Relationship Link. /// </summary> [JsonProperty(PropertyName = "properties.displayName")] public IDictionary<string, string> DisplayName { get; set; } /// <summary> /// Gets or sets localized descriptions for the Relationship Link. /// </summary> [JsonProperty(PropertyName = "properties.description")] public IDictionary<string, string> Description { get; set; } /// <summary> /// Gets or sets the InteractionType associated with the Relationship /// Link. /// </summary> [JsonProperty(PropertyName = "properties.interactionType")] public string InteractionType { get; set; } /// <summary> /// Gets the name of the Relationship Link. /// </summary> [JsonProperty(PropertyName = "properties.linkName")] public string LinkName { get; protected set; } /// <summary> /// Gets or sets the mappings between Interaction and Relationship /// fields. /// </summary> [JsonProperty(PropertyName = "properties.mappings")] public IList<RelationshipLinkFieldMapping> Mappings { get; set; } /// <summary> /// Gets or sets the property references for the Profile of the /// Relationship. /// </summary> [JsonProperty(PropertyName = "properties.profilePropertyReferences")] public IList<ParticipantPropertyReference> ProfilePropertyReferences { get; set; } /// <summary> /// Gets provisioning state. Possible values include: 'Provisioning', /// 'Succeeded', 'Expiring', 'Deleting', 'HumanIntervention', 'Failed' /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; protected set; } /// <summary> /// Gets or sets the property references for the Related Profile of the /// Relationship. /// </summary> [JsonProperty(PropertyName = "properties.relatedProfilePropertyReferences")] public IList<ParticipantPropertyReference> RelatedProfilePropertyReferences { get; set; } /// <summary> /// Gets or sets the Relationship associated with the Link. /// </summary> [JsonProperty(PropertyName = "properties.relationshipName")] public string RelationshipName { get; set; } /// <summary> /// Gets the relationship guid id. /// </summary> [JsonProperty(PropertyName = "properties.relationshipGuidId")] public string RelationshipGuidId { get; protected set; } /// <summary> /// Gets the hub name. /// </summary> [JsonProperty(PropertyName = "properties.tenantId")] public string TenantId { get; protected set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (InteractionType == null) { throw new ValidationException(ValidationRules.CannotBeNull, "InteractionType"); } if (ProfilePropertyReferences == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ProfilePropertyReferences"); } if (RelatedProfilePropertyReferences == null) { throw new ValidationException(ValidationRules.CannotBeNull, "RelatedProfilePropertyReferences"); } if (RelationshipName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "RelationshipName"); } if (Mappings != null) { foreach (var element in Mappings) { if (element != null) { element.Validate(); } } } if (ProfilePropertyReferences != null) { foreach (var element1 in ProfilePropertyReferences) { if (element1 != null) { element1.Validate(); } } } if (RelatedProfilePropertyReferences != null) { foreach (var element2 in RelatedProfilePropertyReferences) { if (element2 != null) { element2.Validate(); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel.Composition.Primitives; using System.Linq; using System.Threading; using Microsoft.Internal; using Microsoft.Internal.Collections; namespace System.ComponentModel.Composition.Hosting { /// <summary> /// This class implements a threadsafe ICollection{T} of ComposablePartCatalog. /// It is exposed as an ICollection(ComposablePartCatalog) /// It is threadsafe, notifications are not marshalled using a SynchronizationContext. /// It is Disposable. /// </summary> internal class ComposablePartCatalogCollection : ICollection<ComposablePartCatalog>, INotifyComposablePartCatalogChanged, IDisposable { private readonly Lock _lock = new Lock(); private Action<ComposablePartCatalogChangeEventArgs> _onChanged; private Action<ComposablePartCatalogChangeEventArgs> _onChanging; private List<ComposablePartCatalog> _catalogs = new List<ComposablePartCatalog>(); private volatile bool _isCopyNeeded = false; private volatile bool _isDisposed = false; private bool _hasChanged = false; public ComposablePartCatalogCollection( IEnumerable<ComposablePartCatalog> catalogs, Action<ComposablePartCatalogChangeEventArgs> onChanged, Action<ComposablePartCatalogChangeEventArgs> onChanging) { catalogs = catalogs ?? Enumerable.Empty<ComposablePartCatalog>(); _catalogs = new List<ComposablePartCatalog>(catalogs); _onChanged = onChanged; _onChanging = onChanging; SubscribeToCatalogNotifications(catalogs); } public void Add(ComposablePartCatalog item) { Requires.NotNull(item, nameof(item)); ThrowIfDisposed(); var addedParts = new Lazy<IEnumerable<ComposablePartDefinition>>(() => item.ToArray(), LazyThreadSafetyMode.PublicationOnly); using (var atomicComposition = new AtomicComposition()) { RaiseChangingEvent(addedParts, null, atomicComposition); using (new WriteLock(_lock)) { if (_isCopyNeeded) { _catalogs = new List<ComposablePartCatalog>(_catalogs); _isCopyNeeded = false; } _hasChanged = true; _catalogs.Add(item); } SubscribeToCatalogNotifications(item); // Complete after the catalog changes are written atomicComposition.Complete(); } RaiseChangedEvent(addedParts, null); } /// <summary> /// Notify when the contents of the Catalog has changed. /// </summary> public event EventHandler<ComposablePartCatalogChangeEventArgs> Changed; /// <summary> /// Notify when the contents of the Catalog has changing. /// </summary> public event EventHandler<ComposablePartCatalogChangeEventArgs> Changing; public void Clear() { ThrowIfDisposed(); // No action is required if we are already empty ComposablePartCatalog[] catalogs = null; using (new ReadLock(_lock)) { if (_catalogs.Count == 0) { return; } catalogs = _catalogs.ToArray(); } // We are doing this outside of the lock, so it's possible that the catalog will continute propagating events from things // we are about to unsubscribe from. Given the non-specificity of our event, in the worst case scenario we would simply fire // unnecessary events. var removedParts = new Lazy<IEnumerable<ComposablePartDefinition>>(() => catalogs.SelectMany(catalog => catalog).ToArray(), LazyThreadSafetyMode.PublicationOnly); // Validate the changes before applying them using (var atomicComposition = new AtomicComposition()) { RaiseChangingEvent(null, removedParts, atomicComposition); UnsubscribeFromCatalogNotifications(catalogs); using (new WriteLock(_lock)) { _catalogs = new List<ComposablePartCatalog>(); _isCopyNeeded = false; _hasChanged = true; } // Complete after the catalog changes are written atomicComposition.Complete(); } RaiseChangedEvent(null, removedParts); } public bool Contains(ComposablePartCatalog item) { Requires.NotNull(item, nameof(item)); ThrowIfDisposed(); using (new ReadLock(_lock)) { return _catalogs.Contains(item); } } public void CopyTo(ComposablePartCatalog[] array, int arrayIndex) { ThrowIfDisposed(); using (new ReadLock(_lock)) { _catalogs.CopyTo(array, arrayIndex); } } public int Count { get { ThrowIfDisposed(); using (new ReadLock(_lock)) { return _catalogs.Count; } } } public bool IsReadOnly { get { ThrowIfDisposed(); return false; } } public bool Remove(ComposablePartCatalog item) { Requires.NotNull(item, nameof(item)); ThrowIfDisposed(); using (new ReadLock(_lock)) { if (!_catalogs.Contains(item)) { return false; } } bool isSuccessfulRemoval = false; var removedParts = new Lazy<IEnumerable<ComposablePartDefinition>>(() => item.ToArray(), LazyThreadSafetyMode.PublicationOnly); using (var atomicComposition = new AtomicComposition()) { RaiseChangingEvent(null, removedParts, atomicComposition); using (new WriteLock(_lock)) { if (_isCopyNeeded) { _catalogs = new List<ComposablePartCatalog>(_catalogs); _isCopyNeeded = false; } isSuccessfulRemoval = _catalogs.Remove(item); if (isSuccessfulRemoval) { _hasChanged = true; } } UnsubscribeFromCatalogNotifications(item); // Complete after the catalog changes are written atomicComposition.Complete(); } RaiseChangedEvent(null, removedParts); return isSuccessfulRemoval; } internal bool HasChanged { get { ThrowIfDisposed(); using (new ReadLock(_lock)) { return _hasChanged; } } } public IEnumerator<ComposablePartCatalog> GetEnumerator() { ThrowIfDisposed(); using (new WriteLock(_lock)) { IEnumerator<ComposablePartCatalog> enumerator = _catalogs.GetEnumerator(); _isCopyNeeded = true; return enumerator; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { if (!_isDisposed) { bool disposeLock = false; IEnumerable<ComposablePartCatalog> catalogs = null; try { using (new WriteLock(_lock)) { if (!_isDisposed) { disposeLock = true; catalogs = _catalogs; _catalogs = null; _isDisposed = true; } } } finally { if (catalogs != null) { UnsubscribeFromCatalogNotifications(catalogs); catalogs.ForEach(catalog => catalog.Dispose()); } if (disposeLock) { _lock.Dispose(); } } } } } private void RaiseChangedEvent( Lazy<IEnumerable<ComposablePartDefinition>> addedDefinitions, Lazy<IEnumerable<ComposablePartDefinition>> removedDefinitions) { if (_onChanged == null || Changed == null) { return; } var added = (addedDefinitions == null ? Enumerable.Empty<ComposablePartDefinition>() : addedDefinitions.Value); var removed = (removedDefinitions == null ? Enumerable.Empty<ComposablePartDefinition>() : removedDefinitions.Value); _onChanged.Invoke(new ComposablePartCatalogChangeEventArgs(added, removed, null)); } public void OnChanged(object sender, ComposablePartCatalogChangeEventArgs e) { var changedEvent = Changed; if (changedEvent != null) { changedEvent(sender, e); } } private void RaiseChangingEvent( Lazy<IEnumerable<ComposablePartDefinition>> addedDefinitions, Lazy<IEnumerable<ComposablePartDefinition>> removedDefinitions, AtomicComposition atomicComposition) { if (_onChanging == null || Changing == null) { return; } var added = (addedDefinitions == null ? Enumerable.Empty<ComposablePartDefinition>() : addedDefinitions.Value); var removed = (removedDefinitions == null ? Enumerable.Empty<ComposablePartDefinition>() : removedDefinitions.Value); _onChanging.Invoke(new ComposablePartCatalogChangeEventArgs(added, removed, atomicComposition)); } public void OnChanging(object sender, ComposablePartCatalogChangeEventArgs e) { var changingEvent = Changing; if (changingEvent != null) { changingEvent(sender, e); } } private void OnContainedCatalogChanged(object sender, ComposablePartCatalogChangeEventArgs e) { if (_onChanged == null || Changed == null) { return; } _onChanged.Invoke(e); } private void OnContainedCatalogChanging(object sender, ComposablePartCatalogChangeEventArgs e) { if (_onChanging == null || Changing == null) { return; } _onChanging.Invoke(e); } private void SubscribeToCatalogNotifications(ComposablePartCatalog catalog) { INotifyComposablePartCatalogChanged notifyCatalog = catalog as INotifyComposablePartCatalogChanged; if (notifyCatalog != null) { notifyCatalog.Changed += OnContainedCatalogChanged; notifyCatalog.Changing += OnContainedCatalogChanging; } } private void SubscribeToCatalogNotifications(IEnumerable<ComposablePartCatalog> catalogs) { foreach (var catalog in catalogs) { SubscribeToCatalogNotifications(catalog); } } private void UnsubscribeFromCatalogNotifications(ComposablePartCatalog catalog) { INotifyComposablePartCatalogChanged notifyCatalog = catalog as INotifyComposablePartCatalogChanged; if (notifyCatalog != null) { notifyCatalog.Changed -= OnContainedCatalogChanged; notifyCatalog.Changing -= OnContainedCatalogChanging; } } private void UnsubscribeFromCatalogNotifications(IEnumerable<ComposablePartCatalog> catalogs) { foreach (var catalog in catalogs) { UnsubscribeFromCatalogNotifications(catalog); } } private void ThrowIfDisposed() { if (_isDisposed) { throw ExceptionBuilder.CreateObjectDisposed(this); } } } }
//----------------------------------------------------------------------------- // Verve // Copyright (C) - Violent Tulip //----------------------------------------------------------------------------- new ScriptObject( VGroupPropertyList ) { SuperClass = "VEditorPropertyList"; Parent = "VObjectPropertyList"; }; //----------------------------------------------------------------------------- function VGroup::OnAdd( %this ) { %ourClass = %this.getClassName(); if ( isWordInList( %ourClass, $VerveEditor::UniqueGroupList ) ) { %controller = $VerveEditor::Controller; %groupCount = %controller.getCount(); for ( %i = 0; %i < %groupCount; %i++ ) { %groupObject = %controller.getObject( %i ); if ( %groupObject.getId() == %this.getId() ) { // Skip. continue; } if ( %groupObject.isMemberOfClass( %ourClass ) ) { // Alert Message. messageBox( "Verve Editor", "You cannot have more than one \"" @ %ourClass @ "\" in your sequence.", "Ok", "Warning" ); // Invalid. return false; } } } // Regular Add. return Parent::OnAdd( %this ); } function VGroup::OnAttach( %this ) { // Add Event Notify. VerveEditor::AddEventNotify( %this, "VGroupObjectUpdate", "OnGroupObjectUpdate" ); } function VGroup::OnDetach( %this ) { // Remove Event Notify. VerveEditor::RemoveEventNotify( %this, "VGroupObjectUpdate" ); } function VGroup::CanPaste( %this, %targetObject ) { if ( !isObject( %targetObject ) ) { // Nope! return false; } if ( !%this.CanAdd( %targetObject.getClassName() ) ) { // Nope! return false; } return %targetObject.isMemberOfClass( "VTrack" ); } function VGroup::CanAdd( %this, %targetClass ) { if ( isWordInList( %targetClass, $VerveEditor::NonUniqueTrackList ) ) { // Non-Unique Class. return true; } // All Tracks are Unique. %trackCount = %this.getCount(); for ( %i = 0; %i < %trackCount; %i++ ) { %trackObject = %this.getObject( %i ); if ( %trackObject.isMemberOfClass( %targetClass ) ) { // Invalid. return false; } } // All Good. return true; } function VGroup::isValid( %this ) { // Yup. return true; } function VGroup::Refresh( %this ) { // Create Control. %groupControl = VerveEditor::CreateGroupControl( %this ); // Update Validity. %this.OnGroupObjectUpdate(); %trackCount = %this.getCount(); for ( %i = 0; %i < %trackCount; %i++ ) { %this.getObject( %i ).Refresh(); } // Return Control. return %groupControl; } function VGroup::OnFieldChange( %this, %fieldName, %oldValue, %newValue ) { // Parent Callback. Parent::OnFieldChange( %this, %fieldName, %oldValue, %newValue ); switch$ ( %fieldName ) { case "Reference" : if ( $VerveEditor::InspectorObject.getId() == %this.getId() ) { // Post Event. VerveEditor::PostEvent( "VGroupObjectUpdate", %this ); } } } function VGroup::OnGroupObjectUpdate( %this, %refObject ) { if ( !isObject( %this.Control ) ) { return; } // Update Validity. if ( %this.isValid() ) { // Valid. %this.Control.setProfile( "VEditorGroupHeaderProfile" ); } else { // Invalid. %this.Control.setProfile( "VEditorGroupHeaderErrorProfile" ); } } //----------------------------------------------------------------------------- function VGroup::PopulateBuildStack( %this, %stack ) { // Void. } function VGroup::ResolveBuildStack( %this, %stack ) { // Void. } //----------------------------------------------------------------------------- function VGroup::DisplayContextMenu( %this, %x, %y ) { %contextMenu = $VerveEditor::VGroup::ContextMenu; if ( !isObject( %contextMenu ) ) { %contextMenu = new PopupMenu() { SuperClass = "VerveWindowMenu"; IsPopup = true; Label = "VGroupContextMenu"; Position = 0; Item[0] = "Add Track" TAB ""; Item[1] = "" TAB ""; Item[2] = "Cu&t" TAB "" TAB "VerveEditor::CutSelection();"; Item[3] = "&Copy" TAB "" TAB "VerveEditor::CopySelection();"; Item[4] = "&Paste" TAB "" TAB "VerveEditor::Paste();"; Item[5] = "" TAB ""; Item[6] = "&Delete" TAB "" TAB "VerveEditor::DeleteSelection();"; AddIndex = 0; PasteIndex = 4; }; %contextMenu.Init(); // Cache. $VerveEditor::VGroup::ContextMenu = %contextMenu; } // Remove Add Menu. %contextMenu.removeItem( %contextMenu.AddIndex ); // Available Tracks Menu. %groupMenu = 0; if ( %this.isMethod( "GetAddTrackMenu" ) ) { %groupMenu = %this.GetAddTrackMenu(); } if ( isObject( %groupMenu ) ) { // Insert Menu. %contextMenu.insertSubMenu( %contextMenu.AddIndex, getField( %contextMenu.Item[0], 0 ), %groupMenu ); // Enable. %contextMenu.enableItem( %contextMenu.AddIndex, true ); } else { // Add Dummy. %contextMenu.insertItem( %contextMenu.AddIndex, getField( %contextMenu.Item[0], 0 ) ); // Disable. %contextMenu.enableItem( %contextMenu.AddIndex, false ); } // Enable/Disable Pasting. %contextMenu.enableItem( %contextMenu.PasteIndex, VerveEditor::CanPaste() ); // Display. %contextMenu.showPopup( VerveEditorWindow, %x, %y ); } function VGroup::GetAddTrackMenu( %this ) { %contextMenu = $VerveEditor::VGroup::ContextMenu[%this.getClassName()]; if ( !isObject( %contextMenu ) ) { %contextMenu = new PopupMenu() { SuperClass = "VerveWindowMenu"; IsPopup = true; Label = "VGroupAddTrackMenu"; Position = 0; Item[0] = "Add Track" TAB "" TAB "VerveEditor::AddTrack( \"VTrack\" );"; }; %contextMenu.Init(); // Cache. $VerveEditor::VGroup::ContextMenu[%this.getClassName()] = %contextMenu; } // Enable/Disable Adding Tracks. %contextMenu.enableItem( 0, %this.CanAdd( "VTrack" ) ); // Return Menu. return %contextMenu; } //----------------------------------------------------------------------------- function VerveEditor::CreateGroupControl( %object ) { %groupWidth = getWord( VerveEditorGroupStack.getExtent(), 0 ); %groupHeight = 26; %trackWidth = getWord( VerveEditorTrackStack.getExtent(), 0 ); %trackHeight = %groupHeight; %groupContainer = new VEditorButton() { SuperClass = "VEditorSelectable"; Class = "VEditorSelectableGroup"; Profile = "VEditorGroupHeaderProfile"; Bitmap = "~/VerveEditor/GUI/Images/GroupBackground"; HorizSizing = "width"; VertSizing = "bottom"; Position = "0 0"; Extent = %groupWidth SPC %groupHeight; ButtonType = "ToggleButton"; GroupNum = "-1"; IsContainer = "1"; }; VerveEditorGroupStack.add( %groupContainer ); %groupCheckbox = new GuiCheckBoxCtrl() { Class = "VEditorBoolPropertyField"; InternalName = "Enabled"; Profile = "VEditorCheckBoxProfile"; HorizSizing = "width"; VertSizing = "bottom"; Position = "4 0"; Extent = "14" SPC %groupHeight; Object = %object; FieldName = "Enabled"; Command = "$ThisControl.ApplyValue();"; Text = ""; }; %groupContainer.add( %groupCheckbox ); %trackContainer = new VEditorButton() { SuperClass = "VEditorSelectable"; Class = "VEditorSelectableGroup"; Profile = "VEditorGroupTrackProfile"; Bitmap = "~/VerveEditor/GUI/Images/GroupBackground"; HorizSizing = "width"; VertSizing = "bottom"; Position = "0 0"; Extent = %trackWidth SPC %trackHeight; ButtonType = "ToggleButton"; GroupNum = "-1"; IsContainer = "1"; }; VerveEditorTrackStack.add( %trackContainer ); // Field Notify. %object.AddFieldNotify( "Label", %groupContainer ); %object.AddFieldNotify( "Enabled", %groupCheckbox ); // Reference Siblings. %trackContainer.SiblingControl = %groupContainer; %groupContainer.SiblingControl = %trackContainer; // Reference Proxy. %groupContainer.Proxy = %object; %trackContainer.Proxy = %object; // Reference Control. %object.Control = %groupContainer; return %trackContainer; } function VEditorSelectableGroup::Update( %this, %fieldName, %fieldValue ) { %this.setText( %fieldValue ); }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.Threading.Tasks; using Xunit; using Xunit.Sdk; using System.Linq; namespace System { public static class AssertExtensions { private static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework"); public static void Throws<T>(Action action, string message) where T : Exception { Assert.Equal(Assert.Throws<T>(action).Message, message); } public static void Throws<T>(string netCoreParamName, string netFxParamName, Action action) where T : ArgumentException { T exception = Assert.Throws<T>(action); if (netFxParamName == null && IsFullFramework) { // Param name varies between NETFX versions -- skip checking it return; } string expectedParamName = IsFullFramework ? netFxParamName : netCoreParamName; if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) Assert.Equal(expectedParamName, exception.ParamName); } public static T Throws<T>(string paramName, Action action) where T : ArgumentException { T exception = Assert.Throws<T>(action); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) Assert.Equal(paramName, exception.ParamName); return exception; } public static T Throws<T>(Action action) where T : Exception { T exception = Assert.Throws<T>(action); return exception; } public static T Throws<T>(string paramName, Func<object> testCode) where T : ArgumentException { T exception = Assert.Throws<T>(testCode); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) Assert.Equal(paramName, exception.ParamName); return exception; } public static async Task<T> ThrowsAsync<T>(string paramName, Func<Task> testCode) where T : ArgumentException { T exception = await Assert.ThrowsAsync<T>(testCode); if (!RuntimeInformation.FrameworkDescription.StartsWith(".NET Native")) Assert.Equal(paramName, exception.ParamName); return exception; } public static void Throws<TNetCoreExceptionType, TNetFxExceptionType>(string paramName, Action action) where TNetCoreExceptionType : ArgumentException where TNetFxExceptionType : ArgumentException { Throws<TNetCoreExceptionType, TNetFxExceptionType>(paramName, paramName, action); } public static Exception Throws<TNetCoreExceptionType, TNetFxExceptionType>(Action action) where TNetCoreExceptionType : Exception where TNetFxExceptionType : Exception { if (IsFullFramework) { return Throws<TNetFxExceptionType>(action); } else { return Throws<TNetCoreExceptionType>(action); } } public static void Throws<TNetCoreExceptionType, TNetFxExceptionType>(string netCoreParamName, string netFxParamName, Action action) where TNetCoreExceptionType : ArgumentException where TNetFxExceptionType : ArgumentException { if (IsFullFramework) { Throws<TNetFxExceptionType>(netFxParamName, action); } else { Throws<TNetCoreExceptionType>(netCoreParamName, action); } } public static void ThrowsAny(Type firstExceptionType, Type secondExceptionType, Action action) { ThrowsAnyInternal(action, firstExceptionType, secondExceptionType); } private static void ThrowsAnyInternal(Action action, params Type[] exceptionTypes) { try { action(); } catch (Exception e) { Type exceptionType = e.GetType(); if (exceptionTypes.Any(t => t.Equals(exceptionType))) return; throw new XunitException($"Expected one of: ({string.Join<Type>(", ", exceptionTypes)}) -> Actual: ({e.GetType()})"); } throw new XunitException($"Expected one of: ({string.Join<Type>(", ", exceptionTypes)}) -> Actual: No exception thrown"); } public static void ThrowsAny<TFirstExceptionType, TSecondExceptionType>(Action action) where TFirstExceptionType : Exception where TSecondExceptionType : Exception { ThrowsAnyInternal(action, typeof(TFirstExceptionType), typeof(TSecondExceptionType)); } public static void ThrowsAny<TFirstExceptionType, TSecondExceptionType, TThirdExceptionType>(Action action) where TFirstExceptionType : Exception where TSecondExceptionType : Exception where TThirdExceptionType : Exception { ThrowsAnyInternal(action, typeof(TFirstExceptionType), typeof(TSecondExceptionType), typeof(TThirdExceptionType)); } public static void ThrowsIf<T>(bool condition, Action action) where T : Exception { if (condition) { Assert.Throws<T>(action); } else { action(); } } private static string AddOptionalUserMessage(string message, string userMessage) { if (userMessage == null) return message; else return $"{message} {userMessage}"; } /// <summary> /// Tests whether the specified string contains the specified substring /// and throws an exception if the substring does not occur within the /// test string or if either string or substring is null. /// </summary> /// <param name="value"> /// The string that is expected to contain <paramref name="substring"/>. /// </param> /// <param name="substring"> /// The string expected to occur within <paramref name="value"/>. /// </param> public static void Contains(string value, string substring) { Assert.NotNull(value); Assert.NotNull(substring); Assert.Contains(substring, value, StringComparison.Ordinal); } /// <summary> /// Validate that a given value is greater than another value. /// </summary> /// <param name="actual">The value that should be greater than <paramref name="greaterThan"/>.</param> /// <param name="greaterThan">The value that <paramref name="actual"/> should be greater than.</param> public static void GreaterThan<T>(T actual, T greaterThan, string userMessage = null) where T : IComparable { if (actual == null) throw new XunitException( greaterThan == null ? AddOptionalUserMessage($"Expected: <null> to be greater than <null>.", userMessage) : AddOptionalUserMessage($"Expected: <null> to be greater than {greaterThan}.", userMessage)); if (actual.CompareTo(greaterThan) <= 0) throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be greater than {greaterThan}", userMessage)); } /// <summary> /// Validate that a given value is less than another value. /// </summary> /// <param name="actual">The value that should be less than <paramref name="lessThan"/>.</param> /// <param name="lessThan">The value that <paramref name="actual"/> should be less than.</param> public static void LessThan<T>(T actual, T lessThan, string userMessage = null) where T : IComparable { if (actual == null) { if (lessThan == null) { throw new XunitException(AddOptionalUserMessage($"Expected: <null> to be less than <null>.", userMessage)); } else { // Null is always less than non-null return; } } if (actual.CompareTo(lessThan) >= 0) throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be less than {lessThan}", userMessage)); } /// <summary> /// Validate that a given value is less than or equal to another value. /// </summary> /// <param name="actual">The value that should be less than or equal to <paramref name="lessThanOrEqualTo"/></param> /// <param name="lessThanOrEqualTo">The value that <paramref name="actual"/> should be less than or equal to.</param> public static void LessThanOrEqualTo<T>(T actual, T lessThanOrEqualTo, string userMessage = null) where T : IComparable { // null, by definition is always less than or equal to if (actual == null) return; if (actual.CompareTo(lessThanOrEqualTo) > 0) throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be less than or equal to {lessThanOrEqualTo}", userMessage)); } /// <summary> /// Validate that a given value is greater than or equal to another value. /// </summary> /// <param name="actual">The value that should be greater than or equal to <paramref name="greaterThanOrEqualTo"/></param> /// <param name="greaterThanOrEqualTo">The value that <paramref name="actual"/> should be greater than or equal to.</param> public static void GreaterThanOrEqualTo<T>(T actual, T greaterThanOrEqualTo, string userMessage = null) where T : IComparable { // null, by definition is always less than or equal to if (actual == null) { if (greaterThanOrEqualTo == null) { // We're equal return; } else { // Null is always less than non-null throw new XunitException(AddOptionalUserMessage($"Expected: <null> to be greater than or equal to <null>.", userMessage)); } } if (actual.CompareTo(greaterThanOrEqualTo) < 0) throw new XunitException(AddOptionalUserMessage($"Expected: {actual} to be greater than or equal to {greaterThanOrEqualTo}", userMessage)); } /// <summary> /// Validates that the actual byte array is equal to the expected byte array. XUnit only displays the first 5 values /// of each collection if the test fails. This doesn't display at what point or how the equality assertion failed. /// </summary> /// <param name="expected">The byte array that <paramref name="actual"/> should be equal to.</param> /// <param name="actual"></param> public static void Equal(byte[] expected, byte[] actual) { try { Assert.Equal(expected, actual); } catch (AssertActualExpectedException) { string expectedString = string.Join(", ", expected); string actualString = string.Join(", ", actual); throw new AssertActualExpectedException(expectedString, actualString, null); } } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Text; using System.Reflection; namespace DBus { //TODO: complete this class class Introspector { const string NAMESPACE = "http://www.freedesktop.org/standards/dbus"; const string PUBLIC_IDENTIFIER = "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"; const string SYSTEM_IDENTIFIER = "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"; public StringBuilder sb; public string xml; public ObjectPath root_path = ObjectPath.Root; public bool ExtendedAnnotations = false; protected XmlWriter writer; public Introspector () { XmlWriterSettings settings = new XmlWriterSettings (); settings.Indent = true; settings.IndentChars = (" "); settings.OmitXmlDeclaration = true; sb = new StringBuilder (); writer = XmlWriter.Create (sb, settings); } static string GetProductDescription () { String version; Assembly assembly = Assembly.GetExecutingAssembly (); AssemblyName aname = assembly.GetName (); AssemblyInformationalVersionAttribute iversion = Attribute.GetCustomAttribute (assembly, typeof (AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute; if (iversion != null) version = iversion.InformationalVersion; else version = aname.Version.ToString (); return aname.Name + " " + version; } public void WriteStart () { writer.WriteDocType ("node", PUBLIC_IDENTIFIER, SYSTEM_IDENTIFIER, null); writer.WriteComment (" " + GetProductDescription () + " "); //the root node element writer.WriteStartElement ("node"); } public void WriteNode (string name) { writer.WriteStartElement ("node"); writer.WriteAttributeString ("name", name); writer.WriteEndElement (); } public void WriteEnd () { /* WriteEnum (typeof (org.freedesktop.DBus.NameFlag)); WriteEnum (typeof (org.freedesktop.DBus.NameReply)); WriteEnum (typeof (org.freedesktop.DBus.ReleaseNameReply)); WriteEnum (typeof (org.freedesktop.DBus.StartReply)); WriteInterface (typeof (org.freedesktop.DBus.IBus)); */ writer.WriteEndElement (); writer.Flush (); xml = sb.ToString (); } //public void WriteNode () public void WriteType (Type target_type) { //writer.WriteStartElement ("node"); //TODO: non-well-known introspection has paths as well, which we don't do yet. read the spec again //hackishly just remove the root '/' to make the path relative for now //writer.WriteAttributeString ("name", target_path.Value.Substring (1)); //writer.WriteAttributeString ("name", "test"); //reflect our own interface manually WriteInterface (typeof (org.freedesktop.DBus.Introspectable)); //reflect the target interface if (target_type != null) { WriteInterface (target_type); foreach (Type ifType in target_type.GetInterfaces ()) WriteInterface (ifType); } //TODO: review recursion of interfaces and inheritance hierarchy //writer.WriteEndElement (); } public void WriteArg (ParameterInfo pi) { WriteArg (pi.ParameterType, Mapper.GetArgumentName (pi), pi.IsOut, false); } public void WriteArgReverse (ParameterInfo pi) { WriteArg (pi.ParameterType, Mapper.GetArgumentName (pi), pi.IsOut, true); } //TODO: clean up and get rid of reverse (or argIsOut) parm public void WriteArg (Type argType, string argName, bool argIsOut, bool reverse) { argType = argIsOut ? argType.GetElementType () : argType; if (argType == typeof (void)) return; writer.WriteStartElement ("arg"); if (!String.IsNullOrEmpty (argName)) writer.WriteAttributeString ("name", argName); //we can't rely on the default direction (qt-dbus requires a direction at time of writing), so we use a boolean to reverse the parameter direction and make it explicit if (argIsOut) writer.WriteAttributeString ("direction", !reverse ? "out" : "in"); else writer.WriteAttributeString ("direction", !reverse ? "in" : "out"); Signature sig = Signature.GetSig (argType); //TODO: avoid writing null (DType.Invalid) to the XML stream writer.WriteAttributeString ("type", sig.Value); //annotations aren't valid in an arg element, so this is disabled //if (argType.IsEnum) // WriteAnnotation ("org.ndesk.DBus.Enum", Mapper.GetInterfaceName (argType)); writer.WriteEndElement (); } public void WriteMethod (MethodInfo mi) { writer.WriteStartElement ("method"); writer.WriteAttributeString ("name", mi.Name); foreach (ParameterInfo pi in mi.GetParameters ()) WriteArg (pi); //Mono <= 1.1.13 doesn't support MethodInfo.ReturnParameter, so avoid it //WriteArgReverse (mi.ReturnParameter); WriteArg (mi.ReturnType, Mapper.GetArgumentName (mi.ReturnTypeCustomAttributes, "ret"), false, true); WriteAnnotations (mi); writer.WriteEndElement (); } public void WriteProperty (PropertyInfo pri) { //expose properties as dbus properties writer.WriteStartElement ("property"); writer.WriteAttributeString ("name", pri.Name); writer.WriteAttributeString ("type", Signature.GetSig (pri.PropertyType).Value); string access = (pri.CanRead ? "read" : String.Empty) + (pri.CanWrite ? "write" : String.Empty); writer.WriteAttributeString ("access", access); WriteAnnotations (pri); writer.WriteEndElement (); //expose properties as methods also //it may not be worth doing this in the long run /* if (pri.CanRead) { writer.WriteStartElement ("method"); writer.WriteAttributeString ("name", "Get" + pri.Name); WriteArgReverse (pri.GetGetMethod ().ReturnParameter); writer.WriteEndElement (); } if (pri.CanWrite) { writer.WriteStartElement ("method"); writer.WriteAttributeString ("name", "Set" + pri.Name); foreach (ParameterInfo pi in pri.GetSetMethod ().GetParameters ()) WriteArg (pi); writer.WriteEndElement (); } */ } public void WriteSignal (EventInfo ei) { writer.WriteStartElement ("signal"); writer.WriteAttributeString ("name", ei.Name); foreach (ParameterInfo pi in ei.EventHandlerType.GetMethod ("Invoke").GetParameters ()) WriteArgReverse (pi); if (ExtendedAnnotations) { string handlerName = Mapper.GetInterfaceName (ei.EventHandlerType); WriteAnnotation ("org.ndesk.DBus.SignalHandler", handlerName); } WriteAnnotations (ei); //no need to consider the delegate return value as dbus doesn't support it writer.WriteEndElement (); } const BindingFlags relevantBindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly; public void WriteInterface (Type type) { if (type == null) return; //TODO: this is unreliable, fix it if (!Mapper.IsPublic (type)) return; writer.WriteStartElement ("interface"); writer.WriteAttributeString ("name", Mapper.GetInterfaceName (type)); /* foreach (MemberInfo mbi in type.GetMembers (relevantBindingFlags)) { switch (mbi.MemberType) { case MemberTypes.Method: if (!((MethodInfo)mbi).IsSpecialName) WriteMethod ((MethodInfo)mbi); break; case MemberTypes.Event: WriteSignal ((EventInfo)mbi); break; case MemberTypes.Property: WriteProperty ((PropertyInfo)mbi); break; default: Console.Error.WriteLine ("Warning: Unhandled MemberType '{0}' encountered while introspecting {1}", mbi.MemberType, type.FullName); break; } } */ foreach (MethodInfo mi in type.GetMethods (relevantBindingFlags)) if (!mi.IsSpecialName) WriteMethod (mi); foreach (EventInfo ei in type.GetEvents (relevantBindingFlags)) WriteSignal (ei); foreach (PropertyInfo pri in type.GetProperties (relevantBindingFlags)) WriteProperty (pri); //TODO: indexers //TODO: attributes as annotations? writer.WriteEndElement (); //this recursion seems somewhat inelegant WriteInterface (type.BaseType); } public void WriteAnnotations (ICustomAttributeProvider attrProvider) { if (Mapper.IsDeprecated (attrProvider)) WriteAnnotation ("org.freedesktop.DBus.Deprecated", "true"); } public void WriteAnnotation (string name, string value) { writer.WriteStartElement ("annotation"); writer.WriteAttributeString ("name", name); writer.WriteAttributeString ("value", value); writer.WriteEndElement (); } //this is not in the spec, and is not finalized public void WriteEnum (Type type) { writer.WriteStartElement ("enum"); writer.WriteAttributeString ("name", Mapper.GetInterfaceName (type)); writer.WriteAttributeString ("type", Signature.GetSig (type.GetElementType ()).Value); writer.WriteAttributeString ("flags", (type.IsDefined (typeof (FlagsAttribute), false)) ? "true" : "false"); string[] names = Enum.GetNames (type); int i = 0; foreach (Enum val in Enum.GetValues (type)) { writer.WriteStartElement ("element"); writer.WriteAttributeString ("name", names[i++]); writer.WriteAttributeString ("value", val.ToString ("d")); writer.WriteEndElement (); } writer.WriteEndElement (); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Statistics.Algo File: IStatisticParameter.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Statistics { using System; using Ecng.ComponentModel; using Ecng.Serialization; using Ecng.Common; /// <summary> /// The interface, describing statistic parameter. /// </summary> public interface IStatisticParameter : IPersistable { /// <summary> /// Parameter name. /// </summary> string Name { get; set; } /// <summary> /// The current value of the parameter. /// </summary> object Value { get; } /// <summary> /// The displayed parameter name. /// </summary> string DisplayName { get; } /// <summary> /// The parameter description. /// </summary> string Description { get; } /// <summary> /// Category. /// </summary> string Category { get; } /// <summary> /// <see cref="IStatisticParameter.Value"/> change event. /// </summary> event Action ValueChanged; /// <summary> /// To reset the parameter value. /// </summary> void Reset(); } /// <summary> /// The interface, describing statistic parameter. /// </summary> /// <typeparam name="TValue">The type of the parameter value.</typeparam> public interface IStatisticParameter<TValue> : IStatisticParameter { /// <summary> /// The current value of the parameter. /// </summary> new TValue Value { get; } } /// <summary> /// The base statistics parameter. /// </summary> /// <typeparam name="TValue">The type of the parameter value.</typeparam> public abstract class BaseStatisticParameter<TValue> : NotifiableObject, IStatisticParameter<TValue> where TValue : IComparable<TValue> { /// <summary> /// Initialize <see cref="BaseStatisticParameter{T}"/>. /// </summary> protected BaseStatisticParameter() { var type = GetType(); _name = type.Name.Remove("Parameter"); DisplayName = type.GetDisplayName(GetReadableName(_name)); Description = type.GetDescription(DisplayName); Category = type.GetCategory(); } private string _name; /// <summary> /// Parameter name. /// </summary> public string Name { get { return _name; } set { if (_name == value) return; _name = value; this.Notify(nameof(Name)); } } /// <summary> /// The displayed parameter name. /// </summary> public string DisplayName { get; } /// <summary> /// The parameter description. /// </summary> public string Description { get; } /// <summary> /// Category. /// </summary> public string Category { get; } private TValue _value; /// <summary> /// The current value of the parameter. /// </summary> public virtual TValue Value { get { return _value; } protected set { if (_value.CompareTo(value) == 0) return; _value = value; RaiseValueChanged(); } } private static string GetReadableName(string name) { var index = 1; while (index < (name.Length - 1)) { if (char.IsUpper(name[index])) { name = name.Insert(index, " "); index += 2; } else index++; } return name; } /// <summary> /// The current value of the parameter. /// </summary> object IStatisticParameter.Value => Value; /// <summary> /// <see cref="Value"/> change event. /// </summary> public virtual event Action ValueChanged; /// <summary> /// To reset the parameter value. /// </summary> public virtual void Reset() { Value = default(TValue); } /// <summary> /// To call the event <see cref="ValueChanged"/>. /// </summary> private void RaiseValueChanged() { ValueChanged?.Invoke(); this.Notify(nameof(Value)); } /// <summary> /// To load the state of statistic parameter. /// </summary> /// <param name="storage">Storage.</param> public virtual void Load(SettingsStorage storage) { Value = storage.GetValue(nameof(Value), default(TValue)); } /// <summary> /// To save the state of statistic parameter. /// </summary> /// <param name="storage">Storage.</param> public virtual void Save(SettingsStorage storage) { storage.SetValue(nameof(Value), 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; using System.Collections; /// <summary> /// System.Math.Floor(System.Double) /// </summary> public class MathFloor { public static int Main(string[] args) { MathFloor floor = new MathFloor(); TestLibrary.TestFramework.BeginTestCase("Testing System.Math.Floor(System.Double)..."); if (floor.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify floor number should be equal to intefer part subtract one of negative number..."); try { double number = TestLibrary.Generator.GetDouble(-55); while (number >= 0) { number = (-TestLibrary.Generator.GetDouble(-55)) * 100; } double floorNumber = Math.Floor(number); if (floorNumber < number - 1 || floorNumber > number) { TestLibrary.TestFramework.LogError("001", "The Ceiling number should be equal to the integer part of negative number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Verify floor number should be equal to itself when number is negative integer..."); try { double number = TestLibrary.Generator.GetDouble(-55); while (number >= 0) { number = (-TestLibrary.Generator.GetDouble(-55)) * 100; } double floorNumber = Math.Floor(number); if (floorNumber != Math.Floor(floorNumber)) { TestLibrary.TestFramework.LogError("003", "The floor number should be equal to itself when number is negative integer..."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Verify floor number should be equal to the integer part of positive number..."); try { double number = TestLibrary.Generator.GetDouble(-55); while (number <= 0) { number = (TestLibrary.Generator.GetDouble(-55)) * 100; } double floorNumber = Math.Floor(number); if (floorNumber < number - 1 || floorNumber > number) { TestLibrary.TestFramework.LogError("005", "The floor number should be equal to the integer part plus one of positive number!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: Verify floor number should be equal to itself when number is positive integer..."); try { double number = TestLibrary.Generator.GetDouble(-55); while (number <= 0) { number = (TestLibrary.Generator.GetDouble(-55)) * 100; } double floorNumber = Math.Floor(number); if (floorNumber != Math.Floor(floorNumber)) { TestLibrary.TestFramework.LogError("007", "The floor number should be equal to itself when number is positive integer..."); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: Verify floor number should be equal to itself when number is maxvalue..."); try { double floorMax = Math.Floor(double.MaxValue); if (floorMax != double.MaxValue) { TestLibrary.TestFramework.LogError("009", "The floor number should be equal to itself when number is maxvalue!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: Verify floor number should be equal to itself when number is minvalue..."); try { double floorMin = Math.Floor(double.MinValue); if (floorMin != double.MinValue) { TestLibrary.TestFramework.LogError("011", "The floor number should be equal to itself when number is minvalue!"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception occurs: " + e); retVal = false; } return retVal; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.Memory; using Orleans; using Orleans.CodeGeneration; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using Orleans.Utilities; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; using TestExtensions; using TestVersionGrainInterfaces; using TestVersionGrains; using Xunit; namespace Tester.HeterogeneousSilosTests.UpgradeTests { public abstract class UpgradeTestsBase : IDisposable, IAsyncLifetime { private static readonly TimeSpan RefreshInterval = TimeSpan.FromMilliseconds(200); private TimeSpan waitDelay; protected IClusterClient Client => this.cluster.Client; protected IManagementGrain ManagementGrain => this.cluster.Client.GetGrain<IManagementGrain>(0); #if DEBUG private const string BuildConfiguration = "Debug"; #else private const string BuildConfiguration = "Release"; #endif private const string CommonParentDirectory = "test"; private const string BinDirectory = "bin"; private const string VersionsProjectDirectory = "Grains"; private const string GrainsV1ProjectName = "TestVersionGrains"; private const string GrainsV2ProjectName = "TestVersionGrains2"; private const string VersionTestBinaryName = "TestVersionGrains.dll"; private readonly DirectoryInfo assemblyGrainsV1Dir; private readonly DirectoryInfo assemblyGrainsV2Dir; private readonly List<SiloHandle> deployedSilos = new List<SiloHandle>(); private int siloIdx = 0; private TestClusterBuilder builder; private TestCluster cluster; protected abstract Type VersionSelectorStrategy { get; } protected abstract Type CompatibilityStrategy { get; } protected virtual short SiloCount => 2; protected UpgradeTestsBase() { var testDirectory = new DirectoryInfo(GetType().Assembly.Location); while (String.Compare(testDirectory.Name, CommonParentDirectory, StringComparison.OrdinalIgnoreCase) != 0 || testDirectory.Parent == null) { testDirectory = testDirectory.Parent; } if (testDirectory.Parent == null) { throw new InvalidOperationException($"Cannot locate 'test' directory starting from '{GetType().Assembly.Location}'"); } assemblyGrainsV1Dir = GetVersionTestDirectory(testDirectory, GrainsV1ProjectName); assemblyGrainsV2Dir = GetVersionTestDirectory(testDirectory, GrainsV2ProjectName); } private DirectoryInfo GetVersionTestDirectory(DirectoryInfo testDirectory, string directoryName) { var projectDirectory = Path.Combine(testDirectory.FullName, VersionsProjectDirectory, directoryName, BinDirectory); var directories = Directory.GetDirectories(projectDirectory, BuildConfiguration, SearchOption.AllDirectories); if (directories.Length != 1) { throw new InvalidOperationException($"Number of directories found for pattern: '{BuildConfiguration}' under {testDirectory.FullName}: {directories.Length}"); } var files = Directory.GetFiles(directories[0], VersionTestBinaryName, SearchOption.AllDirectories); if (files.Length != 1) { throw new InvalidOperationException($"Number of files found for pattern: '{VersionTestBinaryName}' under {testDirectory.FullName}: {files.Length}"); } return new DirectoryInfo(Path.GetDirectoryName(files[0])); } protected async Task Step1_StartV1Silo_Step2_StartV2Silo_Step3_StopV2Silo(int step2Version) { const int numberOfGrains = 100; await StartSiloV1(); // Only V1 exist for now for (var i = 0; i < numberOfGrains; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } // Start a new silo with V2 var siloV2 = await StartSiloV2(); for (var i = 0; i < numberOfGrains; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } for (var i = numberOfGrains; i < numberOfGrains * 2; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(step2Version, await grain.GetVersion()); } // Stop the V2 silo await StopSilo(siloV2); // Now all activation should be V1 for (var i = 0; i < numberOfGrains * 3; i++) { var grain = Client.GetGrain<IVersionUpgradeTestGrain>(i); Assert.Equal(1, await grain.GetVersion()); } } protected async Task ProxyCallNoPendingRequest(int expectedVersion) { await StartSiloV1(); // Only V1 exist for now var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0); Assert.Equal(1, await grain0.GetVersion()); await StartSiloV2(); // New activation should be V2 var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1); Assert.Equal(2, await grain1.GetVersion()); Assert.Equal(expectedVersion, await grain1.ProxyGetVersion(grain0)); Assert.Equal(expectedVersion, await grain0.GetVersion()); } protected async Task ProxyCallWithPendingRequest(int expectedVersion) { await StartSiloV1(); // Only V1 exist for now var grain0 = Client.GetGrain<IVersionUpgradeTestGrain>(0); Assert.Equal(1, await grain0.GetVersion()); // Start a new silo with V2 await StartSiloV2(); // New activation should be V2 var grain1 = Client.GetGrain<IVersionUpgradeTestGrain>(1); Assert.Equal(2, await grain1.GetVersion()); var waitingTask = grain0.LongRunningTask(TimeSpan.FromSeconds(5)); var callBeforeUpgrade = grain0.GetVersion(); await Task.Delay(100); // Make sure requests are not sent out of order var callProvokingUpgrade = grain1.ProxyGetVersion(grain0); await waitingTask; Assert.Equal(1, await callBeforeUpgrade); Assert.Equal(expectedVersion, await callProvokingUpgrade); } protected async Task<SiloHandle> StartSiloV1() { var handle = await StartSilo(assemblyGrainsV1Dir); await Task.Delay(waitDelay); return handle; } protected async Task<SiloHandle> StartSiloV2() { var handle = await StartSilo(assemblyGrainsV2Dir); await Task.Delay(waitDelay); return handle; } private async Task<SiloHandle> StartSilo(DirectoryInfo rootDir) { SiloHandle silo; if (this.siloIdx == 0) { // Setup configuration this.builder = new TestClusterBuilder(1) { CreateSiloAsync = AppDomainSiloHandle.Create }; TestDefaultConfiguration.ConfigureTestCluster(this.builder); builder.Options.ApplicationBaseDirectory = rootDir.FullName; builder.AddSiloBuilderConfigurator<VersionGrainsSiloBuilderConfigurator>(); builder.AddClientBuilderConfigurator<VersionGrainsClientConfigurator>(); builder.Properties[nameof(SiloCount)] = this.SiloCount.ToString(); builder.Properties[nameof(RefreshInterval)] = RefreshInterval.ToString(); builder.Properties[nameof(VersionSelectorStrategy)] = this.VersionSelectorStrategy.Name; builder.Properties[nameof(CompatibilityStrategy)] = this.CompatibilityStrategy.Name; waitDelay = TestCluster.GetLivenessStabilizationTime(new ClusterMembershipOptions(), didKill: false); this.cluster = builder.Build(); await this.cluster.DeployAsync(); silo = this.cluster.Primary; } else { var configBuilder = new ConfigurationBuilder(); foreach (var source in cluster.ConfigurationSources) configBuilder.Add(source); var testClusterOptions = new TestClusterOptions(); configBuilder.Build().Bind(testClusterOptions); // Override the root directory. var sources = new IConfigurationSource[] { new MemoryConfigurationSource {InitialData = new Dictionary<string, string>{ [nameof(TestClusterOptions.ApplicationBaseDirectory)] = rootDir.FullName } } }; silo = await TestCluster.StartSiloAsync(cluster, siloIdx, testClusterOptions, sources); } this.deployedSilos.Add(silo); this.siloIdx++; return silo; } protected async Task StopSilo(SiloHandle handle) { await handle?.StopSiloAsync(true); this.deployedSilos.Remove(handle); await Task.Delay(waitDelay); } public void Dispose() { if (!deployedSilos.Any()) return; var primarySilo = this.deployedSilos[0]; foreach (var silo in this.deployedSilos.Skip(1)) { silo.Dispose(); } primarySilo.Dispose(); this.Client?.Dispose(); } public Task InitializeAsync() { return Task.CompletedTask; } public async Task DisposeAsync() { var primarySilo = this.deployedSilos[0]; foreach (var silo in this.deployedSilos.Skip(1)) { await silo.StopSiloAsync(true); silo.Dispose(); } await primarySilo.StopSiloAsync(true); primarySilo.Dispose(); if (this.Client != null) await this.Client.Close(); this.Client?.Dispose(); } } }
// created on 29/11/2007 // Npgsql.NpgsqlConnectionStringBuilder.cs // // Author: // Glen Parker (glenebob@nwlink.com) // Ben Sagal (bensagal@gmail.com) // Tao Wang (dancefire@gmail.com) // // Copyright (C) 2007 The Npgsql Development Team // npgsql-general@gborg.postgresql.org // http://gborg.postgresql.org/project/npgsql/projdisplay.php // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph and the following two paragraphs appear in all copies. // // IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS // DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS // ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. using System; using System.Collections.Generic; using System.Data.Common; using System.Reflection; using System.Resources; namespace Revenj.DatabasePersistence.Postgres.Npgsql { public sealed class NpgsqlConnectionStringBuilder : DbConnectionStringBuilder { private static readonly ResourceManager resman = new ResourceManager(MethodBase.GetCurrentMethod().DeclaringType); private static readonly Dictionary<Keywords, object> defaults = new Dictionary<Keywords, object>(); private string originalConnectionString; private const int POOL_SIZE_LIMIT = 1024; private const int TIMEOUT_LIMIT = 1024; internal const int DefaultCommandTimeout = 20; static NpgsqlConnectionStringBuilder() { defaults.Add(Keywords.Host, string.Empty); defaults.Add(Keywords.Port, 5432); defaults.Add(Keywords.Database, string.Empty); defaults.Add(Keywords.UserName, string.Empty); defaults.Add(Keywords.Password, string.Empty); defaults.Add(Keywords.SSL, false); defaults.Add(Keywords.SslMode, SslMode.Disable); defaults.Add(Keywords.Timeout, 15); defaults.Add(Keywords.SearchPath, string.Empty); defaults.Add(Keywords.Pooling, true); defaults.Add(Keywords.ConnectionLifeTime, 15); defaults.Add(Keywords.MinPoolSize, 1); defaults.Add(Keywords.MaxPoolSize, 20); defaults.Add(Keywords.SyncNotification, false); defaults.Add(Keywords.CommandTimeout, DefaultCommandTimeout); defaults.Add(Keywords.Enlist, false); defaults.Add(Keywords.PreloadReader, false); defaults.Add(Keywords.UseExtendedTypes, false); defaults.Add(Keywords.IntegratedSecurity, false); defaults.Add(Keywords.Compatible, THIS_VERSION); defaults.Add(Keywords.ApplicationName, string.Empty); } public NpgsqlConnectionStringBuilder() { this.Clear(); } public NpgsqlConnectionStringBuilder(string connectionString) { this.Clear(); this.originalConnectionString = connectionString; base.ConnectionString = connectionString; } /// <summary> /// Return an exact copy of this NpgsqlConnectionString. /// </summary> public NpgsqlConnectionStringBuilder Clone() { NpgsqlConnectionStringBuilder builder = new NpgsqlConnectionStringBuilder(); foreach (string key in this.Keys) { builder[key] = this[key]; } return builder; } #region Parsing Functions private static SslMode ToSslMode(object value) { if (value is SslMode) { return (SslMode)value; } else { return (SslMode)Enum.Parse(typeof(SslMode), value.ToString(), true); } } private static int ToInt32(object value, int min, int max, string key) { int v = Convert.ToInt32(value); if (v < min) { throw new ArgumentOutOfRangeException(String.Format(resman.GetString("Exception_IntegerKeyValMin"), key, min), key); } else if (v > max) { throw new ArgumentOutOfRangeException(String.Format(resman.GetString("Exception_IntegerKeyValMax"), key, max), key); } return v; } private static Boolean ToBoolean(object value) { string text = value as string; if (text != null) { switch (text.ToLowerInvariant()) { case "t": case "true": case "y": case "yes": return true; case "f": case "false": case "n": case "no": return false; default: throw new InvalidCastException(value.ToString()); } } else { return Convert.ToBoolean(value); } } private Boolean ToIntegratedSecurity(object value) { string text = value as string; if (text != null) { switch (text.ToLowerInvariant()) { case "t": case "true": case "y": case "yes": case "sspi": return true; case "f": case "false": case "n": case "no": return false; default: throw new InvalidCastException(value.ToString()); } } else { return Convert.ToBoolean(value); } } #endregion #region Properties private string _host; public string Host { get { return _host; } set { SetValue(GetKeyName(Keywords.Host), value); } } private int _port; public int Port { get { return _port; } set { SetValue(GetKeyName(Keywords.Port), value); } } private string _database; public string Database { get { return _database; } set { SetValue(GetKeyName(Keywords.Database), value); } } private string _username; public string UserName { get { if ((_integrated_security) && (String.IsNullOrEmpty(_username))) { System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent(); _username = identity.Name.Split('\\')[1]; } return _username; } set { SetValue(GetKeyName(Keywords.UserName), value); } } private byte[] _password; public byte[] PasswordAsByteArray { get { return _password; } set { _password = value; } } public string Password { set { SetValue(GetKeyName(Keywords.Password), value); } } private bool _ssl; public bool SSL { get { return _ssl; } set { SetValue(GetKeyName(Keywords.SSL), value); } } private SslMode _sslmode; public SslMode SslMode { get { return _sslmode; } set { SetValue(GetKeyName(Keywords.SslMode), value); } } [Obsolete("UTF-8 is always used regardless of this setting.")] public string Encoding { get { return "UNICODE"; } //set { } } private int _timeout; public int Timeout { get { return _timeout; } set { SetValue(GetKeyName(Keywords.Timeout), value); } } private string _searchpath; public string SearchPath { get { return _searchpath; } set { SetValue(GetKeyName(Keywords.SearchPath), value); } } private bool _pooling; public bool Pooling { get { return _pooling; } set { SetValue(GetKeyName(Keywords.Pooling), value); } } private int _connection_life_time; public int ConnectionLifeTime { get { return _connection_life_time; } set { SetValue(GetKeyName(Keywords.ConnectionLifeTime), value); } } private int _min_pool_size; public int MinPoolSize { get { return _min_pool_size; } set { SetValue(GetKeyName(Keywords.MinPoolSize), value); } } private int _max_pool_size; public int MaxPoolSize { get { return _max_pool_size; } set { SetValue(GetKeyName(Keywords.MaxPoolSize), value); } } private bool _sync_notification; public bool SyncNotification { get { return _sync_notification; } set { SetValue(GetKeyName(Keywords.SyncNotification), value); } } private int _command_timeout; public int CommandTimeout { get { return _command_timeout; } set { SetValue(GetKeyName(Keywords.CommandTimeout), value); } } private bool _enlist; public bool Enlist { get { return _enlist; } set { SetValue(GetKeyName(Keywords.Enlist), value); } } private bool _preloadReader; public bool PreloadReader { get { return _preloadReader; } set { SetValue(GetKeyName(Keywords.PreloadReader), value); } } private bool _useExtendedTypes; public bool UseExtendedTypes { get { return _useExtendedTypes; } set { SetValue(GetKeyName(Keywords.UseExtendedTypes), value); } } private bool _integrated_security; public bool IntegratedSecurity { get { return _integrated_security; } set { SetValue(GetKeyName(Keywords.IntegratedSecurity), value); } } private Version _compatible; private static readonly Version THIS_VERSION = MethodBase.GetCurrentMethod().DeclaringType.Assembly.GetName().Version; /// <summary> /// Compatibilty version. When possible, behaviour caused by breaking changes will be preserved /// if this version is less than that where the breaking change was introduced. /// </summary> public Version Compatible { get { return _compatible; } set { SetValue(GetKeyName(Keywords.Compatible), value); } } private string _application_name; public string ApplicationName { get { return _application_name; } set { SetValue(GetKeyName(Keywords.ApplicationName), value); } } #endregion private static Keywords GetKey(string key) { switch (key.ToUpperInvariant()) { case "HOST": case "SERVER": return Keywords.Host; case "PORT": return Keywords.Port; case "DATABASE": case "DB": return Keywords.Database; case "USERNAME": case "USER NAME": case "USER": case "USERID": case "USER ID": case "UID": return Keywords.UserName; case "PASSWORD": case "PSW": case "PWD": return Keywords.Password; case "SSL": return Keywords.SSL; case "SSLMODE": return Keywords.SslMode; case "ENCODING": #pragma warning disable 618 return Keywords.Encoding; #pragma warning restore 618 case "TIMEOUT": return Keywords.Timeout; case "SEARCHPATH": return Keywords.SearchPath; case "POOLING": return Keywords.Pooling; case "CONNECTIONLIFETIME": return Keywords.ConnectionLifeTime; case "MINPOOLSIZE": return Keywords.MinPoolSize; case "MAXPOOLSIZE": return Keywords.MaxPoolSize; case "SYNCNOTIFICATION": return Keywords.SyncNotification; case "COMMANDTIMEOUT": return Keywords.CommandTimeout; case "ENLIST": return Keywords.Enlist; case "PRELOADREADER": case "PRELOAD READER": return Keywords.PreloadReader; case "USEEXTENDEDTYPES": case "USE EXTENDED TYPES": return Keywords.UseExtendedTypes; case "INTEGRATED SECURITY": return Keywords.IntegratedSecurity; case "COMPATIBLE": return Keywords.Compatible; case "APPLICATIONNAME": return Keywords.ApplicationName; default: throw new ArgumentException(resman.GetString("Exception_WrongKeyVal"), key); } } internal static string GetKeyName(Keywords keyword) { switch (keyword) { case Keywords.Host: return "HOST"; case Keywords.Port: return "PORT"; case Keywords.Database: return "DATABASE"; case Keywords.UserName: return "USER ID"; case Keywords.Password: return "PASSWORD"; case Keywords.SSL: return "SSL"; case Keywords.SslMode: return "SSLMODE"; case Keywords.Encoding: return "ENCODING"; case Keywords.Timeout: return "TIMEOUT"; case Keywords.SearchPath: return "SEARCHPATH"; case Keywords.Pooling: return "POOLING"; case Keywords.ConnectionLifeTime: return "CONNECTIONLIFETIME"; case Keywords.MinPoolSize: return "MINPOOLSIZE"; case Keywords.MaxPoolSize: return "MAXPOOLSIZE"; case Keywords.SyncNotification: return "SYNCNOTIFICATION"; case Keywords.CommandTimeout: return "COMMANDTIMEOUT"; case Keywords.Enlist: return "ENLIST"; case Keywords.PreloadReader: return "PRELOADREADER"; case Keywords.UseExtendedTypes: return "USEEXTENDEDTYPES"; case Keywords.IntegratedSecurity: return "INTEGRATED SECURITY"; case Keywords.Compatible: return "COMPATIBLE"; default: return keyword.ToString().ToUpperInvariant(); } } internal static object GetDefaultValue(Keywords keyword) { return defaults[keyword]; } /// <summary> /// Case insensative accessor for indivual connection string values. /// </summary> public override object this[string keyword] { get { return this[GetKey(keyword)]; } set { this[GetKey(keyword)] = value; } } public object this[Keywords keyword] { get { return base[GetKeyName(keyword)]; } set { SetValue(GetKeyName(keyword), value); } } public override bool Remove(string keyword) { Keywords key = GetKey(keyword); SetValue(key, defaults[key]); return base.Remove(keyword); } public bool ContainsKey(Keywords keyword) { return base.ContainsKey(GetKeyName(keyword)); } /// <summary> /// This function will set value for known key, both private member and base[key]. /// </summary> /// <param name="keyword"></param> /// <param name="value"></param> private void SetValue(string keyword, object value) { if (value == null) { Remove(keyword); } else { Keywords key = GetKey(keyword); SetValue(key, value); if (key == Keywords.Compatible) { base[GetKeyName(key)] = ((Version)this.Compatible).ToString(); } else { base[GetKeyName(key)] = value; } } } /// <summary> /// The function will modify private member only, not base[key]. /// </summary> /// <param name="keyword"></param> /// <param name="value"></param> private void SetValue(Keywords keyword, object value) { string key_name = GetKeyName(keyword); try { switch (keyword) { case Keywords.Host: this._host = Convert.ToString(value); break; case Keywords.Port: this._port = Convert.ToInt32(value); break; case Keywords.Database: this._database = Convert.ToString(value); break; case Keywords.UserName: this._username = Convert.ToString(value); break; case Keywords.Password: this._password = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(value)); break; case Keywords.SSL: this._ssl = ToBoolean(value); break; case Keywords.SslMode: this._sslmode = ToSslMode(value); break; #pragma warning disable 618 case Keywords.Encoding: break; #pragma warning restore 618 case Keywords.Timeout: this._timeout = ToInt32(value, 0, TIMEOUT_LIMIT, key_name); break; case Keywords.SearchPath: this._searchpath = Convert.ToString(value); break; case Keywords.Pooling: this._pooling = ToBoolean(value); break; case Keywords.ConnectionLifeTime: this._connection_life_time = Convert.ToInt32(value); break; case Keywords.MinPoolSize: this._min_pool_size = (MaxPoolSize > 0) ? ToInt32(value, 0, MaxPoolSize, key_name) : Convert.ToInt32(value); break; case Keywords.MaxPoolSize: this._max_pool_size = ToInt32(value, 0, POOL_SIZE_LIMIT, key_name); break; case Keywords.SyncNotification: this._sync_notification = ToBoolean(value); break; case Keywords.CommandTimeout: this._command_timeout = Convert.ToInt32(value); break; case Keywords.Enlist: this._enlist = ToBoolean(value); break; case Keywords.PreloadReader: this._preloadReader = ToBoolean(value); break; case Keywords.UseExtendedTypes: this._useExtendedTypes = ToBoolean(value); break; case Keywords.IntegratedSecurity: this._integrated_security = ToIntegratedSecurity(value); break; case Keywords.Compatible: Version ver = new Version(value.ToString()); if (ver > THIS_VERSION) throw new ArgumentException("Attempt to set compatibility with version " + value + " when using version " + THIS_VERSION); _compatible = ver; break; case Keywords.ApplicationName: this._application_name = Convert.ToString(value); break; } } catch (InvalidCastException exception) { string exception_template = string.Empty; switch (keyword) { case Keywords.Port: case Keywords.Timeout: case Keywords.ConnectionLifeTime: case Keywords.MinPoolSize: case Keywords.MaxPoolSize: case Keywords.CommandTimeout: exception_template = resman.GetString("Exception_InvalidIntegerKeyVal"); break; case Keywords.SSL: case Keywords.Pooling: case Keywords.SyncNotification: exception_template = resman.GetString("Exception_InvalidBooleanKeyVal"); break; } if (!string.IsNullOrEmpty(exception_template)) { throw new ArgumentException(string.Format(exception_template, key_name), key_name, exception); } throw; } } /// <summary> /// Clear the member and assign them to the default value. /// </summary> public override void Clear() { base.Clear(); foreach (Keywords keyword in defaults.Keys) { SetValue(GetKeyName(keyword), defaults[keyword]); } } } public enum Keywords { Host, Port, Database, UserName, Password, SSL, SslMode, [Obsolete("UTF-8 is always used regardless of this setting.")] Encoding, Timeout, SearchPath, // These are for the connection pool Pooling, ConnectionLifeTime, MinPoolSize, MaxPoolSize, SyncNotification, // These are for the command CommandTimeout, // These are for the resource manager Enlist, PreloadReader, UseExtendedTypes, IntegratedSecurity, Compatible, ApplicationName } public enum SslMode { Disable = 1 << 0, Allow = 1 << 1, Prefer = 1 << 2, Require = 1 << 3 } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using Microsoft.Rest.Azure; using Models; /// <summary> /// ResourcesOperations operations. /// </summary> public partial interface IResourcesOperations { /// <summary> /// Move resources from one resource group to another. The resources /// being moved should all be in the same resource group. /// </summary> /// <param name='sourceResourceGroupName'> /// Source resource group name. /// </param> /// <param name='parameters'> /// move resources' parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> MoveResourcesWithHttpMessagesAsync(string sourceResourceGroupName, ResourcesMoveInfo parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<GenericResource>>> ListWithHttpMessagesAsync(Microsoft.Rest.Azure.OData.ODataQuery<GenericResourceFilter> odataQuery = default(Microsoft.Rest.Azure.OData.ODataQuery<GenericResourceFilter>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Create a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='parameters'> /// Create or update resource parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<GenericResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, GenericResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns a resource belonging to a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<GenericResource>> GetWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<bool>> CheckExistenceByIdWithHttpMessagesAsync(string resourceId, string apiVersion, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a resource. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteByIdWithHttpMessagesAsync(string resourceId, string apiVersion, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Create a resource. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='parameters'> /// Create or update resource parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<GenericResource>> CreateOrUpdateByIdWithHttpMessagesAsync(string resourceId, string apiVersion, GenericResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Gets a resource. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<GenericResource>> GetByIdWithHttpMessagesAsync(string resourceId, string apiVersion, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Move resources from one resource group to another. The resources /// being moved should all be in the same resource group. /// </summary> /// <param name='sourceResourceGroupName'> /// Source resource group name. /// </param> /// <param name='parameters'> /// move resources' parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginMoveResourcesWithHttpMessagesAsync(string sourceResourceGroupName, ResourcesMoveInfo parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Create a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='parameters'> /// Create or update resource parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<GenericResource>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, GenericResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a resource. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteByIdWithHttpMessagesAsync(string resourceId, string apiVersion, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Create a resource. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='parameters'> /// Create or update resource parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<GenericResource>> BeginCreateOrUpdateByIdWithHttpMessagesAsync(string resourceId, string apiVersion, GenericResource parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<GenericResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
//----------------------------------------------------------------------- // <copyright file="TangoApplication.cs" company="Google"> // // Copyright 2015 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> //----------------------------------------------------------------------- using System; using System.Collections; using System.Runtime.InteropServices; using System.IO; using System.Linq; using UnityEngine; namespace Tango { /// <summary> /// Delegate for permission callbacks. /// </summary> /// <param name="permissionsGranted"><c>true</c> if permissions were granted, otherwise <c>false</c>.</param> public delegate void PermissionsEvent(bool permissionsGranted); /// <summary> /// Delegate for service connection. /// </summary> public delegate void OnTangoConnectEventHandler(); /// <summary> /// Delegate for service disconnection. /// </summary> public delegate void OnTangoDisconnectEventHandler(); /// <summary> /// Main entry point for the Tango Service. /// /// This component handles nearly all communication with the underlying TangoService. You must have one of these /// in your scene for Tango to work. Customization of the Tango connection can be done in the Unity editor or by /// programatically setting the member flags. /// /// This sends out events to Components that derive from the ITangoPose, ITangoDepth, etc. interfaces and /// register themselves via Register. This also sends out events to callbacks passed in through /// RegisterOnTangoConnect, RegisterOnTangoDisconnect, and RegisterPermissionsCallback. /// /// Note: To connect to the Tango Service, you should call InitApplication after properly registering everything. /// </summary> public class TangoApplication : MonoBehaviour { /// <summary> /// Permission types used by Tango applications. /// </summary> [Flags] private enum PermissionsTypes { // All entries must be a power of two for // use in a bit field as flags. NONE = 0, MOTION_TRACKING = 0x1, AREA_LEARNING = 0x2, } public bool m_enableMotionTracking = true; public bool m_enableDepth = true; public bool m_enableVideoOverlay = false; public bool m_motionTrackingAutoReset = true; public bool m_enableAreaLearning = false; public bool m_useExperimentalVideoOverlay = true; public bool m_useExperimentalADF = false; #if UNITY_EDITOR public static bool m_mouseEmulationViaPoseUpdates = false; #endif private const string CLASS_NAME = "TangoApplication"; private const string ANDROID_PRO_LABEL_TEXT = "<size=30>Tango plugin requires Unity Android Pro!</size>"; private const float ANDROID_PRO_LABEL_PERCENT_X = 0.5f; private const float ANDROID_PRO_LABEL_PERCENT_Y = 0.5f; private const float ANDROID_PRO_LABEL_WIDTH = 200.0f; private const float ANDROID_PRO_LABEL_HEIGHT = 200.0f; private const string DEFAULT_AREA_DESCRIPTION = "/sdcard/defaultArea"; private const string MOTION_TRACKING_LOG_PREFIX = "Motion tracking mode : "; private const int MINIMUM_API_VERSION = 1978; private static string m_tangoServiceVersion = string.Empty; /// <summary> /// Occurs when permission event. /// </summary> private event PermissionsEvent PermissionEvent; /// <summary> /// Occurs when on tango connect. /// </summary> private event OnTangoConnectEventHandler OnTangoConnect; /// <summary> /// Occurs when on tango disconnect. /// </summary> private event OnTangoDisconnectEventHandler OnTangoDisconnect; private PermissionsTypes m_requiredPermissions = 0; private static bool m_isValidTangoAPIVersion = false; private static bool m_hasVersionBeenChecked = false; private DepthProvider m_depthProvider; private IntPtr m_callbackContext = IntPtr.Zero; private bool m_isServiceConnected = false; private bool m_shouldReconnectService = false; private bool m_sendPermissions = false; private bool m_permissionsSuccessful = false; private PoseListener m_poseListener; private DepthListener m_depthListener; private VideoOverlayListener m_videoOverlayListener; private TangoEventListener m_tangoEventListener; private YUVTexture m_yuvTexture; /// <summary> /// Get the Tango service version name. /// </summary> /// <returns>String for the version name.</returns> public static string GetTangoServiceVersion() { if (m_tangoServiceVersion == string.Empty) { m_tangoServiceVersion = AndroidHelper.GetVersionName("com.projecttango.tango"); } return m_tangoServiceVersion; } /// <summary> /// Get the video overlay texture. /// </summary> /// <returns>The video overlay texture.</returns> public YUVTexture GetVideoOverlayTextureYUV() { return m_yuvTexture; } /// <summary> /// Register to get Tango callbacks. /// /// The object should derive from one of ITangoDepth, ITangoEvent, ITangoPos, ITangoVideoOverlay, or /// ITangoExperimentalTangoVideoOverlay. You will get callback during Update until you unregister. /// </summary> /// <param name="tangoObject">Object to get Tango callbacks from.</param> public void Register(System.Object tangoObject) { ITangoEvent tangoEvent = tangoObject as ITangoEvent; if (tangoEvent != null) { RegisterOnTangoEvent(tangoEvent.OnTangoEventAvailableEventHandler); } if (m_enableMotionTracking) { ITangoPose poseHandler = tangoObject as ITangoPose; if (poseHandler != null) { RegisterOnTangoPoseEvent(poseHandler.OnTangoPoseAvailable); } } if (m_enableDepth) { ITangoDepth depthHandler = tangoObject as ITangoDepth; if (depthHandler != null) { RegisterOnTangoDepthEvent(depthHandler.OnTangoDepthAvailable); } } if (m_enableVideoOverlay) { if (m_useExperimentalVideoOverlay) { IExperimentalTangoVideoOverlay videoOverlayHandler = tangoObject as IExperimentalTangoVideoOverlay; if (videoOverlayHandler != null) { RegisterOnExperimentalTangoVideoOverlay(videoOverlayHandler.OnExperimentalTangoImageAvailable); } } else { ITangoVideoOverlay videoOverlayHandler = tangoObject as ITangoVideoOverlay; if (videoOverlayHandler != null) { RegisterOnTangoVideoOverlay(videoOverlayHandler.OnTangoImageAvailableEventHandler); } } } } /// <summary> /// Unregister from Tango callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="tangoObject">Object to stop getting Tango callbacks from.</param> public void Unregister(System.Object tangoObject) { ITangoEvent tangoEvent = tangoObject as ITangoEvent; if (tangoEvent != null) { UnregisterOnTangoEvent(tangoEvent.OnTangoEventAvailableEventHandler); } if (m_enableMotionTracking) { ITangoPose poseHandler = tangoObject as ITangoPose; if (poseHandler != null) { UnregisterOnTangoPoseEvent(poseHandler.OnTangoPoseAvailable); } } if (m_enableDepth) { ITangoDepth depthHandler = tangoObject as ITangoDepth; if (depthHandler != null) { UnregisterOnTangoDepthEvent(depthHandler.OnTangoDepthAvailable); } } if (m_enableVideoOverlay) { if (m_useExperimentalVideoOverlay) { IExperimentalTangoVideoOverlay videoOverlayHandler = tangoObject as IExperimentalTangoVideoOverlay; if (videoOverlayHandler != null) { UnregisterOnExperimentalTangoVideoOverlay(videoOverlayHandler.OnExperimentalTangoImageAvailable); } } else { ITangoVideoOverlay videoOverlayHandler = tangoObject as ITangoVideoOverlay; if (videoOverlayHandler != null) { UnregisterOnTangoVideoOverlay(videoOverlayHandler.OnTangoImageAvailableEventHandler); } } } } /// <summary> /// Check if all requested permissions have been granted. /// </summary> /// <returns><c>true</c> if all requested permissions were granted; otherwise, <c>false</c>.</returns> public bool HasRequestedPermissions() { return m_requiredPermissions == PermissionsTypes.NONE; } /// <summary> /// Register to get an event callback when all permissions are granted. /// /// The passed event will get called once all Tango permissions have been granted. Registering /// after all permissions have already been granted will cause the event to never fire. /// </summary> /// <param name="permissionsEventHandler">Event to call.</param> public void RegisterPermissionsCallback(PermissionsEvent permissionsEventHandler) { if (permissionsEventHandler != null) { PermissionEvent += permissionsEventHandler; } } /// <summary> /// Unregister from the permission callbacks. /// /// See TangoApplication.RegisterPermissionsCallback for more details. /// </summary> /// <param name="permissionsEventHandler">Event to remove.</param> public void UnregisterPermissionsCallback(PermissionsEvent permissionsEventHandler) { if (permissionsEventHandler != null) { PermissionEvent -= permissionsEventHandler; } } /// <summary> /// DEPRECATED: Unregister from the permission callbacks. /// /// See TangoApplication.RegisterPermissionsCallback for more details. /// </summary> /// <param name="permissionsEventHandler">Event to remove.</param> public void RemovePermissionsCallback(PermissionsEvent permissionsEventHandler) { if (permissionsEventHandler != null) { PermissionEvent -= permissionsEventHandler; } } /// <summary> /// Register to get an event callback when connected to the Tango service. /// /// The passed event will get called once connected to the Tango service. Registering /// after already connected will cause the event to not fire until disconnected and then /// connecting again. /// </summary> /// <param name="handler">Event to call.</param> public void RegisterOnTangoConnect(OnTangoConnectEventHandler handler) { if (handler != null) { OnTangoConnect += handler; } } /// <summary> /// Unregister from the callback when connected to the Tango service. /// /// See TangoApplication.RegisterOnTangoConnect for more details. /// </summary> /// <param name="handler">Event to remove.</param> public void UnregisterOnTangoConnect(OnTangoConnectEventHandler handler) { if (handler != null) { OnTangoConnect -= handler; } } /// <summary> /// Register to get an event callback when disconnected from the Tango service. /// /// The passed event will get called when disconnected from the Tango service. /// </summary> /// <param name="handler">Event to remove.</param> public void RegisterOnTangoDisconnect(OnTangoDisconnectEventHandler handler) { if (handler != null) { OnTangoDisconnect += handler; } } /// <summary> /// Unregister from the callback when disconnected from the Tango service. /// /// See TangoApplication.RegisterOnTangoDisconnect for more details. /// </summary> /// <param name="handler">Event to remove.</param> public void UnregisterOnTangoDisconnect(OnTangoDisconnectEventHandler handler) { if (handler != null) { OnTangoDisconnect -= handler; } } /// <summary> /// Init step 1. Call this to request Tango permissions. /// /// After setting up the necessary permissions and callbacks, call this to request each of /// the permissions in order. Once all the permissions are granted, the permission callback /// will get called to do the next step. /// /// Also see TangoApplication.InitApplication, TangoApplication.InitProviders, and /// TangoApplication.ConnectToService. /// </summary> public void RequestNecessaryPermissionsAndConnect() { _ResetPermissionsFlags(); _RequestNextPermission(); } /// <summary> /// Init step 2. Call this to initialize interal state on TangoApplication. /// /// Call this in the permissions callback if all permissions have been granted. /// /// Also see TangoApplication.RequestNecessaryPermissionsandConnect, TangoApplication.InitProviders, and /// TangoApplication.ConnectToService. /// </summary> public void InitApplication() { Debug.Log("-----------------------------------Initializing Tango"); _TangoInitialize(); TangoConfig.InitConfig(TangoEnums.TangoConfigType.TANGO_CONFIG_DEFAULT); if (m_enableVideoOverlay && m_useExperimentalVideoOverlay) { int yTextureWidth = 0; int yTextureHeight = 0; int uvTextureWidth = 0; int uvTextureHeight = 0; TangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_Y_TEXTURE_WIDTH, ref yTextureWidth); TangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_Y_TEXTURE_HEIGHT, ref yTextureHeight); TangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_UV_TEXTURE_WIDTH, ref uvTextureWidth); TangoConfig.GetInt32(TangoConfig.Keys.EXPERIMENTAL_UV_TEXTURE_HEIGHT, ref uvTextureHeight); if (yTextureWidth == 0 || yTextureHeight == 0 || uvTextureWidth == 0 || uvTextureHeight == 0) { Debug.Log("Video overlay texture sizes were not set properly"); } m_yuvTexture.ResizeAll(yTextureWidth, yTextureHeight, uvTextureWidth, uvTextureHeight); } } /// <summary> /// Init step 3. Call this to choose what area description ID to use, if any. /// /// Call this in the permissions callback after calling TangoApplication.InitApplication. /// /// Also see TangoApplication.RequestNecessaryPermissionsAndConnect, TangoApplication.InitApplication, and /// TangoApplication.ConnectToService. /// </summary> /// <param name="uuid">Area description ID to load, or <c>string.Empty</c> to not use any.</param> public void InitProviders(string uuid) { _InitializeMotionTracking(uuid); _InitializeDepth(); _InitializeOverlay(); _SetEventCallbacks(); } /// <summary> /// Init step 4. Call this to connect to the Tango service. /// /// Also see TangoApplication.RequestNecessaryPermissionsAndConnect, TangoApplication.InitApplication, /// and TangoApplication.InitProviders. /// </summary> public void ConnectToService() { Debug.Log("TangoApplication.ConnectToService()"); _TangoConnect(); } /// <summary> /// Disconnect from the Tango service. /// /// This is called automatically when the TangoApplication goes away. You only need /// to call this to disconnect from the Tango service before the TangoApplication goes /// away. /// </summary> public void Shutdown() { Debug.Log("Tango Shutdown"); TangoConfig.Free(); _TangoDisconnect(); } /// <summary> /// Register to get Tango pose callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Handler.</param> internal void RegisterOnTangoPoseEvent(OnTangoPoseAvailableEventHandler handler) { if (m_poseListener != null) { m_poseListener.RegisterTangoPoseAvailable(handler); } } /// <summary> /// Unregister from the Tango pose callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event to remove.</param> internal void UnregisterOnTangoPoseEvent(OnTangoPoseAvailableEventHandler handler) { if (m_poseListener != null) { m_poseListener.UnregisterTangoPoseAvailable(handler); } } /// <summary> /// Register to get Tango depth callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Object to stop getting Tango callbacks from.</param> internal void RegisterOnTangoDepthEvent(OnTangoDepthAvailableEventHandler handler) { if (m_depthListener != null) { m_depthListener.RegisterOnTangoDepthAvailable(handler); } } /// <summary> /// Unregister from the Tango depth callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event to remove.</param> internal void UnregisterOnTangoDepthEvent(OnTangoDepthAvailableEventHandler handler) { if (m_depthListener != null) { m_depthListener.UnregisterOnTangoDepthAvailable(handler); } } /// <summary> /// Register to get Tango event callbacks. /// /// See TangoApplication.Register for details. /// </summary> /// <param name="handler">Object to stop getting Tango callbacks from.</param> internal void RegisterOnTangoEvent(OnTangoEventAvailableEventHandler handler) { if (m_tangoEventListener != null) { m_tangoEventListener.RegisterOnTangoEventAvailable(handler); } } /// <summary> /// Unregister from the Tango event callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event to remove.</param> internal void UnregisterOnTangoEvent(OnTangoEventAvailableEventHandler handler) { if (m_tangoEventListener != null) { m_tangoEventListener.UnregisterOnTangoEventAvailable(handler); } } /// <summary> /// Register to get Tango video overlay callbacks. /// /// See TangoApplication.Register for details. /// </summary> /// <param name="handler">Object to stop getting Tango callbacks from.</param> internal void RegisterOnTangoVideoOverlay(OnTangoImageAvailableEventHandler handler) { if (m_videoOverlayListener != null) { m_videoOverlayListener.RegisterOnTangoImageAvailable(handler); } } /// <summary> /// Unregister from the Tango video overlay callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event to remove.</param> internal void UnregisterOnTangoVideoOverlay(OnTangoImageAvailableEventHandler handler) { if (m_videoOverlayListener != null) { m_videoOverlayListener.UnregisterOnTangoImageAvailable(handler); } } /// <summary> /// Experimental API only, subject to change. Register to get Tango video overlay callbacks. /// </summary> /// <param name="handler">Object to stop getting Tango callbacks from.</param> internal void RegisterOnExperimentalTangoVideoOverlay(OnExperimentalTangoImageAvailableEventHandler handler) { if (m_videoOverlayListener != null) { m_videoOverlayListener.RegisterOnExperimentalTangoImageAvailable(handler); } } /// <summary> /// Experimental API only, subject to change. Unregister from the Tango video overlay callbacks. /// /// See TangoApplication.Register for more details. /// </summary> /// <param name="handler">Event to remove.</param> internal void UnregisterOnExperimentalTangoVideoOverlay(OnExperimentalTangoImageAvailableEventHandler handler) { if (m_videoOverlayListener != null) { m_videoOverlayListener.UnregisterOnExperimentalTangoImageAvailable(handler); } } /// <summary> /// Gets the get tango API version code. /// </summary> /// <returns>The get tango API version code.</returns> private static int _GetTangoAPIVersion() { return AndroidHelper.GetVersionCode("com.projecttango.tango"); } /// <summary> /// Helper method that will resume the tango services on App Resume. /// Locks the config again and connects the service. /// </summary> private void _ResumeTangoServices() { RequestNecessaryPermissionsAndConnect(); } /// <summary> /// Helper method that will suspend the tango services on App Suspend. /// Unlocks the tango config and disconnects the service. /// </summary> private void _SuspendTangoServices() { Debug.Log("Suspending Tango Service"); _TangoDisconnect(); } /// <summary> /// Set callbacks on all PoseListener objects. /// </summary> /// <param name="framePairs">Frame pairs.</param> private void _SetMotionTrackingCallbacks(TangoCoordinateFramePair[] framePairs) { if (m_poseListener != null) { m_poseListener.AutoReset = m_motionTrackingAutoReset; m_poseListener.SetCallback(framePairs); } } /// <summary> /// Set callbacks for all DepthListener objects. /// </summary> private void _SetDepthCallbacks() { if (m_depthListener != null) { m_depthListener.SetCallback(); } } /// <summary> /// Set callbacks for all TangoEventListener objects. /// </summary> private void _SetEventCallbacks() { if (m_tangoEventListener != null) { m_tangoEventListener.SetCallback(); } } /// <summary> /// Set callbacks for all VideoOverlayListener objects. /// </summary> private void _SetVideoOverlayCallbacks() { if (m_videoOverlayListener != null) { m_videoOverlayListener.SetCallback(TangoEnums.TangoCameraId.TANGO_CAMERA_COLOR, m_useExperimentalVideoOverlay, m_yuvTexture); } } /// <summary> /// Initialize motion tracking. /// </summary> /// <param name="uuid">ADF UUID to load.</param> private void _InitializeMotionTracking(string uuid) { System.Collections.Generic.List<TangoCoordinateFramePair> framePairs = new System.Collections.Generic.List<TangoCoordinateFramePair>(); if (TangoConfig.SetBool(TangoConfig.Keys.ENABLE_MOTION_TRACKING_BOOL, m_enableMotionTracking) && m_enableMotionTracking) { TangoCoordinateFramePair motionTracking; motionTracking.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE; motionTracking.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; framePairs.Add(motionTracking); if (TangoConfig.SetBool(TangoConfig.Keys.ENABLE_AREA_LEARNING_BOOL, m_enableAreaLearning) && m_enableAreaLearning) { Debug.Log("Area Learning is enabled."); if (!string.IsNullOrEmpty(uuid)) { TangoConfig.SetBool("config_experimental_high_accuracy_small_scale_adf", m_useExperimentalADF); TangoConfig.SetString(TangoConfig.Keys.LOAD_AREA_DESCRIPTION_UUID_STRING, uuid); } TangoCoordinateFramePair areaDescription; areaDescription.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION; areaDescription.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_DEVICE; TangoCoordinateFramePair startToADF; startToADF.baseFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_AREA_DESCRIPTION; startToADF.targetFrame = TangoEnums.TangoCoordinateFrameType.TANGO_COORDINATE_FRAME_START_OF_SERVICE; framePairs.Add(areaDescription); framePairs.Add(startToADF); } } if (framePairs.Count > 0) { _SetMotionTrackingCallbacks(framePairs.ToArray()); } // The C API does not default this to on, but it is locked down. TangoConfig.SetBool(TangoConfig.Keys.ENABLE_LOW_LATENCY_IMU_INTEGRATION, true); TangoConfig.SetBool(TangoConfig.Keys.ENABLE_MOTION_TRACKING_AUTO_RECOVERY_BOOL, m_motionTrackingAutoReset); } /// <summary> /// Initialize depth perception. /// </summary> private void _InitializeDepth() { if (TangoConfig.SetBool(TangoConfig.Keys.ENABLE_DEPTH_PERCEPTION_BOOL, m_enableDepth) && m_enableDepth) { _SetDepthCallbacks(); } } /// <summary> /// Initialize the RGB overlay. /// </summary> private void _InitializeOverlay() { _SetVideoOverlayCallbacks(); } /// <summary> /// Initialize the Tango Service. /// </summary> private void _TangoInitialize() { if (_IsValidTangoAPIVersion()) { int status = TangoServiceAPI.TangoService_initialize(IntPtr.Zero, IntPtr.Zero); if (status != Common.ErrorType.TANGO_SUCCESS) { Debug.Log("-------------------Tango initialize status : " + status); Debug.Log(CLASS_NAME + ".Initialize() The service has not been initialized!"); } else { Debug.Log(CLASS_NAME + ".Initialize() Tango was initialized!"); } } else { Debug.Log(CLASS_NAME + ".Initialize() Invalid API version. please update to minimul API version."); } } /// <summary> /// Connect to the Tango Service. /// </summary> private void _TangoConnect() { if (!m_isServiceConnected) { m_isServiceConnected = true; AndroidHelper.PerformanceLog("Unity _TangoConnect start"); if (TangoServiceAPI.TangoService_connect(m_callbackContext, TangoConfig.GetConfig()) != Common.ErrorType.TANGO_SUCCESS) { Debug.Log(CLASS_NAME + ".Connect() Could not connect to the Tango Service!"); } else { AndroidHelper.PerformanceLog("Unity _TangoConnect end"); Debug.Log(CLASS_NAME + ".Connect() Tango client connected to service!"); if (OnTangoConnect != null) { OnTangoConnect(); } } } } /// <summary> /// Disconnect from the Tango Service. /// </summary> private void _TangoDisconnect() { Debug.Log(CLASS_NAME + ".Disconnect() Disconnecting from the Tango Service"); m_isServiceConnected = false; if (TangoServiceAPI.TangoService_disconnect() != Common.ErrorType.TANGO_SUCCESS) { Debug.Log(CLASS_NAME + ".Disconnect() Could not disconnect from the Tango Service!"); } else { Debug.Log(CLASS_NAME + ".Disconnect() Tango client disconnected from service!"); if (OnTangoDisconnect != null) { OnTangoDisconnect(); } } } /// <summary> /// Checks to see if the current Tango Service is supported. /// </summary> /// <returns><c>true</c>, if is valid tango API version is greater /// than or equal to the minimum supported version, <c>false</c> otherwise.</returns> private bool _IsValidTangoAPIVersion() { if (!m_hasVersionBeenChecked) { int versionCode = _GetTangoAPIVersion(); if (versionCode < 0) { m_isValidTangoAPIVersion = false; } else { m_isValidTangoAPIVersion = versionCode >= MINIMUM_API_VERSION; } m_hasVersionBeenChecked = true; } return m_isValidTangoAPIVersion; } /// <summary> /// Android on pause. /// </summary> private void _androidOnPause() { if (m_isServiceConnected && m_requiredPermissions == PermissionsTypes.NONE) { Debug.Log("Pausing services"); m_shouldReconnectService = true; _SuspendTangoServices(); } Debug.Log("androidOnPause done"); } /// <summary> /// Android on resume. /// </summary> private void _androidOnResume() { if (m_shouldReconnectService) { Debug.Log("Resuming services"); m_shouldReconnectService = false; _ResumeTangoServices(); } Debug.Log("androidOnResume done"); } /// <summary> /// EventHandler for Android's on activity result. /// </summary> /// <param name="requestCode">Request code.</param> /// <param name="resultCode">Result code.</param> /// <param name="data">Data.</param> private void _androidOnActivityResult(int requestCode, int resultCode, AndroidJavaObject data) { Debug.Log("Activity returned result code : " + resultCode); switch (requestCode) { case Common.TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE: { if (resultCode == (int)Common.AndroidResult.SUCCESS) { _FlipBitAndCheckPermissions(PermissionsTypes.MOTION_TRACKING); } else { _PermissionWasDenied(); } break; } case Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE: { if (resultCode == (int)Common.AndroidResult.SUCCESS) { _FlipBitAndCheckPermissions(PermissionsTypes.AREA_LEARNING); } else { _PermissionWasDenied(); } break; } default: { break; } } Debug.Log("Activity returned result end"); } /// <summary> /// Awake this instance. /// </summary> private void Awake() { AndroidHelper.RegisterPauseEvent(_androidOnPause); AndroidHelper.RegisterResumeEvent(_androidOnResume); AndroidHelper.RegisterOnActivityResultEvent(_androidOnActivityResult); m_tangoEventListener = new TangoEventListener(); if (m_enableMotionTracking) { m_poseListener = new PoseListener(); } if (m_enableDepth) { m_depthListener = new DepthListener(); } if (m_enableVideoOverlay) { int yTextureWidth = 0; int yTextureHeight = 0; int uvTextureWidth = 0; int uvTextureHeight = 0; m_yuvTexture = new YUVTexture(yTextureWidth, yTextureHeight, uvTextureWidth, uvTextureHeight, TextureFormat.RGBA32, false); m_videoOverlayListener = new VideoOverlayListener(); } } /// <summary> /// Reset permissions flags. /// </summary> private void _ResetPermissionsFlags() { if (m_requiredPermissions == PermissionsTypes.NONE) { m_requiredPermissions |= m_enableMotionTracking ? PermissionsTypes.MOTION_TRACKING : PermissionsTypes.NONE; m_requiredPermissions |= m_enableAreaLearning ? PermissionsTypes.AREA_LEARNING : PermissionsTypes.NONE; } } /// <summary> /// Flip a permission bit and check to see if all permissions were accepted. /// </summary> /// <param name="permission">Permission.</param> private void _FlipBitAndCheckPermissions(PermissionsTypes permission) { m_requiredPermissions ^= permission; if (m_requiredPermissions == 0) { // all permissions are good! Debug.Log("All permissions have been accepted!"); _SendPermissionEvent(true); } else { _RequestNextPermission(); } } /// <summary> /// A Tango permission was denied. /// </summary> private void _PermissionWasDenied() { m_requiredPermissions = PermissionsTypes.NONE; if (PermissionEvent != null) { _SendPermissionEvent(false); } } /// <summary> /// Request next permission. /// </summary> private void _RequestNextPermission() { Debug.Log("TangoApplication._RequestNextPermission()"); // if no permissions are needed let's kick-off the Tango connect if (m_requiredPermissions == PermissionsTypes.NONE) { _SendPermissionEvent(true); } if ((m_requiredPermissions & PermissionsTypes.MOTION_TRACKING) == PermissionsTypes.MOTION_TRACKING) { if (AndroidHelper.ApplicationHasTangoPermissions(Common.TANGO_MOTION_TRACKING_PERMISSIONS)) { _androidOnActivityResult(Common.TANGO_MOTION_TRACKING_PERMISSIONS_REQUEST_CODE, -1, null); } else { AndroidHelper.StartTangoPermissionsActivity(Common.TANGO_MOTION_TRACKING_PERMISSIONS); } } else if ((m_requiredPermissions & PermissionsTypes.AREA_LEARNING) == PermissionsTypes.AREA_LEARNING) { if (AndroidHelper.ApplicationHasTangoPermissions(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS)) { _androidOnActivityResult(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS_REQUEST_CODE, -1, null); } else { AndroidHelper.StartTangoPermissionsActivity(Common.TANGO_ADF_LOAD_SAVE_PERMISSIONS); } } } /// <summary> /// Sends the permission event. /// </summary> /// <param name="permissions">If set to <c>true</c> permissions.</param> private void _SendPermissionEvent(bool permissions) { m_sendPermissions = true; m_permissionsSuccessful = permissions; } /// <summary> /// Disperse any events related to Tango functionality. /// </summary> private void Update() { if (m_sendPermissions) { if (PermissionEvent != null) { PermissionEvent(m_permissionsSuccessful); } m_sendPermissions = false; } if (m_poseListener != null) { m_poseListener.SendPoseIfAvailable(); } if (m_tangoEventListener != null) { m_tangoEventListener.SendIfTangoEventAvailable(); } if (m_depthListener != null) { m_depthListener.SendDepthIfAvailable(); } if (m_videoOverlayListener != null) { m_videoOverlayListener.SendIfVideoOverlayAvailable(); } } /// <summary> /// Unity callback when this object is destroyed. /// </summary> private void OnDestroy() { Shutdown(); } #region NATIVE_FUNCTIONS /// <summary> /// Interface for native function calls to Tango Service. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "C API Wrapper.")] private struct TangoServiceAPI { #if UNITY_ANDROID && !UNITY_EDITOR [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_initialize(IntPtr jniEnv, IntPtr appContext); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_connect(IntPtr callbackContext, IntPtr config); [DllImport(Common.TANGO_UNITY_DLL)] public static extern int TangoService_disconnect(); #else public static int TangoService_initialize(IntPtr jniEnv, IntPtr appContext) { return Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_connect(IntPtr callbackContext, IntPtr config) { return Common.ErrorType.TANGO_SUCCESS; } public static int TangoService_disconnect() { return Common.ErrorType.TANGO_SUCCESS; } #endif } #endregion // NATIVE_FUNCTIONS } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using NHibernate; using NHibernate.Criterion; using NHibernate.Impl; using NHibernate.Linq; using Orchard.ContentManagement.Records; using Orchard.Data; using NHibernate.Transform; using NHibernate.SqlCommand; using Orchard.Utility.Extensions; using Orchard.Caching; namespace Orchard.ContentManagement { public class DefaultContentQuery : IContentQuery { private readonly ITransactionManager _transactionManager; private ISession _session; private ICriteria _itemVersionCriteria; private VersionOptions _versionOptions; private ICacheManager _cacheManager; private ISignals _signals; private IRepository<ContentTypeRecord> _contentTypeRepository; public DefaultContentQuery( IContentManager contentManager, ITransactionManager transactionManager, ICacheManager cacheManager, ISignals signals, IRepository<ContentTypeRecord> contentTypeRepository) { _transactionManager = transactionManager; ContentManager = contentManager; _cacheManager = cacheManager; _signals = signals; _contentTypeRepository = contentTypeRepository; } public IContentManager ContentManager { get; private set; } ISession BindSession() { if (_session == null) _session = _transactionManager.GetSession(); return _session; } ICriteria BindCriteriaByPath(ICriteria criteria, string path) { return criteria.GetCriteriaByPath(path) ?? criteria.CreateCriteria(path); } //ICriteria BindTypeCriteria() { // // ([ContentItemVersionRecord] >join> [ContentItemRecord]) >join> [ContentType] // return BindCriteriaByPath(BindItemCriteria(), "ContentType"); //} ICriteria BindItemCriteria() { // [ContentItemVersionRecord] >join> [ContentItemRecord] return BindCriteriaByPath(BindItemVersionCriteria(), "ContentItemRecord"); } ICriteria BindItemVersionCriteria() { if (_itemVersionCriteria == null) { _itemVersionCriteria = BindSession().CreateCriteria<ContentItemVersionRecord>(); _itemVersionCriteria.SetCacheable(true); } return _itemVersionCriteria; } ICriteria BindPartCriteria<TRecord>() where TRecord : ContentPartRecord { if (typeof(TRecord).IsSubclassOf(typeof(ContentPartVersionRecord))) { return BindCriteriaByPath(BindItemVersionCriteria(), typeof(TRecord).Name); } return BindCriteriaByPath(BindItemCriteria(), typeof(TRecord).Name); } private int GetContentTypeRecordId(string contentType) { return _cacheManager.Get(contentType + "_Record", true, ctx => { ctx.Monitor(_signals.When(contentType + "_Record")); var contentTypeRecord = _contentTypeRepository.Get(x => x.Name == contentType); if (contentTypeRecord == null) { //TEMP: this is not safe... ContentItem types could be created concurrently? contentTypeRecord = new ContentTypeRecord { Name = contentType }; _contentTypeRepository.Create(contentTypeRecord); } return contentTypeRecord.Id; }); } private void ForType(params string[] contentTypeNames) { if (contentTypeNames != null && contentTypeNames.Length != 0) { var contentTypeIds = contentTypeNames.Select(GetContentTypeRecordId).ToArray(); // don't use the IN operator if not needed for performance reasons if (contentTypeNames.Length == 1) { BindItemCriteria().Add(Restrictions.Eq("ContentType.Id", contentTypeIds[0])); } else { BindItemCriteria().Add(Restrictions.InG("ContentType.Id", contentTypeIds)); } } } public void ForVersion(VersionOptions options) { _versionOptions = options; } private void ForContentItems(IEnumerable<int> ids) { if (ids == null) throw new ArgumentNullException("ids"); // Converting to array as otherwise an exception "Expression argument must be of type ICollection." is thrown. Where<ContentItemRecord>(record => ids.ToArray().Contains(record.Id), BindCriteriaByPath(BindItemCriteria(), typeof(ContentItemRecord).Name)); } private void Where<TRecord>() where TRecord : ContentPartRecord { // this simply demands an inner join BindPartCriteria<TRecord>(); } private void Where<TRecord>(Expression<Func<TRecord, bool>> predicate) where TRecord : ContentPartRecord { Where<TRecord>(predicate, BindPartCriteria<TRecord>()); } private void Where<TRecord>(Expression<Func<TRecord, bool>> predicate, ICriteria bindCriteria) { // build a linq to nhibernate expression var options = new QueryOptions(); var queryProvider = new NHibernateQueryProvider(BindSession(), options); var queryable = new Query<TRecord>(queryProvider, options).Where(predicate); // translate it into the nhibernate ICriteria implementation var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression); // attach the criterion from the predicate to this query's criteria for the record var recordCriteria = bindCriteria; foreach (var expressionEntry in criteria.IterateExpressionEntries()) { recordCriteria.Add(expressionEntry.Criterion); } } private void OrderBy<TRecord, TKey>(Expression<Func<TRecord, TKey>> keySelector) where TRecord : ContentPartRecord { // build a linq to nhibernate expression var options = new QueryOptions(); var queryProvider = new NHibernateQueryProvider(BindSession(), options); var queryable = new Query<TRecord>(queryProvider, options).OrderBy(keySelector); // translate it into the nhibernate ordering var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression); // attaching orderings to the query's criteria var recordCriteria = BindPartCriteria<TRecord>(); foreach (var ordering in criteria.IterateOrderings()) { recordCriteria.AddOrder(ordering.Order); } } private void OrderByDescending<TRecord, TKey>(Expression<Func<TRecord, TKey>> keySelector) where TRecord : ContentPartRecord { // build a linq to nhibernate expression var options = new QueryOptions(); var queryProvider = new NHibernateQueryProvider(BindSession(), options); var queryable = new Query<TRecord>(queryProvider, options).OrderByDescending(keySelector); // translate it into the nhibernate ICriteria implementation var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression); // attaching orderings to the query's criteria var recordCriteria = BindPartCriteria<TRecord>(); foreach (var ordering in criteria.IterateOrderings()) { recordCriteria.AddOrder(ordering.Order); } } private IEnumerable<ContentItem> Slice(int skip, int count) { var criteria = BindItemVersionCriteria(); criteria.ApplyVersionOptionsRestrictions(_versionOptions); criteria.SetFetchMode("ContentItemRecord", FetchMode.Eager); criteria.SetFetchMode("ContentItemRecord.ContentType", FetchMode.Eager); // TODO: put 'removed false' filter in place if (skip != 0) { criteria = criteria.SetFirstResult(skip); } if (count != 0) { criteria = criteria.SetMaxResults(count); } return criteria .List<ContentItemVersionRecord>() .Select(x => ContentManager.Get(x.ContentItemRecord.Id, _versionOptions != null && _versionOptions.IsDraftRequired ? _versionOptions : VersionOptions.VersionRecord(x.Id))) .ToReadOnlyCollection(); } int Count() { var criteria = (ICriteria)BindItemVersionCriteria().Clone(); criteria.ClearOrders(); criteria.ApplyVersionOptionsRestrictions(_versionOptions); return criteria.SetProjection(Projections.RowCount()).UniqueResult<Int32>(); } void WithQueryHints(QueryHints hints) { if (hints == QueryHints.Empty) { return; } var contentItemVersionCriteria = BindItemVersionCriteria(); var contentItemCriteria = BindItemCriteria(); var contentItemMetadata = _session.SessionFactory.GetClassMetadata(typeof(ContentItemRecord)); var contentItemVersionMetadata = _session.SessionFactory.GetClassMetadata(typeof(ContentItemVersionRecord)); // break apart and group hints by their first segment var hintDictionary = hints.Records .Select(hint => new { Hint = hint, Segments = hint.Split('.') }) .GroupBy(item => item.Segments.FirstOrDefault()) .ToDictionary(grouping => grouping.Key, StringComparer.InvariantCultureIgnoreCase); // locate hints that match properties in the ContentItemVersionRecord foreach (var hit in contentItemVersionMetadata.PropertyNames.Where(hintDictionary.ContainsKey).SelectMany(key => hintDictionary[key])) { contentItemVersionCriteria.SetFetchMode(hit.Hint, FetchMode.Eager); hit.Segments.Take(hit.Segments.Count() - 1).Aggregate(contentItemVersionCriteria, ExtendCriteria); } // locate hints that match properties in the ContentItemRecord foreach (var hit in contentItemMetadata.PropertyNames.Where(hintDictionary.ContainsKey).SelectMany(key => hintDictionary[key])) { contentItemVersionCriteria.SetFetchMode("ContentItemRecord." + hit.Hint, FetchMode.Eager); hit.Segments.Take(hit.Segments.Count() - 1).Aggregate(contentItemCriteria, ExtendCriteria); } if (hintDictionary.SelectMany(x => x.Value).Any(x => x.Segments.Count() > 1)) contentItemVersionCriteria.SetResultTransformer(new DistinctRootEntityResultTransformer()); } void WithQueryHintsFor(string contentType) { var contentItem = ContentManager.New(contentType); var contentPartRecords = new List<string>(); foreach (var part in contentItem.Parts) { var partType = part.GetType().BaseType; if (partType.IsGenericType && partType.GetGenericTypeDefinition() == typeof(ContentPart<>)) { var recordType = partType.GetGenericArguments().Single(); contentPartRecords.Add(recordType.Name); } } WithQueryHints(new QueryHints().ExpandRecords(contentPartRecords)); } private static ICriteria ExtendCriteria(ICriteria criteria, string segment) { return criteria.GetCriteriaByPath(segment) ?? criteria.CreateCriteria(segment, JoinType.LeftOuterJoin); } IContentQuery<TPart> IContentQuery.ForPart<TPart>() { return new ContentQuery<TPart>(this); } class ContentQuery<T> : IContentQuery<T> where T : IContent { protected readonly DefaultContentQuery _query; public ContentQuery(DefaultContentQuery query) { _query = query; } public IContentManager ContentManager { get { return _query.ContentManager; } } IContentQuery<TPart> IContentQuery.ForPart<TPart>() { return new ContentQuery<TPart>(_query); } IContentQuery<T> IContentQuery<T>.ForType(params string[] contentTypes) { _query.ForType(contentTypes); return this; } IContentQuery<T> IContentQuery<T>.ForVersion(VersionOptions options) { _query.ForVersion(options); return this; } IContentQuery<T> IContentQuery<T>.ForContentItems(IEnumerable<int> ids) { _query.ForContentItems(ids); return this; } IEnumerable<T> IContentQuery<T>.List() { return _query.Slice(0, 0).AsPart<T>(); } IEnumerable<T> IContentQuery<T>.Slice(int skip, int count) { return _query.Slice(skip, count).AsPart<T>(); } int IContentQuery<T>.Count() { return _query.Count(); } IContentQuery<T, TRecord> IContentQuery<T>.Join<TRecord>() { _query.Where<TRecord>(); return new ContentQuery<T, TRecord>(_query); } IContentQuery<T, TRecord> IContentQuery<T>.Where<TRecord>(Expression<Func<TRecord, bool>> predicate) { _query.Where(predicate); return new ContentQuery<T, TRecord>(_query); } IContentQuery<T, TRecord> IContentQuery<T>.OrderBy<TRecord>(Expression<Func<TRecord, object>> keySelector) { _query.OrderBy(keySelector); return new ContentQuery<T, TRecord>(_query); } IContentQuery<T, TRecord> IContentQuery<T>.OrderByDescending<TRecord>(Expression<Func<TRecord, object>> keySelector) { _query.OrderByDescending(keySelector); return new ContentQuery<T, TRecord>(_query); } IContentQuery<T> IContentQuery<T>.WithQueryHints(QueryHints hints) { _query.WithQueryHints(hints); return this; } IContentQuery<T> IContentQuery<T>.WithQueryHintsFor(string contentType) { _query.WithQueryHintsFor(contentType); return this; } } class ContentQuery<T, TR> : ContentQuery<T>, IContentQuery<T, TR> where T : IContent where TR : ContentPartRecord { public ContentQuery(DefaultContentQuery query) : base(query) { } IContentQuery<T, TR> IContentQuery<T, TR>.ForVersion(VersionOptions options) { _query.ForVersion(options); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.Where(Expression<Func<TR, bool>> predicate) { _query.Where(predicate); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.OrderBy<TKey>(Expression<Func<TR, TKey>> keySelector) { _query.OrderBy(keySelector); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.OrderByDescending<TKey>(Expression<Func<TR, TKey>> keySelector) { _query.OrderByDescending(keySelector); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.WithQueryHints(QueryHints hints) { _query.WithQueryHints(hints); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.WithQueryHintsFor(string contentType) { _query.WithQueryHintsFor(contentType); return this; } } } internal static class CriteriaExtensions { internal static void ApplyVersionOptionsRestrictions(this ICriteria criteria, VersionOptions versionOptions) { if (versionOptions == null) { criteria.Add(Restrictions.Eq("Published", true)); } else if (versionOptions.IsPublished) { criteria.Add(Restrictions.Eq("Published", true)); } else if (versionOptions.IsLatest) { criteria.Add(Restrictions.Eq("Latest", true)); } else if (versionOptions.IsDraft && !versionOptions.IsDraftRequired) { criteria.Add(Restrictions.And( Restrictions.Eq("Latest", true), Restrictions.Eq("Published", false))); } else if (versionOptions.IsDraft || versionOptions.IsDraftRequired) { criteria.Add(Restrictions.Eq("Latest", true)); } else if (versionOptions.IsAllVersions) { // no-op... all versions will be returned by default } else { throw new ApplicationException("Invalid VersionOptions for content query"); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableSortedDictionaryTest : ImmutableDictionaryTestBase { private enum Operation { Add, Set, Remove, Last, } [Fact] public void RandomOperationsTest() { int operationCount = this.RandomOperationsCount; var expected = new SortedDictionary<int, bool>(); var actual = ImmutableSortedDictionary<int, bool>.Empty; int seed = (int)DateTime.Now.Ticks; Debug.WriteLine("Using random seed {0}", seed); var random = new Random(seed); for (int iOp = 0; iOp < operationCount; iOp++) { switch ((Operation)random.Next((int)Operation.Last)) { case Operation.Add: int key; do { key = random.Next(); } while (expected.ContainsKey(key)); bool value = random.Next() % 2 == 0; Debug.WriteLine("Adding \"{0}\"={1} to the set.", key, value); expected.Add(key, value); actual = actual.Add(key, value); break; case Operation.Set: bool overwrite = expected.Count > 0 && random.Next() % 2 == 0; if (overwrite) { int position = random.Next(expected.Count); key = expected.Skip(position).First().Key; } else { do { key = random.Next(); } while (expected.ContainsKey(key)); } value = random.Next() % 2 == 0; Debug.WriteLine("Setting \"{0}\"={1} to the set (overwrite={2}).", key, value, overwrite); expected[key] = value; actual = actual.SetItem(key, value); break; case Operation.Remove: if (expected.Count > 0) { int position = random.Next(expected.Count); key = expected.Skip(position).First().Key; Debug.WriteLine("Removing element \"{0}\" from the set.", key); Assert.True(expected.Remove(key)); actual = actual.Remove(key); } break; } Assert.Equal<KeyValuePair<int, bool>>(expected.ToList(), actual.ToList()); } } [Fact] public void AddExistingKeySameValueTest() { AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "Microsoft"); AddExistingKeySameValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void AddExistingKeyDifferentValueTest() { AddExistingKeyDifferentValueTestHelper(Empty(StringComparer.Ordinal, StringComparer.Ordinal), "Company", "Microsoft", "MICROSOFT"); } [Fact] public void ToUnorderedTest() { var sortedMap = Empty<int, GenericParameterHelper>().AddRange(Enumerable.Range(1, 100).Select(n => new KeyValuePair<int, GenericParameterHelper>(n, new GenericParameterHelper(n)))); var unsortedMap = sortedMap.ToImmutableDictionary(); Assert.IsAssignableFrom(typeof(ImmutableDictionary<int, GenericParameterHelper>), unsortedMap); Assert.Equal(sortedMap.Count, unsortedMap.Count); Assert.Equal<KeyValuePair<int, GenericParameterHelper>>(sortedMap.ToList(), unsortedMap.ToList()); } [Fact] public void SortChangeTest() { var map = Empty<string, string>(StringComparer.Ordinal) .Add("Johnny", "Appleseed") .Add("JOHNNY", "Appleseed"); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("Johnny")); Assert.False(map.ContainsKey("johnny")); var newMap = map.ToImmutableSortedDictionary(StringComparer.OrdinalIgnoreCase); Assert.Equal(1, newMap.Count); Assert.True(newMap.ContainsKey("Johnny")); Assert.True(newMap.ContainsKey("johnny")); // because it's case insensitive } [Fact] public void InitialBulkAddUniqueTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("c", "d"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); var actual = map.AddRange(uniqueEntries); Assert.Equal(2, actual.Count); } [Fact] public void InitialBulkAddWithExactDuplicatesTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("a", "b"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); var actual = map.AddRange(uniqueEntries); Assert.Equal(1, actual.Count); } [Fact] public void ContainsValueTest() { this.ContainsValueTestHelper(ImmutableSortedDictionary<int, GenericParameterHelper>.Empty, 1, new GenericParameterHelper()); } [Fact] public void InitialBulkAddWithKeyCollisionTest() { var uniqueEntries = new List<KeyValuePair<string, string>> { new KeyValuePair<string,string>("a", "b"), new KeyValuePair<string,string>("a", "d"), }; var map = Empty<string, string>(StringComparer.Ordinal, StringComparer.Ordinal); Assert.Throws<ArgumentException>(() => map.AddRange(uniqueEntries)); } [Fact] public void Create() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "b" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; var dictionary = ImmutableSortedDictionary.Create<string, string>(); Assert.Equal(0, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.Create<string, string>(keyComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.Create(keyComparer, valueComparer); Assert.Equal(0, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(pairs); Assert.Equal(1, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = ImmutableSortedDictionary.CreateRange(keyComparer, valueComparer, pairs); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); } [Fact] public void ToImmutableSortedDictionary() { IEnumerable<KeyValuePair<string, string>> pairs = new Dictionary<string, string> { { "a", "B" } }; var keyComparer = StringComparer.OrdinalIgnoreCase; var valueComparer = StringComparer.CurrentCulture; ImmutableSortedDictionary<string, string> dictionary = pairs.ToImmutableSortedDictionary(); Assert.Equal(1, dictionary.Count); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(keyComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant()); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(Comparer<string>.Default, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(EqualityComparer<string>.Default, dictionary.ValueComparer); dictionary = pairs.ToImmutableSortedDictionary(p => p.Key.ToUpperInvariant(), p => p.Value.ToLowerInvariant(), keyComparer, valueComparer); Assert.Equal(1, dictionary.Count); Assert.Equal("A", dictionary.Keys.Single()); Assert.Equal("b", dictionary.Values.Single()); Assert.Same(keyComparer, dictionary.KeyComparer); Assert.Same(valueComparer, dictionary.ValueComparer); } [Fact] public void WithComparers() { var map = ImmutableSortedDictionary.Create<string, string>().Add("a", "1").Add("B", "1"); Assert.Same(Comparer<string>.Default, map.KeyComparer); Assert.True(map.ContainsKey("a")); Assert.False(map.ContainsKey("A")); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); var cultureComparer = StringComparer.CurrentCulture; map = map.WithComparers(StringComparer.OrdinalIgnoreCase, cultureComparer); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(cultureComparer, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("A")); Assert.True(map.ContainsKey("b")); } [Fact] public void WithComparersCollisions() { // First check where collisions have matching values. var map = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("A", "1"); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Equal(1, map.Count); Assert.True(map.ContainsKey("a")); Assert.Equal("1", map["a"]); // Now check where collisions have conflicting values. map = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("A", "2").Add("b", "3"); Assert.Throws<ArgumentException>(() => map.WithComparers(StringComparer.OrdinalIgnoreCase)); // Force all values to be considered equal. map = map.WithComparers(StringComparer.OrdinalIgnoreCase, EverythingEqual<string>.Default); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); Assert.Same(EverythingEqual<string>.Default, map.ValueComparer); Assert.Equal(2, map.Count); Assert.True(map.ContainsKey("a")); Assert.True(map.ContainsKey("b")); } [Fact] public void WithComparersEmptyCollection() { var map = ImmutableSortedDictionary.Create<string, string>(); Assert.Same(Comparer<string>.Default, map.KeyComparer); map = map.WithComparers(StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.OrdinalIgnoreCase, map.KeyComparer); } [Fact] public void EnumeratorRecyclingMisuse() { var collection = ImmutableSortedDictionary.Create<int, int>().Add(3, 5); var enumerator = collection.GetEnumerator(); var enumeratorCopy = enumerator; Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); enumerator.Dispose(); Assert.Throws<ObjectDisposedException>(() => enumerator.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumerator.Reset()); Assert.Throws<ObjectDisposedException>(() => enumerator.Current); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.MoveNext()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Reset()); Assert.Throws<ObjectDisposedException>(() => enumeratorCopy.Current); enumerator.Dispose(); // double-disposal should not throw enumeratorCopy.Dispose(); // We expect that acquiring a new enumerator will use the same underlying Stack<T> object, // but that it will not throw exceptions for the new enumerator. enumerator = collection.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); enumerator.Dispose(); } ////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces. public void EnumerationPerformance() { var dictionary = Enumerable.Range(1, 1000).ToImmutableSortedDictionary(k => k, k => k); var timing = new TimeSpan[3]; var sw = new Stopwatch(); for (int j = 0; j < timing.Length; j++) { sw.Start(); for (int i = 0; i < 10000; i++) { foreach (var entry in dictionary) { } } timing[j] = sw.Elapsed; sw.Reset(); } string timingText = string.Join(Environment.NewLine, timing); Debug.WriteLine("Timing:{0}{1}", Environment.NewLine, timingText); } ////[Fact] // not really a functional test -- but very useful to enable when collecting perf traces. public void EnumerationPerformance_Empty() { var dictionary = ImmutableSortedDictionary<int, int>.Empty; var timing = new TimeSpan[3]; var sw = new Stopwatch(); for (int j = 0; j < timing.Length; j++) { sw.Start(); for (int i = 0; i < 10000; i++) { foreach (var entry in dictionary) { } } timing[j] = sw.Elapsed; sw.Reset(); } string timingText = string.Join(Environment.NewLine, timing); Debug.WriteLine("Timing_Empty:{0}{1}", Environment.NewLine, timingText); } protected override IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>() { return ImmutableSortedDictionaryTest.Empty<TKey, TValue>(); } protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer) { return ImmutableSortedDictionary.Create<string, TValue>(comparer); } protected override IEqualityComparer<TValue> GetValueComparer<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).ValueComparer; } internal override IBinaryTree GetRootNode<TKey, TValue>(IImmutableDictionary<TKey, TValue> dictionary) { return ((ImmutableSortedDictionary<TKey, TValue>)dictionary).Root; } protected void ContainsValueTestHelper<TKey, TValue>(ImmutableSortedDictionary<TKey, TValue> map, TKey key, TValue value) { Assert.False(map.ContainsValue(value)); Assert.True(map.Add(key, value).ContainsValue(value)); } private static IImmutableDictionary<TKey, TValue> Empty<TKey, TValue>(IComparer<TKey> keyComparer = null, IEqualityComparer<TValue> valueComparer = null) { return ImmutableSortedDictionary<TKey, TValue>.Empty.WithComparers(keyComparer, valueComparer); } } }
// Unity SDK for Qualisys Track Manager. Copyright 2015-2018 Qualisys AB // using QTMRealTimeSDK; using System; using System.Collections.Generic; using UnityEngine; using System.Threading; namespace QualisysRealTime.Unity { public class RTClient : IDisposable { static RtProtocolVersion rtProtocolVersionMax = new RtProtocolVersion(RTProtocol.Constants.MAJOR_VERSION, RTProtocol.Constants.MINOR_VERSION); static RTClient instance; int previousFrame = -1; ushort replyPort = (ushort)new System.Random().Next(1333, 1388); bool disposed = false; RTStreamThread rtStreamThread = null; string errorString = string.Empty; public List<SixDOFBody> Bodies { get { return rtStreamThread == null ? new List<SixDOFBody>() : rtStreamThread.ReaderThreadState.bodies; } } public List<LabeledMarker> Markers { get { return rtStreamThread == null ? new List<LabeledMarker>() : rtStreamThread.ReaderThreadState.markers; } } public List<UnlabeledMarker> UnlabeledMarkers { get { return rtStreamThread == null ? new List<UnlabeledMarker>() : rtStreamThread.ReaderThreadState.unlabeledMarkers; } } public List<Bone> Bones { get { return rtStreamThread == null ? new List<Bone>() : rtStreamThread.ReaderThreadState.bones; } } public List<GazeVector> GazeVectors { get { return rtStreamThread == null ? new List<GazeVector>() : rtStreamThread.ReaderThreadState.gazeVectors; } } public List<AnalogChannel> AnalogChannels { get { return rtStreamThread == null ? new List<AnalogChannel>() : rtStreamThread.ReaderThreadState.analogChannels; } } public List<Skeleton> Skeletons { get { return rtStreamThread == null ? new List<Skeleton>() : rtStreamThread.ReaderThreadState.skeletons; } } public RTConnectionState ConnectionState { get { return rtStreamThread == null ? RTConnectionState.Disconnected : rtStreamThread.ReaderThreadState.connectionState; } } public RtProtocolVersion RtProtocolVersion { get{ return rtStreamThread == null ? RtProtocolVersionMax : rtStreamThread.ReaderThreadState.rtProtocolVersion; } } public RtProtocolVersion RtProtocolVersionMax { get{ return rtProtocolVersionMax; } } // Get frame number from latest packet public int GetFrame() { if (rtStreamThread == null) { return 0; } return rtStreamThread.ReaderThreadState.frameNumber; } public int GetFrequency() { if (rtStreamThread == null) { return 0; } return rtStreamThread.ReaderThreadState.frequency; } public static RTClient GetInstance() { if (instance == null) { instance = new RTClient(); } RTClientUpdater.AssertExistence(); return instance; } public SixDOFBody GetBody(string name) { if (rtStreamThread == null) { return null; } return rtStreamThread.ReaderThreadState.GetBody(name); } public Skeleton GetSkeleton(string name) { if (rtStreamThread == null) { return null; } return rtStreamThread.ReaderThreadState.GetSkeleton(name); } public LabeledMarker GetMarker(string name) { if (rtStreamThread == null) { return null; } return rtStreamThread.ReaderThreadState.GetMarker(name); } public UnlabeledMarker GetUnlabeledMarker(uint id) { if (rtStreamThread == null) { return null; } return rtStreamThread.ReaderThreadState.GetUnlabeledMarker(id); } public AnalogChannel GetAnalogChannel(string name) { if (rtStreamThread == null) { return null; } return rtStreamThread.ReaderThreadState.GetAnalogChannel(name); } public List<AnalogChannel> GetAnalogChannels(List<string> names) { if (rtStreamThread == null) { return new List<AnalogChannel>(); } return rtStreamThread.ReaderThreadState.GetAnalogChannels(names); } public bool GetStreamingStatus() { return ConnectionState == RTConnectionState.Connected && rtStreamThread.ReaderThreadState.isStreaming; } /// <summary> /// Get list of servers available on network (always add localhost) /// </summary> /// <returns><c>true</c>, if discovery packet was sent, <c>false</c> otherwise.</returns> /// <param name="list">List of discovered servers</param> public List<DiscoveryResponse> GetServers() { // Send discovery packet using (var protocol = new RTProtocol()) { List<DiscoveryResponse> list = new List<DiscoveryResponse>(); if (protocol.DiscoverRTServers(replyPort)) { if (protocol.DiscoveryResponses.Count > 0) { //Get list of all servers from protocol foreach (var discoveryResponse in protocol.DiscoveryResponses) { //add them to our list for user to pick from list.Add(discoveryResponse); } } } list.Add(new DiscoveryResponse { HostName = "Localhost", IpAddress = "127.0.0.1", Port = RTProtocol.Constants.STANDARD_BASE_PORT, InfoText = "", CameraCount = 0 }); return list; } } [Obsolete("IsConnected is deprecated, use ConnectionState property instead.")] public bool IsConnected() { return ConnectionState != RTConnectionState.Disconnected; } /// <summary> /// Connect to QTM and start streaming /// This method is non blocking /// </summary> /// <param name="pickedServer">Picked server.</param> /// <param name="udpPort">UDP port streaming should occur on.</param> /// <param name="stream6d">if 6DOF data should be streamed.</param> /// <param name="stream3d">if labeled markers should be streamed.</param> /// <param name="stream3dNoLabels">if unlabeled markers should be streamed.</param> /// <param name="streamGaze">if gaze vectors should be streamed.</param> /// <param name="streamAnalog">if analog data should be streamed.</param> public void StartConnecting(string IpAddress, short udpPort, bool stream6d, bool stream3d, bool stream3dNoLabels, bool streamGaze, bool streamAnalog, bool streamSkeleton) { errorString = string.Empty; if (rtStreamThread != null) { rtStreamThread.Dispose(); rtStreamThread = null; } rtStreamThread = new RTStreamThread(IpAddress, udpPort, StreamRate.RateAllFrames, stream6d, stream3d, stream3dNoLabels, streamGaze, streamAnalog, streamSkeleton); } /// <summary> /// Connect to QTM and start streaming /// This method blocks the calling thread. /// </summary> /// <param name="pickedServer">Picked server.</param> /// <param name="udpPort">UDP port streaming should occur on.</param> /// <param name="stream6d">if 6DOF data should be streamed.</param> /// <param name="stream3d">if labeled markers should be streamed.</param> /// <param name="stream3dNoLabels">if unlabeled markers should be streamed.</param> /// <param name="streamGaze">if gaze vectors should be streamed.</param> /// <param name="streamAnalog">if analog data should be streamed.</param> public bool Connect(DiscoveryResponse discoveryResponse, short udpPort, bool stream6d, bool stream3d, bool stream3dNoLabels, bool streamGaze, bool streamAnalog, bool streamSkeleton) { StartConnecting(discoveryResponse.IpAddress, udpPort, stream6d, stream3d, stream3dNoLabels, streamGaze, streamAnalog, streamSkeleton); while (ConnectionState == RTConnectionState.Connecting) { Thread.Sleep(TimeSpan.FromMilliseconds(200)); UpdateThread(); } return ConnectionState == RTConnectionState.Connected; } /// <summary> /// Connect to QTM and start streaming /// This method blocks the calling thread. /// </summary> /// <param name="ipAddress">IP address of the QTM host</param> /// <param name="udpPort">UDP port streaming should occur on.</param> /// <param name="stream6d">if 6DOF data should be streamed.</param> /// <param name="stream3d">if labeled markers should be streamed.</param> /// <param name="stream3d">if unlabeled markers should be streamed.</param> /// <param name="streamGaze">if gaze vectors should be streamed.</param> /// <param name="streamAnalog">if analog data should be streamed.</param> public bool Connect(string ipAddress, short udpPort, bool stream6d, bool stream3d, bool stream3dNoLabels, bool streamGaze, bool streamAnalog, bool streamSkeleton) { StartConnecting(ipAddress, udpPort, stream6d, stream3d, stream3dNoLabels, streamGaze, streamAnalog, streamSkeleton); while (ConnectionState == RTConnectionState.Connecting) { Thread.Sleep(TimeSpan.FromMilliseconds(200)); UpdateThread(); } return ConnectionState == RTConnectionState.Connected; } public string GetErrorString() { return errorString; } public void Update() { int frameNumber = Time.frameCount; if (previousFrame == frameNumber) { return; } else { previousFrame = frameNumber; } if (ConnectionState != RTConnectionState.Disconnected) { UpdateThread(); } } void UpdateThread() { var oldConnectionState = this.ConnectionState; bool result = rtStreamThread.Update(); if (!string.IsNullOrEmpty(rtStreamThread.ReaderThreadState.errorString)) { errorString = rtStreamThread.ReaderThreadState.errorString; Debug.Log(errorString); } if (!result) { Disconnect(); } if (ConnectionState == RTConnectionState.Connected && oldConnectionState != RTConnectionState.Connected) { if (RtProtocolVersion < RtProtocolVersionMax) { Debug.Log("Using RT protocol " + RtProtocolVersionMax + " failed. QTM is using an older version (" + RtProtocolVersion + "). Some features might not be available."); } } } public void Disconnect() { if (rtStreamThread != null) { rtStreamThread.Dispose(); rtStreamThread = null; } } public void Dispose() { if (!disposed) { Disconnect(); disposed = true; instance = null; } } } }
// // ScanSegment.cs // MSAGL class for visibility scan segments for Rectilinear Edge Routing. // // Copyright Microsoft Corporation. using System; using System.Diagnostics; using System.Linq; using Microsoft.Msagl.Core.DataStructures; using Microsoft.Msagl.Core.Geometry; using Microsoft.Msagl.Routing.Visibility; namespace Microsoft.Msagl.Routing.Rectilinear { internal class ScanSegment : SegmentBase { // This is a single segment added by the ScanLine. internal PointAndCrossingsList GroupBoundaryPointAndCrossingsList; private Point endPoint; private Point startPoint; internal const double NormalWeight = VisibilityEdge.DefaultWeight; internal const double ReflectionWeight = 5; internal const double OverlappedWeight = 500; internal double Weight { get; private set; } // For sparse visibility graph. internal ScanSegment NextSegment { get; set; } internal ScanSegment(Point start, Point end) : this(start, end, NormalWeight, gbcList:null) { } internal ScanSegment(Point start, Point end, double weight, PointAndCrossingsList gbcList) { Update(start, end); Weight = weight; GroupBoundaryPointAndCrossingsList = gbcList; } internal override Point Start { get { return startPoint; } } internal override Point End { get { return endPoint; } } internal bool IsVertical { get { return IsVerticalSegment(Start, End); } } internal ScanDirection ScanDirection { get { return IsVertical ? ScanDirection.VerticalInstance : ScanDirection.HorizontalInstance; } } // For fast intersection calculation and ScanSegment splicing. internal VisibilityVertex LowestVisibilityVertex { get; private set; } internal VisibilityVertex HighestVisibilityVertex { get; private set; } // For overlaps, we will need to create a VisibilityVertex at the junction of overlapped/nonoverlapped // segments, but we don't want to create this for non-overlapped situations. internal bool IsOverlapped { get { return OverlappedWeight == this.Weight; } } internal bool IsReflection { get { return ReflectionWeight == this.Weight; } } internal bool NeedStartOverlapVertex { get; set; } internal bool NeedEndOverlapVertex { get; set; } internal static bool IsVerticalSegment(Point start, Point end) { return start.X == end.X; } // For group boundary crossings. internal void MergeGroupBoundaryCrossingList(PointAndCrossingsList other) { if (null != other) { if (null == GroupBoundaryPointAndCrossingsList) { GroupBoundaryPointAndCrossingsList = new PointAndCrossingsList(); } GroupBoundaryPointAndCrossingsList.MergeFrom(other); } } internal void TrimGroupBoundaryCrossingList() { if (null != GroupBoundaryPointAndCrossingsList) { GroupBoundaryPointAndCrossingsList.Trim(Start, End); } } // ctor internal void Update(Point start, Point end) { Debug.Assert(PointComparer.Equal(start, end) || StaticGraphUtility.IsAscending(PointComparer.GetPureDirection(start, end)) , "non-ascending segment"); startPoint = start; endPoint = end; } private void SetInitialVisibilityVertex(VisibilityVertex newVertex) { LowestVisibilityVertex = newVertex; HighestVisibilityVertex = newVertex; } // Append a vertex before LowestVisibilityVertex or after HighestVisibilityVertex. internal void AppendVisibilityVertex(VisibilityGraph vg, VisibilityVertex newVertex) { Debug.Assert(null != newVertex, "newVertex must not be null"); Debug.Assert((null == LowestVisibilityVertex) == (null == HighestVisibilityVertex), "Mismatched null Lowest/HighestVisibilityVertex"); Debug.Assert(StaticGraphUtility.PointIsOnSegment(this, newVertex.Point), "newVertex is out of segment range"); if (null == HighestVisibilityVertex) { if (!AddGroupCrossingsBeforeHighestVisibilityVertex(vg, newVertex)) { SetInitialVisibilityVertex(newVertex); } } else { // In the event of overlaps where ScanSegments share a Start/End at a border, SegmentIntersector // may be appending the same Vertex twice. If that point is on the border of a group, // then we may have just added the border-crossing edge as well. if (PointComparer.IsPureLower(newVertex.Point, HighestVisibilityVertex.Point)) { Debug.Assert(null != vg.FindEdge(newVertex.Point, HighestVisibilityVertex.Point) , "unexpected low/middle insertion to ScanSegment"); return; } // Add the new edge. This will always be in the ascending direction. if (!AddGroupCrossingsBeforeHighestVisibilityVertex(vg, newVertex)) { AppendHighestVisibilityVertex(newVertex); } } } private VisibilityEdge AddVisibilityEdge( VisibilityVertex source, VisibilityVertex target) { Debug.Assert(source.Point != target.Point, "Self-edges are not allowed"); Debug.Assert(PointComparer.IsPureLower(source.Point, target.Point), "Impure or reversed direction encountered"); // Make sure we aren't adding two edges in the same direction to the same vertex. Debug.Assert(null == StaticGraphUtility.FindNextVertex(source, StaticGraphUtility.EdgeDirection(source, target)) , "Duplicate outEdge from Source vertex"); Debug.Assert(null == StaticGraphUtility.FindNextVertex(target, StaticGraphUtility.EdgeDirection(target, source)) , "Duplicate inEdge to Target vertex"); var edge = new VisibilityEdge(source, target, this.Weight); VisibilityGraph.AddEdge(edge); return edge; } private void AppendHighestVisibilityVertex( VisibilityVertex newVertex) { if (!PointComparer.Equal(HighestVisibilityVertex.Point, newVertex.Point)) { AddVisibilityEdge( HighestVisibilityVertex, newVertex); HighestVisibilityVertex = newVertex; } } private void LoadStartOverlapVertexIfNeeded(VisibilityGraph vg) { // For adjacent segments with different IsOverlapped, we need a vertex that // joins the two so a path may be run. This is paired with the other segment's // LoadEndOverlapVertexIfNeeded. if (NeedStartOverlapVertex) { VisibilityVertex vertex = vg.FindVertex(Start); AppendVisibilityVertex(vg, vertex ?? vg.AddVertex(Start)); } } private void LoadEndOverlapVertexIfNeeded(VisibilityGraph vg) { // See comments in LoadStartOverlapVertexIfNeeded. if (NeedEndOverlapVertex) { VisibilityVertex vertex = vg.FindVertex(End); AppendVisibilityVertex(vg, vertex ?? vg.AddVertex(End)); } } internal void OnSegmentIntersectorBegin(VisibilityGraph vg) { // If we process any group crossings, they'll have created the first point. if (!AppendGroupCrossingsThroughPoint(vg, Start)) { LoadStartOverlapVertexIfNeeded(vg); } } internal void OnSegmentIntersectorEnd(VisibilityGraph vg) { AppendGroupCrossingsThroughPoint(vg, End); GroupBoundaryPointAndCrossingsList = null; if ((null == HighestVisibilityVertex) || (PointComparer.IsPureLower(HighestVisibilityVertex.Point, End))) { LoadEndOverlapVertexIfNeeded(vg); } } // If we have collinear segments, then we may be able to just update the previous one // instead of growing the ScanSegmentTree. // - For multiple collinear OpenVertexEvents, neighbors to the high side have not yet // been seen, so a segment is created that spans the lowest and highest neighbors. // A subsequent collinear OpenVertexEvent will be to the high side and will add a // subsegment of that segment, so we subsume it into LastAddedSegment. // - For multiple collinear CloseVertexEvents, closing neighbors to the high side are // still open, so a segment is created from the lowest neighbor to the next-highest // collinear obstacle to be closed. When that next-highest CloseVertexEvent is // encountered, it will extend LastAddedSegment. // - For multiple collinear mixed Open and Close events, we'll do all Opens first, // followed by all closes (per EventQueue opening), so we may add multiple discrete // segments, which ScanSegmentTree will merge. internal static bool Subsume(ref ScanSegment seg, Point newStart, Point newEnd, double weight, PointAndCrossingsList gbcList, ScanDirection scanDir, ScanSegmentTree tree, out bool extendStart, out bool extendEnd) { // Initialize these to the non-subsumed state; the endpoints were extended (or on a // different line). extendStart = true; extendEnd = true; if (null == seg) { return false; } // If they don't overlap (including touching at an endpoint), we don't subsume. if (!StaticGraphUtility.IntervalsOverlap(seg.Start, seg.End, newStart, newEnd)) { return false; } // If the overlapped-ness isn't the same, we don't subsume. ScanSegmentTree::MergeSegments // will mark that the low-to-high direction needs a VisibilityVertex to link the two segments. // These may differ by more than Curve.DistanceEpsilon in the case of reflection lookahead // segments collinear with vertex-derived segments, so have a looser tolerance here and we'll // adjust the segments in ScanSegmentTree.MergeSegments. if (seg.Weight != weight) { if ((seg.Start == newStart) && (seg.End == newEnd)) { // This is probably because of a rounding difference by one DistanceEpsilon reporting being // inside an obstacle vs. the scanline intersection calculation side-ordering. // Test is RectilinearFileTests.Overlap_Rounding_Vertex_Intersects_Side. seg.Weight = Math.Min(seg.Weight, weight); return true; } // In the case of groups, we go through the group boundary; this may coincide with a // reflection segment. RectilinearFileTests.ReflectionSubsumedBySegmentExitingGroup. Debug.Assert((seg.Weight == OverlappedWeight) == (weight == OverlappedWeight) || ApproximateComparer.CloseIntersections(seg.End, newStart) || ApproximateComparer.CloseIntersections(seg.Start, newEnd) , "non-equal overlap-mismatched ScanSegments overlap by more than just Start/End"); return false; } // Subsume the input segment. Return whether the start/end points were extended (newStart // is before this.Start, or newEnd is after this.End), so the caller can generate reflections // and so we can merge group border crossings. extendStart = (-1 == scanDir.CompareScanCoord(newStart, seg.Start)); extendEnd = (1 == scanDir.CompareScanCoord(newEnd, seg.End)); if (extendStart || extendEnd) { // We order by start and end so need to replace this in the tree regardless of which end changes. tree.Remove(seg); seg.startPoint = scanDir.Min(seg.Start, newStart); seg.endPoint = scanDir.Max(seg.End, newEnd); seg = tree.InsertUnique(seg).Item; seg.MergeGroupBoundaryCrossingList(gbcList); } return true; } internal Point GetIntersection(ScanSegment seg) { return StaticGraphUtility.SegmentIntersection(this, seg); } internal bool IntersectsSegment(ScanSegment seg) { return StaticGraphUtility.SegmentsIntersect(this, seg); } /// <summary> /// </summary> /// <returns></returns> public override string ToString() { return "[" + Start + " -> " + End + (IsOverlapped ? " olap" : " free") + "]"; } #region SparseVisibilityGraphGenerator utilities internal bool ContainsPoint(Point test) { // This may be off the line so do not use GetPureDirections. return PointComparer.Equal(this.Start, test) || PointComparer.Equal(this.End, test) || (PointComparer.GetDirections(this.Start, test) == PointComparer.GetDirections(test, this.End)); } private Set<double> sparsePerpendicularCoords; internal bool HasSparsePerpendicularCoords { get { return (this.sparsePerpendicularCoords == null) ? false : (this.sparsePerpendicularCoords.Count > 0); } } private Point CreatePointFromPerpCoord(double perpCoord) { return this.IsVertical ? new Point(this.Start.X, perpCoord) : new Point(perpCoord, this.Start.Y); } internal void AddSparseVertexCoord(double perpCoord) { Debug.Assert(this.ContainsPoint(this.CreatePointFromPerpCoord(perpCoord)), "vertexLocation is not on Segment"); if (this.sparsePerpendicularCoords == null) { this.sparsePerpendicularCoords = new Set<double>(); } this.sparsePerpendicularCoords.Insert(perpCoord); } internal bool AddSparseEndpoint(double coord) { // This is called after AddSparseVertexCoord so this.sparsePerpendicularCoords is already instantiated. if (!this.sparsePerpendicularCoords.Contains(coord)) { this.sparsePerpendicularCoords.Insert(coord); return true; } return false; } internal void CreateSparseVerticesAndEdges(VisibilityGraph vg) { if (this.sparsePerpendicularCoords == null) { return; } AppendGroupCrossingsThroughPoint(vg, Start); foreach (var perpCoord in this.sparsePerpendicularCoords.OrderBy(d => d)) { var vertexLocation = this.CreatePointFromPerpCoord(perpCoord); Debug.Assert(this.ContainsPoint(vertexLocation), "vertexLocation is not on Segment"); this.AppendVisibilityVertex(vg, vg.FindVertex(vertexLocation) ?? vg.AddVertex(vertexLocation)); } AppendGroupCrossingsThroughPoint(vg, End); GroupBoundaryPointAndCrossingsList = null; this.sparsePerpendicularCoords.Clear(); this.sparsePerpendicularCoords = null; } internal bool HasVisibility() { // Skip this only if it has no visibility vertex. return (null != this.LowestVisibilityVertex); } #endregion // SparseVisibilityGraphGenerator utilities #region Group utilities private bool AddGroupCrossingsBeforeHighestVisibilityVertex(VisibilityGraph vg, VisibilityVertex newVertex) { if (AppendGroupCrossingsThroughPoint(vg, newVertex.Point)) { // We may have added an interior vertex that is just higher than newVertex. if (PointComparer.IsPureLower(HighestVisibilityVertex.Point, newVertex.Point)) { AddVisibilityEdge(HighestVisibilityVertex, newVertex); HighestVisibilityVertex = newVertex; } return true; } return false; } private bool AppendGroupCrossingsThroughPoint(VisibilityGraph vg, Point lastPoint) { if (null == GroupBoundaryPointAndCrossingsList) { return false; } bool found = false; while (GroupBoundaryPointAndCrossingsList.CurrentIsBeforeOrAt(lastPoint)) { // We will only create crossing Edges that the segment actually crosses, not those it ends before crossing. // For those terminal crossings, the adjacent segment creates the interior vertex and crossing edge. PointAndCrossings pac = GroupBoundaryPointAndCrossingsList.Pop(); GroupBoundaryCrossing[] lowDirCrossings = null; GroupBoundaryCrossing[] highDirCrossings = null; if (PointComparer.Compare(pac.Location, Start) > 0) { lowDirCrossings = PointAndCrossingsList.ToCrossingArray(pac.Crossings, ScanDirection.OppositeDirection); } if (PointComparer.Compare(pac.Location, End) < 0) { highDirCrossings = PointAndCrossingsList.ToCrossingArray(pac.Crossings, ScanDirection.Direction); } found = true; VisibilityVertex crossingVertex = vg.FindVertex(pac.Location) ?? vg.AddVertex(pac.Location); if ((null != lowDirCrossings) || (null != highDirCrossings)) { AddLowCrossings(vg, crossingVertex, lowDirCrossings); AddHighCrossings(vg, crossingVertex, highDirCrossings); } else { // This is at this.Start with only lower-direction toward group interior(s), or at this.End with only // higher-direction toward group interior(s). Therefore an adjacent ScanSegment will create the crossing // edge, so create the crossing vertex here and we'll link to it. if (null == LowestVisibilityVertex) { SetInitialVisibilityVertex(crossingVertex); } else { Debug.Assert(PointComparer.Equal(End, crossingVertex.Point), "Expected this.End crossingVertex"); AppendHighestVisibilityVertex(crossingVertex); } } } return found; } private static VisibilityVertex GetCrossingInteriorVertex(VisibilityGraph vg, VisibilityVertex crossingVertex, GroupBoundaryCrossing crossing) { Point interiorPoint = crossing.GetInteriorVertexPoint(crossingVertex.Point); return vg.FindVertex(interiorPoint) ?? vg.AddVertex(interiorPoint); } private void AddCrossingEdge(VisibilityGraph vg, VisibilityVertex lowVertex, VisibilityVertex highVertex, GroupBoundaryCrossing[] crossings) { VisibilityEdge edge = null; if (null != HighestVisibilityVertex) { // We may have a case where point xx.xxxxx8 has added an ascending-direction crossing, and now we're on // xx.xxxxx9 adding a descending-direction crossing. In that case there should already be a VisibilityEdge // in the direction we want. if (PointComparer.Equal(this.HighestVisibilityVertex.Point, highVertex.Point)) { edge = vg.FindEdge(lowVertex.Point, highVertex.Point); Debug.Assert(edge != null, "Inconsistent forward-backward sequencing in HighVisibilityVertex"); } else { AppendHighestVisibilityVertex(lowVertex); } } if (edge == null) { edge = AddVisibilityEdge(lowVertex, highVertex); } var crossingsArray = crossings.Select(c => c.Group.InputShape).ToArray(); var prevIsPassable = edge.IsPassable; if (prevIsPassable == null) { edge.IsPassable = delegate { return crossingsArray.Any(s => s.IsTransparent); }; } else { // Because we don't have access to the previous delegate's internals, we have to chain. Fortunately this // will never be more than two deep. File Test: Groups_Forward_Backward_Between_Same_Vertices. edge.IsPassable = delegate { return crossingsArray.Any(s => s.IsTransparent) || prevIsPassable(); }; } if (null == LowestVisibilityVertex) { SetInitialVisibilityVertex(lowVertex); } HighestVisibilityVertex = highVertex; } private void AddLowCrossings(VisibilityGraph vg, VisibilityVertex crossingVertex, GroupBoundaryCrossing[] crossings) { if (null != crossings) { VisibilityVertex interiorVertex = GetCrossingInteriorVertex(vg, crossingVertex, crossings[0]); this.AddCrossingEdge(vg, interiorVertex, crossingVertex, crossings); // low-to-high } } private void AddHighCrossings(VisibilityGraph vg, VisibilityVertex crossingVertex, GroupBoundaryCrossing[] crossings) { if (null != crossings) { VisibilityVertex interiorVertex = GetCrossingInteriorVertex(vg, crossingVertex, crossings[0]); this.AddCrossingEdge(vg, crossingVertex, interiorVertex, crossings); // low-to-high } } #endregion // Group utilities } }
using System; using System.Reflection; using System.Xaml; using System.Linq; using System.Xaml.Schema; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; namespace Eto.Serialization.Xaml { #if NET45 class TypeConverterConverter : System.ComponentModel.TypeConverter { readonly Eto.TypeConverter etoConverter; public TypeConverterConverter(Eto.TypeConverter etoConverter) { this.etoConverter = etoConverter; } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType) { return etoConverter.CanConvertFrom(sourceType); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, Type destinationType) { return etoConverter.CanConvertTo(destinationType); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return etoConverter.ConvertFrom(null, culture, value); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { return etoConverter.ConvertTo(null, culture, value, destinationType); } } class EtoValueConverter : XamlValueConverter<System.ComponentModel.TypeConverter> { public EtoValueConverter(Type converterType, XamlType targetType) : base(converterType, targetType) { } protected override System.ComponentModel.TypeConverter CreateInstance() { var etoConverter = Activator.CreateInstance(ConverterType) as Eto.TypeConverter; return new TypeConverterConverter(etoConverter); } } #endif public class EtoXamlType : XamlType { public EtoXamlType(Type underlyingType, XamlSchemaContext schemaContext) : base(underlyingType, schemaContext) { } T GetCustomAttribute<T>(bool inherit = true) { return UnderlyingType.GetCustomAttributes(typeof(T), inherit).OfType<T>().FirstOrDefault(); } #if NET45 XamlValueConverter<System.ComponentModel.TypeConverter> typeConverter; protected override XamlType LookupItemType() { if (Xaml.IsMono) { // mono doesn't use SchemaContext.GetXamlType here, which we need to override the type converter. var underlyingType = UnderlyingType; Type type; if (IsArray) type = underlyingType.GetElementType(); else if (IsDictionary) { type = !IsGeneric ? typeof(object) : underlyingType.GetGenericArguments()[1]; } else if (!IsCollection) type = null; else if (!IsGeneric) type = typeof(object); else type = underlyingType.GetGenericArguments()[0]; return type != null ? SchemaContext.GetXamlType(type) : null; } return base.LookupItemType(); } class EmptyXamlMember : XamlMember { public EmptyXamlMember(EventInfo eventInfo, XamlSchemaContext context) : base(eventInfo, context) { } class EmptyConverter : System.ComponentModel.TypeConverter { public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, Type sourceType) { return true; } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, CultureInfo culture, object value) { return null; } } protected override XamlValueConverter<System.ComponentModel.TypeConverter> LookupTypeConverter() { var eventConverter = base.LookupTypeConverter(); return new XamlValueConverter<System.ComponentModel.TypeConverter>(typeof(EmptyConverter), eventConverter.TargetType); } } protected override XamlMember LookupMember(string name, bool skipReadOnlyCheck) { var member = base.LookupMember(name, skipReadOnlyCheck); if (member != null && member.IsEvent) { var context = SchemaContext as EtoXamlSchemaContext; if (context != null && context.DesignMode) { return new EmptyXamlMember(member.UnderlyingMember as EventInfo, context); } } return member; } protected override XamlValueConverter<System.ComponentModel.TypeConverter> LookupTypeConverter() { if (typeConverter != null) return typeConverter; var typeConverterAttrib = UnderlyingType.GetCustomAttribute<Eto.TypeConverterAttribute>(); if (typeConverterAttrib != null) { var converterType = Type.GetType(typeConverterAttrib.ConverterTypeName); if (converterType != null) typeConverter = new EtoValueConverter(converterType, this); } if (typeof(MulticastDelegate).IsAssignableFrom(UnderlyingType)) { var context = SchemaContext as EtoXamlSchemaContext; if (context.DesignMode) { return null; } } if (typeConverter == null) // convert from Eto.TypeConverter to System.ComponentModel.TypeConverter typeConverter = base.LookupTypeConverter(); return typeConverter; } #endif XamlMember contentProperty; protected override XamlMember LookupContentProperty() { if (contentProperty != null) return contentProperty; var contentAttribute = GetCustomAttribute<ContentPropertyAttribute>(); if (contentAttribute == null || contentAttribute.Name == null) contentProperty = base.LookupContentProperty(); else contentProperty = GetMember(contentAttribute.Name); return contentProperty; } protected override XamlMember LookupAliasedProperty(XamlDirective directive) { if (directive == XamlLanguage.Name) { // mono doesn't support the name attribute yet (throws null exception) if (!Xaml.IsMono) { var nameAttribute = GetCustomAttribute<RuntimeNamePropertyAttribute>(); if (nameAttribute != null && nameAttribute.Name != null) return GetMember(nameAttribute.Name); } // Remap Name to ID property if present XamlMember member = GetMember("ID"); if (member != null) return member; } return base.LookupAliasedProperty(directive); } protected override XamlMember LookupAttachableMember(string name) { XamlMember mbr = base.LookupAttachableMember(name); if (mbr == null) { mbr = GetMember(name); } return mbr; } //protected override XamlType LookupKeyType() //{ // return base.LookupKeyType(); //} //protected override XamlType LookupMarkupExtensionReturnType() //{ // return base.LookupMarkupExtensionReturnType(); //} //protected override XamlMember LookupMember(string name, bool skipReadOnlyCheck) //{ // XamlMember mbr = base.LookupMember(name, skipReadOnlyCheck); // return mbr; //} } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Threading; namespace System.Drawing { public sealed partial class BufferedGraphicsContext : IDisposable { private Size _bufferSize = Size.Empty; private Size _virtualSize; private Point _targetLoc; private IntPtr _compatDC; private IntPtr _dib; private IntPtr _oldBitmap; private Graphics _compatGraphics; private BufferedGraphics _buffer; private int _busy; private bool _invalidateWhenFree; private const int BufferFree = 0; // The graphics buffer is free to use. private const int BufferBusyPainting = 1; // The graphics buffer is busy being created/painting. private const int BufferBusyDisposing = 2; // The graphics buffer is busy disposing. /// <summary> /// Returns a BufferedGraphics that is matched for the specified target HDC object. /// </summary> private BufferedGraphics AllocBuffer(Graphics targetGraphics, IntPtr targetDC, Rectangle targetRectangle) { int oldBusy = Interlocked.CompareExchange(ref _busy, BufferBusyPainting, BufferFree); // In the case were we have contention on the buffer - i.e. two threads // trying to use the buffer at the same time, we just create a temp // buffermanager and have the buffer dispose of it when it is done. // if (oldBusy != BufferFree) { return AllocBufferInTempManager(targetGraphics, targetDC, targetRectangle); } Graphics surface; _targetLoc = new Point(targetRectangle.X, targetRectangle.Y); try { if (targetGraphics != null) { IntPtr destDc = targetGraphics.GetHdc(); try { surface = CreateBuffer(destDc, -_targetLoc.X, -_targetLoc.Y, targetRectangle.Width, targetRectangle.Height); } finally { targetGraphics.ReleaseHdcInternal(destDc); } } else { surface = CreateBuffer(targetDC, -_targetLoc.X, -_targetLoc.Y, targetRectangle.Width, targetRectangle.Height); } _buffer = new BufferedGraphics(surface, this, targetGraphics, targetDC, _targetLoc, _virtualSize); } catch { // Free the buffer so it can be disposed. _busy = BufferFree; throw; } return _buffer; } /// <summary> /// Fills in the fields of a BITMAPINFO so that we can create a bitmap /// that matches the format of the display. /// /// This is done by creating a compatible bitmap and calling GetDIBits /// to return the color masks. This is done with two calls. The first /// call passes in biBitCount = 0 to GetDIBits which will fill in the /// base BITMAPINFOHEADER data. The second call to GetDIBits (passing /// in the BITMAPINFO filled in by the first call) will return the color /// table or bitmasks, as appropriate. /// </summary> /// <returns>True if successful, false otherwise.</returns> private bool FillBitmapInfo(IntPtr hdc, IntPtr hpal, ref NativeMethods.BITMAPINFO_FLAT pbmi) { IntPtr hbm = IntPtr.Zero; bool bRet = false; try { // Create a dummy bitmap from which we can query color format info // about the device surface. hbm = SafeNativeMethods.CreateCompatibleBitmap(new HandleRef(null, hdc), 1, 1); if (hbm == IntPtr.Zero) { throw new OutOfMemoryException(SR.GraphicsBufferQueryFail); } pbmi.bmiHeader_biSize = Marshal.SizeOf(typeof(NativeMethods.BITMAPINFOHEADER)); pbmi.bmiColors = new byte[NativeMethods.BITMAPINFO_MAX_COLORSIZE * 4]; // Call first time to fill in BITMAPINFO header. SafeNativeMethods.GetDIBits(new HandleRef(null, hdc), new HandleRef(null, hbm), 0, 0, IntPtr.Zero, ref pbmi, NativeMethods.DIB_RGB_COLORS); if (pbmi.bmiHeader_biBitCount <= 8) { bRet = FillColorTable(hdc, hpal, ref pbmi); } else { if (pbmi.bmiHeader_biCompression == NativeMethods.BI_BITFIELDS) { // Call a second time to get the color masks. SafeNativeMethods.GetDIBits(new HandleRef(null, hdc), new HandleRef(null, hbm), 0, pbmi.bmiHeader_biHeight, IntPtr.Zero, ref pbmi, NativeMethods.DIB_RGB_COLORS); } bRet = true; } } finally { if (hbm != IntPtr.Zero) { SafeNativeMethods.DeleteObject(new HandleRef(null, hbm)); hbm = IntPtr.Zero; } } return bRet; } /// <summary> /// Initialize the color table of the BITMAPINFO pointed to by pbmi. Colors /// are set to the current system palette. /// /// Note: call only valid for displays of 8bpp or less. /// </summary> /// <returns>True is successful, false otherwise.</returns> private unsafe bool FillColorTable(IntPtr hdc, IntPtr hpal, ref NativeMethods.BITMAPINFO_FLAT pbmi) { byte[] aj = new byte[sizeof(NativeMethods.PALETTEENTRY) * 256]; fixed (byte* pcolors = pbmi.bmiColors) { fixed (byte* ppal = aj) { NativeMethods.RGBQUAD* prgb = (NativeMethods.RGBQUAD*)pcolors; NativeMethods.PALETTEENTRY* lppe = (NativeMethods.PALETTEENTRY*)ppal; int cColors = 1 << pbmi.bmiHeader_biBitCount; if (cColors <= 256) { // Note: we don't support 4bpp displays. uint palRet; IntPtr palHalftone = IntPtr.Zero; if (hpal == IntPtr.Zero) { palHalftone = Graphics.GetHalftonePalette(); palRet = SafeNativeMethods.GetPaletteEntries(new HandleRef(null, palHalftone), 0, cColors, aj); } else { palRet = SafeNativeMethods.GetPaletteEntries(new HandleRef(null, hpal), 0, cColors, aj); } if (palRet != 0) { for (int i = 0; i < cColors; i++) { prgb[i].rgbRed = lppe[i].peRed; prgb[i].rgbGreen = lppe[i].peGreen; prgb[i].rgbBlue = lppe[i].peBlue; prgb[i].rgbReserved = 0; } return true; } } } } return false; } /// <summary> /// Returns a Graphics object representing a buffer. /// </summary> private Graphics CreateBuffer(IntPtr src, int offsetX, int offsetY, int width, int height) { // Create the compat DC. _busy = BufferBusyDisposing; DisposeDC(); _busy = BufferBusyPainting; _compatDC = UnsafeNativeMethods.CreateCompatibleDC(new HandleRef(null, src)); // Recreate the bitmap if necessary. if (width > _bufferSize.Width || height > _bufferSize.Height) { int optWidth = Math.Max(width, _bufferSize.Width); int optHeight = Math.Max(height, _bufferSize.Height); _busy = BufferBusyDisposing; DisposeBitmap(); _busy = BufferBusyPainting; IntPtr pvbits = IntPtr.Zero; _dib = CreateCompatibleDIB(src, IntPtr.Zero, optWidth, optHeight, ref pvbits); _bufferSize = new Size(optWidth, optHeight); } // Select the bitmap. _oldBitmap = SafeNativeMethods.SelectObject(new HandleRef(this, _compatDC), new HandleRef(this, _dib)); // Create compat graphics. _compatGraphics = Graphics.FromHdcInternal(_compatDC); _compatGraphics.TranslateTransform(-_targetLoc.X, -_targetLoc.Y); _virtualSize = new Size(width, height); return _compatGraphics; } /// <summary> /// Create a DIB section with an optimal format w.r.t. the specified hdc. /// /// If DIB &lt;= 8bpp, then the DIB color table is initialized based on the /// specified palette. If the palette handle is NULL, then the system /// palette is used. /// /// Note: The hdc must be a direct DC (not an info or memory DC). /// /// Note: On palettized displays, if the system palette changes the /// UpdateDIBColorTable function should be called to maintain /// the identity palette mapping between the DIB and the display. /// </summary> /// <returns>A valid bitmap handle if successful, IntPtr.Zero otherwise.</returns> private IntPtr CreateCompatibleDIB(IntPtr hdc, IntPtr hpal, int ulWidth, int ulHeight, ref IntPtr ppvBits) { if (hdc == IntPtr.Zero) { throw new ArgumentNullException(nameof(hdc)); } IntPtr hbmRet = IntPtr.Zero; var pbmi = new NativeMethods.BITMAPINFO_FLAT(); // Validate hdc. int objType = UnsafeNativeMethods.GetObjectType(new HandleRef(null, hdc)); switch (objType) { case NativeMethods.OBJ_DC: case NativeMethods.OBJ_METADC: case NativeMethods.OBJ_MEMDC: case NativeMethods.OBJ_ENHMETADC: break; default: throw new ArgumentException(SR.DCTypeInvalid); } if (FillBitmapInfo(hdc, hpal, ref pbmi)) { // Change bitmap size to match specified dimensions. pbmi.bmiHeader_biWidth = ulWidth; pbmi.bmiHeader_biHeight = ulHeight; if (pbmi.bmiHeader_biCompression == NativeMethods.BI_RGB) { pbmi.bmiHeader_biSizeImage = 0; } else { if (pbmi.bmiHeader_biBitCount == 16) { pbmi.bmiHeader_biSizeImage = ulWidth * ulHeight * 2; } else if (pbmi.bmiHeader_biBitCount == 32) { pbmi.bmiHeader_biSizeImage = ulWidth * ulHeight * 4; } else { pbmi.bmiHeader_biSizeImage = 0; } } pbmi.bmiHeader_biClrUsed = 0; pbmi.bmiHeader_biClrImportant = 0; // Create the DIB section. Let Win32 allocate the memory and return // a pointer to the bitmap surface. hbmRet = SafeNativeMethods.CreateDIBSection(new HandleRef(null, hdc), ref pbmi, NativeMethods.DIB_RGB_COLORS, ref ppvBits, IntPtr.Zero, 0); Win32Exception ex = null; if (hbmRet == IntPtr.Zero) { ex = new Win32Exception(Marshal.GetLastWin32Error()); } if (ex != null) { throw ex; } } return hbmRet; } /// <summary> /// Disposes the DC, but leaves the bitmap alone. /// </summary> private void DisposeDC() { if (_oldBitmap != IntPtr.Zero && _compatDC != IntPtr.Zero) { SafeNativeMethods.SelectObject(new HandleRef(this, _compatDC), new HandleRef(this, _oldBitmap)); _oldBitmap = IntPtr.Zero; } if (_compatDC != IntPtr.Zero) { UnsafeNativeMethods.DeleteDC(new HandleRef(this, _compatDC)); _compatDC = IntPtr.Zero; } } /// <summary> /// Disposes the bitmap, will ASSERT if bitmap is being used (checks oldbitmap). if ASSERTed, call DisposeDC() first. /// </summary> private void DisposeBitmap() { if (_dib != IntPtr.Zero) { Debug.Assert(_oldBitmap == IntPtr.Zero); SafeNativeMethods.DeleteObject(new HandleRef(this, _dib)); _dib = IntPtr.Zero; } } /// <summary> /// Disposes of the Graphics buffer. /// </summary> private void Dispose(bool disposing) { int oldBusy = Interlocked.CompareExchange(ref _busy, BufferBusyDisposing, BufferFree); if (disposing) { if (oldBusy == BufferBusyPainting) { throw new InvalidOperationException(SR.GraphicsBufferCurrentlyBusy); } if (_compatGraphics != null) { _compatGraphics.Dispose(); _compatGraphics = null; } } DisposeDC(); DisposeBitmap(); if (_buffer != null) { _buffer.Dispose(); _buffer = null; } _bufferSize = Size.Empty; _virtualSize = Size.Empty; _busy = BufferFree; } /// <summary> /// Invalidates the cached graphics buffer. /// </summary> public void Invalidate() { int oldBusy = Interlocked.CompareExchange(ref _busy, BufferBusyDisposing, BufferFree); // If we're not busy with our buffer, lets clean it up now if (oldBusy == BufferFree) { Dispose(); _busy = BufferFree; } else { // This will indicate to free the buffer as soon as it becomes non-busy. _invalidateWhenFree = true; } } /// <summary> /// Returns a Graphics object representing a buffer. /// </summary> internal void ReleaseBuffer(BufferedGraphics buffer) { _buffer = null; if (_invalidateWhenFree) { // Clears everything including the bitmap. _busy = BufferBusyDisposing; Dispose(); } else { // Otherwise, just dispose the DC. A new one will be created next time. _busy = BufferBusyDisposing; // Only clears out the DC. DisposeDC(); } _busy = BufferFree; } } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.IO; using System.Net; using System.Text; using System.Web; using System.Xml; namespace AlchemyAPI { public class AlchemyAPI { private string _apiKey; private string _requestUri; public AlchemyAPI() { _apiKey = ""; _requestUri = "http://access.alchemyapi.com/calls/"; } public void SetAPIHost(string apiHost) { if (apiHost.Length < 2) { System.ApplicationException ex = new System.ApplicationException("Error setting API host."); throw ex; } _requestUri = "http://" + apiHost + ".alchemyapi.com/calls/"; } public void SetAPIKey(string apiKey) { _apiKey = apiKey; if (_apiKey.Length < 5) { System.ApplicationException ex = new System.ApplicationException("Error setting API key."); throw ex; } } public void LoadAPIKey(string filename) { StreamReader reader; reader = File.OpenText(filename); string line = reader.ReadLine(); reader.Close(); _apiKey = line.Trim(); if (_apiKey.Length < 5) { System.ApplicationException ex = new System.ApplicationException("Error loading API key."); throw ex; } } #region GetAuthor public string URLGetAuthor(string url) { CheckURL(url); return URLGetAuthor(url, new AlchemyAPI_BaseParams()); } public string URLGetAuthor(string url, AlchemyAPI_BaseParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetAuthor", "url", parameters); } public string HTMLGetAuthor(string html,string url) { CheckHTML(html, url); return HTMLGetAuthor(html, url, new AlchemyAPI_BaseParams()); } public string HTMLGetAuthor(string html, string url, AlchemyAPI_BaseParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetAuthor", "html", parameters); } #endregion #region GetRankedNamedEntities public string URLGetRankedNamedEntities(string url) { CheckURL(url); return URLGetRankedNamedEntities(url, new AlchemyAPI_EntityParams()); } public string URLGetRankedNamedEntities(string url, AlchemyAPI_EntityParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetRankedNamedEntities", "url", parameters); } public string HTMLGetRankedNamedEntities(string html, string url) { CheckHTML(html, url); return HTMLGetRankedNamedEntities(html, url, new AlchemyAPI_EntityParams()); } public string HTMLGetRankedNamedEntities(string html, string url, AlchemyAPI_EntityParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetRankedNamedEntities", "html", parameters); } public string TextGetRankedNamedEntities(string text) { CheckText(text); return TextGetRankedNamedEntities(text,new AlchemyAPI_EntityParams()); } public string TextGetRankedNamedEntities(string text, AlchemyAPI_EntityParams parameters) { CheckText(text); parameters.setText(text); return POST("TextGetRankedNamedEntities", "text", parameters); } #endregion #region GetRankedConcepts public string URLGetRankedConcepts(string url) { CheckURL(url); return URLGetRankedConcepts(url, new AlchemyAPI_ConceptParams()); } public string URLGetRankedConcepts(string url, AlchemyAPI_ConceptParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetRankedConcepts", "url", parameters); } public string HTMLGetRankedConcepts(string html, string url) { CheckHTML(html, url); return HTMLGetRankedConcepts(html, url, new AlchemyAPI_ConceptParams()); } public string HTMLGetRankedConcepts(string html, string url, AlchemyAPI_ConceptParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetRankedConcepts", "html", parameters); } public string TextGetRankedConcepts(string text) { CheckText(text); return TextGetRankedConcepts(text,new AlchemyAPI_ConceptParams()); } public string TextGetRankedConcepts(string text, AlchemyAPI_ConceptParams parameters) { CheckText(text); parameters.setText(text); return POST("TextGetRankedConcepts", "text", parameters); } #endregion #region GetRankedKeywords public string URLGetRankedKeywords(string url) { CheckURL(url); return URLGetRankedKeywords(url, new AlchemyAPI_KeywordParams()); } public string URLGetRankedKeywords(string url, AlchemyAPI_KeywordParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetRankedKeywords", "url", parameters); } public string HTMLGetRankedKeywords(string html, string url) { CheckHTML(html, url); return HTMLGetRankedKeywords(html, url, new AlchemyAPI_KeywordParams()); } public string HTMLGetRankedKeywords(string html, string url, AlchemyAPI_KeywordParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetRankedKeywords", "html", parameters); } public string TextGetRankedKeywords(string text) { CheckText(text); return TextGetRankedKeywords(text,new AlchemyAPI_KeywordParams()); } public string TextGetRankedKeywords(string text, AlchemyAPI_KeywordParams parameters) { CheckText(text); parameters.setText(text); return POST("TextGetRankedKeywords", "text", parameters); } #endregion #region GetLanguage public string URLGetLanguage(string url) { CheckURL(url); return URLGetLanguage(url,new AlchemyAPI_LanguageParams()); } public string URLGetLanguage(string url, AlchemyAPI_LanguageParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetLanguage", "url", parameters); } public string HTMLGetLanguage(string html, string url) { CheckHTML(html, url); return HTMLGetLanguage(html,url,new AlchemyAPI_LanguageParams()); } public string HTMLGetLanguage(string html, string url, AlchemyAPI_LanguageParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetLanguage", "html", parameters); } public string TextGetLanguage(string text) { CheckText(text); return TextGetLanguage(text, new AlchemyAPI_LanguageParams()); } public string TextGetLanguage(string text, AlchemyAPI_LanguageParams parameters) { CheckText(text); parameters.setText(text); return POST("TextGetLanguage", "text", parameters); } #endregion #region GetCategory public string URLGetCategory(string url) { CheckURL(url); return URLGetCategory(url, new AlchemyAPI_CategoryParams() ); } public string URLGetCategory(string url, AlchemyAPI_CategoryParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetCategory", "url", parameters); } public string HTMLGetCategory(string html, string url) { CheckHTML(html, url); return HTMLGetCategory(html, url, new AlchemyAPI_CategoryParams()); } public string HTMLGetCategory(string html, string url, AlchemyAPI_CategoryParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetCategory", "html", parameters); } public string TextGetCategory(string text) { CheckText(text); return TextGetCategory(text, new AlchemyAPI_CategoryParams()); } public string TextGetCategory(string text, AlchemyAPI_CategoryParams parameters) { CheckText(text); parameters.setText(text); return POST("TextGetCategory", "text", parameters); } #endregion #region GetText public string URLGetText(string url) { CheckURL(url); return URLGetText(url, new AlchemyAPI_TextParams()); } public string URLGetText(string url, AlchemyAPI_TextParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetText", "url", parameters); } public string HTMLGetText(string html, string url) { CheckHTML(html, url); return HTMLGetText(html,url, new AlchemyAPI_TextParams()); } public string HTMLGetText(string html, string url,AlchemyAPI_TextParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetText", "html", parameters); } #endregion #region GetRawText public string URLGetRawText(string url) { CheckURL(url); return URLGetRawText(url, new AlchemyAPI_BaseParams()); } public string URLGetRawText(string url, AlchemyAPI_BaseParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetRawText", "url", parameters); } public string HTMLGetRawText(string html, string url) { CheckHTML(html, url); return HTMLGetRawText(html, url, new AlchemyAPI_BaseParams()); } public string HTMLGetRawText(string html, string url, AlchemyAPI_BaseParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetRawText", "html", parameters); } #endregion #region GetTitle public string URLGetTitle(string url) { CheckURL(url); return URLGetTitle(url, new AlchemyAPI_BaseParams()); } public string URLGetTitle(string url, AlchemyAPI_BaseParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetTitle", "url", parameters); } public string HTMLGetTitle(string html, string url) { CheckHTML(html, url); return HTMLGetTitle(html, url, new AlchemyAPI_BaseParams()); } public string HTMLGetTitle(string html, string url, AlchemyAPI_BaseParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetTitle", "html", parameters); } #endregion #region GetFeedLinks public string URLGetFeedLinks(string url) { CheckURL(url); return URLGetFeedLinks(url, new AlchemyAPI_BaseParams()); } public string URLGetFeedLinks(string url, AlchemyAPI_BaseParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetFeedLinks", "url", parameters); } public string HTMLGetFeedLinks(string html, string url) { CheckHTML(html, url); return HTMLGetFeedLinks(html,url, new AlchemyAPI_BaseParams()); } public string HTMLGetFeedLinks(string html, string url, AlchemyAPI_BaseParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetFeedLinks", "html", parameters); } #endregion #region GetMicroformats public string URLGetMicroformats(string url) { CheckURL(url); return URLGetMicroformats(url, new AlchemyAPI_BaseParams()); } public string URLGetMicroformats(string url, AlchemyAPI_BaseParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetMicroformatData", "url", parameters); } public string HTMLGetMicroformats(string html, string url) { CheckHTML(html, url); return HTMLGetMicroformats(html,url, new AlchemyAPI_BaseParams()); } public string HTMLGetMicroformats(string html, string url, AlchemyAPI_BaseParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetMicroformatData", "html", parameters); } #endregion #region GetConstraintQuery public string URLGetConstraintQuery(string url, string query) { CheckURL(url); if (query.Length < 2) { System.ApplicationException ex = new System.ApplicationException("Invalid constraint query specified."); throw ex; } AlchemyAPI_ConstraintQueryParams cqParams = new AlchemyAPI_ConstraintQueryParams(); cqParams.setCQuery(query); return URLGetConstraintQuery(url,cqParams); } public string URLGetConstraintQuery(string url, AlchemyAPI_ConstraintQueryParams parameters) { CheckURL(url); if (parameters.getCQuery().Length < 2) { System.ApplicationException ex = new System.ApplicationException("Invalid constraint query specified."); throw ex; } parameters.setUrl(url); return POST("URLGetConstraintQuery", "url", parameters); } public string HTMLGetConstraintQuery(string html, string url, string query) { CheckHTML(html, url); if (query.Length < 2) { System.ApplicationException ex = new System.ApplicationException("Invalid constraint query specified."); throw ex; } AlchemyAPI_ConstraintQueryParams cqParams = new AlchemyAPI_ConstraintQueryParams(); cqParams.setCQuery(query); return HTMLGetConstraintQuery(html, url, cqParams); } public string HTMLGetConstraintQuery(string html, string url, AlchemyAPI_ConstraintQueryParams parameters) { CheckHTML(html, url); if (parameters.getCQuery().Length < 2) { System.ApplicationException ex = new System.ApplicationException("Invalid constraint query specified."); throw ex; } parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetConstraintQuery", "html", parameters); } #endregion #region GetTextSentiment public string URLGetTextSentiment(string url) { CheckURL(url); return URLGetTextSentiment(url, new AlchemyAPI_BaseParams()); } public string URLGetTextSentiment(string url, AlchemyAPI_BaseParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetTextSentiment", "url", parameters); } public string HTMLGetTextSentiment(string html, string url) { CheckHTML(html, url); return HTMLGetTextSentiment(html, url, new AlchemyAPI_BaseParams()); } public string HTMLGetTextSentiment(string html, string url, AlchemyAPI_BaseParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetTextSentiment", "html", parameters); } public string TextGetTextSentiment(string text) { CheckText(text); return TextGetTextSentiment(text,new AlchemyAPI_BaseParams()); } public string TextGetTextSentiment(string text, AlchemyAPI_BaseParams parameters) { CheckText(text); parameters.setText(text); return POST("TextGetTextSentiment", "text", parameters); } #endregion #region GetTargetedSentiment public string URLGetTargetedSentiment(string url, string target) { CheckURL(url); CheckText(target); return URLGetTargetedSentiment(url, target, new AlchemyAPI_TargetedSentimentParams()); } public string URLGetTargetedSentiment(string url, string target, AlchemyAPI_TargetedSentimentParams parameters) { CheckURL(url); CheckText(target); parameters.setUrl(url); parameters.setTarget(target); return GET("URLGetTargetedSentiment", "url", parameters); } public string HTMLGetTargetedSentiment(string html, string url, string target) { CheckHTML(html, url); CheckText(target); return HTMLGetTargetedSentiment(html, url, target, new AlchemyAPI_TargetedSentimentParams()); } public string HTMLGetTargetedSentiment(string html, string url, string target, AlchemyAPI_TargetedSentimentParams parameters) { CheckHTML(html, url); CheckText(target); parameters.setHtml(html); parameters.setUrl(url); parameters.setTarget(target); return POST("HTMLGetTargetedSentiment", "html", parameters); } public string TextGetTargetedSentiment(string text, string target) { CheckText(text); CheckText(target); return TextGetTargetedSentiment(text, target, new AlchemyAPI_TargetedSentimentParams()); } public string TextGetTargetedSentiment(string text, string target, AlchemyAPI_TargetedSentimentParams parameters) { CheckText(text); CheckText(target); parameters.setText(text); parameters.setTarget(target); return POST("TextGetTargetedSentiment", "text", parameters); } #endregion #region GetRelations public string URLGetRelations(string url) { CheckURL(url); return URLGetRelations(url, new AlchemyAPI_RelationParams()); } public string URLGetRelations(string url, AlchemyAPI_RelationParams parameters) { CheckURL(url); parameters.setUrl(url); return GET("URLGetRelations", "url", parameters); } public string HTMLGetRelations(string html, string url) { CheckHTML(html, url); return HTMLGetRelations(html, url, new AlchemyAPI_RelationParams()); } public string HTMLGetRelations(string html, string url, AlchemyAPI_RelationParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST("HTMLGetRelations", "html", parameters); } public string TextGetRelations(string text) { CheckText(text); return TextGetRelations(text,new AlchemyAPI_RelationParams()); } public string TextGetRelations(string text, AlchemyAPI_RelationParams parameters) { CheckText(text); parameters.setText(text); return POST("TextGetRelations", "text", parameters); } #endregion #region GetCombinedData public string URLGetCombinedData(string url, AlchemyAPI_CombinedDataParams parameters) { CheckURL(url); parameters.setUrl(url); return GET ("URLGetCombinedData", "url", parameters); } public string TextGetCombinedData(string text, AlchemyAPI_CombinedDataParams parameters) { CheckText(text); parameters.setText(text); return POST ("TextGetCombinedData", "text", parameters); } #endregion #region GetRankedTaxonomy public string URLGetRankedTaxonomy (string url) { return URLGetRankedTaxonomy(url, new AlchemyAPI_TaxonomyParams()); } public string URLGetRankedTaxonomy (string url, AlchemyAPI_TaxonomyParams parameters) { CheckURL(url); parameters.setUrl(url); return GET ("URLGetRankedTaxonomy", "url", parameters); } public string HTMLGetRankedTaxonomy (string html, string url) { return HTMLGetRankedTaxonomy(html, url, new AlchemyAPI_TaxonomyParams()); } public string HTMLGetRankedTaxonomy (string html, string url, AlchemyAPI_TaxonomyParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST ("HTMLGetRankedTaxonomy", "html", parameters); } public string TextGetRankedTaxonomy (string text) { return TextGetRankedTaxonomy(text, new AlchemyAPI_TaxonomyParams()); } public string TextGetRankedTaxonomy (string text, AlchemyAPI_TaxonomyParams parameters) { CheckText(text); parameters.setText(text); return POST ("TextGetRankedTaxonomy", "text", parameters); } #endregion #region GetImage public string HTMLGetImage (string html, string url) { return HTMLGetImage(html, url, new AlchemyAPI_ImageParams()); } public string HTMLGetImage (string html, string url, AlchemyAPI_ImageParams parameters) { CheckHTML(html, url); parameters.setHtml(html); parameters.setUrl(url); return POST ("HTMLGetImage", "html", parameters); } public string URLGetImage (string url) { return URLGetImage (url, new AlchemyAPI_ImageParams()); } public string URLGetImage (string url, AlchemyAPI_ImageParams parameters) { CheckURL(url); parameters.setUrl(url); return GET ("URLGetImage", "url", parameters); } #endregion #region GetRankedImageKeywords public string URLGetRankedImageKeywords(string url) { AlchemyAPI_RankedImageKeywords pms = new AlchemyAPI_RankedImageKeywords { ImageURL = url }; return URLGetRankedImageKeywords(pms); } public string URLGetRankedImageKeywords(AlchemyAPI_RankedImageKeywords parameters) { CheckURL(parameters.ImageURL); return GET("URLGetRankedImageKeywords", "url", parameters); } public string ImageGetRankedImageKeywords(AlchemyAPI_RankedImageKeywords parameters) { return GET("ImageGetRankedImageKeywords", "image", parameters); } #endregion private void CheckHTML(string html, string url) { if (html.Length < 10) { System.ApplicationException ex = new System.ApplicationException ("Enter a HTML document to analyze."); throw ex; } if (url.Length < 10) { System.ApplicationException ex = new System.ApplicationException ("Enter a web URL to analyze."); throw ex; } } private void CheckText(string text) { if (text.Length < 5) { System.ApplicationException ex = new System.ApplicationException ("Enter some text to analyze."); throw ex; } } private void CheckURL(string url) { if (url.Length < 10) { System.ApplicationException ex = new System.ApplicationException ("Enter a web URL to analyze."); throw ex; } } private string GET(string callName, string callPrefix, AlchemyAPI_BaseParams parameters) { // callMethod, callPrefix, ... params StringBuilder uri = new StringBuilder (); uri.Append(_requestUri).Append(callPrefix).Append("/").Append(callName); uri.Append("?apikey=").Append(_apiKey).Append(parameters.getParameterString()); parameters.resetBaseParams(); Uri address = new Uri (uri.ToString()); HttpWebRequest wreq = WebRequest.Create(address) as HttpWebRequest; wreq.Proxy = null; byte[] postData = parameters.GetPostData(); if (postData == null) { wreq.Method = "GET"; } else { wreq.Method = "POST"; using (var ps = wreq.GetRequestStream()) { ps.Write(postData, 0, postData.Length); } } return DoRequest(wreq, parameters.getOutputMode()); } private string POST(string callName, string callPrefix, AlchemyAPI_BaseParams parameters) { // callMethod, callPrefix, ... params Uri address = new Uri (_requestUri + callPrefix + "/" + callName); HttpWebRequest wreq = WebRequest.Create(address) as HttpWebRequest; wreq.Proxy = null; wreq.Method = "POST"; wreq.ContentType = "application/x-www-form-urlencoded"; StringBuilder d = new StringBuilder (); d.Append("apikey=").Append(_apiKey).Append(parameters.getParameterString()); parameters.resetBaseParams(); byte[] bd = UTF8Encoding.UTF8.GetBytes(d.ToString()); wreq.ContentLength = bd.Length; using (Stream ps = wreq.GetRequestStream()) { ps.Write(bd, 0, bd.Length); } return DoRequest(wreq, parameters.getOutputMode()); } private string DoRequest(HttpWebRequest wreq, AlchemyAPI_BaseParams.OutputMode outputMode) { using (HttpWebResponse wres = wreq.GetResponse() as HttpWebResponse) { StreamReader r = new StreamReader (wres.GetResponseStream()); string xml = r.ReadToEnd(); if (string.IsNullOrEmpty(xml)) throw new XmlException ("The API request returned back an empty response. Please verify that the url is correct."); XmlDocument xmlDoc = new XmlDocument (); xmlDoc.LoadXml(xml); XmlElement root = xmlDoc.DocumentElement; if (AlchemyAPI_BaseParams.OutputMode.XML == outputMode) { XmlNode status = root.SelectSingleNode("/results/status"); if (status.InnerText != "OK") { string errorMessage = "Error making API call."; try { XmlNode statusInfo = root.SelectSingleNode("/results/statusInfo"); errorMessage = statusInfo.InnerText; } catch { errorMessage = "An error occurred: Unable to access XmlNode /results/statusInfo"; } System.ApplicationException ex = new System.ApplicationException (errorMessage); throw ex; } } else if (AlchemyAPI_BaseParams.OutputMode.RDF == outputMode) { XmlNamespaceManager nm = new XmlNamespaceManager (xmlDoc.NameTable); nm.AddNamespace("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"); nm.AddNamespace("aapi", "http://rdf.alchemyapi.com/rdf/v1/s/aapi-schema#"); XmlNode status = root.SelectSingleNode("/rdf:RDF/rdf:Description/aapi:ResultStatus", nm); if (status.InnerText != "OK") { string errorMessage = "Error making API call."; try { XmlNode statusInfo = root.SelectSingleNode("/results/statusInfo"); errorMessage = statusInfo.InnerText; } catch { errorMessage = "An error occurred: Unable to access XmlNode /results/statusInfo"; } System.ApplicationException ex = new System.ApplicationException (errorMessage); throw ex; } } return xml; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Xunit; using Validation; using System.Diagnostics; namespace System.Collections.Immutable.Test { public abstract class ImmutableListTestBase : SimpleElementImmutablesTestBase { #if NET45PLUS internal abstract ImmutableList<T> GetListQuery<T>(ImmutableList<T> list); #else internal abstract IImmutableListQueries<T> GetListQuery<T>(ImmutableList<T> list); #endif [Fact] public void CopyToEmptyTest() { var array = new int[0]; this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(array, 0); this.GetListQuery(ImmutableList<int>.Empty).CopyTo(0, array, 0, 0); ((ICollection)this.GetListQuery(ImmutableList<int>.Empty)).CopyTo(array, 0); } [Fact] public void CopyToTest() { var listQuery = this.GetListQuery(ImmutableList.Create(1, 2)); var list = (IEnumerable<int>)listQuery; var array = new int[2]; listQuery.CopyTo(array); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(array, 0); Assert.Equal(list, array); array = new int[2]; listQuery.CopyTo(0, array, 0, listQuery.Count); Assert.Equal(list, array); array = new int[1]; // shorter than source length listQuery.CopyTo(0, array, 0, array.Length); Assert.Equal(list.Take(array.Length), array); array = new int[3]; listQuery.CopyTo(1, array, 2, 1); Assert.Equal(new[] { 0, 0, 2 }, array); array = new int[2]; ((ICollection)listQuery).CopyTo(array, 0); Assert.Equal(list, array); } [Fact] public void ForEachTest() { this.GetListQuery(ImmutableList<int>.Empty).ForEach(n => Assert.True(false, "Empty list should not invoke this.")); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 3)); var hitTest = new bool[list.Max() + 1]; this.GetListQuery(list).ForEach(i => { Assert.False(hitTest[i]); hitTest[i] = true; }); for (int i = 0; i < hitTest.Length; i++) { Assert.Equal(list.Contains(i), hitTest[i]); Assert.Equal(((IList)list).Contains(i), hitTest[i]); } } [Fact] public void ExistsTest() { Assert.False(this.GetListQuery(ImmutableList<int>.Empty).Exists(n => true)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 5)); Assert.True(this.GetListQuery(list).Exists(n => n == 3)); Assert.False(this.GetListQuery(list).Exists(n => n == 8)); } [Fact] public void FindAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).FindAll(n => true).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); var actual = this.GetListQuery(list).FindAll(n => n % 2 == 1); var expected = list.ToList().FindAll(n => n % 2 == 1); Assert.Equal<int>(expected, actual.ToList()); } [Fact] public void FindTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).Find(n => true)); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(3, this.GetListQuery(list).Find(n => (n % 2) == 1)); } [Fact] public void FindLastTest() { Assert.Equal(0, this.GetListQuery(ImmutableList<int>.Empty).FindLast(n => { Assert.True(false, "Predicate should not have been invoked."); return true; })); var list = ImmutableList<int>.Empty.AddRange(new[] { 2, 3, 4, 5, 6 }); Assert.Equal(5, this.GetListQuery(list).FindLast(n => (n % 2) == 1)); } [Fact] public void FindIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= list.Count - idx; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == 0) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void FindLastIndexTest() { Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, n => true)); Assert.Equal(-1, this.GetListQuery(ImmutableList<int>.Empty).FindLastIndex(0, 0, n => true)); // Create a list with contents: 100,101,102,103,104,100,101,102,103,104 var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(100, 5).Concat(Enumerable.Range(100, 5))); var bclList = list.ToList(); Assert.Equal(-1, this.GetListQuery(list).FindLastIndex(n => n == 6)); for (int idx = 0; idx < list.Count; idx++) { for (int count = 0; count <= idx + 1; count++) { foreach (int c in list) { int predicateInvocationCount = 0; Predicate<int> match = n => { predicateInvocationCount++; return n == c; }; int expected = bclList.FindLastIndex(idx, count, match); int expectedInvocationCount = predicateInvocationCount; predicateInvocationCount = 0; int actual = this.GetListQuery(list).FindLastIndex(idx, count, match); int actualInvocationCount = predicateInvocationCount; Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (count == list.Count) { // Also test the FindIndex overload that takes no count parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(idx, match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); if (idx == list.Count - 1) { // Also test the FindIndex overload that takes no index parameter. predicateInvocationCount = 0; actual = this.GetListQuery(list).FindLastIndex(match); Assert.Equal(expected, actual); Assert.Equal(expectedInvocationCount, actualInvocationCount); } } } } } } [Fact] public void ConvertAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).ConvertAll<float>(n => n).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); Func<int, double> converter = n => 2.0 * n; var expected = list.ToList().Select(converter).ToList(); var actual = this.GetListQuery(list).ConvertAll(converter); Assert.Equal<double>(expected.ToList(), actual.ToList()); } [Fact] public void GetRangeTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).GetRange(0, 0).IsEmpty); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); var bclList = list.ToList(); for (int index = 0; index < list.Count; index++) { for (int count = 0; count < list.Count - index; count++) { var expected = bclList.GetRange(index, count); var actual = this.GetListQuery(list).GetRange(index, count); Assert.Equal<int>(expected.ToList(), actual.ToList()); } } } [Fact] public void TrueForAllTest() { Assert.True(this.GetListQuery(ImmutableList<int>.Empty).TrueForAll(n => false)); var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.TrueForAllTestHelper(list, n => n % 2 == 0); this.TrueForAllTestHelper(list, n => n % 2 == 1); this.TrueForAllTestHelper(list, n => true); } [Fact] public void RemoveAllTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); this.RemoveAllTestHelper(list, n => false); this.RemoveAllTestHelper(list, n => true); this.RemoveAllTestHelper(list, n => n < 7); this.RemoveAllTestHelper(list, n => n > 7); this.RemoveAllTestHelper(list, n => n == 7); } [Fact] public void ReverseTest() { var list = ImmutableList<int>.Empty.AddRange(Enumerable.Range(5, 10)); for (int i = 0; i < list.Count; i++) { for (int j = 0; j < list.Count - i; j++) { this.ReverseTestHelper(list, i, j); } } } [Fact] public void SortTest() { var scenarios = new[] { ImmutableList<int>.Empty, ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50)), ImmutableList<int>.Empty.AddRange(Enumerable.Range(1, 50).Reverse()), }; foreach (var scenario in scenarios) { var expected = scenario.ToList(); expected.Sort(); var actual = this.SortTestHelper(scenario); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); Comparison<int> comparison = (x, y) => x > y ? 1 : (x < y ? -1 : 0); expected.Sort(comparison); actual = this.SortTestHelper(scenario, comparison); Assert.Equal<int>(expected, actual); expected = scenario.ToList(); IComparer<int> comparer = Comparer<int>.Default; expected.Sort(comparer); actual = this.SortTestHelper(scenario, comparer); Assert.Equal<int>(expected, actual); for (int i = 0; i < scenario.Count; i++) { for (int j = 0; j < scenario.Count - i; j++) { expected = scenario.ToList(); comparer = Comparer<int>.Default; expected.Sort(i, j, comparer); actual = this.SortTestHelper(scenario, i, j, comparer); Assert.Equal<int>(expected, actual); } } } } [Fact] public void BinarySearch() { var basis = new List<int>(Enumerable.Range(1, 50).Select(n => n * 2)); var query = this.GetListQuery(basis.ToImmutableList()); for (int value = basis.First() - 1; value <= basis.Last() + 1; value++) { int expected = basis.BinarySearch(value); int actual = query.BinarySearch(value); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); for (int index = 0; index < basis.Count - 1; index++) { for (int count = 0; count <= basis.Count - index; count++) { expected = basis.BinarySearch(index, count, value, null); actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void BinarySearchPartialSortedList() { var reverseSorted = ImmutableArray.CreateRange(Enumerable.Range(1, 150).Select(n => n * 2).Reverse()); this.BinarySearchPartialSortedListHelper(reverseSorted, 0, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 50, 50); this.BinarySearchPartialSortedListHelper(reverseSorted, 100, 50); } private void BinarySearchPartialSortedListHelper(ImmutableArray<int> inputData, int sortedIndex, int sortedLength) { #if !NET45PLUS Requires.Range(sortedIndex >= 0, "sortedIndex"); Requires.Range(sortedLength > 0, "sortedLength"); #endif inputData = inputData.Sort(sortedIndex, sortedLength, Comparer<int>.Default); int min = inputData[sortedIndex]; int max = inputData[sortedIndex + sortedLength - 1]; var basis = new List<int>(inputData); var query = this.GetListQuery(inputData.ToImmutableList()); for (int value = min - 1; value <= max + 1; value++) { for (int index = sortedIndex; index < sortedIndex + sortedLength; index++) // make sure the index we pass in is always within the sorted range in the list. { for (int count = 0; count <= sortedLength - index; count++) { int expected = basis.BinarySearch(index, count, value, null); int actual = query.BinarySearch(index, count, value, null); if (expected != actual) Debugger.Break(); Assert.Equal(expected, actual); } } } } [Fact] public void SyncRoot() { var collection = (ICollection)this.GetEnumerableOf<int>(); Assert.NotNull(collection.SyncRoot); Assert.Same(collection.SyncRoot, collection.SyncRoot); } [Fact] public void GetEnumeratorTest() { var enumerable = this.GetEnumerableOf(1); Assert.Equal(new[] { 1 }, enumerable.ToList()); // exercises the enumerator IEnumerable enumerableNonGeneric = enumerable; Assert.Equal(new[] { 1 }, enumerableNonGeneric.Cast<int>().ToList()); // exercises the enumerator } protected abstract void RemoveAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test); protected abstract void ReverseTestHelper<T>(ImmutableList<T> list, int index, int count); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, Comparison<T> comparison); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, IComparer<T> comparer); protected abstract List<T> SortTestHelper<T>(ImmutableList<T> list, int index, int count, IComparer<T> comparer); private void TrueForAllTestHelper<T>(ImmutableList<T> list, Predicate<T> test) { var bclList = list.ToList(); var expected = bclList.TrueForAll(test); var actual = this.GetListQuery(list).TrueForAll(test); Assert.Equal(expected, actual); } } }
// Copyright (c) 2012 DotNetAnywhere // // 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; #if LOCALTEST using System.Collections; using System.Collections.Generic; namespace System_.Collections.Generic { #else namespace System.Collections.Generic { #endif public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable { public struct Enumerator : IEnumerator<T>, IDisposable { private List<T> list; private int index; internal Enumerator(List<T> list) { this.list = list; this.index = -1; } public T Current { get { return this.list[this.index]; } } public void Dispose() { } object IEnumerator.Current { get { return this.list[this.index]; } } public bool MoveNext() { this.index++; return (this.index < this.list.Count); } public void Reset() { this.index = -1; } } private const int defaultCapacity = 4; private T[] items; private int size; public List() : this(defaultCapacity) { } public List(int capacity) { if (capacity < 0) { throw new ArgumentOutOfRangeException("capacity"); } this.items = new T[capacity]; this.size = 0; } public List(IEnumerable<T> collection) { ICollection<T> iCol = collection as ICollection<T>; if (iCol != null) { this.size = iCol.Count; this.items = new T[this.size]; iCol.CopyTo(this.items, 0); } else { this.items = new T[defaultCapacity]; this.size = 0; foreach (T item in collection) { this.Add(item); } } } private void EnsureSpace(int space) { if (this.size + space > this.items.Length) { Array.Resize<T>(ref this.items, Math.Max(this.items.Length << 1, 4)); } } private void Shift(int index, int count) { if (count > 0) { this.EnsureSpace(count); for (int i = this.size - 1; i >= index; i--) { this.items[i + count] = this.items[i]; } } else { for (int i = index; i < this.size + count; i++) { this.items[i] = this.items[i - count]; } } this.size += count; } public void Add(T item) { this.EnsureSpace(1); this.items[this.size++] = item; } public int Count { get { return this.size; } } public int Capacity { get { return this.items.Length; } set { throw new NotImplementedException(); } } public T this[int index] { get { if (index >= this.size || index < 0) { throw new ArgumentOutOfRangeException("index"); } return this.items[index]; } set { if (index >= this.size || index < 0) { throw new ArgumentOutOfRangeException("index"); } this.items[index] = value; } } public Enumerator GetEnumerator() { return new Enumerator(this); } public int IndexOf(T item, int start, int count) { return Array.IndexOf<T>(this.items, item, start, count); } public int IndexOf(T item, int start) { return this.IndexOf(item, start, this.size - start); } public void InsertRange(int index, IEnumerable<T> collection) { if (collection == null) { throw new ArgumentNullException("collection"); } if (index < 0 || index > this.size) { throw new ArgumentOutOfRangeException("index"); } List<T> toInsert = new List<T>(collection); this.Shift(index, toInsert.Count); for (int i = 0; i < toInsert.Count; i++) { this.items[index + i] = toInsert[i]; } } public T[] ToArray() { T[] array = new T[this.size]; Array.Copy(this.items, array, this.size); return array; } #region Interface Members public int IndexOf(T item) { return this.IndexOf(item, 0, size); } public void Insert(int index, T item) { if (index < 0 || index > this.size) { throw new ArgumentOutOfRangeException("index"); } this.Shift(index, 1); this.items[index] = item; } public void RemoveAt(int index) { this.Shift(index, -1); } public bool IsReadOnly { get { return false; } } public void Clear() { Array.Clear(this.items, 0, this.items.Length); this.size = 0; } public bool Contains(T item) { return Array.IndexOf(this.items, item) >= 0; } public void CopyTo(T[] array, int arrayIndex) { Array.Copy(this.items, 0, (Array)array, arrayIndex, this.size); } public bool Remove(T item) { int idx = Array.IndexOf(this.items, item); if (idx >= 0) { this.RemoveAt(idx); return true; } return false; } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this); } public bool IsFixedSize { get { return false; } } object IList.this[int index] { get { return this[index]; } set { this[index] = (T)value; } } public int Add(object value) { this.Add((T)value); return this.items.Length - 1; } public bool Contains(object value) { return this.Contains((T)value); } public int IndexOf(object value) { return this.IndexOf((T)value); } public void Insert(int index, object value) { this.Insert(index, (T)value); } public void Remove(object value) { this.Remove((T)value); } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } public void CopyTo(Array array, int index) { Array.Copy(this.items, 0, array, index, this.size); } #endregion } }
using System; using System.IO; using System.Net; using System.Runtime.Serialization; using System.Text; using System.Threading; using Funq; using NUnit.Framework; using ServiceStack.Common.Web; using ServiceStack.Service; using ServiceStack.ServiceClient.Web; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface.ServiceModel; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Support; using ServiceStack.WebHost.Endpoints.Tests.Support; using ServiceStack.WebHost.Endpoints.Tests.Support.Host; namespace ServiceStack.WebHost.Endpoints.Tests { [DataContract] [RestService("/secure")] public class Secure { [DataMember] public string UserName { get; set; } } [DataContract] public class SecureResponse : IHasResponseStatus { [DataMember] public string Result { get; set; } [DataMember] public ResponseStatus ResponseStatus { get; set; } } public class SecureService : IService<Secure> { public object Execute(Secure request) { return new SecureResponse { Result = "Confidential" }; } } [DataContract] [RestService("/insecure")] public class Insecure { [DataMember] public string UserName { get; set; } } [DataContract] public class InsecureResponse : IHasResponseStatus { [DataMember] public string Result { get; set; } [DataMember] public ResponseStatus ResponseStatus { get; set; } } public class InsecureService : IService<Insecure> { public object Execute(Insecure request) { return new InsecureResponse { Result = "Public" }; } } [TestFixture] public abstract class RequestFiltersTests { private const string ListeningOn = "http://localhost:82/"; private const string ServiceClientBaseUri = "http://localhost:82/"; private const string AllowedUser = "user"; private const string AllowedPass = "p@55word"; public class RequestFiltersAppHostHttpListener : AppHostHttpListenerBase { private Guid currentSessionGuid; public RequestFiltersAppHostHttpListener() : base("Request Filters Tests", typeof(GetFactorialService).Assembly) { } public override void Configure(Container container) { this.RequestFilters.Add((req, res, dto) => { var userPass = req.GetBasicAuthUserAndPassword(); if (userPass == null) { return; } var userName = userPass.Value.Key; if (userName == AllowedUser && userPass.Value.Value == AllowedPass) { currentSessionGuid = Guid.NewGuid(); var sessionKey = userName + "/" + currentSessionGuid.ToString("N"); //set session for this request (as no cookies will be set on this request) req.Items["ss-session"] = sessionKey; res.SetPermanentCookie("ss-session", sessionKey); } }); this.RequestFilters.Add((req, res, dto) => { if (dto is Secure) { var sessionId = req.GetItemOrCookie("ss-session") ?? string.Empty; var sessionIdParts = sessionId.SplitOnFirst('/'); if (sessionIdParts.Length < 2 || sessionIdParts[0] != AllowedUser || sessionIdParts[1] != currentSessionGuid.ToString("N")) { res.ReturnAuthRequired(); } } }); } } RequestFiltersAppHostHttpListener appHost; [TestFixtureSetUp] public void OnTestFixtureSetUp() { appHost = new RequestFiltersAppHostHttpListener(); appHost.Init(); appHost.Start(ListeningOn); } [TestFixtureTearDown] public void OnTestFixtureTearDown() { appHost.Dispose(); } protected abstract IServiceClient CreateNewServiceClient(); protected abstract IRestClientAsync CreateNewRestClientAsync(); protected virtual string GetFormat() { return null; } private static void Assert401(IServiceClient client, WebServiceException ex) { if (client is Soap11ServiceClient || client is Soap12ServiceClient) { if (ex.StatusCode != 401) { Console.WriteLine("WARNING: SOAP clients returning 500 instead of 401"); } return; } Console.WriteLine(ex); Assert.That(ex.StatusCode, Is.EqualTo(401)); } private static void FailOnAsyncError<T>(T response, Exception ex) { Assert.Fail(ex.Message); } private static bool Assert401(object response, Exception ex) { var webEx = (WebServiceException)ex; Assert.That(webEx.StatusCode, Is.EqualTo(401)); return true; } [Test] public void Can_login_with_Basic_auth_to_access_Secure_service() { var format = GetFormat(); if (format == null) return; var req = (HttpWebRequest)WebRequest.Create( string.Format("http://localhost:82/{0}/syncreply/Secure", format)); req.Headers[HttpHeaders.Authorization] = "basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(AllowedUser + ":" + AllowedPass)); var dtoString = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd(); Assert.That(dtoString.Contains("Confidential")); Console.WriteLine(dtoString); } [Test] public void Can_login_with_Basic_auth_to_access_Secure_service_using_ServiceClient() { var format = GetFormat(); if (format == null) return; var client = CreateNewServiceClient(); client.SetCredentials(AllowedUser, AllowedPass); var response = client.Send<SecureResponse>(new Secure()); Assert.That(response.Result, Is.EqualTo("Confidential")); } [Test] public void Can_login_with_Basic_auth_to_access_Secure_service_using_RestClientAsync() { var format = GetFormat(); if (format == null) return; var client = CreateNewRestClientAsync(); client.SetCredentials(AllowedUser, AllowedPass); SecureResponse response = null; client.GetAsync<SecureResponse>(ServiceClientBaseUri + "secure", r => response = r, FailOnAsyncError); Thread.Sleep(2000); Assert.That(response.Result, Is.EqualTo("Confidential")); } [Test] public void Can_login_without_authorization_to_access_Insecure_service() { var format = GetFormat(); if (format == null) return; var req = (HttpWebRequest)WebRequest.Create( string.Format("{0}{1}/syncreply/Insecure", ServiceClientBaseUri, format)); req.Headers[HttpHeaders.Authorization] = "basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(AllowedUser + ":" + AllowedPass)); var dtoString = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd(); Assert.That(dtoString.Contains("Public")); Console.WriteLine(dtoString); } [Test] public void Can_login_without_authorization_to_access_Insecure_service_using_ServiceClient() { var format = GetFormat(); if (format == null) return; var client = CreateNewServiceClient(); var response = client.Send<InsecureResponse>(new Insecure()); Assert.That(response.Result, Is.EqualTo("Public")); } [Test] public void Can_login_without_authorization_to_access_Insecure_service_using_RestClientAsync() { var format = GetFormat(); if (format == null) return; var client = CreateNewRestClientAsync(); InsecureResponse response = null; client.GetAsync<InsecureResponse>(ServiceClientBaseUri + "insecure", r => response = r, FailOnAsyncError); Thread.Sleep(2000); Assert.That(response.Result, Is.EqualTo("Public")); } [Test] public void Can_login_with_session_cookie_to_access_Secure_service() { var format = GetFormat(); if (format == null) return; var req = (HttpWebRequest)WebRequest.Create( string.Format("http://localhost:82/{0}/syncreply/Secure", format)); req.Headers[HttpHeaders.Authorization] = "basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(AllowedUser + ":" + AllowedPass)); var res = (HttpWebResponse)req.GetResponse(); var cookie = res.Cookies["ss-session"]; if (cookie != null) { req = (HttpWebRequest)WebRequest.Create( string.Format("http://localhost:82/{0}/syncreply/Secure", format)); req.CookieContainer.Add(new Cookie("ss-session", cookie.Value)); var dtoString = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd(); Assert.That(dtoString.Contains("Confidential")); Console.WriteLine(dtoString); } } [Test] public void Get_401_When_accessing_Secure_using_fake_sessionid_cookie() { var format = GetFormat(); if (format == null) return; var req = (HttpWebRequest)WebRequest.Create( string.Format("http://localhost:82/{0}/syncreply/Secure", format)); req.CookieContainer = new CookieContainer(); req.CookieContainer.Add(new Cookie("ss-session", AllowedUser + "/" + Guid.NewGuid().ToString("N"), "/", "localhost")); try { var res = req.GetResponse(); } catch (WebException x) { Assert.That(((HttpWebResponse)x.Response).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); } } [Test] public void Get_401_When_accessing_Secure_using_ServiceClient_without_Authorization() { var client = CreateNewServiceClient(); try { var response = client.Send<SecureResponse>(new Secure()); Console.WriteLine(response.Dump()); } catch (WebServiceException ex) { Assert401(client, ex); return; } Assert.Fail("Should throw WebServiceException.StatusCode == 401"); } [Test] public void Get_401_When_accessing_Secure_using_RestClient_GET_without_Authorization() { var client = CreateNewRestClientAsync(); if (client == null) return; SecureResponse response = null; var wasError = false; client.GetAsync<SecureResponse>(ServiceClientBaseUri + "secure", r => response = r, (r, ex) => wasError = Assert401(r, ex)); Thread.Sleep(1000); Assert.That(wasError, Is.True, "Should throw WebServiceException.StatusCode == 401"); Assert.IsNull(response); } [Test] public void Get_401_When_accessing_Secure_using_RestClient_DELETE_without_Authorization() { var client = CreateNewRestClientAsync(); if (client == null) return; SecureResponse response = null; var wasError = false; client.DeleteAsync<SecureResponse>(ServiceClientBaseUri + "secure", r => response = r, (r, ex) => wasError = Assert401(r, ex)); Thread.Sleep(1000); Assert.That(wasError, Is.True, "Should throw WebServiceException.StatusCode == 401"); Assert.IsNull(response); } [Test] public void Get_401_When_accessing_Secure_using_RestClient_POST_without_Authorization() { var client = CreateNewRestClientAsync(); if (client == null) return; SecureResponse response = null; var wasError = false; client.PostAsync<SecureResponse>(ServiceClientBaseUri + "secure", new Secure(), r => response = r, (r, ex) => wasError = Assert401(r, ex)); Thread.Sleep(1000); Assert.That(wasError, Is.True, "Should throw WebServiceException.StatusCode == 401"); Assert.IsNull(response); } [Test] public void Get_401_When_accessing_Secure_using_RestClient_PUT_without_Authorization() { var client = CreateNewRestClientAsync(); if (client == null) return; SecureResponse response = null; var wasError = false; client.PutAsync<SecureResponse>(ServiceClientBaseUri + "secure", new Secure(), r => response = r, (r, ex) => wasError = Assert401(r, ex)); Thread.Sleep(1000); Assert.That(wasError, Is.True, "Should throw WebServiceException.StatusCode == 401"); Assert.IsNull(response); } public class UnitTests : RequestFiltersTests { protected override IServiceClient CreateNewServiceClient() { EndpointHandlerBase.ServiceManager = new ServiceManager(true, typeof(SecureService).Assembly); return new DirectServiceClient(EndpointHandlerBase.ServiceManager); } protected override IRestClientAsync CreateNewRestClientAsync() { return null; //TODO implement REST calls with DirectServiceClient (i.e. Unit Tests) //EndpointHandlerBase.ServiceManager = new ServiceManager(true, typeof(SecureService).Assembly); //return new DirectServiceClient(EndpointHandlerBase.ServiceManager); } } public class XmlIntegrationTests : RequestFiltersTests { protected override string GetFormat() { return "xml"; } protected override IServiceClient CreateNewServiceClient() { return new XmlServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return new XmlRestClientAsync(ServiceClientBaseUri); } } [TestFixture] public class JsonIntegrationTests : RequestFiltersTests { protected override string GetFormat() { return "json"; } protected override IServiceClient CreateNewServiceClient() { return new JsonServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return new JsonRestClientAsync(ServiceClientBaseUri); } } [TestFixture] public class JsvIntegrationTests : RequestFiltersTests { protected override string GetFormat() { return "jsv"; } protected override IServiceClient CreateNewServiceClient() { return new JsvServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return new JsvRestClientAsync(ServiceClientBaseUri); } } #if !MONOTOUCH [TestFixture] public class Soap11IntegrationTests : RequestFiltersTests { protected override IServiceClient CreateNewServiceClient() { return new Soap11ServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return null; } } [TestFixture] public class Soap12IntegrationTests : RequestFiltersTests { protected override IServiceClient CreateNewServiceClient() { return new Soap12ServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return null; } } #endif } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Box.V2.Managers; using Box.V2.Models; using Box.V2.Models.Request; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Box.V2.Test { [TestClass] public class BoxRetentionPoliciesManagerTest : BoxResourceManagerTest { private readonly BoxRetentionPoliciesManager _retentionPoliciesManager; public BoxRetentionPoliciesManagerTest() { _retentionPoliciesManager = new BoxRetentionPoliciesManager(Config.Object, Service, Converter, AuthRepository); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task CreateRetentionPolicy_OptionalParams_Success() { /*** Arrange ***/ var policyName = "Tax Documents"; var retentionLength = 365; var policyType = "finite"; var policyAction = "permanently_delete"; var notifiedUserID = "12345"; var responseString = "{" + "\"type\": \"retention_policy\"," + "\"id\": \"123456789\"," + "\"policy_name\": \"" + policyName + "\"," + "\"policy_type\": \"" + policyType + "\"," + "\"retention_length\": " + retentionLength + "," + "\"disposition_action\": \"" + policyAction + "\"," + "\"status\": \"active\"," + "\"created_by\": {" + " \"type\": \"user\"," + " \"id\": \"11993747\"," + " \"name\": \"Sean\"," + " \"login\": \"sean@box.com\"" + "}," + "\"created_at\": \"2015-05-01T11:12:54-07:00\"," + "\"modified_at\": null," + "\"can_owner_extend_retention\": true," + "\"are_owners_notified\": true," + "\"custom_notification_recipients\": [" + " {" + " \"type\": \"user\"," + " \"id\": \"" + notifiedUserID + "\"" + " }" + "]" + "}"; Handler.Setup(h => h.ExecuteAsync<BoxRetentionPolicy>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxRetentionPolicy>>(new BoxResponse<BoxRetentionPolicy>() { Status = ResponseStatus.Success, ContentString = responseString })); /*** Act ***/ var requestParams = new BoxRetentionPolicyRequest { AreOwnersNotified = true, CanOwnerExtendRetention = true }; var notifiedUser = new BoxRequestEntity { Type = BoxType.user, Id = notifiedUserID }; requestParams.CustomNotificationRecipients = new List<BoxRequestEntity>() { notifiedUser }; requestParams.PolicyName = policyName; requestParams.PolicyType = policyType; requestParams.RetentionLength = retentionLength; requestParams.DispositionAction = policyAction; BoxRetentionPolicy results = await _retentionPoliciesManager.CreateRetentionPolicyAsync(requestParams); /*** Assert ***/ Assert.AreEqual(policyAction, results.DispositionAction); Assert.AreEqual(policyName, results.PolicyName); Assert.AreEqual(policyType, results.PolicyType); Assert.AreEqual(retentionLength.ToString(), results.RetentionLength); Assert.AreEqual(true, results.CanOwnerExtendRetention); Assert.AreEqual(true, results.AreOwnersNotified); Assert.IsNotNull(results.CustomNotificationRecipients); Assert.AreEqual(1, results.CustomNotificationRecipients.Count); Assert.AreEqual(notifiedUserID, results.CustomNotificationRecipients[0].Id); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task AssignPolicyToMetadataTemplate_OptionalParams_Success() { /*** Arrange ***/ var responseString = "{" + "\"type\": \"retention_policy_assignment\"," + "\"id\": \"3233225\"," + "\"retention_policy\": {" + " \"type\": \"retention_policy\"," + " \"id\": \"32131\"," + " \"policy_name\": \"TaxDocuments\"" + "}," + "\"assigned_to\": {" + " \"type\": \"metadata_template\"," + " \"id\": \"enterprise.my_template\"" + "}," + "\"assigned_by\": {" + " \"type\": \"user\"," + " \"id\": \"123456789\"," + " \"name\": \"Sean\"," + " \"login\": \"sean@box.com\"" + "}," + "\"assigned_at\": \"2015-07-20T14:28:09-07:00\"," + "\"filter_fields\": [" + " {" + " \"field\": \"foo\"," + " \"value\": \"bar\"" + " }," + " {" + " \"field\": \"baz\"," + " \"value\": 42" + " }" + "]" + "}"; Handler.Setup(h => h.ExecuteAsync<BoxRetentionPolicyAssignment>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxRetentionPolicyAssignment>>(new BoxResponse<BoxRetentionPolicyAssignment>() { Status = ResponseStatus.Success, ContentString = responseString })); /*** Act ***/ var assignmentParams = new BoxRetentionPolicyAssignmentRequest { AssignTo = new BoxRequestEntity { Type = BoxType.metadata_template, Id = "enterprise.my_template" }, FilterFields = new List<object> { new { field = "foo", value = "bar" }, new { field = "baz", value = 42 } } }; BoxRetentionPolicyAssignment result = await _retentionPoliciesManager.CreateRetentionPolicyAssignmentAsync(assignmentParams); /*** Assert ***/ Assert.IsInstanceOfType(result.AssignedTo, typeof(BoxMetadataTemplate)); Assert.AreEqual("enterprise.my_template", result.AssignedTo.Id); Assert.AreEqual("foo", result.FilterFields[0].Field); Assert.AreEqual("bar", result.FilterFields[0].Value); Assert.AreEqual("baz", result.FilterFields[1].Field); Assert.AreEqual(42.ToString(), result.FilterFields[1].Value); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task GetFileVersionRetentions_OptionalParams_Success() { /*** Arrange ***/ var fileId = "12345"; var dispositionAfterString = "2010-08-18T09:30:00+00:00"; var dispositionAfter = new DateTimeOffset(2010, 8, 18, 9, 30, 0, TimeSpan.Zero); DispositionAction dispositionAction = DispositionAction.permanently_delete; var responseString = "{ \"entries\": [ {\"id\": \"11446498\", \"type\": \"file_version_retention\",\"file_version\": {\"id\": \"12345\",\"type\": \"file_version\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\"},\"file\": {\"id\": \"12345\",\"etag\": \"1\", \"type\": \"file\",\"sequence_id\": \"3\",\"name\": \"Contract.pdf\", \"sha1\": \"85136C79CBF9FE36BB9D05D0639C70C265C18D37\", \"file_version\": {\"id\": \"12345\",\"type\": \"file_version\",\"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\" }},\"applied_at\": \"2012-12-12T10:53:43-08:00\", \"disposition_at\": \"2012-12-12T10:53:43-08:00\", \"winning_retention_policy\": { \"id\": \"12345\", \"type\": \"retention_policy\",\"policy_name\": \"Some Policy Name\", \"retention_length\": \"365\",\"disposition_action\": \"permanently_delete\"}}],\"limit\": 100,\"next_marker\": \"\",\"prev_marker\": \"\"}"; IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<BoxCollectionMarkerBased<BoxFileVersionRetention>>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxCollectionMarkerBased<BoxFileVersionRetention>>>(new BoxResponse<BoxCollectionMarkerBased<BoxFileVersionRetention>>() { Status = ResponseStatus.Success, ContentString = responseString })) .Callback<IBoxRequest>(r => boxRequest = r); /*** Act ***/ BoxCollectionMarkerBased<BoxFileVersionRetention> results = await _retentionPoliciesManager.GetFileVersionRetentionsAsync(fileId: fileId, dispositionAfter: dispositionAfter, dispositionAction: dispositionAction); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Get, boxRequest.Method); Assert.AreEqual(fileId, boxRequest.Parameters["file_id"]); Assert.AreEqual(dispositionAfterString, boxRequest.Parameters["disposition_after"]); Assert.AreEqual(dispositionAction.ToString(), boxRequest.Parameters["disposition_action"]); // Response check Assert.AreEqual("11446498", results.Entries[0].Id); Assert.AreEqual("Contract.pdf", results.Entries[0].File.Name); Assert.AreEqual("12345", results.Entries[0].WinningRetentionPolicy.Id); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task GetFilesUnderRetentionForAssignment_ValidResponse() { /*** Arrange ***/ var retentionPolicyAssignmentId = "12345"; var responseString = "{ \"entries\": [{ \"id\": 12345, \"etag\": 1, \"type\": \"file\", \"sequence_id\": 3, \"name\": \"Contract.pdf\", \"sha1\": \"85136C79CBF9FE36BB9D05D0639C70C265C18D37\", \"file_version\": { \"id\": 123456, \"type\": \"file_version\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\" }, \"applied_at\": \"2012-12-12T10:53:43-08:00\" } ], \"limit\": 1000, \"marker\": \"some marker\" }"; IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<BoxCollectionMarkerBased<BoxFile>>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxCollectionMarkerBased<BoxFile>>>(new BoxResponse<BoxCollectionMarkerBased<BoxFile>>() { Status = ResponseStatus.Success, ContentString = responseString })) .Callback<IBoxRequest>(r => boxRequest = r); /*** Act ***/ BoxCollectionMarkerBased<BoxFile> results = await _retentionPoliciesManager.GetFilesUnderRetentionForAssignmentAsync(retentionPolicyAssignmentId); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Get, boxRequest.Method); Assert.AreEqual(retentionPolicyAssignmentId, boxRequest.Parameters["retention_policy_assignment_id"]); // Response check Assert.AreEqual("12345", results.Entries[0].Id); Assert.AreEqual("Contract.pdf", results.Entries[0].Name); Assert.AreEqual("file", results.Entries[0].Type); } [TestMethod] [TestCategory("CI-UNIT-TEST")] public async Task GetFileVersionsUnderRetentionForAssignment_ValidResponse() { /*** Arrange ***/ var retentionPolicyAssignmentId = "12345"; var responseString = "{ \"entries\": [{ \"id\": 12345, \"etag\": 1, \"type\": \"file_version\", \"sequence_id\": 3, \"name\": \"Contract.pdf\", \"sha1\": \"85136C79CBF9FE36BB9D05D0639C70C265C18D37\", \"file_version\": { \"id\": 123456, \"type\": \"file_version\", \"sha1\": \"134b65991ed521fcfe4724b7d814ab8ded5185dc\" }, \"applied_at\": \"2012-12-12T10:53:43-08:00\" } ], \"limit\": 1000, \"marker\": \"some marker\" }"; IBoxRequest boxRequest = null; Handler.Setup(h => h.ExecuteAsync<BoxCollectionMarkerBased<BoxFileVersion>>(It.IsAny<IBoxRequest>())) .Returns(Task.FromResult<IBoxResponse<BoxCollectionMarkerBased<BoxFileVersion>>>(new BoxResponse<BoxCollectionMarkerBased<BoxFileVersion>>() { Status = ResponseStatus.Success, ContentString = responseString })) .Callback<IBoxRequest>(r => boxRequest = r); /*** Act ***/ BoxCollectionMarkerBased<BoxFileVersion> results = await _retentionPoliciesManager.GetFileVersionsUnderRetentionForAssignmentAsync(retentionPolicyAssignmentId); /*** Assert ***/ // Request check Assert.IsNotNull(boxRequest); Assert.AreEqual(RequestMethod.Get, boxRequest.Method); Assert.AreEqual(retentionPolicyAssignmentId, boxRequest.Parameters["retention_policy_assignment_id"]); // Response check Assert.AreEqual("12345", results.Entries[0].Id); Assert.AreEqual("Contract.pdf", results.Entries[0].Name); Assert.AreEqual("file_version", results.Entries[0].Type); Assert.AreEqual("file_version", results.Entries[0].FileVersion.Type); } } }
using NetSparkleUpdater.AppCastHandlers; using NetSparkleUpdater.Interfaces; using System; using System.Globalization; using System.Xml.Linq; namespace NetSparkleUpdater { /// <summary> /// Item from a Sparkle AppCast file /// </summary> [Serializable] public class AppCastItem : IComparable<AppCastItem> { /// <summary> /// The application name /// </summary> public string AppName { get; set; } /// <summary> /// The installed version /// </summary> public string AppVersionInstalled { get; set; } /// <summary> /// The item title /// </summary> public string Title { get; set; } /// <summary> /// The available version /// </summary> public string Version { get; set; } /// <summary> /// Shortened version /// </summary> public string ShortVersion { get; set; } /// <summary> /// The release notes link /// </summary> public string ReleaseNotesLink { get; set; } /// <summary> /// The signature of the Release Notes file /// </summary> public string ReleaseNotesSignature { get; set; } /// <summary> /// The embedded description /// </summary> public string Description { get; set; } /// <summary> /// The download link /// </summary> public string DownloadLink { get; set; } /// <summary> /// The signature of the download file /// </summary> public string DownloadSignature { get; set; } /// <summary> /// Date item was published /// </summary> public DateTime PublicationDate { get; set; } /// <summary> /// Whether the update was marked critical or not via sparkle:critical /// </summary> public bool IsCriticalUpdate { get; set; } /// <summary> /// Length of update set via sparkle:length (usually the # of bytes of the update) /// </summary> public long UpdateSize { get; set; } /// <summary> /// Operating system that this update applies to /// </summary> public string OperatingSystemString { get; set; } /// <summary> /// True if this update is a windows update; false otherwise. /// Acceptable OS strings are: "win" or "windows" (this is /// checked with a case-insensitive check). If not specified, /// assumed to be a Windows update. /// </summary> public bool IsWindowsUpdate { get { if (OperatingSystemString != null) { var lowercasedOS = OperatingSystemString.ToLower(); if (lowercasedOS == "win" || lowercasedOS == "windows") { return true; } return false; } return true; } } /// <summary> /// True if this update is a macOS update; false otherwise. /// Acceptable OS strings are: "mac", "osx", or "macos" (this is /// checked with a case-insensitive check). If not specified, /// assumed to be a Windows update. /// </summary> public bool IsMacOSUpdate { get { if (OperatingSystemString != null) { var lowercasedOS = OperatingSystemString.ToLower(); if (lowercasedOS == "mac" || lowercasedOS == "macos" || lowercasedOS == "osx") { return true; } } return false; } } /// <summary> /// True if this update is a macOS update; false otherwise. /// Acceptable OS strings are: "linux" (this is /// checked with a case-insensitive check). If not specified, /// assumed to be a Linux update. /// </summary> public bool IsLinuxUpdate { get { if (OperatingSystemString != null) { var lowercasedOS = OperatingSystemString.ToLower(); if (lowercasedOS == "linux") { return true; } } return false; } } /// <summary> /// MIME type for file as specified in the closure tag. Defaults to "application/octet-stream". /// </summary> public string MIMEType { get; set; } #region XML private const string _itemNode = "item"; private const string _titleNode = "title"; private const string _enclosureNode = "enclosure"; private const string _releaseNotesLinkNode = "releaseNotesLink"; private const string _descriptionNode = "description"; private const string _versionAttribute = "version"; private const string _shortVersionAttribute = "shortVersionString"; private const string _dsaSignatureAttribute = "dsaSignature"; private const string _ed25519SignatureAttribute = "edSignature"; private const string _signatureAttribute = "signature"; private const string _criticalAttribute = "criticalUpdate"; private const string _operatingSystemAttribute = "os"; private const string _lengthAttribute = "length"; private const string _typeAttribute = "type"; private const string _urlAttribute = "url"; private const string _pubDateNode = "pubDate"; private const string _defaultOperatingSystem = "windows"; private const string _defaultType = "application/octet-stream"; /// <summary> /// Parse item Xml Node to AppCastItem /// </summary> /// <param name="installedVersion">Currently installed version</param> /// <param name="applicationName">Application name</param> /// <param name="castUrl">The url of the appcast</param> /// <param name="item">The item XML node</param> /// <param name="logWriter">logwriter instance</param> /// <returns>AppCastItem from Xml Node</returns> public static AppCastItem Parse(string installedVersion, string applicationName, string castUrl, XElement item, ILogger logWriter) { var newAppCastItem = new AppCastItem() { AppVersionInstalled = installedVersion, AppName = applicationName, UpdateSize = 0, IsCriticalUpdate = false, OperatingSystemString = _defaultOperatingSystem, MIMEType = _defaultType }; //title newAppCastItem.Title = item.Element(_titleNode)?.Value ?? string.Empty; //release notes var releaseNotesElement = item.Element(XMLAppCast.SparkleNamespace + _releaseNotesLinkNode); newAppCastItem.ReleaseNotesSignature = releaseNotesElement?.Attribute(XMLAppCast.SparkleNamespace + _signatureAttribute)?.Value ?? string.Empty; if (newAppCastItem.ReleaseNotesSignature == string.Empty) { newAppCastItem.ReleaseNotesSignature = releaseNotesElement?.Attribute(XMLAppCast.SparkleNamespace + _dsaSignatureAttribute)?.Value ?? string.Empty; } if (newAppCastItem.ReleaseNotesSignature == string.Empty) { newAppCastItem.ReleaseNotesSignature = releaseNotesElement?.Attribute(XMLAppCast.SparkleNamespace + _ed25519SignatureAttribute)?.Value ?? string.Empty; } newAppCastItem.ReleaseNotesLink = releaseNotesElement?.Value.Trim() ?? string.Empty; //description newAppCastItem.Description = item.Element(_descriptionNode)?.Value.Trim() ?? string.Empty; //enclosure var enclosureElement = item.Element(_enclosureNode) ?? item.Element(XMLAppCast.SparkleNamespace + _enclosureNode); newAppCastItem.Version = enclosureElement?.Attribute(XMLAppCast.SparkleNamespace + _versionAttribute)?.Value ?? string.Empty; newAppCastItem.ShortVersion = enclosureElement?.Attribute(XMLAppCast.SparkleNamespace + _shortVersionAttribute)?.Value ?? string.Empty; newAppCastItem.DownloadLink = enclosureElement?.Attribute(_urlAttribute)?.Value ?? string.Empty; if (!string.IsNullOrEmpty(newAppCastItem.DownloadLink) && !newAppCastItem.DownloadLink.Contains("/")) { // Download link contains only the filename -> complete with _castUrl newAppCastItem.DownloadLink = castUrl.Substring(0, castUrl.LastIndexOf('/') + 1) + newAppCastItem.DownloadLink; } newAppCastItem.DownloadSignature = enclosureElement?.Attribute(XMLAppCast.SparkleNamespace + _signatureAttribute)?.Value ?? string.Empty; if (newAppCastItem.DownloadSignature == string.Empty) { newAppCastItem.DownloadSignature = enclosureElement?.Attribute(XMLAppCast.SparkleNamespace + _dsaSignatureAttribute)?.Value ?? string.Empty; } if (newAppCastItem.DownloadSignature == string.Empty) { newAppCastItem.DownloadSignature = enclosureElement?.Attribute(XMLAppCast.SparkleNamespace + _ed25519SignatureAttribute)?.Value ?? string.Empty; } string length = enclosureElement?.Attribute(_lengthAttribute)?.Value ?? string.Empty; if (length != null) { if (long.TryParse(length, out var size)) { newAppCastItem.UpdateSize = size; } else { newAppCastItem.UpdateSize = 0; } } bool isCritical = false; string critical = enclosureElement?.Attribute(XMLAppCast.SparkleNamespace + _criticalAttribute)?.Value ?? string.Empty; if (critical != null && critical == "true" || critical == "1") { isCritical = true; } newAppCastItem.IsCriticalUpdate = isCritical; newAppCastItem.OperatingSystemString = enclosureElement?.Attribute(XMLAppCast.SparkleNamespace + _operatingSystemAttribute)?.Value ?? _defaultOperatingSystem; newAppCastItem.MIMEType = enclosureElement?.Attribute(_typeAttribute)?.Value ?? _defaultType; //pub date var pubDateElement = item.Element(_pubDateNode); if (pubDateElement != null) { // "ddd, dd MMM yyyy HH:mm:ss zzz" => Standard date format // e.g. "Sat, 26 Oct 2019 22:05:11 -05:00" // "ddd, dd MMM yyyy HH:mm:ss Z" => Check for MS AppCenter Sparkle date format which ends with GMT // e.g. "Sat, 26 Oct 2019 22:05:11 GMT" // "ddd, dd MMM yyyy HH:mm:ss" => Standard date format with no timezone (fallback) // e.g. "Sat, 26 Oct 2019 22:05:11" string[] formats = { "ddd, dd MMM yyyy HH:mm:ss zzz", "ddd, dd MMM yyyy HH:mm:ss Z", "ddd, dd MMM yyyy HH:mm:ss" }; string dt = pubDateElement.Value.Trim(); if (DateTime.TryParseExact(dt, formats, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime dateValue)) { logWriter?.PrintMessage("While parsing app cast item, converted '{0}' to {1}.", dt, dateValue); newAppCastItem.PublicationDate = dateValue; } else { logWriter?.PrintMessage("Cannot parse item's DateTime: {0}", dt); } } return newAppCastItem; } /// <summary> /// Create Xml node from this instance of AppCastItem /// </summary> /// <returns>An XML node</returns> public XElement GetXElement() { var item = new XElement(_itemNode); item.Add(new XElement(_titleNode) { Value = Title }); if (!string.IsNullOrEmpty(ReleaseNotesLink)) { var releaseNotes = new XElement(XMLAppCast.SparkleNamespace + _releaseNotesLinkNode) { Value = ReleaseNotesLink }; if (!string.IsNullOrEmpty(ReleaseNotesSignature)) { releaseNotes.Add(new XAttribute(XMLAppCast.SparkleNamespace + _signatureAttribute, ReleaseNotesSignature)); } item.Add(releaseNotes); } if (!string.IsNullOrEmpty(Description)) { item.Add(new XElement(_descriptionNode) { Value = Description }); } if (PublicationDate != DateTime.MinValue && PublicationDate != DateTime.MaxValue) { item.Add(new XElement(_pubDateNode) { Value = PublicationDate.ToString("ddd, dd MMM yyyy HH:mm:ss zzz", System.Globalization.CultureInfo.InvariantCulture) }); } if (!string.IsNullOrEmpty(DownloadLink)) { var enclosure = new XElement(_enclosureNode); enclosure.Add(new XAttribute(_urlAttribute, DownloadLink)); enclosure.Add(new XAttribute(XMLAppCast.SparkleNamespace + _versionAttribute, Version)); if (!string.IsNullOrEmpty(ShortVersion)) { enclosure.Add(new XAttribute(XMLAppCast.SparkleNamespace + _shortVersionAttribute, ShortVersion)); } enclosure.Add(new XAttribute(_lengthAttribute, UpdateSize)); enclosure.Add(new XAttribute(XMLAppCast.SparkleNamespace + _operatingSystemAttribute, OperatingSystemString ?? _defaultOperatingSystem)); enclosure.Add(new XAttribute(_typeAttribute, MIMEType ?? _defaultType)); if (!string.IsNullOrEmpty(DownloadSignature)) { enclosure.Add(new XAttribute(XMLAppCast.SparkleNamespace + _signatureAttribute, DownloadSignature)); } item.Add(enclosure); } return item; } #endregion #region IComparable<AppCastItem> Members /// <summary> /// Compares this <see cref="AppCastItem"/> version to the version of another <see cref="AppCastItem"/> /// </summary> /// <param name="other">the other instance</param> /// <returns>-1, 0, 1 if this instance is less than, equal to, or greater than the <paramref name="other"/></returns> public int CompareTo(AppCastItem other) { if (!Version.Contains(".") || !other.Version.Contains(".")) { return 0; } Version v1 = new Version(Version); Version v2 = new Version(other.Version); return v1.CompareTo(v2); } /// <summary> /// See if this this <see cref="AppCastItem"/> version equals the version of another <see cref="AppCastItem"/>. /// Also checks to make sure the application names match. /// </summary> /// <param name="obj">the instance to compare to</param> /// <returns></returns> public override bool Equals(object obj) { if (!(obj is AppCastItem item)) { return false; } if (ReferenceEquals(this, item)) { return true; } return AppName.Equals(item.AppName) && CompareTo(item) == 0; } /// <summary> /// Derive hashcode from immutable variables /// </summary> /// <returns>the integer haschode of this app cast item</returns> public override int GetHashCode() { return Version.GetHashCode() * 17 + AppName.GetHashCode(); } /// <summary> /// Check the equality of two <see cref="AppCastItem"/> instances /// </summary> /// <param name="left">first <see cref="AppCastItem"/> to compare</param> /// <param name="right">second <see cref="AppCastItem"/> to compare</param> /// <returns>True if items are the same; false otherwise</returns> public static bool operator ==(AppCastItem left, AppCastItem right) { if (left is null) { return right is null; } return left.Equals(right); } /// <summary> /// Check if two <see cref="AppCastItem"/> instances are different /// </summary> /// <param name="left">first <see cref="AppCastItem"/> to compare</param> /// <param name="right">second <see cref="AppCastItem"/> to compare</param> /// <returns>True if items are different; false if they are the same</returns> public static bool operator !=(AppCastItem left, AppCastItem right) { return !(left == right); } /// <summary> /// Less than comparison of version between two <see cref="AppCastItem"/> instances /// </summary> /// <param name="left">first <see cref="AppCastItem"/> to compare</param> /// <param name="right">second <see cref="AppCastItem"/> to compare</param> /// <returns>True if left version is less than right version; false otherwise</returns> public static bool operator <(AppCastItem left, AppCastItem right) { return left is null ? !(right is null) : left.CompareTo(right) < 0; } /// <summary> /// Less than or equal to comparison of version between two AppCastItem instances /// </summary> /// <param name="left">AppCastItem to compare</param> /// <param name="right">AppCastItem to compare</param> /// <returns>True if left version is less than or equal to right version</returns> public static bool operator <=(AppCastItem left, AppCastItem right) { return left is null || left.CompareTo(right) <= 0; } /// <summary> /// Greater than comparison of version between two <see cref="AppCastItem"/> instances /// </summary> /// <param name="left">first <see cref="AppCastItem"/> to compare</param> /// <param name="right">second <see cref="AppCastItem"/> to compare</param> /// <returns>True if left version is greater than right version; false otherwise</returns> public static bool operator >(AppCastItem left, AppCastItem right) { return !(left is null) && left.CompareTo(right) > 0; } /// <summary> /// Greater than or equal to comparison of version between two <see cref="AppCastItem"/> instances /// </summary> /// <param name="left">first <see cref="AppCastItem"/> to compare</param> /// <param name="right">second <see cref="AppCastItem"/> to compare</param> /// <returns>True if left version is greater than or equal to right version; false otherwise</returns> public static bool operator >=(AppCastItem left, AppCastItem right) { return left is null ? right is null : left.CompareTo(right) >= 0; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.ObjectPool; using Microsoft.Extensions.Options; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc { public class RemoteAttributeTest { public static TheoryData<string> SomeNames { get { return new TheoryData<string> { string.Empty, "Action", "In a controller", " slightly\t odd\t whitespace\t\r\n", }; } } // Null or empty property names are invalid. (Those containing just whitespace are legal.) public static TheoryData<string> NullOrEmptyNames { get { return new TheoryData<string> { null, string.Empty, }; } } [Fact] public void Constructor_WithNullAction_IgnoresArgument() { // Arrange & Act var attribute = new TestableRemoteAttribute(action: null, controller: "AController"); // Assert var keyValuePair = Assert.Single(attribute.RouteData); Assert.Equal("controller", keyValuePair.Key); } [Fact] public void Constructor_WithNullController_IgnoresArgument() { // Arrange & Act var attribute = new TestableRemoteAttribute("AnAction", controller: null); // Assert var keyValuePair = Assert.Single(attribute.RouteData); Assert.Equal("action", keyValuePair.Key); Assert.Null(attribute.RouteName); } [Theory] [InlineData(null)] [MemberData(nameof(SomeNames))] public void Constructor_WithRouteName_UpdatesProperty(string routeName) { // Arrange & Act var attribute = new TestableRemoteAttribute(routeName); // Assert Assert.Empty(attribute.RouteData); Assert.Equal(routeName, attribute.RouteName); } [Theory] [MemberData(nameof(SomeNames))] public void Constructor_WithActionController_UpdatesActionRouteData(string action) { // Arrange & Act var attribute = new TestableRemoteAttribute(action, "AController"); // Assert Assert.Equal(2, attribute.RouteData.Count); Assert.Contains("controller", attribute.RouteData.Keys); var resultName = Assert.Single( attribute.RouteData, keyValuePair => string.Equals(keyValuePair.Key, "action", StringComparison.Ordinal)) .Value; Assert.Equal(action, resultName); Assert.Null(attribute.RouteName); } [Theory] [MemberData(nameof(SomeNames))] public void Constructor_WithActionController_UpdatesControllerRouteData(string controller) { // Arrange & Act var attribute = new TestableRemoteAttribute("AnAction", controller); // Assert Assert.Equal(2, attribute.RouteData.Count); Assert.Contains("action", attribute.RouteData.Keys); var resultName = Assert.Single( attribute.RouteData, keyValuePair => string.Equals(keyValuePair.Key, "controller", StringComparison.Ordinal)) .Value; Assert.Equal(controller, resultName); Assert.Null(attribute.RouteName); } [Theory] [InlineData(null)] [MemberData(nameof(SomeNames))] public void Constructor_WithActionControllerAreaName_UpdatesAreaRouteData(string areaName) { // Arrange & Act var attribute = new TestableRemoteAttribute("AnAction", "AController", areaName: areaName); // Assert Assert.Equal(3, attribute.RouteData.Count); Assert.Contains("action", attribute.RouteData.Keys); Assert.Contains("controller", attribute.RouteData.Keys); var resultName = Assert.Single( attribute.RouteData, keyValuePair => string.Equals(keyValuePair.Key, "area", StringComparison.Ordinal)) .Value; Assert.Equal(areaName, resultName); Assert.Null(attribute.RouteName); } [Fact] public void GetUrl_WithBadRouteName_Throws() { // Arrange var testableAttribute = new TestableRemoteAttribute("nonexistentRoute"); var context = GetValidationContextWithArea(currentArea: null); // Act & Assert var exception = Assert.Throws<InvalidOperationException>(() => testableAttribute.InvokeGetUrl(context)); Assert.Equal("No URL for remote validation could be found.", exception.Message); } [Fact] public void GetUrl_WithRoute_CallsUrlHelperWithExpectedValues() { // Arrange var routeName = "RouteName"; var testableRemoteAttribute = new TestableRemoteAttribute(routeName); var url = "/my/URL"; var urlHelper = new MockUrlHelper(url, routeName); var context = GetValidationContext(urlHelper); // Act var actualUrl = testableRemoteAttribute.InvokeGetUrl(context); // Assert Assert.Equal(url, actualUrl); var routeDictionary = Assert.IsType<RouteValueDictionary>(urlHelper.RouteValues); Assert.Empty(routeDictionary); } [Fact] public void GetUrl_WithActionController_CallsUrlHelperWithExpectedValues() { // Arrange var testableRemoteAttribute = new TestableRemoteAttribute("Action", "Controller"); var url = "/Controller/Action"; var urlHelper = new MockUrlHelper(url, routeName: null); var context = GetValidationContext(urlHelper); // Act var actualUrl = testableRemoteAttribute.InvokeGetUrl(context); // Assert Assert.Equal(url, actualUrl); var routeDictionary = Assert.IsType<RouteValueDictionary>(urlHelper.RouteValues); Assert.Equal(2, routeDictionary.Count); Assert.Equal("Action", routeDictionary["action"] as string); Assert.Equal("Controller", routeDictionary["controller"] as string); } [Fact] public void GetUrl_WithActionControllerArea_CallsUrlHelperWithExpectedValues() { // Arrange var testableAttribute = new TestableRemoteAttribute("Action", "Controller", "Test"); var url = "/Test/Controller/Action"; var urlHelper = new MockUrlHelper(url, routeName: null); var context = GetValidationContext(urlHelper); // Act var actualUrl = testableAttribute.InvokeGetUrl(context); // Assert Assert.Equal(url, actualUrl); var routeDictionary = Assert.IsType<RouteValueDictionary>(urlHelper.RouteValues); Assert.Equal(3, routeDictionary.Count); Assert.Equal("Action", routeDictionary["action"] as string); Assert.Equal("Controller", routeDictionary["controller"] as string); Assert.Equal("Test", routeDictionary["area"] as string); } // Root area is current in this case. [Fact] public void GetUrl_WithActionController_FindsControllerInCurrentArea() { // Arrange var testableAttribute = new TestableRemoteAttribute("Action", "Controller"); var context = GetValidationContextWithArea(currentArea: null); // Act var actualUrl = testableAttribute.InvokeGetUrl(context); // Assert Assert.Equal("/Controller/Action", actualUrl); } // Test area is current in this case. [Fact] public void GetUrl_WithActionControllerInArea_FindsControllerInCurrentArea() { // Arrange var testableAttribute = new TestableRemoteAttribute("Action", "Controller"); var context = GetValidationContextWithArea(currentArea: "Test"); // Act var actualUrl = testableAttribute.InvokeGetUrl(context); // Assert Assert.Equal("/Test/Controller/Action", actualUrl); } // Explicit reference to the (current) root area. [Theory] [MemberData(nameof(NullOrEmptyNames))] public void GetUrl_WithActionControllerArea_FindsControllerInRootArea(string areaName) { // Arrange var testableAttribute = new TestableRemoteAttribute("Action", "Controller", areaName); var context = GetValidationContextWithArea(currentArea: null); // Act var actualUrl = testableAttribute.InvokeGetUrl(context); // Assert Assert.Equal("/Controller/Action", actualUrl); } // Test area is current in this case. [Theory] [MemberData(nameof(NullOrEmptyNames))] public void GetUrl_WithActionControllerAreaInArea_FindsControllerInRootArea(string areaName) { // Arrange var testableAttribute = new TestableRemoteAttribute("Action", "Controller", areaName); var context = GetValidationContextWithArea(currentArea: "Test"); // Act var actualUrl = testableAttribute.InvokeGetUrl(context); // Assert Assert.Equal("/Controller/Action", actualUrl); } // Root area is current in this case. [Fact] public void GetUrl_WithActionControllerArea_FindsControllerInNamedArea() { // Arrange var testableAttribute = new TestableRemoteAttribute("Action", "Controller", "Test"); var context = GetValidationContextWithArea(currentArea: null); // Act var actualUrl = testableAttribute.InvokeGetUrl(context); // Assert Assert.Equal("/Test/Controller/Action", actualUrl); } // Explicit reference to the current (Test) area. [Fact] public void GetUrl_WithActionControllerAreaInArea_FindsControllerInNamedArea() { // Arrange var testableAttribute = new TestableRemoteAttribute("Action", "Controller", "Test"); var context = GetValidationContextWithArea(currentArea: "Test"); // Act var actualUrl = testableAttribute.InvokeGetUrl(context); // Assert Assert.Equal("/Test/Controller/Action", actualUrl); } // Test area is current in this case. [Fact] public void GetUrl_WithActionControllerAreaInArea_FindsControllerInDifferentArea() { // Arrange var testableAttribute = new TestableRemoteAttribute("Action", "Controller", "AnotherArea"); var context = GetValidationContextWithArea(currentArea: "Test"); // Act var actualUrl = testableAttribute.InvokeGetUrl(context); // Assert Assert.Equal("/AnotherArea/Controller/Action", actualUrl); } // Test area is current in this case. [Fact] public void AddValidation_DoesNotTrounceExistingAttributes() { // Arrange var attribute = new RemoteAttribute("Action", "Controller", "AnotherArea") { HttpMethod = "PUT", }; var context = GetValidationContextWithArea(currentArea: "Test"); context.Attributes.Add("data-val", "original"); context.Attributes.Add("data-val-remote", "original"); context.Attributes.Add("data-val-remote-additionalfields", "original"); context.Attributes.Add("data-val-remote-type", "original"); context.Attributes.Add("data-val-remote-url", "original"); // Act attribute.AddValidation(context); // Assert Assert.Collection( context.Attributes, kvp => { Assert.Equal("data-val", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-remote", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-remote-additionalfields", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-remote-type", kvp.Key); Assert.Equal("original", kvp.Value); }, kvp => { Assert.Equal("data-val-remote-url", kvp.Key); Assert.Equal("original", kvp.Value); }); } private static ClientModelValidationContext GetValidationContext(string url) { var urlHelper = new MockUrlHelper(url, routeName: null); return GetValidationContext(urlHelper); } private static ClientModelValidationContext GetValidationContext( IUrlHelper urlHelper) { var serviceCollection = GetServiceCollection(); var factory = new Mock<IUrlHelperFactory>(MockBehavior.Strict); serviceCollection.AddSingleton<IUrlHelperFactory>(factory.Object); var serviceProvider = serviceCollection.BuildServiceProvider(); var actionContext = GetActionContext(serviceProvider, routeData: null); factory .Setup(f => f.GetUrlHelper(actionContext)) .Returns(urlHelper); var metadataProvider = new EmptyModelMetadataProvider(); var metadata = metadataProvider.GetMetadataForProperty( containerType: typeof(string), propertyName: nameof(string.Length)); return new ClientModelValidationContext( actionContext, metadata, metadataProvider, new AttributeDictionary()); } private static ClientModelValidationContext GetValidationContextWithArea(string currentArea) { var serviceCollection = GetServiceCollection(); var serviceProvider = serviceCollection.BuildServiceProvider(); var routeCollection = GetRouteCollectionWithArea(serviceProvider); var routeData = new RouteData { Routers = { routeCollection, }, Values = { { "action", "Index" }, { "controller", "Home" }, }, }; if (!string.IsNullOrEmpty(currentArea)) { routeData.Values["area"] = currentArea; } var actionContext = GetActionContext(serviceProvider, routeData); var urlHelper = new UrlHelper(actionContext); var factory = new Mock<IUrlHelperFactory>(MockBehavior.Strict); factory .Setup(f => f.GetUrlHelper(actionContext)) .Returns(urlHelper); // Make an IUrlHelperFactory available through the ActionContext. serviceCollection.AddSingleton<IUrlHelperFactory>(factory.Object); serviceProvider = serviceCollection.BuildServiceProvider(); actionContext.HttpContext.RequestServices = serviceProvider; var metadataProvider = new EmptyModelMetadataProvider(); var metadata = metadataProvider.GetMetadataForProperty( containerType: typeof(string), propertyName: nameof(string.Length)); return new ClientModelValidationContext( actionContext, metadata, metadataProvider, new AttributeDictionary()); } private static IRouter GetRouteCollectionWithArea(IServiceProvider serviceProvider) { var builder = GetRouteBuilder(serviceProvider); // Setting IsBound to true makes order more important than usual. First try the route that requires the // area value. Skip usual "area:exists" constraint because that isn't relevant for link generation and it // complicates the setup significantly. builder.MapRoute("areaRoute", "{area}/{controller}/{action}"); builder.MapRoute("default", "{controller}/{action}", new { controller = "Home", action = "Index" }); return builder.Build(); } private static RouteBuilder GetRouteBuilder(IServiceProvider serviceProvider) { var app = new Mock<IApplicationBuilder>(MockBehavior.Strict); app .SetupGet(a => a.ApplicationServices) .Returns(serviceProvider); var builder = new RouteBuilder(app.Object); var handler = new Mock<IRouter>(MockBehavior.Strict); handler .Setup(router => router.GetVirtualPath(It.IsAny<VirtualPathContext>())) .Returns((VirtualPathData)null); builder.DefaultHandler = handler.Object; return builder; } private static ActionContext GetActionContext(IServiceProvider serviceProvider, RouteData routeData) { // Set IServiceProvider properties because TemplateRoute gets services (e.g. an ILoggerFactory instance) // through the HttpContext. var httpContext = new DefaultHttpContext { RequestServices = serviceProvider, }; if (routeData == null) { routeData = new RouteData { Routers = { Mock.Of<IRouter>(), }, }; } return new ActionContext(httpContext, routeData, new ActionDescriptor()); } private static ServiceCollection GetServiceCollection() { var serviceCollection = new ServiceCollection(); serviceCollection .AddSingleton<ILoggerFactory>(new NullLoggerFactory()); serviceCollection.AddOptions(); serviceCollection.AddRouting(); serviceCollection.AddSingleton<IInlineConstraintResolver>( provider => new DefaultInlineConstraintResolver(provider.GetRequiredService<IOptions<RouteOptions>>(), provider)); return serviceCollection; } private class MockUrlHelper : IUrlHelper { private readonly string _routeName; private readonly string _url; public MockUrlHelper(string url, string routeName) { _routeName = routeName; _url = url; } public ActionContext ActionContext { get; } public object RouteValues { get; private set; } public string Action(UrlActionContext actionContext) { throw new NotImplementedException(); } public string Content(string contentPath) { throw new NotImplementedException(); } public bool IsLocalUrl(string url) { throw new NotImplementedException(); } public string Link(string routeName, object values) { throw new NotImplementedException(); } public string RouteUrl(UrlRouteContext routeContext) { Assert.Equal(_routeName, routeContext.RouteName); Assert.Null(routeContext.Protocol); Assert.Null(routeContext.Host); Assert.Null(routeContext.Fragment); RouteValues = routeContext.Values; return _url; } } private class TestableRemoteAttribute : RemoteAttribute { public TestableRemoteAttribute(string routeName) : base(routeName) { } public TestableRemoteAttribute(string action, string controller) : base(action, controller) { } public TestableRemoteAttribute(string action, string controller, string areaName) : base(action, controller, areaName) { } public new string RouteName { get { return base.RouteName; } } public new RouteValueDictionary RouteData { get { return base.RouteData; } } public string InvokeGetUrl(ClientModelValidationContext context) { return base.GetUrl(context); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #if !CLR2 #else using Microsoft.Scripting.Ast; #endif using System.Reflection; namespace System.Management.Automation.ComInterop { internal static class TypeUtils { private const BindingFlags AnyStatic = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; internal const MethodAttributes PublicStatic = MethodAttributes.Public | MethodAttributes.Static; //CONFORMING internal static Type GetNonNullableType(Type type) { if (IsNullableType(type)) { return type.GetGenericArguments()[0]; } return type; } //CONFORMING internal static bool IsNullableType(this Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } //CONFORMING internal static bool AreReferenceAssignable(Type dest, Type src) { // WARNING: This actually implements "Is this identity assignable and/or reference assignable?" if (dest == src) { return true; } if (!dest.IsValueType && !src.IsValueType && AreAssignable(dest, src)) { return true; } return false; } //CONFORMING internal static bool AreAssignable(Type dest, Type src) { if (dest == src) { return true; } if (dest.IsAssignableFrom(src)) { return true; } if (dest.IsArray && src.IsArray && dest.GetArrayRank() == src.GetArrayRank() && AreReferenceAssignable(dest.GetElementType(), src.GetElementType())) { return true; } if (src.IsArray && dest.IsGenericType && (dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IEnumerable<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.IList<>) || dest.GetGenericTypeDefinition() == typeof(System.Collections.Generic.ICollection<>)) && dest.GetGenericArguments()[0] == src.GetElementType()) { return true; } return false; } //CONFORMING internal static bool IsImplicitlyConvertible(Type source, Type destination) { return IsIdentityConversion(source, destination) || IsImplicitNumericConversion(source, destination) || IsImplicitReferenceConversion(source, destination) || IsImplicitBoxingConversion(source, destination); } internal static bool IsImplicitlyConvertible(Type source, Type destination, bool considerUserDefined) { return IsImplicitlyConvertible(source, destination) || (considerUserDefined && GetUserDefinedCoercionMethod(source, destination, true) != null); } //CONFORMING internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type convertToType, bool implicitOnly) { // check for implicit coercions first Type nnExprType = TypeUtils.GetNonNullableType(convertFrom); Type nnConvType = TypeUtils.GetNonNullableType(convertToType); // try exact match on types MethodInfo[] eMethods = nnExprType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); MethodInfo method = FindConversionOperator(eMethods, convertFrom, convertToType, implicitOnly); if (method != null) { return method; } MethodInfo[] cMethods = nnConvType.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); method = FindConversionOperator(cMethods, convertFrom, convertToType, implicitOnly); if (method != null) { return method; } // try lifted conversion if (nnExprType != convertFrom || nnConvType != convertToType) { method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly) ?? FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); if (method != null) { return method; } } return null; } //CONFORMING internal static MethodInfo FindConversionOperator(MethodInfo[] methods, Type typeFrom, Type typeTo, bool implicitOnly) { foreach (MethodInfo mi in methods) { if (mi.Name != "op_Implicit" && (implicitOnly || mi.Name != "op_Explicit")) continue; if (mi.ReturnType != typeTo) continue; ParameterInfo[] pis = mi.GetParameters(); if (pis[0].ParameterType != typeFrom) continue; return mi; } return null; } //CONFORMING private static bool IsIdentityConversion(Type source, Type destination) { return source == destination; } //CONFORMING [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static bool IsImplicitNumericConversion(Type source, Type destination) { TypeCode tcSource = Type.GetTypeCode(source); TypeCode tcDest = Type.GetTypeCode(destination); switch (tcSource) { case TypeCode.SByte: switch (tcDest) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Byte: switch (tcDest) { case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int16: switch (tcDest) { case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.UInt16: switch (tcDest) { case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int32: switch (tcDest) { case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.UInt32: switch (tcDest) { case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Int64: case TypeCode.UInt64: switch (tcDest) { case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Char: switch (tcDest) { case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } return false; case TypeCode.Single: return (tcDest == TypeCode.Double); } return false; } //CONFORMING private static bool IsImplicitReferenceConversion(Type source, Type destination) { return AreAssignable(destination, source); } //CONFORMING private static bool IsImplicitBoxingConversion(Type source, Type destination) { if (source.IsValueType && (destination == typeof(object) || destination == typeof(System.ValueType))) return true; if (source.IsEnum && destination == typeof(System.Enum)) return true; return false; } } }
/* ' Copyright (c) 2015 Aspose.com ' All rights reserved. ' ' 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 DotNetNuke.Security; using DotNetNuke.Services.Exceptions; using DotNetNuke.Entities.Modules; using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.Services.Localization; using Aspose.Cells; using Aspose.DNN.ImportUsersFromExcel; using System.IO; using System.Data; using System.Web.UI.WebControls; using DotNetNuke.Security.Membership; using DotNetNuke.Entities.Users; using DotNetNuke.Security.Roles; using System.Collections.Generic; using DotNetNuke.Common.Utilities; using System.Collections; namespace Aspose.DNN.ImportUsersFromExcel { /// ----------------------------------------------------------------------------- /// <summary> /// The View class displays the content /// /// Typically your view control would be used to display content or functionality in your module. /// /// View may be the only control you have in your project depending on the complexity of your module /// /// Because the control inherits from Aspose.DNN.ImportUsersFromExcelModuleBase you have access to any custom properties /// defined there, as well as properties from DNN such as PortalId, ModuleId, TabId, UserId and many more. /// /// </summary> /// ----------------------------------------------------------------------------- public partial class View : ImportUsersFromExcelModuleBase, IActionable { protected void Page_Load(object sender, EventArgs e) { try { } catch (Exception exc) //Module failed to load { Exceptions.ProcessModuleLoadException(this, exc); } } public ModuleActionCollection ModuleActions { get { var actions = new ModuleActionCollection { { GetNextActionID(), Localization.GetString("EditModule", LocalResourceFile), "", "", "", EditUrl(), false, SecurityAccessLevel.Edit, true, false } }; return actions; } } protected void UploadButton_Click(object sender, EventArgs e) { success_msg.Visible = false; error_msg.Visible = false; info_msg.Visible = false; // Check for license and apply if exists string licenseFile = Server.MapPath("~/App_Data/Aspose.Total.lic"); if (File.Exists(licenseFile)) { License license = new License(); license.SetLicense(licenseFile); } try { Stream stream = ImportFileUpload.FileContent; Workbook wb = new Workbook(stream); string filePath = Server.MapPath("~/temp/"); if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath); filePath += "\\" + ImportFileUpload.FileName; wb.Save(filePath); Workbook workbook = new Workbook(filePath); Worksheet sheet = workbook.Worksheets[0]; if(sheet.Cells.MaxDataRow > 1) { DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[4] { new DataColumn("ID", typeof(int)), new DataColumn("Username", typeof(string)), new DataColumn("DisplayName", typeof(string)), new DataColumn("Email",typeof(string)) }); int r = 1; while (r <= sheet.Cells.MaxRow) { UserInfo userInfo = UserController.GetUserByName(PortalId, sheet.Cells[r, 0].Value.ToString()); if (userInfo == null) { dt.Rows.Add(r, sheet.Cells[r, 0].Value, sheet.Cells[r, 1].Value, sheet.Cells[r, 2].Value); } r++; } if (dt.Rows.Count > 0) { UsersGridView.DataSource = dt; UsersGridView.DataBind(); UsersGridView.Visible = true; ProcessButton.Visible = true; ImportHeading.Visible = true; } else { info_msg.Visible = true; info_msg.InnerText = "All the users in file already exists in DNN."; } } else { error_msg.Visible = true; error_msg.InnerText = "No data found in file."; } } catch( Exception exc) { error_msg.Visible = true; error_msg.InnerText = exc.Message; } } protected void ProcessButton_Click(object sender, EventArgs e) { int importedCount = 0; foreach (GridViewRow row in UsersGridView.Rows) { if (row.RowType == DataControlRowType.DataRow) { CheckBox chkRow = (row.Cells[0].FindControl("SelectedCheckBox") as CheckBox); if (chkRow.Checked) { UserInfo user = new UserInfo(); user.Email = row.Cells[2].Text; user.DisplayName = row.Cells[1].Text; user.Username = row.Cells[3].Text; UserInfo userInfo = UserController.GetUserByName(PortalId, user.Username); if(userInfo == null) { CreateDNNUser(user); importedCount++; } } } } success_msg.Visible = true; success_msg.InnerText = importedCount.ToString() + " users imported successfully."; } private UserCreateStatus CreateDNNUser(UserInfo user) { user.Membership.Password = UserController.GeneratePassword(12).ToString(); user.PortalID = PortalId; user.IsSuperUser = false; UserCreateStatus createStatus = UserCreateStatus.AddUser; //Create the User createStatus = UserController.CreateUser(ref user); if (createStatus == UserCreateStatus.Success) { RoleController objRoles = new RoleController(); List<int> rolesList = new List<int>(); foreach (int roleID in rolesList) { objRoles.AddUserRole(user.PortalID, user.UserID, roleID, Null.NullDate, Null.NullDate); } } return createStatus; } protected void DownloadTemplate() { string fileName = "./TemplateFile.xlsx"; FileStream fs = new FileStream(MapPath(fileName), FileMode.Open); long cntBytes = new FileInfo(MapPath(fileName)).Length; byte[] byteArray = new byte[Convert.ToInt32(cntBytes)]; fs.Read(byteArray, 0, Convert.ToInt32(cntBytes)); fs.Close(); if (byteArray != null) { this.Response.Clear(); this.Response.ContentType = "text/plain"; this.Response.AddHeader("content-disposition", "attachment;filename=TemplateFile.xlsx"); this.Response.BinaryWrite(byteArray); this.Response.End(); this.Response.Flush(); this.Response.Close(); } File.Delete(Server.MapPath(fileName)); } protected void templateFile_Click(object sender, EventArgs e) { DownloadTemplate(); } } }
/* Copyright (c) 2006 Ladislav Prosek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.Text; using System.Reflection; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.InteropServices; using PHP.Core; using PHP.Core.Reflection; namespace PHP.Library.Xml { /// <summary> /// Enumerates the clone behavior. (Where is this supposed to be used?) /// </summary> public enum CloneType { [ImplementsConstant("XSL_CLONE_AUTO")] Auto = 0, [ImplementsConstant("XSL_CLONE_NEVER")] Never = 1, [ImplementsConstant("XSL_CLONE_ALWAYS")] Always = -1 } /// <summary> /// Implements the XSLT processor. /// </summary> [ImplementsType] public partial class XSLTProcessor { #region Delegates private delegate void LoadDelegate(IXPathNavigable stylesheet); private delegate XmlWriterSettings GetOutputSettingsDelegate(); private delegate void TransformToWriterDelegate(IXPathNavigable input, XsltArgumentList arguments, XmlWriter results); private delegate void TransformToStreamDelegate(IXPathNavigable input, XsltArgumentList arguments, Stream results); #endregion #region Fields and Properties private LoadDelegate Load; private GetOutputSettingsDelegate GetOutputSettings; private TransformToWriterDelegate TransformToWriter; private TransformToStreamDelegate TransformToStream; private XsltArgumentList xsltArgumentList; private XsltUserFunctionHandler xsltUserFunctionHandler; private const string PhpNameSpaceUri = "http://php.net/xsl"; private static bool mvpXmlAvailable; private static Type mvpXmlType; private static MethodInfo getOutputSettingsMethodFW; private static MethodInfo loadMethodMvp; private static MethodInfo getOutputSettingsMethodMvp; private static MethodInfo transformToWriterMethodMvp; private static MethodInfo transformToStreamMethodMvp; #endregion #region Construction /// <summary> /// Determines whether Mvp.Xml is available and reflects the MvpXslTransform type. /// </summary> static XSLTProcessor() { getOutputSettingsMethodFW = typeof(XslCompiledTransform).GetProperty("OutputSettings").GetGetMethod(); // try to load the Mvp.Xml assembly try { Assembly mvp_xml_assembly = Assembly.Load("Mvp.Xml, Version=2.0.2158.1055, Culture=neutral, PublicKeyToken=dd92544dc05f5671"); mvpXmlType = mvp_xml_assembly.GetType("Mvp.Xml.Exslt.ExsltTransform"); if (mvpXmlType != null) { loadMethodMvp = mvpXmlType.GetMethod("Load", new Type[] { typeof(IXPathNavigable) }); getOutputSettingsMethodMvp = mvpXmlType.GetProperty("OutputSettings").GetGetMethod(); transformToWriterMethodMvp = mvpXmlType.GetMethod("Transform", new Type[] { typeof(IXPathNavigable), typeof(XsltArgumentList), typeof(XmlWriter) }); transformToStreamMethodMvp = mvpXmlType.GetMethod("Transform", new Type[] { typeof(IXPathNavigable), typeof(XsltArgumentList), typeof(Stream) }); mvpXmlAvailable = (loadMethodMvp != null && getOutputSettingsMethodMvp != null && transformToWriterMethodMvp != null && transformToStreamMethodMvp != null); } } catch (Exception) { return; } } public XSLTProcessor() : base(ScriptContext.CurrentContext, true) { if (mvpXmlAvailable) { object transform = Activator.CreateInstance(mvpXmlType); Load = (LoadDelegate)Delegate.CreateDelegate(typeof(LoadDelegate), transform, loadMethodMvp); GetOutputSettings = (GetOutputSettingsDelegate)Delegate.CreateDelegate(typeof(GetOutputSettingsDelegate), transform, getOutputSettingsMethodMvp); TransformToWriter = (TransformToWriterDelegate)Delegate.CreateDelegate(typeof(TransformToWriterDelegate), transform, transformToWriterMethodMvp); TransformToStream = (TransformToStreamDelegate)Delegate.CreateDelegate(typeof(TransformToStreamDelegate), transform, transformToStreamMethodMvp); } else { // Mvp.Xml not available -> falling back to XslCompiledTransform XslCompiledTransform transform = new XslCompiledTransform(); Load = new LoadDelegate(transform.Load); GetOutputSettings = (GetOutputSettingsDelegate) Delegate.CreateDelegate(typeof(GetOutputSettingsDelegate), transform, getOutputSettingsMethodFW); TransformToWriter = new TransformToWriterDelegate(transform.Transform); TransformToStream = new TransformToStreamDelegate(transform.Transform); } this.xsltArgumentList = new XsltArgumentList(); } public override bool ToBoolean() { return true; } #endregion #region Transformation /// <summary> /// Import a stylesheet. /// </summary> /// <param name="doc">The imported style sheet passed as a <see cref="DOMDocument"/> object.</param> /// <returns><B>True</B> or <B>false</B>.</returns> [PhpVisible] public object importStylesheet(DOMDocument doc) { try { Load(doc.XmlDocument); } catch (XsltException e) { PhpException.Throw(PhpError.Warning, e.Message); return false; } return true; } /// <summary> /// Transforms the source node to a <see cref="DOMDocument"/> applying the stylesheet given by the /// <see cref="importStylesheet(DOMDocument)"/> method. /// </summary> /// <param name="node">The node to be transformed.</param> /// <returns>The resulting <see cref="DOMDocument"/> or <B>false</B> on error.</returns> [PhpVisible] public object transformToDoc(IXmlDomNode node) { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; using (MemoryStream stream = new MemoryStream()) { XmlWriterSettings settings = GetOutputSettings(); if (settings.Encoding is UTF8Encoding) { // no BOM in UTF-8 please! settings = settings.Clone(); settings.Encoding = new UTF8Encoding(false); } using (XmlWriter writer = XmlWriter.Create(stream, settings)) { // transform the document try { TransformToWriter(node.UnderlyingObject, xsltArgumentList, writer); } catch (XsltException e) { if (e.InnerException != null) { // ScriptDiedException etc. throw e.InnerException; } PhpException.Throw(PhpError.Warning, e.Message); return false; } catch (InvalidOperationException e) { PhpException.Throw(PhpError.Warning, e.Message); return false; } } stream.Seek(0, SeekOrigin.Begin); // build the resulting XML document try { doc.Load(stream); } catch (XmlException e) { PhpException.Throw(PhpError.Warning, e.Message); return false; } } return new DOMDocument(doc); } /// <summary> /// Transforms the source node to an URI applying the stylesheet given by the /// <see cref="importStylesheet(DOMDocument)"/> method. /// </summary> /// <param name="doc">The document to transform.</param> /// <param name="uri">The destination URI.</param> /// <returns>Returns the number of bytes written or <B>false</B> if an error occurred.</returns> [PhpVisible] public object transformToUri(DOMDocument doc, string uri) { using (PhpStream stream = PhpStream.Open(uri, "wt")) { if (stream == null) return false; // transform the document try { TransformToStream(doc.XmlNode, xsltArgumentList, stream.RawStream); } catch (XsltException e) { if (e.InnerException != null) { // ScriptDiedException etc. throw e.InnerException; } PhpException.Throw(PhpError.Warning, e.Message); return false; } catch (InvalidOperationException e) { PhpException.Throw(PhpError.Warning, e.Message); return false; } // TODO: return (stream.RawStream.CanSeek ? stream.RawStream.Position : 1); } } /// <summary> /// Transforms the source node to a string applying the stylesheet given by the /// <see cref="importStylesheet(DOMDocument)"/> method. /// </summary> /// <param name="doc">The document to transform.</param> /// <returns>The result of the transformation as a string or FALSE on error.</returns> [PhpVisible] public object transformToXml(DOMDocument doc) { // writing to a StringWriter would result in forcing UTF-16 encoding using (MemoryStream stream = new MemoryStream()) { XmlWriterSettings settings = GetOutputSettings(); if (settings.Encoding is UTF8Encoding) { // no BOM in UTF-8 please! settings = settings.Clone(); settings.Encoding = new UTF8Encoding(false); } using (XmlWriter writer = XmlWriter.Create(stream, settings)) { // transform the document try { TransformToWriter(doc.XmlNode, xsltArgumentList, writer); } catch (XsltException e) { if (e.InnerException != null) { // ScriptDiedException etc. throw e.InnerException; } PhpException.Throw(PhpError.Warning, e.Message); return false; } catch (InvalidOperationException e) { PhpException.Throw(PhpError.Warning, e.Message); return false; } } return new PhpBytes(stream.ToArray()); } } /// <summary> /// Sets value for a parameter. /// </summary> /// <param name="ns">The namespace URI of the XSLT parameter.</param> /// <param name="name">The local name of the XSLT parameter or an array of name =&gt; option pairs.</param> /// <param name="value">The new value of the XSLT parameter.</param> /// <returns><B>True</B> or <B>false</B>.</returns> [PhpVisible] public object setParameter(string ns, object name, [Optional] string value) { PhpArray array = name as PhpArray; if (array != null) { // set all name => value pairs contained in the array foreach (KeyValuePair<IntStringKey, object> pair in array) { if (!pair.Key.IsString) { PhpException.Throw(PhpError.Warning, Resources.InvalidParameterKey); return false; } if (xsltArgumentList.GetParam(pair.Key.String, ns) != null) { xsltArgumentList.RemoveParam(pair.Key.String, ns); } xsltArgumentList.AddParam(pair.Key.String, ns, XsltConvertor.PhpToDotNet(pair.Value)); } } else { string name_str = PHP.Core.Convert.ObjectToString(name); if (xsltArgumentList.GetParam(name_str, ns) != null) xsltArgumentList.RemoveParam(name_str, ns); xsltArgumentList.AddParam(name_str, ns, XsltConvertor.PhpToDotNet(value)); } return true; } /// <summary> /// Gets value of a parameter. /// </summary> /// <param name="ns">The namespace URI of the XSLT parameter.</param> /// <param name="name">The local name of the XSLT parameter.</param> /// <returns>The value of the parameter or NULL if it's not set.</returns> [PhpVisible] public object getParameter(string ns, string name) { return XsltConvertor.DotNetToPhp(xsltArgumentList.GetParam(name, ns)); } /// <summary> /// Removes a parameter. /// </summary> /// <param name="ns">The namespace URI of the XSLT parameter.</param> /// <param name="name">The local name of the XSLT parameter.</param> /// <returns><B>True</B> or <B>false</B>.</returns> [PhpVisible] public object removeParameter(string ns, string name) { return (xsltArgumentList.RemoveParam(name, ns) != null); } /// <summary> /// Determine if this extension has EXSLT support. /// </summary> /// <returns><B>False</B>.</returns> /// <remarks> /// A EXSLT implementation for the .NET XSL can be found here /// <A href="http://mvp-xml.sourceforge.net/exslt/">http://mvp-xml.sourceforge.net/exslt/</A>.</remarks> [PhpVisible] public object hasExsltSupport() { if (!mvpXmlAvailable) { PhpException.Throw(PhpError.Notice, Resources.ExsltSupportMissing); return false; } else return true; } /// <summary> /// Enables the ability to use PHP functions as XSLT functions. /// </summary> /// <param name="restrict">A string or array denoting function(s) to be made callable.</param> [PhpVisible] public void registerPHPFunctions([Optional] object restrict) { if (xsltUserFunctionHandler == null) { xsltUserFunctionHandler = new XsltUserFunctionHandler(); xsltArgumentList.AddExtensionObject(PhpNameSpaceUri, xsltUserFunctionHandler); } if (restrict == null) xsltUserFunctionHandler.RegisterAllFunctions(); else { // check for string argument string func_name = PhpVariable.AsString(restrict); if (func_name != null) xsltUserFunctionHandler.RegisterFunction(func_name); else { // check for array argument PhpArray func_names = restrict as PhpArray; if (func_names != null) { foreach (KeyValuePair<IntStringKey, object> pair in func_names) { xsltUserFunctionHandler.RegisterFunction(PHP.Core.Convert.ObjectToString(pair.Key.Object)); } } else xsltUserFunctionHandler.RegisterAllFunctions(); } } } #endregion } /// <summary> /// Provides conversion routines between .NET and PHP representation of W3C data types. /// </summary> internal static class XsltConvertor { #region Conversions /// <summary> /// Converts a W3C .NET object to the corresponding W3C PHP object. /// </summary> public static object DotNetToPhp(object arg) { // Result Tree Fragment (XSLT) / Node (XPath) XPathNavigator nav = arg as XPathNavigator; if (nav != null) return DOMNode.Create(nav.UnderlyingObject as XmlNode); // Node Set (XPath) - XPathNavigator[] XPathNavigator[] navs = arg as XPathNavigator[]; if (navs != null) { PhpArray array = new PhpArray(navs.Length, 0); for (int i = 0; i < navs.Length; i++) { IXmlDomNode node = DOMNode.Create(navs[i].UnderlyingObject as XmlNode); if (node != null) array.Add(node); } return array; } // Node Set (XPath) - XPathNodeIterator XPathNodeIterator iter = arg as XPathNodeIterator; if (iter != null) { PhpArray array = new PhpArray(); foreach (XPathNavigator navigator in iter) { IXmlDomNode node = DOMNode.Create(navigator.UnderlyingObject as XmlNode); if (node != null) array.Add(node); } return array; } // Number (XPath), Boolean (XPath), String (XPath) return arg; } /// <summary> /// Converts a W3C PHP object to the corresponding W3C .NET object. /// </summary> public static object/*!*/ PhpToDotNet(object arg) { if (arg == null) return String.Empty; // Node* (XPath) IXmlDomNode node = arg as IXmlDomNode; if (node != null) return node.UnderlyingObject.CreateNavigator(); // Node Set (XPath), Result Tree Fragment (XSLT) DOMNodeList list = arg as DOMNodeList; if (list != null) { XPathNavigator[] navs = new XPathNavigator[list.length]; int i = 0; foreach (var pair in (IEnumerable<KeyValuePair<object, object>>)list) { navs[i++] = ((IXmlDomNode)pair.Value).UnderlyingObject.CreateNavigator(); } return navs; } // any other object IPhpVariable var = arg as IPhpVariable; if (var != null) return var.ToString(); // String (XPath), Boolean (XPath), Number (XPath) return arg; } /// <summary> /// Converts a W3C PHP object to a corresponding string. /// </summary> public static string/*!*/ PhpToString(object arg) { // Node* (XPath) IXmlDomNode node = arg as IXmlDomNode; if (node != null) return node.UnderlyingObject.Value; // Node Set (XPath), Result Tree Fragment (XSLT) DOMNodeList list = arg as DOMNodeList; if (list != null) { if (list.length == 0) return String.Empty; return list.item(0).UnderlyingObject.Value; } // any other object return PHP.Core.Convert.ObjectToString(arg); } #endregion } /// <summary> /// Handles PHP function invocations via <code>php:function</code> and <code>php:functionString</code>. /// </summary> internal sealed class XsltUserFunctionHandler { #region Fields private bool allFunctionsRegistered; private Dictionary<string, PhpCallback> registeredFunctions = new Dictionary<string, PhpCallback>(); #endregion #region Function registration internal void RegisterAllFunctions() { allFunctionsRegistered = true; } internal void RegisterFunction(string functionName) { if (!registeredFunctions.ContainsKey(functionName)) { registeredFunctions.Add(functionName, null); } } #endregion #region Function invocation private object InvokeFunction(string name, params object[] args) { return XsltConvertor.PhpToDotNet(InvokeFunctionCore(name, args)); } private string InvokeFunctionString(string name, params object[] args) { return XsltConvertor.PhpToString(InvokeFunctionCore(name, args)); } private object InvokeFunctionCore(string name, params object[] args) { // check whether this function is allowed to be called PhpCallback callback; if (allFunctionsRegistered) { registeredFunctions.TryGetValue(name, out callback); } else { if (registeredFunctions.TryGetValue(name, out callback)) { PhpException.Throw(PhpError.Warning, String.Format(Resources.HandlerNotAllowed, name)); return null; } } // if the callback does not already exists, create it if (callback == null) { // parse name int index = name.IndexOf("::"); switch (index) { case -1: callback = new PhpCallback(name); break; case 0: callback = new PhpCallback(name.Substring(2)); break; default: callback = new PhpCallback(name.Substring(0, index), name.Substring(index + 2)); break; } if (!callback.Bind()) return null; registeredFunctions[name] = callback; } // convert arguments for (int i = 0; i < args.Length; i++) args[i] = XsltConvertor.DotNetToPhp(args[i]); // invoke! return callback.Invoke(args); } #endregion #region function (exposed to XSL) public object function(string name) { return InvokeFunction(name); } public object function(string name, object arg1) { return InvokeFunction(name, arg1); } public object function(string name, object arg1, object arg2) { return InvokeFunction(name, arg1, arg2); } public object function(string name, object arg1, object arg2, object arg3) { return InvokeFunction(name, arg1, arg2, arg3); } public object function(string name, object arg1, object arg2, object arg3, object arg4) { return InvokeFunction(name, arg1, arg2, arg3, arg4); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); } public object function(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20) { return InvokeFunction(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20); } #endregion #region functionString (exposed to XSL) public object functionString(string name) { return InvokeFunctionString(name); } public object functionString(string name, object arg1) { return InvokeFunctionString(name, arg1); } public object functionString(string name, object arg1, object arg2) { return InvokeFunctionString(name, arg1, arg2); } public object functionString(string name, object arg1, object arg2, object arg3) { return InvokeFunctionString(name, arg1, arg2, arg3); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19); } public object functionString(string name, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14, object arg15, object arg16, object arg17, object arg18, object arg19, object arg20) { return InvokeFunctionString(name, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15, arg16, arg17, arg18, arg19, arg20); } #endregion } }
using Microsoft.WindowsAzure.Storage.Auth; using Microsoft.WindowsAzure.Storage.Core; using Microsoft.WindowsAzure.Storage.Core.Auth; using Microsoft.WindowsAzure.Storage.Core.Executor; using Microsoft.WindowsAzure.Storage.Core.Util; using Microsoft.WindowsAzure.Storage.Queue.Protocol; using Microsoft.WindowsAzure.Storage.Shared.Protocol; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; namespace Microsoft.WindowsAzure.Storage.Queue { public class CloudQueue { public CloudQueueClient ServiceClient { get; private set; } public Uri Uri { get { throw new System.NotImplementedException(); } } public StorageUri StorageUri { get; private set; } public string Name { get; private set; } public int? ApproximateMessageCount { get; private set; } public bool EncodeMessage { get; set; } public IDictionary<string, string> Metadata { get; private set; } public CloudQueue(Uri queueAddress) : this(queueAddress, (StorageCredentials) null) { throw new System.NotImplementedException(); } public CloudQueue(Uri queueAddress, StorageCredentials credentials) : this(new StorageUri(queueAddress), credentials) { throw new System.NotImplementedException(); } public CloudQueue(StorageUri queueAddress, StorageCredentials credentials) { throw new System.NotImplementedException(); } internal CloudQueue(string queueName, CloudQueueClient serviceClient) : this((IDictionary<string, string>) new Dictionary<string, string>(), queueName, serviceClient) { throw new System.NotImplementedException(); } internal CloudQueue(IDictionary<string, string> metadata, string queueName, CloudQueueClient serviceClient) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task CreateAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task CreateAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task CreateAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> CreateIfNotExistsAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> CreateIfNotExistsAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> CreateIfNotExistsAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> DeleteIfExistsAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> DeleteIfExistsAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> DeleteIfExistsAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetPermissionsAsync(QueuePermissions permissions) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetPermissionsAsync(QueuePermissions permissions, QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetPermissionsAsync(QueuePermissions permissions, QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<QueuePermissions> GetPermissionsAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<QueuePermissions> GetPermissionsAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<QueuePermissions> GetPermissionsAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> ExistsAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> ExistsAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<bool> ExistsAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task FetchAttributesAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task FetchAttributesAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task FetchAttributesAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetMetadataAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetMetadataAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task SetMetadataAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task AddMessageAsync(CloudQueueMessage message) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task AddMessageAsync(CloudQueueMessage message, TimeSpan? timeToLive, TimeSpan? initialVisibilityDelay, QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task AddMessageAsync(CloudQueueMessage message, TimeSpan? timeToLive, TimeSpan? initialVisibilityDelay, QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UpdateMessageAsync(CloudQueueMessage message, TimeSpan visibilityTimeout, MessageUpdateFields updateFields) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UpdateMessageAsync(CloudQueueMessage message, TimeSpan visibilityTimeout, MessageUpdateFields updateFields, QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task UpdateMessageAsync(CloudQueueMessage message, TimeSpan visibilityTimeout, MessageUpdateFields updateFields, QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteMessageAsync(CloudQueueMessage message) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteMessageAsync(CloudQueueMessage message, QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteMessageAsync(string messageId, string popReceipt) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteMessageAsync(string messageId, string popReceipt, QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task DeleteMessageAsync(string messageId, string popReceipt, QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<CloudQueueMessage>> GetMessagesAsync(int messageCount) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<CloudQueueMessage>> GetMessagesAsync(int messageCount, TimeSpan? visibilityTimeout, QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<CloudQueueMessage>> GetMessagesAsync(int messageCount, TimeSpan? visibilityTimeout, QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudQueueMessage> GetMessageAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudQueueMessage> GetMessageAsync(TimeSpan? visibilityTimeout, QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudQueueMessage> GetMessageAsync(TimeSpan? visibilityTimeout, QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<CloudQueueMessage>> PeekMessagesAsync(int messageCount) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<CloudQueueMessage>> PeekMessagesAsync(int messageCount, QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<IEnumerable<CloudQueueMessage>> PeekMessagesAsync(int messageCount, QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudQueueMessage> PeekMessageAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudQueueMessage> PeekMessageAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task<CloudQueueMessage> PeekMessageAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task ClearAsync() { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task ClearAsync(QueueRequestOptions options, OperationContext operationContext) { throw new System.NotImplementedException(); } [DoesServiceRequest] public virtual Task ClearAsync(QueueRequestOptions options, OperationContext operationContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } private RESTCommand<NullType> CreateQueueImpl(QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> DeleteQueueImpl(QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> FetchAttributesImpl(QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<bool> ExistsImpl(QueueRequestOptions options, bool primaryOnly) { throw new System.NotImplementedException(); } private RESTCommand<NullType> SetMetadataImpl(QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> SetPermissionsImpl(QueuePermissions acl, QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<QueuePermissions> GetPermissionsImpl(QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> AddMessageImpl(CloudQueueMessage message, TimeSpan? timeToLive, TimeSpan? initialVisibilityDelay, QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> UpdateMessageImpl(CloudQueueMessage message, TimeSpan visibilityTimeout, MessageUpdateFields updateFields, QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<NullType> DeleteMessageImpl(string messageId, string popReceipt, QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<IEnumerable<CloudQueueMessage>> GetMessagesImpl(int messageCount, TimeSpan? visibilityTimeout, QueueRequestOptions options) { throw new System.NotImplementedException(); } private RESTCommand<IEnumerable<CloudQueueMessage>> PeekMessagesImpl(int messageCount, QueueRequestOptions options) { throw new System.NotImplementedException(); } internal StorageUri GetMessageRequestAddress() { throw new System.NotImplementedException(); } internal StorageUri GetIndividualMessageAddress(string messageId) { throw new System.NotImplementedException(); } private void ParseQueryAndVerify(StorageUri address, StorageCredentials credentials) { throw new System.NotImplementedException(); } private string GetCanonicalName() { throw new System.NotImplementedException(); } private static void CopyMessage(CloudQueueMessage message, QueueMessage protocolMessage) { throw new System.NotImplementedException(); } private CloudQueueMessage SelectGetMessageResponse(QueueMessage protocolMessage, QueueRequestOptions options = null) { throw new System.NotImplementedException(); } private CloudQueueMessage SelectPeekMessageResponse(QueueMessage protocolMessage, QueueRequestOptions options = null) { throw new System.NotImplementedException(); } public string GetSharedAccessSignature(SharedAccessQueuePolicy policy) { throw new System.NotImplementedException(); } public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier) { throw new System.NotImplementedException(); } public string GetSharedAccessSignature(SharedAccessQueuePolicy policy, string accessPolicyIdentifier, SharedAccessProtocol? protocols, IPAddressOrRange ipAddressOrRange) { throw new System.NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal class WinHttpRequestStream : Stream { private static byte[] s_crLfTerminator = new byte[] { 0x0d, 0x0a }; // "\r\n" private static byte[] s_endChunk = new byte[] { 0x30, 0x0d, 0x0a, 0x0d, 0x0a }; // "0\r\n\r\n" private volatile bool _disposed; private WinHttpRequestState _state; private bool _chunkedMode; // TODO (Issue 2505): temporary pinned buffer caches of 1 item. Will be replaced by PinnableBufferCache. private GCHandle _cachedSendPinnedBuffer; internal WinHttpRequestStream(WinHttpRequestState state, bool chunkedMode) { _state = state; _chunkedMode = chunkedMode; } public override bool CanRead { get { return false; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return !_disposed; } } public override long Length { get { CheckDisposed(); throw new NotSupportedException(); } } public override long Position { get { CheckDisposed(); throw new NotSupportedException(); } set { CheckDisposed(); throw new NotSupportedException(); } } public override void Flush() { // Nothing to do. } public override Task FlushAsync(CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { if (buffer == null) { throw new ArgumentNullException(nameof(buffer)); } if (offset < 0) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } if (count > buffer.Length - offset) { throw new ArgumentException(SR.net_http_buffer_insufficient_length, nameof(buffer)); } if (token.IsCancellationRequested) { var tcs = new TaskCompletionSource<int>(); tcs.TrySetCanceled(token); return tcs.Task; } CheckDisposed(); if (_state.TcsInternalWriteDataToRequestStream != null && !_state.TcsInternalWriteDataToRequestStream.Task.IsCompleted) { throw new InvalidOperationException(SR.net_http_no_concurrent_io_allowed); } return InternalWriteAsync(buffer, offset, count, token); } public override void Write(byte[] buffer, int offset, int count) { WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); } public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); throw new NotSupportedException(); } public override void SetLength(long value) { CheckDisposed(); throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { CheckDisposed(); throw new NotSupportedException(); } internal async Task EndUploadAsync(CancellationToken token) { if (_chunkedMode) { await InternalWriteDataAsync(s_endChunk, 0, s_endChunk.Length, token).ConfigureAwait(false); } } protected override void Dispose(bool disposing) { if (!_disposed) { _disposed = true; // TODO (Issue 2508): Pinned buffers must be released in the callback, when it is guaranteed no further // operations will be made to the send/receive buffers. if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } } base.Dispose(disposing); } private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().FullName); } } private Task InternalWriteAsync(byte[] buffer, int offset, int count, CancellationToken token) { return _chunkedMode ? InternalWriteChunkedModeAsync(buffer, offset, count, token) : InternalWriteDataAsync(buffer, offset, count, token); } private async Task InternalWriteChunkedModeAsync(byte[] buffer, int offset, int count, CancellationToken token) { // WinHTTP does not fully support chunked uploads. It simply allows one to omit the 'Content-Length' header // and instead use the 'Transfer-Encoding: chunked' header. The caller is still required to encode the // request body according to chunking rules. Debug.Assert(_chunkedMode); string chunkSizeString = String.Format("{0:x}\r\n", count); byte[] chunkSize = Encoding.UTF8.GetBytes(chunkSizeString); await InternalWriteDataAsync(chunkSize, 0, chunkSize.Length, token).ConfigureAwait(false); await InternalWriteDataAsync(buffer, offset, count, token).ConfigureAwait(false); await InternalWriteDataAsync(s_crLfTerminator, 0, s_crLfTerminator.Length, token).ConfigureAwait(false); } private Task<bool> InternalWriteDataAsync(byte[] buffer, int offset, int count, CancellationToken token) { Debug.Assert(count >= 0); if (count == 0) { return Task.FromResult<bool>(true); } // TODO (Issue 2505): replace with PinnableBufferCache. if (!_cachedSendPinnedBuffer.IsAllocated || _cachedSendPinnedBuffer.Target != buffer) { if (_cachedSendPinnedBuffer.IsAllocated) { _cachedSendPinnedBuffer.Free(); } _cachedSendPinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned); } _state.TcsInternalWriteDataToRequestStream = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); lock (_state.Lock) { if (!Interop.WinHttp.WinHttpWriteData( _state.RequestHandle, Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset), (uint)count, IntPtr.Zero)) { _state.TcsInternalWriteDataToRequestStream.TrySetException( new IOException(SR.net_http_io_write, WinHttpException.CreateExceptionUsingLastError())); } } // TODO: Issue #2165. Register callback on cancellation token to cancel WinHTTP operation. return _state.TcsInternalWriteDataToRequestStream.Task; } } }
// --------------------------------------------------------------------------- // <copyright file="AttachmentCollection.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Implements an attachment collection.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; /// <summary> /// Represents an item's attachment collection. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public sealed class AttachmentCollection : ComplexPropertyCollection<Attachment>, IOwnedProperty { #region Fields /// <summary> /// The item owner that owns this attachment collection /// </summary> private Item owner; #endregion #region Constructors /// <summary> /// Initializes a new instance of AttachmentCollection. /// </summary> internal AttachmentCollection() : base() { } #endregion #region Properties #region IOwnedProperty Members /// <summary> /// The owner of this attachment collection. /// </summary> ServiceObject IOwnedProperty.Owner { get { return this.owner; } set { Item item = value as Item; EwsUtilities.Assert( item != null, "AttachmentCollection.IOwnedProperty.set_Owner", "value is not a descendant of ItemBase"); this.owner = item; } } #endregion #endregion #region Methods /// <summary> /// Adds a file attachment to the collection. /// </summary> /// <param name="fileName">The name of the file representing the content of the attachment.</param> /// <returns>A FileAttachment instance.</returns> public FileAttachment AddFileAttachment(string fileName) { return this.AddFileAttachment(Path.GetFileName(fileName), fileName); } /// <summary> /// Adds a file attachment to the collection. /// </summary> /// <param name="name">The display name of the new attachment.</param> /// <param name="fileName">The name of the file representing the content of the attachment.</param> /// <returns>A FileAttachment instance.</returns> public FileAttachment AddFileAttachment(string name, string fileName) { FileAttachment fileAttachment = new FileAttachment(this.owner); fileAttachment.Name = name; fileAttachment.FileName = fileName; this.InternalAdd(fileAttachment); return fileAttachment; } /// <summary> /// Adds a file attachment to the collection. /// </summary> /// <param name="name">The display name of the new attachment.</param> /// <param name="contentStream">The stream from which to read the content of the attachment.</param> /// <returns>A FileAttachment instance.</returns> public FileAttachment AddFileAttachment(string name, Stream contentStream) { FileAttachment fileAttachment = new FileAttachment(this.owner); fileAttachment.Name = name; fileAttachment.ContentStream = contentStream; this.InternalAdd(fileAttachment); return fileAttachment; } /// <summary> /// Adds a file attachment to the collection. /// </summary> /// <param name="name">The display name of the new attachment.</param> /// <param name="content">A byte arrays representing the content of the attachment.</param> /// <returns>A FileAttachment instance.</returns> public FileAttachment AddFileAttachment(string name, byte[] content) { FileAttachment fileAttachment = new FileAttachment(this.owner); fileAttachment.Name = name; fileAttachment.Content = content; this.InternalAdd(fileAttachment); return fileAttachment; } /// <summary> /// Adds an item attachment to the collection /// </summary> /// <typeparam name="TItem">The type of the item to attach.</typeparam> /// <returns>An ItemAttachment instance.</returns> public ItemAttachment<TItem> AddItemAttachment<TItem>() where TItem : Item { if (typeof(TItem).GetCustomAttributes(typeof(AttachableAttribute), false).Length == 0) { throw new InvalidOperationException( string.Format( "Items of type {0} are not supported as attachments.", typeof(TItem).Name)); } ItemAttachment<TItem> itemAttachment = new ItemAttachment<TItem>(this.owner); itemAttachment.Item = (TItem)EwsUtilities.CreateItemFromItemClass(itemAttachment, typeof(TItem), true); this.InternalAdd(itemAttachment); return itemAttachment; } /// <summary> /// Removes all attachments from this collection. /// </summary> public void Clear() { this.InternalClear(); } /// <summary> /// Removes the attachment at the specified index. /// </summary> /// <param name="index">Index of the attachment to remove.</param> public void RemoveAt(int index) { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException("index", Strings.IndexIsOutOfRange); } this.InternalRemoveAt(index); } /// <summary> /// Removes the specified attachment. /// </summary> /// <param name="attachment">The attachment to remove.</param> /// <returns>True if the attachment was successfully removed from the collection, false otherwise.</returns> public bool Remove(Attachment attachment) { EwsUtilities.ValidateParam(attachment, "attachment"); return this.InternalRemove(attachment); } /// <summary> /// Instantiate the appropriate attachment type depending on the current XML element name. /// </summary> /// <param name="xmlElementName">The XML element name from which to determine the type of attachment to create.</param> /// <returns>An Attachment instance.</returns> internal override Attachment CreateComplexProperty(string xmlElementName) { switch (xmlElementName) { case XmlElementNames.FileAttachment: return new FileAttachment(this.owner); case XmlElementNames.ItemAttachment: return new ItemAttachment(this.owner); default: return null; } } /// <summary> /// Creates the default complex property. /// </summary> /// <returns>An Attachment instance.</returns> internal override Attachment CreateDefaultComplexProperty() { throw new JsonDeserializationNotImplementedException(); } /// <summary> /// Determines the name of the XML element associated with the complexProperty parameter. /// </summary> /// <param name="complexProperty">The attachment object for which to determine the XML element name with.</param> /// <returns>The XML element name associated with the complexProperty parameter.</returns> internal override string GetCollectionItemXmlElementName(Attachment complexProperty) { if (complexProperty is FileAttachment) { return XmlElementNames.FileAttachment; } else { return XmlElementNames.ItemAttachment; } } /// <summary> /// Saves this collection by creating new attachment and deleting removed ones. /// </summary> internal void Save() { List<Attachment> attachments = new List<Attachment>(); // Retrieve a list of attachments that have to be deleted. foreach (Attachment attachment in this.RemovedItems) { if (!attachment.IsNew) { attachments.Add(attachment); } } // If any, delete them by calling the DeleteAttachment web method. if (attachments.Count > 0) { this.InternalDeleteAttachments(attachments); } attachments.Clear(); // Retrieve a list of attachments that have to be created. foreach (Attachment attachment in this) { if (attachment.IsNew) { attachments.Add(attachment); } } // If there are any, create them by calling the CreateAttachment web method. if (attachments.Count > 0) { if (this.owner.IsAttachment) { this.InternalCreateAttachments(this.owner.ParentAttachment.Id, attachments); } else { this.InternalCreateAttachments(this.owner.Id.UniqueId, attachments); } } // Process all of the item attachments in this collection. foreach (Attachment attachment in this) { ItemAttachment itemAttachment = attachment as ItemAttachment; if (itemAttachment != null) { // Make sure item was created/loaded before trying to create/delete sub-attachments if (itemAttachment.Item != null) { // Create/delete any sub-attachments itemAttachment.Item.Attachments.Save(); // Clear the item's change log itemAttachment.Item.ClearChangeLog(); } } } base.ClearChangeLog(); } /// <summary> /// Determines whether there are any unsaved attachment collection changes. /// </summary> /// <returns>True if attachment adds or deletes haven't been processed yet.</returns> internal bool HasUnprocessedChanges() { // Any new attachments? foreach (Attachment attachment in this) { if (attachment.IsNew) { return true; } } // Any pending deletions? foreach (Attachment attachment in this.RemovedItems) { if (!attachment.IsNew) { return true; } } // Recurse: process item attachments to check for new or deleted sub-attachments. foreach (ItemAttachment itemAttachment in this.OfType<ItemAttachment>()) { if (itemAttachment.Item != null) { if (itemAttachment.Item.Attachments.HasUnprocessedChanges()) { return true; } } } return false; } /// <summary> /// Disables the change log clearing mechanism. Attachment collections are saved separately /// from the items they belong to. /// </summary> internal override void ClearChangeLog() { // Do nothing } /// <summary> /// Validates this instance. /// </summary> internal void Validate() { // Validate all added attachments bool contactPhotoFound = false; for (int attachmentIndex = 0; attachmentIndex < this.AddedItems.Count; attachmentIndex++) { Attachment attachment = this.AddedItems[attachmentIndex]; if (attachment.IsNew) { // At the server side, only the last attachment with IsContactPhoto is kept, all other IsContactPhoto // attachments are removed. CreateAttachment will generate AttachmentId for each of such attachments (although // only the last one is valid). // // With E14 SP2 CreateItemWithAttachment, such request will only return 1 AttachmentId; but the client // expects to see all, so let us prevent such "invalid" request in the first place. // // The IsNew check is to still let CreateAttachmentRequest allow multiple IsContactPhoto attachments. // if (this.owner.IsNew && this.owner.Service.RequestedServerVersion >= ExchangeVersion.Exchange2010_SP2) { FileAttachment fileAttachment = attachment as FileAttachment; if (fileAttachment != null && fileAttachment.IsContactPhoto) { if (contactPhotoFound) { throw new ServiceValidationException(Strings.MultipleContactPhotosInAttachment); } contactPhotoFound = true; } } attachment.Validate(attachmentIndex); } } } /// <summary> /// Calls the DeleteAttachment web method to delete a list of attachments. /// </summary> /// <param name="attachments">The attachments to delete.</param> private void InternalDeleteAttachments(IEnumerable<Attachment> attachments) { ServiceResponseCollection<DeleteAttachmentResponse> responses = this.owner.Service.DeleteAttachments(attachments); foreach (DeleteAttachmentResponse response in responses) { // We remove all attachments that were successfully deleted from the change log. We should never // receive a warning from EWS, so we ignore them. if (response.Result != ServiceResult.Error) { this.RemoveFromChangeLog(response.Attachment); } } // TODO : Should we throw for warnings as well? if (responses.OverallResult == ServiceResult.Error) { throw new DeleteAttachmentException(responses, Strings.AtLeastOneAttachmentCouldNotBeDeleted); } } /// <summary> /// Calls the CreateAttachment web method to create a list of attachments. /// </summary> /// <param name="parentItemId">The Id of the parent item of the new attachments.</param> /// <param name="attachments">The attachments to create.</param> private void InternalCreateAttachments(string parentItemId, IEnumerable<Attachment> attachments) { ServiceResponseCollection<CreateAttachmentResponse> responses = this.owner.Service.CreateAttachments(parentItemId, attachments); foreach (CreateAttachmentResponse response in responses) { // We remove all attachments that were successfully created from the change log. We should never // receive a warning from EWS, so we ignore them. if (response.Result != ServiceResult.Error) { this.RemoveFromChangeLog(response.Attachment); } } // TODO : Should we throw for warnings as well? if (responses.OverallResult == ServiceResult.Error) { throw new CreateAttachmentException(responses, Strings.AttachmentCreationFailed); } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Serialization; using GlmSharp.Swizzle; // ReSharper disable InconsistentNaming namespace GlmSharp { /// <summary> /// A matrix of type long with 2 columns and 4 rows. /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct lmat2x4 : IEnumerable<long>, IEquatable<lmat2x4> { #region Fields /// <summary> /// Column 0, Rows 0 /// </summary> public long m00; /// <summary> /// Column 0, Rows 1 /// </summary> public long m01; /// <summary> /// Column 0, Rows 2 /// </summary> public long m02; /// <summary> /// Column 0, Rows 3 /// </summary> public long m03; /// <summary> /// Column 1, Rows 0 /// </summary> public long m10; /// <summary> /// Column 1, Rows 1 /// </summary> public long m11; /// <summary> /// Column 1, Rows 2 /// </summary> public long m12; /// <summary> /// Column 1, Rows 3 /// </summary> public long m13; #endregion #region Constructors /// <summary> /// Component-wise constructor /// </summary> public lmat2x4(long m00, long m01, long m02, long m03, long m10, long m11, long m12, long m13) { this.m00 = m00; this.m01 = m01; this.m02 = m02; this.m03 = m03; this.m10 = m10; this.m11 = m11; this.m12 = m12; this.m13 = m13; } /// <summary> /// Constructs this matrix from a lmat2. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a lmat3x2. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat3x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a lmat4x2. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat4x2 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = 0; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a lmat2x3. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat2x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a lmat3. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a lmat4x3. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat4x3 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = 0; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = 0; } /// <summary> /// Constructs this matrix from a lmat2x4. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat2x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a lmat3x4. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat3x4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a lmat4. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lmat4 m) { this.m00 = m.m00; this.m01 = m.m01; this.m02 = m.m02; this.m03 = m.m03; this.m10 = m.m10; this.m11 = m.m11; this.m12 = m.m12; this.m13 = m.m13; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lvec2 c0, lvec2 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = 0; this.m03 = 0; this.m10 = c1.x; this.m11 = c1.y; this.m12 = 0; this.m13 = 0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lvec3 c0, lvec3 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = 0; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = 0; } /// <summary> /// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix. /// </summary> public lmat2x4(lvec4 c0, lvec4 c1) { this.m00 = c0.x; this.m01 = c0.y; this.m02 = c0.z; this.m03 = c0.w; this.m10 = c1.x; this.m11 = c1.y; this.m12 = c1.z; this.m13 = c1.w; } #endregion #region Properties /// <summary> /// Creates a 2D array with all values (address: Values[x, y]) /// </summary> public long[,] Values => new[,] { { m00, m01, m02, m03 }, { m10, m11, m12, m13 } }; /// <summary> /// Creates a 1D array with all values (internal order) /// </summary> public long[] Values1D => new[] { m00, m01, m02, m03, m10, m11, m12, m13 }; /// <summary> /// Gets or sets the column nr 0 /// </summary> public lvec4 Column0 { get { return new lvec4(m00, m01, m02, m03); } set { m00 = value.x; m01 = value.y; m02 = value.z; m03 = value.w; } } /// <summary> /// Gets or sets the column nr 1 /// </summary> public lvec4 Column1 { get { return new lvec4(m10, m11, m12, m13); } set { m10 = value.x; m11 = value.y; m12 = value.z; m13 = value.w; } } /// <summary> /// Gets or sets the row nr 0 /// </summary> public lvec2 Row0 { get { return new lvec2(m00, m10); } set { m00 = value.x; m10 = value.y; } } /// <summary> /// Gets or sets the row nr 1 /// </summary> public lvec2 Row1 { get { return new lvec2(m01, m11); } set { m01 = value.x; m11 = value.y; } } /// <summary> /// Gets or sets the row nr 2 /// </summary> public lvec2 Row2 { get { return new lvec2(m02, m12); } set { m02 = value.x; m12 = value.y; } } /// <summary> /// Gets or sets the row nr 3 /// </summary> public lvec2 Row3 { get { return new lvec2(m03, m13); } set { m03 = value.x; m13 = value.y; } } #endregion #region Static Properties /// <summary> /// Predefined all-zero matrix /// </summary> public static lmat2x4 Zero { get; } = new lmat2x4(0, 0, 0, 0, 0, 0, 0, 0); /// <summary> /// Predefined all-ones matrix /// </summary> public static lmat2x4 Ones { get; } = new lmat2x4(1, 1, 1, 1, 1, 1, 1, 1); /// <summary> /// Predefined identity matrix /// </summary> public static lmat2x4 Identity { get; } = new lmat2x4(1, 0, 0, 0, 0, 1, 0, 0); /// <summary> /// Predefined all-MaxValue matrix /// </summary> public static lmat2x4 AllMaxValue { get; } = new lmat2x4(long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue, long.MaxValue); /// <summary> /// Predefined diagonal-MaxValue matrix /// </summary> public static lmat2x4 DiagonalMaxValue { get; } = new lmat2x4(long.MaxValue, 0, 0, 0, 0, long.MaxValue, 0, 0); /// <summary> /// Predefined all-MinValue matrix /// </summary> public static lmat2x4 AllMinValue { get; } = new lmat2x4(long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue, long.MinValue); /// <summary> /// Predefined diagonal-MinValue matrix /// </summary> public static lmat2x4 DiagonalMinValue { get; } = new lmat2x4(long.MinValue, 0, 0, 0, 0, long.MinValue, 0, 0); #endregion #region Functions /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> public IEnumerator<long> GetEnumerator() { yield return m00; yield return m01; yield return m02; yield return m03; yield return m10; yield return m11; yield return m12; yield return m13; } /// <summary> /// Returns an enumerator that iterates through all fields. /// </summary> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); #endregion /// <summary> /// Returns the number of Fields (2 x 4 = 8). /// </summary> public int Count => 8; /// <summary> /// Gets/Sets a specific indexed component (a bit slower than direct access). /// </summary> public long this[int fieldIndex] { get { switch (fieldIndex) { case 0: return m00; case 1: return m01; case 2: return m02; case 3: return m03; case 4: return m10; case 5: return m11; case 6: return m12; case 7: return m13; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } set { switch (fieldIndex) { case 0: this.m00 = value; break; case 1: this.m01 = value; break; case 2: this.m02 = value; break; case 3: this.m03 = value; break; case 4: this.m10 = value; break; case 5: this.m11 = value; break; case 6: this.m12 = value; break; case 7: this.m13 = value; break; default: throw new ArgumentOutOfRangeException("fieldIndex"); } } } /// <summary> /// Gets/Sets a specific 2D-indexed component (a bit slower than direct access). /// </summary> public long this[int col, int row] { get { return this[col * 4 + row]; } set { this[col * 4 + row] = value; } } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public bool Equals(lmat2x4 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && (m02.Equals(rhs.m02) && m03.Equals(rhs.m03))) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && (m12.Equals(rhs.m12) && m13.Equals(rhs.m13)))); /// <summary> /// Returns true iff this equals rhs type- and component-wise. /// </summary> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is lmat2x4 && Equals((lmat2x4) obj); } /// <summary> /// Returns true iff this equals rhs component-wise. /// </summary> public static bool operator ==(lmat2x4 lhs, lmat2x4 rhs) => lhs.Equals(rhs); /// <summary> /// Returns true iff this does not equal rhs (component-wise). /// </summary> public static bool operator !=(lmat2x4 lhs, lmat2x4 rhs) => !lhs.Equals(rhs); /// <summary> /// Returns a hash code for this instance. /// </summary> public override int GetHashCode() { unchecked { return ((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m03.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m13.GetHashCode(); } } /// <summary> /// Returns a transposed version of this matrix. /// </summary> public lmat4x2 Transposed => new lmat4x2(m00, m10, m01, m11, m02, m12, m03, m13); /// <summary> /// Returns the minimal component of this matrix. /// </summary> public long MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m03), m10), m11), m12), m13); /// <summary> /// Returns the maximal component of this matrix. /// </summary> public long MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m03), m10), m11), m12), m13); /// <summary> /// Returns the euclidean length of this matrix. /// </summary> public double Length => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the squared euclidean length of this matrix. /// </summary> public double LengthSqr => (((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13))); /// <summary> /// Returns the sum of all fields. /// </summary> public long Sum => (((m00 + m01) + (m02 + m03)) + ((m10 + m11) + (m12 + m13))); /// <summary> /// Returns the euclidean norm of this matrix. /// </summary> public double Norm => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the one-norm of this matrix. /// </summary> public double Norm1 => (((Math.Abs(m00) + Math.Abs(m01)) + (Math.Abs(m02) + Math.Abs(m03))) + ((Math.Abs(m10) + Math.Abs(m11)) + (Math.Abs(m12) + Math.Abs(m13)))); /// <summary> /// Returns the two-norm of this matrix. /// </summary> public double Norm2 => (double)Math.Sqrt((((m00*m00 + m01*m01) + (m02*m02 + m03*m03)) + ((m10*m10 + m11*m11) + (m12*m12 + m13*m13)))); /// <summary> /// Returns the max-norm of this matrix. /// </summary> public long NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m03)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m13)); /// <summary> /// Returns the p-norm of this matrix. /// </summary> public double NormP(double p) => Math.Pow((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + (Math.Pow((double)Math.Abs(m02), p) + Math.Pow((double)Math.Abs(m03), p))) + ((Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p)) + (Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m13), p)))), 1 / p); /// <summary> /// Executes a matrix-matrix-multiplication lmat2x4 * lmat2 -> lmat2x4. /// </summary> public static lmat2x4 operator*(lmat2x4 lhs, lmat2 rhs) => new lmat2x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11)); /// <summary> /// Executes a matrix-matrix-multiplication lmat2x4 * lmat3x2 -> lmat3x4. /// </summary> public static lmat3x4 operator*(lmat2x4 lhs, lmat3x2 rhs) => new lmat3x4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21)); /// <summary> /// Executes a matrix-matrix-multiplication lmat2x4 * lmat4x2 -> lmat4. /// </summary> public static lmat4 operator*(lmat2x4 lhs, lmat4x2 rhs) => new lmat4((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m03 * rhs.m00 + lhs.m13 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m03 * rhs.m10 + lhs.m13 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m03 * rhs.m20 + lhs.m13 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31), (lhs.m03 * rhs.m30 + lhs.m13 * rhs.m31)); /// <summary> /// Executes a matrix-vector-multiplication. /// </summary> public static lvec4 operator*(lmat2x4 m, lvec2 v) => new lvec4((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y), (m.m03 * v.x + m.m13 * v.y)); /// <summary> /// Executes a component-wise * (multiply). /// </summary> public static lmat2x4 CompMul(lmat2x4 A, lmat2x4 B) => new lmat2x4(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m03 * B.m03, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m13 * B.m13); /// <summary> /// Executes a component-wise / (divide). /// </summary> public static lmat2x4 CompDiv(lmat2x4 A, lmat2x4 B) => new lmat2x4(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m03 / B.m03, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m13 / B.m13); /// <summary> /// Executes a component-wise + (add). /// </summary> public static lmat2x4 CompAdd(lmat2x4 A, lmat2x4 B) => new lmat2x4(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m03 + B.m03, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m13 + B.m13); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static lmat2x4 CompSub(lmat2x4 A, lmat2x4 B) => new lmat2x4(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m03 - B.m03, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m13 - B.m13); /// <summary> /// Executes a component-wise + (add). /// </summary> public static lmat2x4 operator+(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m03 + rhs.m03, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m13 + rhs.m13); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static lmat2x4 operator+(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m03 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m13 + rhs); /// <summary> /// Executes a component-wise + (add) with a scalar. /// </summary> public static lmat2x4 operator+(long lhs, lmat2x4 rhs) => new lmat2x4(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m03, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m13); /// <summary> /// Executes a component-wise - (subtract). /// </summary> public static lmat2x4 operator-(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m03 - rhs.m03, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m13 - rhs.m13); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static lmat2x4 operator-(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m03 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m13 - rhs); /// <summary> /// Executes a component-wise - (subtract) with a scalar. /// </summary> public static lmat2x4 operator-(long lhs, lmat2x4 rhs) => new lmat2x4(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m03, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m13); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static lmat2x4 operator/(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m03 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m13 / rhs); /// <summary> /// Executes a component-wise / (divide) with a scalar. /// </summary> public static lmat2x4 operator/(long lhs, lmat2x4 rhs) => new lmat2x4(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m03, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m13); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static lmat2x4 operator*(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m03 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m13 * rhs); /// <summary> /// Executes a component-wise * (multiply) with a scalar. /// </summary> public static lmat2x4 operator*(long lhs, lmat2x4 rhs) => new lmat2x4(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m03, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m13); /// <summary> /// Executes a component-wise % (modulo). /// </summary> public static lmat2x4 operator%(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m02 % rhs.m02, lhs.m03 % rhs.m03, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11, lhs.m12 % rhs.m12, lhs.m13 % rhs.m13); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static lmat2x4 operator%(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m02 % rhs, lhs.m03 % rhs, lhs.m10 % rhs, lhs.m11 % rhs, lhs.m12 % rhs, lhs.m13 % rhs); /// <summary> /// Executes a component-wise % (modulo) with a scalar. /// </summary> public static lmat2x4 operator%(long lhs, lmat2x4 rhs) => new lmat2x4(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m02, lhs % rhs.m03, lhs % rhs.m10, lhs % rhs.m11, lhs % rhs.m12, lhs % rhs.m13); /// <summary> /// Executes a component-wise ^ (xor). /// </summary> public static lmat2x4 operator^(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m02 ^ rhs.m02, lhs.m03 ^ rhs.m03, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11, lhs.m12 ^ rhs.m12, lhs.m13 ^ rhs.m13); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static lmat2x4 operator^(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m02 ^ rhs, lhs.m03 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs, lhs.m12 ^ rhs, lhs.m13 ^ rhs); /// <summary> /// Executes a component-wise ^ (xor) with a scalar. /// </summary> public static lmat2x4 operator^(long lhs, lmat2x4 rhs) => new lmat2x4(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m02, lhs ^ rhs.m03, lhs ^ rhs.m10, lhs ^ rhs.m11, lhs ^ rhs.m12, lhs ^ rhs.m13); /// <summary> /// Executes a component-wise | (bitwise-or). /// </summary> public static lmat2x4 operator|(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m02 | rhs.m02, lhs.m03 | rhs.m03, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11, lhs.m12 | rhs.m12, lhs.m13 | rhs.m13); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static lmat2x4 operator|(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m02 | rhs, lhs.m03 | rhs, lhs.m10 | rhs, lhs.m11 | rhs, lhs.m12 | rhs, lhs.m13 | rhs); /// <summary> /// Executes a component-wise | (bitwise-or) with a scalar. /// </summary> public static lmat2x4 operator|(long lhs, lmat2x4 rhs) => new lmat2x4(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m02, lhs | rhs.m03, lhs | rhs.m10, lhs | rhs.m11, lhs | rhs.m12, lhs | rhs.m13); /// <summary> /// Executes a component-wise &amp; (bitwise-and). /// </summary> public static lmat2x4 operator&(lmat2x4 lhs, lmat2x4 rhs) => new lmat2x4(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m02 & rhs.m02, lhs.m03 & rhs.m03, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11, lhs.m12 & rhs.m12, lhs.m13 & rhs.m13); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static lmat2x4 operator&(lmat2x4 lhs, long rhs) => new lmat2x4(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m02 & rhs, lhs.m03 & rhs, lhs.m10 & rhs, lhs.m11 & rhs, lhs.m12 & rhs, lhs.m13 & rhs); /// <summary> /// Executes a component-wise &amp; (bitwise-and) with a scalar. /// </summary> public static lmat2x4 operator&(long lhs, lmat2x4 rhs) => new lmat2x4(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m02, lhs & rhs.m03, lhs & rhs.m10, lhs & rhs.m11, lhs & rhs.m12, lhs & rhs.m13); /// <summary> /// Executes a component-wise left-shift with a scalar. /// </summary> public static lmat2x4 operator<<(lmat2x4 lhs, int rhs) => new lmat2x4(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m02 << rhs, lhs.m03 << rhs, lhs.m10 << rhs, lhs.m11 << rhs, lhs.m12 << rhs, lhs.m13 << rhs); /// <summary> /// Executes a component-wise right-shift with a scalar. /// </summary> public static lmat2x4 operator>>(lmat2x4 lhs, int rhs) => new lmat2x4(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m02 >> rhs, lhs.m03 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs, lhs.m12 >> rhs, lhs.m13 >> rhs); /// <summary> /// Executes a component-wise lesser-than comparison. /// </summary> public static bmat2x4 operator<(lmat2x4 lhs, lmat2x4 rhs) => new bmat2x4(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m03 < rhs.m03, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m13 < rhs.m13); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2x4 operator<(lmat2x4 lhs, long rhs) => new bmat2x4(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m03 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m13 < rhs); /// <summary> /// Executes a component-wise lesser-than comparison with a scalar. /// </summary> public static bmat2x4 operator<(long lhs, lmat2x4 rhs) => new bmat2x4(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m03, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m13); /// <summary> /// Executes a component-wise lesser-or-equal comparison. /// </summary> public static bmat2x4 operator<=(lmat2x4 lhs, lmat2x4 rhs) => new bmat2x4(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m03 <= rhs.m03, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m13 <= rhs.m13); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator<=(lmat2x4 lhs, long rhs) => new bmat2x4(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m03 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m13 <= rhs); /// <summary> /// Executes a component-wise lesser-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator<=(long lhs, lmat2x4 rhs) => new bmat2x4(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m03, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m13); /// <summary> /// Executes a component-wise greater-than comparison. /// </summary> public static bmat2x4 operator>(lmat2x4 lhs, lmat2x4 rhs) => new bmat2x4(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m03 > rhs.m03, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m13 > rhs.m13); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2x4 operator>(lmat2x4 lhs, long rhs) => new bmat2x4(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m03 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m13 > rhs); /// <summary> /// Executes a component-wise greater-than comparison with a scalar. /// </summary> public static bmat2x4 operator>(long lhs, lmat2x4 rhs) => new bmat2x4(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m03, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m13); /// <summary> /// Executes a component-wise greater-or-equal comparison. /// </summary> public static bmat2x4 operator>=(lmat2x4 lhs, lmat2x4 rhs) => new bmat2x4(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m03 >= rhs.m03, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m13 >= rhs.m13); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator>=(lmat2x4 lhs, long rhs) => new bmat2x4(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m03 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m13 >= rhs); /// <summary> /// Executes a component-wise greater-or-equal comparison with a scalar. /// </summary> public static bmat2x4 operator>=(long lhs, lmat2x4 rhs) => new bmat2x4(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m03, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m13); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility001.accessibility001 { public class Test { public void Method() { } protected void Method(int x, object o) { s_status = 1; } protected internal void Method(long x, object o) { s_status = 2; } internal void Method(short x, object o) { s_status = 3; } private static int s_status = -1; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Test b = new Test(); dynamic x = 1; dynamic y = null; b.Method(x, y); return s_status == 1 ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility002.accessibility002 { public class Test { public void Method() { } protected void Method(int x, object o) { s_status = 1; } protected internal void Method(long x, object o) { s_status = 2; } internal void Method(short x, object o) { s_status = 3; } private static int s_status = -1; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { var b = new Test(); b.Method(); dynamic x = short.MinValue; dynamic y = null; b.Method(x, y); return s_status == 3 ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.errorverifier.errorverifier { public enum ErrorElementId { None, SK_METHOD, // method SK_CLASS, // type SK_NAMESPACE, // namespace SK_FIELD, // field SK_PROPERTY, // property SK_UNKNOWN, // element SK_VARIABLE, // variable SK_EVENT, // event SK_TYVAR, // type parameter SK_ALIAS, // using alias ERRORSYM, // <error> NULL, // <null> GlobalNamespace, // <global namespace> MethodGroup, // method group AnonMethod, // anonymous method Lambda, // lambda expression AnonymousType, // anonymous type } public enum ErrorMessageId { None, BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' IntDivByZero, // Division by constant zero BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}' BadIndexCount, // Wrong number of indices inside []; expected '{0}' BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}' NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}' NoExplicitConv, // Cannot convert type '{0}' to '{1}' ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}' AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}' ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}' NoSuchMember, // '{0}' does not contain a definition for '{1}' ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}' AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}' BadAccess, // '{0}' is inaccessible due to its protection level MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}' AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer NoConstructors, // The type '{0}' has no constructors defined BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer) RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor) AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor) AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only AbstractBaseCall, // Cannot call an abstract base member: '{0}' RefProperty, // A property or indexer may not be passed as an out or ref parameter ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}') FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false CheckedOverflow, // The operation overflows at compile time in checked mode ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override) AmbigMember, // Ambiguity between '{0}' and '{1}' SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}' CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor. BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?) InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments BadTypeArgument, // The type '{0}' may not be used as a type argument TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}' GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints. GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'. TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead. BadRetType, // '{1} {0}' has the wrong return type CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly. MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method? RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}' ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}' CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}' BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}' ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}' AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}' PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly BindToBogus, // '{0}' is not supported by the language CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor BogusType, // '{0}' is a type not supported by the language MissingPredefinedMember, // Missing compiler required member '{0}.{1}' LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions ConvertToStaticClass, // Cannot convert to static type '{0}' GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?) ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates BadArgCount, // No overload for method '{0}' takes '{1}' arguments BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}' RefLvalueExpected, // A ref or out argument must be an assignable variable BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it) BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}' BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}' BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments BadDelArgTypes, // Delegate '{0}' has some invalid arguments AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword // DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED) BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer) RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor) AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor) AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}' RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}' ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}' BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters. NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method. NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}' BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}' DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given } public enum RuntimeErrorId { None, // RuntimeBinderInternalCompilerException InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation // ArgumentException BindRequireArguments, // Cannot bind call with no calling object // RuntimeBinderException BindCallFailedOverloadResolution, // Overload resolution failed // ArgumentException BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments // ArgumentException BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument // RuntimeBinderException BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property // RuntimeBinderException BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -= // RuntimeBinderException BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type // ArgumentException BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument // ArgumentException BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument // ArgumentException BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument // RuntimeBinderException BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference // RuntimeBinderException NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference // RuntimeBinderException BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute // RuntimeBinderException BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object' // EE? EmptyDynamicView, // No further information on this object could be discovered // MissingMemberException GetValueonWriteOnlyProperty, // Write Only properties are not supported } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility003.accessibility003 { public class Test { private delegate void Del(long x, int y); public void Method(long x, int y) { } private void Method(int x, int y) { } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic b = new Test(); try { Del ddd = new Del(b.Method); dynamic d1 = 1; dynamic d2 = 2; ddd(d1, d2); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility004.accessibility004 { // <Title>Accessibility</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success></Expects> // <Code> public struct Test { public void Method() { } private void Method(int x, object o) { s_status = 1; } internal void Method(long x, object o) { s_status = 2; } internal void Method(short x, object o) { s_status = 3; } private static int s_status = -1; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Test b = new Test(); dynamic x = -1; dynamic y = null; b.Method(x, y); return s_status == 1 ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility005.accessibility005 { public class Test { private class Base { public void Method(int x) { } } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new Base(); dynamic x = int.MaxValue; b.Method(x); return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility006.accessibility006 { public class Test { protected class Base { public void Method() { } protected void Method(int x, object o) { } protected internal void Method(long x, object o) { } internal void Method(short x, object o) { } public void Method(byte x, object o) { } } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new Base(); dynamic x = byte.MaxValue; dynamic y = new object(); b.Method(x, y); return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility007.accessibility007 { public class Test { public void Method(int x, int y) { s_status = 1; } private void Method(long x, int y) { s_status = 2; } internal void Method1(short x, int y) { s_status = 3; } protected void Method1(long x, int y) { s_status = 4; } private static int s_status = -1; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic b = new Test(); dynamic d1 = 1; dynamic d2 = 2; b.Method(d1, d2); bool ret = s_status == 1; b.Method1(d1, d2); ret &= (s_status == 4); return ret ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility011.accessibility011 { public class Test { public class Higher { private class Base { public void Method(int x) { } } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new Base(); dynamic x = int.MaxValue; b.Method(x); return 0; } } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Twoparam.accessibility012.accessibility012 { public class Test { internal class Base { public void Method(int x) { Test.Status = 1; } } public static int Status; public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Base b = new Base(); dynamic x = int.MaxValue; b.Method(x); if (Test.Status == 1) return 0; return 1; } } // </Code> }
using UnityEngine; using System.Collections; public enum Mode { Displacement3D, Animation2D } public class NoiseExample : MonoBehaviour { public Mode currentMode = Mode.Displacement3D; // 3D Displacement Materials public Material currentDisplacementMaterial; public Material perlinDisplacementMaterial; public Material fBmDisplacementMaterial; public Material turbulenceDisplacementMaterial; public Material ridgedDisplacementMaterial; public Material voronoiDisplacementMaterial; public Material F2DisplacementMaterial; public Material F2MinusF1DisplacementMaterial; public Material F1PlusF2DisplacementMaterial; public Material craterDisplacementMaterial; // 2D Animation Materials public Material currentMaterial; public Material perlinMaterial; public Material fBmMaterial; public Material turbulenceMaterial; public Material ridgedMaterial; public Material voronoiMaterial; public Material F2Material; public Material F2MinusF1Material; public Material F1PlusF2Material; public Material craterMaterial; // GLSL 3D Displacement Materials public Material currentGLSLDisplacementMaterial; public Material GLSLPerlinDisplacementMaterial; public Material GLSLfBmDisplacementMaterial; public Material GLSLTurbulenceDisplacementMaterial; public Material GLSLRidgedDisplacementMaterial; public Material GLSLVoronoiDisplacementMaterial; public Material GLSLF2DisplacementMaterial; public Material GLSLF2MinusF1DisplacementMaterial; public Material GLSLF1PlusF2DisplacementMaterial; public Material GLSLCraterDisplacementMaterial; // GLSL 2D Animation Materials public Material currentGLSLMaterial; public Material GLSLPerlinMaterial; public Material GLSLfBmMaterial; public Material GLSLTurbulenceMaterial; public Material GLSLRidgedMaterial; public Material GLSLVoronoiMaterial; public Material GLSLF2Material; public Material GLSLF2MinusF1Material; public Material GLSLF1PlusF2Material; public Material GLSLCraterMaterial; private float time = 0; private float heightScale = 0.05f; private float noiseScale = 5; private bool animate = true; private string[] noiseTypes = { "Perlin", "fBm", "Turbulence", "Ridged", "Voronoi", "F2", "F2 - F1", "(F1 + F2) / 2", "Crater" }; private int currentNoiseSelection = 0; private int previousNoiseSelection = 0; private Rect lowColorWindow; private float lowRed = 0; private float lowGreen = 0; private float lowBlue = 1; private Rect highColorWindow; private float highRed = 0; private float highGreen = 1; private float highBlue = 0; private Rect shaderLevelWindow; private Mesh sphereMesh; private Mesh quadMesh; private bool useGLSL; void Start() { // force it to Landscape on mobile (can be set in the Player Settings, too) Screen.orientation = ScreenOrientation.Landscape; // procedurally build the sphere mesh (for 3D Displacement) sphereMesh = Shape3D.CreateSphereMesh(0.5f, 100, 100); // highly tessellated sphere //sphereMesh = Shape3D.CreateSphereMesh(0.5f, 10, 10); // low poly sphere // use the sphere mesh built-in to Unity //GameObject sphere = GameObject.CreatePrimitive(PrimitiveType.Sphere); //sphereMesh = sphere.GetComponent<MeshFilter>().mesh; //GameObject.DestroyImmediate(sphere); // build the mesh (full screen quad) in clip-space (for 2D Animation) quadMesh = new Mesh(); quadMesh.vertices = new Vector3[] { new Vector3(-1, 1), new Vector3(1, 1), new Vector3(-1, -1), new Vector3(1, -1) }; quadMesh.uv = new Vector2[] { new Vector2(0, 1), new Vector2(1, 1), new Vector2(0, 0), new Vector2(1, 0) }; quadMesh.triangles = new int[] { 0, 1, 2, 1, 3, 2 }; // if not on Windows, default to use the GLSL version of noise if (!SystemInfo.operatingSystem.ToLower().Contains("windows")) { Debug.Log("Detected " + SystemInfo.operatingSystem + ". Using GLSL..."); useGLSL = true; } else { Debug.Log("Detected " + SystemInfo.operatingSystem + ". Using Cg..."); } } void OnGUI() { lowColorWindow = new Rect(5, Screen.height - 100 - 5, 200, 100); highColorWindow = new Rect(Screen.width - 200 - 5, Screen.height - 100 - 5, 200, 100); shaderLevelWindow = new Rect(Screen.width / 2 - 350 / 2, Screen.height / 2 - 100 / 2, 350, 100); GUI.Label(new Rect(25, 45, 100, 30), "Noise Scale"); noiseScale = GUI.HorizontalSlider(new Rect(25, 70, 100, 20), noiseScale, 1.0f, 20.0f); animate = GUI.Toggle(new Rect(25, 90, 100, 30), animate, " Animate"); useGLSL = GUI.Toggle(new Rect(25, 120, 100, 30), useGLSL, " Use GLSL"); GUI.Label(new Rect(25, 150, 100, 30), "Noise Type"); currentNoiseSelection = GUI.SelectionGrid(new Rect(25, 170, 100, 200), previousNoiseSelection, noiseTypes, 1); if (currentNoiseSelection != previousNoiseSelection) { switch (currentNoiseSelection) { case 0: currentDisplacementMaterial = perlinDisplacementMaterial; currentGLSLDisplacementMaterial = GLSLPerlinDisplacementMaterial; currentMaterial = perlinMaterial; currentGLSLMaterial = GLSLPerlinMaterial; break; case 1: currentDisplacementMaterial = fBmDisplacementMaterial; currentGLSLDisplacementMaterial = GLSLfBmDisplacementMaterial; currentMaterial = fBmMaterial; currentGLSLMaterial = GLSLfBmMaterial; break; case 2: currentDisplacementMaterial = turbulenceDisplacementMaterial; currentGLSLDisplacementMaterial = GLSLTurbulenceDisplacementMaterial; currentMaterial = turbulenceMaterial; currentGLSLMaterial = GLSLTurbulenceMaterial; break; case 3: currentDisplacementMaterial = ridgedDisplacementMaterial; currentGLSLDisplacementMaterial = GLSLRidgedDisplacementMaterial; currentMaterial = ridgedMaterial; currentGLSLMaterial = GLSLRidgedMaterial; break; case 4: currentDisplacementMaterial = voronoiDisplacementMaterial; currentGLSLDisplacementMaterial = GLSLVoronoiDisplacementMaterial; currentMaterial = voronoiMaterial; currentGLSLMaterial = GLSLVoronoiMaterial; break; case 5: currentDisplacementMaterial = F2DisplacementMaterial; currentGLSLDisplacementMaterial = GLSLF2DisplacementMaterial; currentMaterial = F2Material; currentGLSLMaterial = GLSLF2Material; break; case 6: currentDisplacementMaterial = F2MinusF1DisplacementMaterial; currentGLSLDisplacementMaterial = GLSLF2MinusF1DisplacementMaterial; currentMaterial = F2MinusF1Material; currentGLSLMaterial = GLSLF2MinusF1Material; break; case 7: currentDisplacementMaterial = F1PlusF2DisplacementMaterial; currentGLSLDisplacementMaterial = GLSLF1PlusF2DisplacementMaterial; currentMaterial = F1PlusF2Material; currentGLSLMaterial = GLSLF1PlusF2Material; break; case 8: currentDisplacementMaterial = craterDisplacementMaterial; currentGLSLDisplacementMaterial = GLSLCraterDisplacementMaterial; currentMaterial = craterMaterial; currentGLSLMaterial = GLSLCraterMaterial; break; } Debug.Log("Selecting " + noiseTypes[currentNoiseSelection]); previousNoiseSelection = currentNoiseSelection; } lowColorWindow = GUI.Window(0, lowColorWindow, LowColorWindowFunction, "Low Color"); highColorWindow = GUI.Window(1, highColorWindow, HighColorWindowFunction, "High Color"); if (currentMode == Mode.Displacement3D) { GUI.Label(new Rect(Screen.width / 2 - 250 / 2, 0, 250, 30), "Use mouse buttons to rotate view."); GUI.Label(new Rect(25, 0, 100, 30), "Height Scale"); heightScale = GUI.HorizontalSlider(new Rect(25, 25, 100, 30), heightScale, 0.0f, 1.0f); if (GUI.Button(new Rect(Screen.width - 150 - 5, 5, 150, 30), "2D Animation")) currentMode = Mode.Animation2D; if (useGLSL) { if (SystemInfo.graphicsShaderLevel < 30 || !currentGLSLDisplacementMaterial.shader.isSupported) shaderLevelWindow = GUI.Window(2, shaderLevelWindow, ShaderLevelWindowFunction, "Shader Error"); } else { if (SystemInfo.graphicsShaderLevel < 30 || !currentDisplacementMaterial.shader.isSupported) shaderLevelWindow = GUI.Window(2, shaderLevelWindow, ShaderLevelWindowFunction, "Shader Error"); } } else // Animation2D { if (GUI.Button(new Rect(Screen.width - 150 - 5, 5, 150, 30), "3D Displacement")) currentMode = Mode.Displacement3D; if (useGLSL) { if (SystemInfo.graphicsShaderLevel < 30 || !currentGLSLMaterial.shader.isSupported) shaderLevelWindow = GUI.Window(2, shaderLevelWindow, ShaderLevelWindowFunction, "Shader Error"); } else { if (SystemInfo.graphicsShaderLevel < 30 || !currentMaterial.shader.isSupported) shaderLevelWindow = GUI.Window(2, shaderLevelWindow, ShaderLevelWindowFunction, "Shader Error"); } } } void LowColorWindowFunction(int id) { GUI.Label(new Rect(5, 20, 100, 30), "R"); lowRed = GUI.HorizontalSlider(new Rect(25, 25, 150, 20), lowRed, 0.0f, 1.0f); GUI.Label(new Rect(5, 45, 100, 30), "G"); lowGreen = GUI.HorizontalSlider(new Rect(25, 50, 150, 20), lowGreen, 0.0f, 1.0f); GUI.Label(new Rect(5, 70, 100, 30), "B"); lowBlue = GUI.HorizontalSlider(new Rect(25, 75, 150, 20), lowBlue, 0.0f, 1.0f); } void HighColorWindowFunction(int id) { GUI.Label(new Rect(5, 20, 100, 30), "R"); highRed = GUI.HorizontalSlider(new Rect(25, 25, 150, 20), highRed, 0.0f, 1.0f); GUI.Label(new Rect(5, 45, 100, 30), "G"); highGreen = GUI.HorizontalSlider(new Rect(25, 50, 150, 20), highGreen, 0.0f, 1.0f); GUI.Label(new Rect(5, 70, 100, 30), "B"); highBlue = GUI.HorizontalSlider(new Rect(25, 75, 150, 20), highBlue, 0.0f, 1.0f); } void ShaderLevelWindowFunction(int id) { GUI.Label(new Rect(5, 20, 350, 30), "Your shader model level is " + SystemInfo.graphicsShaderLevel + ". You need 30 (or higher)."); if (useGLSL) GUI.Label(new Rect(5, 40, 350, 40), "Shader supported = " + currentGLSLDisplacementMaterial.shader.isSupported); else GUI.Label(new Rect(5, 40, 350, 40), "Shader supported = " + currentDisplacementMaterial.shader.isSupported); //GUI.Label(new Rect(5, 60, 350, 40), "This is most likely due to Cg to GLSL cross-compiling bugs in Unity."); // Make the windows be draggable. GUI.DragWindow(new Rect(0, 0, 10000, 10000)); } void Update() { // the Back button on Android is mapped to the Escape key if (Input.GetKeyDown(KeyCode.Escape)) { Application.Quit(); } if (currentMode == Mode.Displacement3D) { if (useGLSL) { if (animate) { time += Time.deltaTime; currentGLSLDisplacementMaterial.SetFloat("time", time); } currentGLSLDisplacementMaterial.SetFloat("heightScale", heightScale); currentGLSLDisplacementMaterial.SetFloat("noiseScale", noiseScale); currentGLSLDisplacementMaterial.SetColor("lowColor", new Color(lowRed, lowGreen, lowBlue)); currentGLSLDisplacementMaterial.SetColor("highColor", new Color(highRed, highGreen, highBlue)); } else // use Cg { if (animate) { time += Time.deltaTime; currentDisplacementMaterial.SetFloat("time", time); } currentDisplacementMaterial.SetFloat("heightScale", heightScale); currentDisplacementMaterial.SetFloat("noiseScale", noiseScale); currentDisplacementMaterial.SetColor("lowColor", new Color(lowRed, lowGreen, lowBlue)); currentDisplacementMaterial.SetColor("highColor", new Color(highRed, highGreen, highBlue)); } } else // Animation2D { if (useGLSL) { if (animate) { time += Time.deltaTime; currentGLSLMaterial.SetFloat("time", time); } currentGLSLMaterial.SetFloat("noiseScale", noiseScale); currentGLSLMaterial.SetColor("lowColor", new Color(lowRed, lowGreen, lowBlue)); currentGLSLMaterial.SetColor("highColor", new Color(highRed, highGreen, highBlue)); } else // use Cg { if (animate) { time += Time.deltaTime; currentMaterial.SetFloat("time", time); } currentMaterial.SetFloat("noiseScale", noiseScale); currentMaterial.SetColor("lowColor", new Color(lowRed, lowGreen, lowBlue)); currentMaterial.SetColor("highColor", new Color(highRed, highGreen, highBlue)); } } } void OnRenderObject() { // force the mesh to draw, and bypass the normal Unity rendering (lighting, shadowing, etc) if (currentMode == Mode.Displacement3D) { if (useGLSL) currentGLSLDisplacementMaterial.SetPass(0); else currentDisplacementMaterial.SetPass(0); Graphics.DrawMeshNow(sphereMesh, Matrix4x4.identity); } else { if (useGLSL) currentGLSLMaterial.SetPass(0); else currentMaterial.SetPass(0); Graphics.DrawMeshNow(quadMesh, Matrix4x4.identity); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.BraceMatching { public class CSharpBraceMatcherTests : AbstractBraceMatcherTests { protected override Task<TestWorkspace> CreateWorkspaceFromCodeAsync(string code) { return CSharpWorkspaceFactory.CreateWorkspaceFromLinesAsync(code); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestEmptyFile() { var code = @"$$"; var expected = @""; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAtFirstPositionInFile() { var code = @"$$public class C { }"; var expected = @"public class C { }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAtLastPositionInFile() { var code = @"public class C { }$$"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace1() { var code = @"public class C $${ }"; var expected = @"public class C { [|}|]"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace2() { var code = @"public class C {$$ }"; var expected = @"public class C { [|}|]"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace3() { var code = @"public class C { $$}"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestCurlyBrace4() { var code = @"public class C { }$$"; var expected = @"public class C [|{|] }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen1() { var code = @"public class C { void Foo$$() { } }"; var expected = @"public class C { void Foo([|)|] { } }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen2() { var code = @"public class C { void Foo($$) { } }"; var expected = @"public class C { void Foo([|)|] { } }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen3() { var code = @"public class C { void Foo($$ ) { } }"; var expected = @"public class C { void Foo( [|)|] { } }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen4() { var code = @"public class C { void Foo( $$) { } }"; var expected = @"public class C { void Foo[|(|] ) { } }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen5() { var code = @"public class C { void Foo( )$$ { } }"; var expected = @"public class C { void Foo[|(|] ) { } }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestParen6() { var code = @"public class C { void Foo()$$ { } }"; var expected = @"public class C { void Foo[|(|]) { } }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket1() { var code = @"public class C { int$$[] i; }"; var expected = @"public class C { int[[|]|] i; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket2() { var code = @"public class C { int[$$] i; }"; var expected = @"public class C { int[[|]|] i; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket3() { var code = @"public class C { int[$$ ] i; }"; var expected = @"public class C { int[ [|]|] i; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket4() { var code = @"public class C { int[ $$] i; }"; var expected = @"public class C { int[|[|] ] i; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket5() { var code = @"public class C { int[ ]$$ i; }"; var expected = @"public class C { int[|[|] ] i; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestSquareBracket6() { var code = @"public class C { int[]$$ i; }"; var expected = @"public class C { int[|[|]] i; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket1() { var code = @"public class C { Foo$$<int> f; }"; var expected = @"public class C { Foo<int[|>|] f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket2() { var code = @"public class C { Foo<$$int> f; }"; var expected = @"public class C { Foo<int[|>|] f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket3() { var code = @"public class C { Foo<int$$> f; }"; var expected = @"public class C { Foo[|<|]int> f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestAngleBracket4() { var code = @"public class C { Foo<int>$$ f; }"; var expected = @"public class C { Foo[|<|]int> f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket1() { var code = @"public class C { Func$$<Func<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int>[|>|] f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket2() { var code = @"public class C { Func<$$Func<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int>[|>|] f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket3() { var code = @"public class C { Func<Func$$<int,int>> f; }"; var expected = @"public class C { Func<Func<int,int[|>|]> f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket4() { var code = @"public class C { Func<Func<$$int,int>> f; }"; var expected = @"public class C { Func<Func<int,int[|>|]> f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket5() { var code = @"public class C { Func<Func<int,int$$>> f; }"; var expected = @"public class C { Func<Func[|<|]int,int>> f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket6() { var code = @"public class C { Func<Func<int,int>$$> f; }"; var expected = @"public class C { Func<Func[|<|]int,int>> f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket7() { var code = @"public class C { Func<Func<int,int> $$> f; }"; var expected = @"public class C { Func[|<|]Func<int,int> > f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestNestedAngleBracket8() { var code = @"public class C { Func<Func<int,int>>$$ f; }"; var expected = @"public class C { Func[|<|]Func<int,int>> f; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString1() { var code = @"public class C { string s = $$""Foo""; }"; var expected = @"public class C { string s = ""Foo[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString2() { var code = @"public class C { string s = ""$$Foo""; }"; var expected = @"public class C { string s = ""Foo[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString3() { var code = @"public class C { string s = ""Foo$$""; }"; var expected = @"public class C { string s = [|""|]Foo""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString4() { var code = @"public class C { string s = ""Foo""$$; }"; var expected = @"public class C { string s = [|""|]Foo""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestString5() { var code = @"public class C { string s = ""Foo$$ "; var expected = @"public class C { string s = ""Foo "; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString1() { var code = @"public class C { string s = $$@""Foo""; }"; var expected = @"public class C { string s = @""Foo[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString2() { var code = @"public class C { string s = @$$""Foo""; }"; var expected = @"public class C { string s = @""Foo[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString3() { var code = @"public class C { string s = @""$$Foo""; }"; var expected = @"public class C { string s = @""Foo[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString4() { var code = @"public class C { string s = @""Foo$$""; }"; var expected = @"public class C { string s = [|@""|]Foo""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestVerbatimString5() { var code = @"public class C { string s = @""Foo""$$; }"; var expected = @"public class C { string s = [|@""|]Foo""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString1() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""$${x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString2() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{$$x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x[|}|], {y}""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString3() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x$$}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString4() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}$$, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""[|{|]x}, {y}""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString5() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, $${y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString6() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {$$y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y[|}|]""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString7() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y$$}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString8() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}$$""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, [|{|]y}""; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString9() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString10() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString11() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $$[||]$@""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString12() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $[||]$$@""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterpolatedString13() { var code = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@$$""{x}, {y}""; }"; var expected = @"public class C { void M() { var x = ""Hello""; var y = ""World""; var s = $@""{x}, {y}[|""|]; }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithSingleMatchingDirective() { var code = @" public class C { #if$$ CHK #endif }"; var expected = @" public class C { #if$$ CHK [|#endif|] }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithTwoMatchingDirectives() { var code = @" public class C { #if$$ CHK #else #endif }"; var expected = @" public class C { #if$$ CHK [|#else|] #endif }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestConditionalDirectiveWithAllMatchingDirectives() { var code = @" public class C { #if CHK #elif RET #else #endif$$ }"; var expected = @" public class C { [|#if|] CHK #elif RET #else #endif }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestRegionDirective() { var code = @" public class C { $$#region test #endregion }"; var expected = @" public class C { #region test [|#endregion|] }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterleavedDirectivesInner() { var code = @" #define CHK public class C { void Test() { #if CHK $$#region test var x = 5; #endregion #else var y = 6; #endif } }"; var expected = @" #define CHK public class C { void Test() { #if CHK #region test var x = 5; [|#endregion|] #else var y = 6; #endif } }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestInterleavedDirectivesOuter() { var code = @" #define CHK public class C { void Test() { #if$$ CHK #region test var x = 5; #endregion #else var y = 6; #endif } }"; var expected = @" #define CHK public class C { void Test() { #if CHK #region test var x = 5; #endregion [|#else|] var y = 6; #endif } }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedDirective1() { var code = @" public class C { $$#region test }"; var expected = @" public class C { #region test }"; await TestAsync(code, expected); } [WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")] [WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)] public async Task TestUnmatchedDirective2() { var code = @" #d$$efine CHK public class C { }"; var expected = @" #define CHK public class C { }"; await TestAsync(code, expected); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using WebsitePanel.Installer.Core; using WebsitePanel.Installer.Common; using System.Data; using System.Threading; using WebsitePanel.Installer.Configuration; using System.IO; using System.Collections; namespace WebsitePanel.SilentInstaller { class Program { public const string ComponentNameParam = "cname"; public static readonly Hashtable ServiceCliParams = new Hashtable { { Global.CLI.WebSiteIP, Global.Parameters.WebSiteIP }, // IP Address { Global.CLI.ServiceAccountPassword, Global.Parameters.UserPassword }, // Service account password { Global.CLI.ServiceAccountDomain, Global.Parameters.UserDomain }, // Service account domain (AD only) { Global.CLI.ServiceAccountName, Global.Parameters.UserAccount }, // Service account name { Global.CLI.WebSitePort, Global.Parameters.WebSitePort }, // TCP Port { Global.CLI.WebSiteDomain, Global.Parameters.WebSiteDomain } // Website domain (if any assigned) }; public static readonly Hashtable ServerCliParams = new Hashtable { { Global.Server.CLI.ServerPassword, Global.Parameters.ServerPassword }, // Server password }; public static readonly Hashtable EntServerCliParams = new Hashtable { { Global.EntServer.CLI.ServeradminPassword, Global.Parameters.ServerAdminPassword }, // serveradmin password { Global.EntServer.CLI.DatabaseName, Global.Parameters.DatabaseName }, // Database name { Global.EntServer.CLI.DatabaseServer, Global.Parameters.DatabaseServer }, // Database server { Global.EntServer.CLI.DbServerAdmin, Global.Parameters.DbServerAdmin }, // Database server administrator login { Global.EntServer.CLI.DbServerAdminPassword, Global.Parameters.DbServerAdminPassword }, // Database server administrator password }; public static readonly Hashtable WebPortalCliParams = new Hashtable { { Global.WebPortal.CLI.EnterpriseServerUrl, Global.Parameters.EnterpriseServerUrl }, // Enterprise Server URL }; public static readonly Hashtable StdServerSetupCliParams = new Hashtable { { Global.EntServer.CLI.DatabaseServer, Global.Parameters.DatabaseServer }, { Global.EntServer.CLI.DatabaseName, Global.Parameters.DatabaseName }, { Global.EntServer.CLI.DbServerAdmin , Global.Parameters.DbServerAdmin }, { Global.EntServer.CLI.DbServerAdminPassword, Global.Parameters.DbServerAdminPassword }, { Global.EntServer.CLI.ServeradminPassword, Global.Parameters.ServerAdminPassword } }; [STAThread] static int Main(string[] args) { // Utils.FixConfigurationSectionDefinition(); // // Ensure arguments supplied for the application if (args.Length == 0) { Log.WriteError(Global.Messages.NoInputParametersSpecified); return Global.Messages.NoInputParametersSpecifiedError; } // Check user's security permissions if (!Utils.CheckSecurity()) { ShowSecurityError(); return Global.Messages.NotEnoughPermissionsErrorCode; } // Check administrator permissions if (!Utils.IsAdministrator()) { ShowSecurityError(); return Global.Messages.NotEnoughPermissionsErrorCode; } // Check for running instance if (!Utils.IsNewInstance()) { ShowInstanceRunningErrorMessage(); return Global.Messages.AnotherInstanceIsRunningError; } // var cname = GetCommandLineArgumentValue(ComponentNameParam); if (Utils.CheckForInstalledComponent(cname)) { Log.WriteError(Global.Messages.ComponentIsAlreadyInstalled); // return Global.Messages.ComponentIsAlreadyInstalledError; } try { // Make sure no other installations could be run at the same time Utils.SaveMutex(); // Log.WriteApplicationStart(); //check OS version Log.WriteInfo("{0} detected", Global.OSVersion); //check IIS version if (Global.IISVersion.Major == 0) Log.WriteError("IIS not found."); else Log.WriteInfo("IIS {0} detected", Global.IISVersion); var service = ServiceProviderProxy.GetInstallerWebService(); var record = default(DataRow); // var ds = service.GetAvailableComponents(); // foreach (DataRow row in ds.Tables[0].Rows) { string componentCode = Utils.GetDbString(row["ComponentCode"]); // if (!String.Equals(componentCode, cname, StringComparison.OrdinalIgnoreCase)) { continue; } // record = row; break; } // if (record == null) { Log.WriteError(String.Format("{0} => {1}", ComponentNameParam, cname)); Log.WriteInfo("Incorrect component name specified"); return Global.Messages.UnknownComponentCodeError; } // var cli_args = ParseInputFromCLI(cname); // StartInstaller(record, cli_args); // return Global.Messages.SuccessInstallation; } catch (Exception ex) { Log.WriteError("Failed to install the component", ex); // return Global.Messages.InstallationError; } finally { Log.WriteApplicationEnd(); } } private static void ShowInstanceRunningErrorMessage() { Log.WriteError(Global.Messages.AnotherInstanceIsRunning); } private static void ShowSecurityError() { Log.WriteError(Global.Messages.NotEnoughPermissionsError); } /// <summary> /// Parses user input from the command-line for the component specified and returns it in the form of a Hashtable to pass run the installer with arguments then. /// </summary> /// <param name="cname">Component code whose input from the command-line is being parsed</param> /// <exception cref="System.Exception">Thrown when wrong component code is specified. See Global class for supported component codes.</exception> /// <returns></returns> static Hashtable ParseInputFromCLI(string cname) { // if (cname.Equals(Global.Server.ComponentCode, StringComparison.OrdinalIgnoreCase)) { // return LoadInputFromCLI( ServerCliParams, ServiceCliParams, output: new Hashtable { { Global.Parameters.WebSiteIP, Global.Server.DefaultIP }, { Global.Parameters.WebSiteDomain, String.Empty }, { Global.Parameters.WebSitePort, Global.Server.DefaultPort }, { Global.Parameters.UserAccount, Global.Server.ServiceAccount }, { Global.Parameters.UserDomain, String.Empty }, { Global.Parameters.UserPassword, String.Empty }, { Global.Parameters.ServerPassword, null } // Required CLI parameters must be initialized with null value! } ); } else if (cname.Equals(Global.EntServer.ComponentCode, StringComparison.OrdinalIgnoreCase)) { // return LoadInputFromCLI( EntServerCliParams, ServiceCliParams, output: new Hashtable { { Global.Parameters.WebSiteIP, Global.EntServer.DefaultIP }, { Global.Parameters.WebSiteDomain, String.Empty }, { Global.Parameters.WebSitePort, Global.EntServer.DefaultPort }, { Global.Parameters.UserAccount, Global.EntServer.ServiceAccount }, { Global.Parameters.UserDomain, String.Empty }, { Global.Parameters.UserPassword, String.Empty }, { Global.Parameters.DatabaseName, Global.EntServer.DefaultDatabase }, { Global.Parameters.DbServerAdmin, String.Empty }, { Global.Parameters.DbServerAdminPassword, String.Empty }, { Global.Parameters.DatabaseServer, Global.EntServer.DefaultDbServer }, { Global.Parameters.ServerAdminPassword, null } // Required CLI parameters must be initialized with null value! } ); } else if (cname.Equals(Global.WebPortal.ComponentCode, StringComparison.OrdinalIgnoreCase)) { // return LoadInputFromCLI( WebPortalCliParams, ServiceCliParams, output: new Hashtable { { Global.Parameters.WebSiteIP, Global.WebPortal.DefaultIP }, { Global.Parameters.WebSiteDomain, String.Empty }, { Global.Parameters.WebSitePort, Global.WebPortal.DefaultPort }, { Global.Parameters.UserAccount, Global.WebPortal.ServiceAccount }, { Global.Parameters.UserDomain, String.Empty }, { Global.Parameters.UserPassword, String.Empty }, { Global.Parameters.EnterpriseServerUrl, null } // Required CLI parameters must be initialized with null value! } ); } else if (cname.Equals(Global.StandaloneServer.ComponentCode, StringComparison.OrdinalIgnoreCase)) { return LoadInputFromCLI( StdServerSetupCliParams, ServiceCliParams, output: new Hashtable { { Global.Parameters.WebSiteIP, Global.WebPortal.DefaultIP }, { Global.Parameters.WebSiteDomain, String.Empty }, { Global.Parameters.WebSitePort, Global.WebPortal.DefaultPort }, { Global.Parameters.DatabaseName, Global.EntServer.DefaultDatabase }, { Global.Parameters.DatabaseServer, Global.EntServer.DefaultDbServer }, { Global.Parameters.DbServerAdmin, String.Empty }, { Global.Parameters.DbServerAdminPassword, String.Empty }, { Global.Parameters.ServerAdminPassword, String.Empty } } ); } // throw new Exception("Wrong component code!"); } /// <summary> /// Loads an input from the command-line interface into a Hashtable instance to use for calls to the Installer and checks whether or not the required parameters are set. /// </summary> /// <param name="inputA">A collection with service-specific parameter names to match the input from the command-line interface (CLI)</param> /// <param name="inputB">A collection with service-generic parameter names to match the input from the command-line interface (CLI)</param> /// <param name="output">An output storage to put the input data into</param> /// <returns>This method</returns> static Hashtable LoadInputFromCLI(Hashtable inputA, Hashtable inputB, Hashtable output) { // Process service foreach (var item in inputA.Keys) { var cli_argv = GetCommandLineArgumentValue(item as String); // if (String.IsNullOrEmpty(cli_argv)) continue; // Assign argument value from CLI output[inputA[item]] = cli_argv; } // foreach (var item in inputB.Keys) { var cli_argv = GetCommandLineArgumentValue(item as String); // if (String.IsNullOrEmpty(cli_argv)) continue; // Assign argument value from CLI output[inputB[item]] = cli_argv; } // Ensure all required parameters are set foreach (var item in output.Keys) { // If a parameter is required, then you should assign null value if (output[item] == null) { throw new ArgumentNullException(item as String); } } // return output; } static void StartInstaller(DataRow row, Hashtable args) { string applicationName = Utils.GetDbString(row["ApplicationName"]); string componentName = Utils.GetDbString(row["ComponentName"]); string componentCode = Utils.GetDbString(row["ComponentCode"]); string componentDescription = Utils.GetDbString(row["ComponentDescription"]); string component = Utils.GetDbString(row["Component"]); string version = Utils.GetDbString(row["Version"]); string fileName = row["FullFilePath"].ToString(); string installerPath = Utils.GetDbString(row["InstallerPath"]); string installerType = Utils.GetDbString(row["InstallerType"]); // Get appropriate loader to download the app distributive var loader = LoaderFactory.CreateFileLoader(fileName); // Mimic synchronous download process for the console app AutoResetEvent autoEvent = new AutoResetEvent(false); try { // loader.OperationCompleted += new EventHandler<EventArgs>((object sender, EventArgs e) => { Log.WriteInfo("Download completed!"); // string tmpFolder = FileUtils.GetTempDirectory(); string path = Path.Combine(tmpFolder, installerPath); //Update(); string method = "Install"; Log.WriteStart(string.Format("Running installer {0}.{1} from {2}", installerType, method, path)); //prepare installer args args[Global.Parameters.ComponentName] = componentName; args[Global.Parameters.ApplicationName] = applicationName; args[Global.Parameters.ComponentCode] = componentCode; args[Global.Parameters.ComponentDescription] = componentDescription; args[Global.Parameters.Version] = version; args[Global.Parameters.InstallerFolder] = tmpFolder; args[Global.Parameters.InstallerPath] = installerPath; args[Global.Parameters.InstallerType] = installerType; args[Global.Parameters.Installer] = Path.GetFileName(fileName); args[Global.Parameters.BaseDirectory] = FileUtils.GetCurrentDirectory(); args[Global.Parameters.IISVersion] = Global.IISVersion; args[Global.Parameters.ShellVersion] = AssemblyLoader.GetShellVersion(); args[Global.Parameters.ShellMode] = Global.SilentInstallerShell; args[Global.Parameters.SetupXml] = String.Empty; // Run the installer var res = AssemblyLoader.Execute(path, installerType, method, new object[] { args }); Log.WriteInfo(string.Format("Installer returned {0}", res)); Log.WriteEnd("Installer finished"); // Remove temporary directory FileUtils.DeleteTempDirectory(); // We are done autoEvent.Set(); }); // TODO: Add cleanup for events. loader.OperationFailed += new EventHandler<LoaderEventArgs<Exception>>(loader_OperationFailed); loader.ProgressChanged += new EventHandler<LoaderEventArgs<int>>(loader_ProgressChanged); loader.StatusChanged += new EventHandler<LoaderEventArgs<string>>(loader_StatusChanged); // loader.LoadAppDistributive(); // Wait until the download is complete autoEvent.WaitOne(); } catch (Exception ex) { Log.WriteError("Installer error", ex); } finally { autoEvent.Set(); } } static void loader_StatusChanged(object sender, LoaderEventArgs<string> e) { if (String.IsNullOrEmpty(e.EventData)) Log.WriteInfo(e.StatusMessage); else Log.WriteInfo("{0} {1}", e.StatusMessage, e.EventData); } static void loader_ProgressChanged(object sender, LoaderEventArgs<int> e) { if (!String.IsNullOrEmpty(e.StatusMessage)) Log.WriteInfo("{0} {1}%", e.StatusMessage, e.EventData); else Log.WriteInfo("Current progress is {0}%", e.EventData); } static void loader_OperationFailed(object sender, LoaderEventArgs<Exception> e) { Log.WriteInfo(e.EventData.ToString()); } /// <summary> /// Check for existing command line argument /// </summary> private static bool CheckCommandLineArgument(string argName) { string[] args = Environment.GetCommandLineArgs(); for (int i = 1; i < args.Length; i++) { string arg = args[i]; if (string.Equals(arg, argName, StringComparison.InvariantCultureIgnoreCase)) { return true; } } return false; } /// <summary> /// Check for existing command line argument /// </summary> private static string GetCommandLineArgumentValue(string argName) { string key = "/" + argName.ToLower() + ":"; string[] args = Environment.GetCommandLineArgs(); for (int i = 1; i < args.Length; i++) { string arg = args[i].ToLower(); if (arg.StartsWith(key)) { // Remove leading and trailing double quotes if any return args[i].Substring(key.Length).TrimStart('"').TrimEnd('"'); } } return null; } } }
namespace MarkHeath.MidiUtils { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBoxInputFolder = new System.Windows.Forms.TextBox(); this.textBoxOutputFolder = new System.Windows.Forms.TextBox(); this.buttonBrowseEZDrummer = new System.Windows.Forms.Button(); this.buttonBrowseOutputFolder = new System.Windows.Forms.Button(); this.buttonConvert = new System.Windows.Forms.Button(); this.label3 = new System.Windows.Forms.Label(); this.checkBoxVerbose = new System.Windows.Forms.CheckBox(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.clearLogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveLogToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.contentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.radioButtonType1 = new System.Windows.Forms.RadioButton(); this.radioButtonTypeUnchanged = new System.Windows.Forms.RadioButton(); this.radioButtonType0 = new System.Windows.Forms.RadioButton(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.radioButtonChannel10 = new System.Windows.Forms.RadioButton(); this.radioButtonChannelUnchanged = new System.Windows.Forms.RadioButton(); this.radioButtonChannel1 = new System.Windows.Forms.RadioButton(); this.groupBox4 = new System.Windows.Forms.GroupBox(); this.checkBoxUseFilename = new System.Windows.Forms.CheckBox(); this.checkBoxApplyNamingRules = new System.Windows.Forms.CheckBox(); this.progressLog1 = new NAudio.Utils.ProgressLog(); this.menuStrip1.SuspendLayout(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.groupBox4.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 34); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(66, 13); this.label1.TabIndex = 0; this.label1.Text = "Input Folder:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 64); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(74, 13); this.label2.TabIndex = 3; this.label2.Text = "Output Folder:"; // // textBoxInputFolder // this.textBoxInputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxInputFolder.Location = new System.Drawing.Point(144, 31); this.textBoxInputFolder.Name = "textBoxInputFolder"; this.textBoxInputFolder.ReadOnly = true; this.textBoxInputFolder.Size = new System.Drawing.Size(310, 20); this.textBoxInputFolder.TabIndex = 1; // // textBoxOutputFolder // this.textBoxOutputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBoxOutputFolder.Location = new System.Drawing.Point(144, 61); this.textBoxOutputFolder.Name = "textBoxOutputFolder"; this.textBoxOutputFolder.ReadOnly = true; this.textBoxOutputFolder.Size = new System.Drawing.Size(310, 20); this.textBoxOutputFolder.TabIndex = 4; // // buttonBrowseEZDrummer // this.buttonBrowseEZDrummer.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonBrowseEZDrummer.Location = new System.Drawing.Point(460, 29); this.buttonBrowseEZDrummer.Name = "buttonBrowseEZDrummer"; this.buttonBrowseEZDrummer.Size = new System.Drawing.Size(75, 23); this.buttonBrowseEZDrummer.TabIndex = 2; this.buttonBrowseEZDrummer.Text = "Browse..."; this.buttonBrowseEZDrummer.UseVisualStyleBackColor = true; this.buttonBrowseEZDrummer.Click += new System.EventHandler(this.buttonBrowseEZDrummer_Click); // // buttonBrowseOutputFolder // this.buttonBrowseOutputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonBrowseOutputFolder.Location = new System.Drawing.Point(460, 59); this.buttonBrowseOutputFolder.Name = "buttonBrowseOutputFolder"; this.buttonBrowseOutputFolder.Size = new System.Drawing.Size(75, 23); this.buttonBrowseOutputFolder.TabIndex = 5; this.buttonBrowseOutputFolder.Text = "Browse..."; this.buttonBrowseOutputFolder.UseVisualStyleBackColor = true; this.buttonBrowseOutputFolder.Click += new System.EventHandler(this.buttonBrowseOutputFolder_Click); // // buttonConvert // this.buttonConvert.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.buttonConvert.Location = new System.Drawing.Point(460, 204); this.buttonConvert.Name = "buttonConvert"; this.buttonConvert.Size = new System.Drawing.Size(75, 23); this.buttonConvert.TabIndex = 11; this.buttonConvert.Text = "Convert"; this.buttonConvert.UseVisualStyleBackColor = true; this.buttonConvert.Click += new System.EventHandler(this.buttonConvert_Click); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 209); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(319, 13); this.label3.TabIndex = 9; this.label3.Text = "When you have verified the above settings, click Convert to begin"; // // checkBoxVerbose // this.checkBoxVerbose.AutoSize = true; this.checkBoxVerbose.Checked = true; this.checkBoxVerbose.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxVerbose.Location = new System.Drawing.Point(351, 208); this.checkBoxVerbose.Name = "checkBoxVerbose"; this.checkBoxVerbose.Size = new System.Drawing.Size(100, 17); this.checkBoxVerbose.TabIndex = 10; this.checkBoxVerbose.Text = "Verbose Output"; this.checkBoxVerbose.UseVisualStyleBackColor = true; // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.toolsToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(551, 24); this.menuStrip1.TabIndex = 10; this.menuStrip1.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(103, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.optionsToolStripMenuItem, this.clearLogToolStripMenuItem, this.saveLogToolStripMenuItem}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; this.toolsToolStripMenuItem.Size = new System.Drawing.Size(44, 20); this.toolsToolStripMenuItem.Text = "&Tools"; // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; this.optionsToolStripMenuItem.Size = new System.Drawing.Size(185, 22); this.optionsToolStripMenuItem.Text = "Advanced &Options..."; this.optionsToolStripMenuItem.Click += new System.EventHandler(this.optionsToolStripMenuItem_Click); // // clearLogToolStripMenuItem // this.clearLogToolStripMenuItem.Name = "clearLogToolStripMenuItem"; this.clearLogToolStripMenuItem.Size = new System.Drawing.Size(185, 22); this.clearLogToolStripMenuItem.Text = "&Clear Log"; this.clearLogToolStripMenuItem.Click += new System.EventHandler(this.clearLogToolStripMenuItem_Click); // // saveLogToolStripMenuItem // this.saveLogToolStripMenuItem.Enabled = false; this.saveLogToolStripMenuItem.Name = "saveLogToolStripMenuItem"; this.saveLogToolStripMenuItem.Size = new System.Drawing.Size(185, 22); this.saveLogToolStripMenuItem.Text = "&Save Log..."; this.saveLogToolStripMenuItem.Click += new System.EventHandler(this.saveLogToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.contentsToolStripMenuItem, this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.helpToolStripMenuItem.Text = "&Help"; // // contentsToolStripMenuItem // this.contentsToolStripMenuItem.Name = "contentsToolStripMenuItem"; this.contentsToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.contentsToolStripMenuItem.Text = "&Contents"; this.contentsToolStripMenuItem.Click += new System.EventHandler(this.contentsToolStripMenuItem_Click); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(152, 22); this.aboutToolStripMenuItem.Text = "&About"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.radioButtonType1); this.groupBox1.Controls.Add(this.radioButtonTypeUnchanged); this.groupBox1.Controls.Add(this.radioButtonType0); this.groupBox1.Location = new System.Drawing.Point(337, 96); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(148, 100); this.groupBox1.TabIndex = 8; this.groupBox1.TabStop = false; this.groupBox1.Text = "Output File Type"; // // radioButtonType1 // this.radioButtonType1.AutoSize = true; this.radioButtonType1.Checked = true; this.radioButtonType1.Location = new System.Drawing.Point(6, 65); this.radioButtonType1.Name = "radioButtonType1"; this.radioButtonType1.Size = new System.Drawing.Size(84, 17); this.radioButtonType1.TabIndex = 2; this.radioButtonType1.TabStop = true; this.radioButtonType1.Text = "MIDI Type 1"; this.radioButtonType1.UseVisualStyleBackColor = true; // // radioButtonTypeUnchanged // this.radioButtonTypeUnchanged.AutoSize = true; this.radioButtonTypeUnchanged.Location = new System.Drawing.Point(6, 19); this.radioButtonTypeUnchanged.Name = "radioButtonTypeUnchanged"; this.radioButtonTypeUnchanged.Size = new System.Drawing.Size(114, 17); this.radioButtonTypeUnchanged.TabIndex = 0; this.radioButtonTypeUnchanged.Text = "Leave Unchanged"; this.radioButtonTypeUnchanged.UseVisualStyleBackColor = true; // // radioButtonType0 // this.radioButtonType0.AutoSize = true; this.radioButtonType0.Location = new System.Drawing.Point(6, 42); this.radioButtonType0.Name = "radioButtonType0"; this.radioButtonType0.Size = new System.Drawing.Size(84, 17); this.radioButtonType0.TabIndex = 1; this.radioButtonType0.Text = "MIDI Type 0"; this.radioButtonType0.UseVisualStyleBackColor = true; // // groupBox2 // this.groupBox2.Controls.Add(this.radioButtonChannel10); this.groupBox2.Controls.Add(this.radioButtonChannelUnchanged); this.groupBox2.Controls.Add(this.radioButtonChannel1); this.groupBox2.Location = new System.Drawing.Point(187, 96); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(144, 100); this.groupBox2.TabIndex = 7; this.groupBox2.TabStop = false; this.groupBox2.Text = "MIDI Note Channel"; // // radioButtonChannel10 // this.radioButtonChannel10.AutoSize = true; this.radioButtonChannel10.Location = new System.Drawing.Point(6, 65); this.radioButtonChannel10.Name = "radioButtonChannel10"; this.radioButtonChannel10.Size = new System.Drawing.Size(134, 17); this.radioButtonChannel10.TabIndex = 5; this.radioButtonChannel10.Text = "Force all to Channel 10"; this.radioButtonChannel10.UseVisualStyleBackColor = true; // // radioButtonChannelUnchanged // this.radioButtonChannelUnchanged.AutoSize = true; this.radioButtonChannelUnchanged.Checked = true; this.radioButtonChannelUnchanged.Location = new System.Drawing.Point(6, 19); this.radioButtonChannelUnchanged.Name = "radioButtonChannelUnchanged"; this.radioButtonChannelUnchanged.Size = new System.Drawing.Size(114, 17); this.radioButtonChannelUnchanged.TabIndex = 3; this.radioButtonChannelUnchanged.TabStop = true; this.radioButtonChannelUnchanged.Text = "Leave Unchanged"; this.radioButtonChannelUnchanged.UseVisualStyleBackColor = true; // // radioButtonChannel1 // this.radioButtonChannel1.AutoSize = true; this.radioButtonChannel1.Location = new System.Drawing.Point(6, 42); this.radioButtonChannel1.Name = "radioButtonChannel1"; this.radioButtonChannel1.Size = new System.Drawing.Size(128, 17); this.radioButtonChannel1.TabIndex = 4; this.radioButtonChannel1.Text = "Force all to Channel 1"; this.radioButtonChannel1.UseVisualStyleBackColor = true; // // groupBox4 // this.groupBox4.Controls.Add(this.checkBoxUseFilename); this.groupBox4.Controls.Add(this.checkBoxApplyNamingRules); this.groupBox4.Location = new System.Drawing.Point(15, 96); this.groupBox4.Name = "groupBox4"; this.groupBox4.Size = new System.Drawing.Size(163, 100); this.groupBox4.TabIndex = 6; this.groupBox4.TabStop = false; this.groupBox4.Text = "Clip Naming"; // // checkBoxUseFilename // this.checkBoxUseFilename.AutoSize = true; this.checkBoxUseFilename.Checked = true; this.checkBoxUseFilename.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxUseFilename.Location = new System.Drawing.Point(6, 55); this.checkBoxUseFilename.Name = "checkBoxUseFilename"; this.checkBoxUseFilename.Size = new System.Drawing.Size(117, 30); this.checkBoxUseFilename.TabIndex = 2; this.checkBoxUseFilename.Text = "Use filename for\r\nother MIDI patterns"; this.checkBoxUseFilename.UseVisualStyleBackColor = true; // // checkBoxApplyNamingRules // this.checkBoxApplyNamingRules.AutoSize = true; this.checkBoxApplyNamingRules.Checked = true; this.checkBoxApplyNamingRules.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBoxApplyNamingRules.Location = new System.Drawing.Point(6, 19); this.checkBoxApplyNamingRules.Name = "checkBoxApplyNamingRules"; this.checkBoxApplyNamingRules.Size = new System.Drawing.Size(153, 30); this.checkBoxApplyNamingRules.TabIndex = 1; this.checkBoxApplyNamingRules.Text = "Apply XML naming rules\r\nto Toontrack EZD patterns"; this.checkBoxApplyNamingRules.UseVisualStyleBackColor = true; // // progressLog1 // this.progressLog1.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.progressLog1.BackColor = System.Drawing.SystemColors.InactiveCaption; this.progressLog1.Location = new System.Drawing.Point(15, 234); this.progressLog1.Name = "progressLog1"; this.progressLog1.Padding = new System.Windows.Forms.Padding(1); this.progressLog1.Size = new System.Drawing.Size(520, 161); this.progressLog1.TabIndex = 12; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(551, 407); this.Controls.Add(this.progressLog1); this.Controls.Add(this.groupBox4); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.checkBoxVerbose); this.Controls.Add(this.label3); this.Controls.Add(this.buttonConvert); this.Controls.Add(this.buttonBrowseOutputFolder); this.Controls.Add(this.buttonBrowseEZDrummer); this.Controls.Add(this.textBoxOutputFolder); this.Controls.Add(this.textBoxInputFolder); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.MinimumSize = new System.Drawing.Size(559, 441); this.Name = "MainForm"; this.Text = "MIDI File Converter"; this.Load += new System.EventHandler(this.MainForm_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.groupBox4.ResumeLayout(false); this.groupBox4.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBoxInputFolder; private System.Windows.Forms.TextBox textBoxOutputFolder; private System.Windows.Forms.Button buttonBrowseEZDrummer; private System.Windows.Forms.Button buttonBrowseOutputFolder; private System.Windows.Forms.Button buttonConvert; private System.Windows.Forms.Label label3; private System.Windows.Forms.CheckBox checkBoxVerbose; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem contentsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.RadioButton radioButtonType1; private System.Windows.Forms.RadioButton radioButtonTypeUnchanged; private System.Windows.Forms.RadioButton radioButtonType0; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.RadioButton radioButtonChannel10; private System.Windows.Forms.RadioButton radioButtonChannelUnchanged; private System.Windows.Forms.RadioButton radioButtonChannel1; private System.Windows.Forms.GroupBox groupBox4; private System.Windows.Forms.CheckBox checkBoxUseFilename; private System.Windows.Forms.CheckBox checkBoxApplyNamingRules; private NAudio.Utils.ProgressLog progressLog1; private System.Windows.Forms.ToolStripMenuItem toolsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem clearLogToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem saveLogToolStripMenuItem; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Web; using System.Text.RegularExpressions; using System.Security.Cryptography; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Com.Aspose.Storage.Model; namespace Com.Aspose.Storage { public struct FileInfo { public string Name; public string MimeType; public byte[] file; } public class ApiInvoker { private static readonly ApiInvoker _instance = new ApiInvoker(); private Dictionary<String, String> defaultHeaderMap = new Dictionary<String, String>(); public String APP_SID = "appSid"; public String API_KEY = "apiKey"; public static ApiInvoker GetInstance() { return _instance; } public void addDefaultHeader(string key, string value) { defaultHeaderMap.Add(key, value); } public string escapeString(string str) { return str; } public static object deserialize(string json, Type type) { try { if (json.StartsWith("{") || json.StartsWith("[")) return JsonConvert.DeserializeObject(json, type); else { System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); xmlDoc.LoadXml(json); return JsonConvert.SerializeXmlNode(xmlDoc); } } catch (IOException e) { throw new ApiException(500, e.Message); } catch (JsonSerializationException jse) { throw new ApiException(500, jse.Message); } catch (System.Xml.XmlException xmle) { throw new ApiException(500, xmle.Message); } } public static object deserialize(byte[] BinaryData, Type type) { try { return new ResponseMessage(BinaryData); } catch (IOException e) { throw new ApiException(500, e.Message); } } private static string Sign(string url, string appKey) { UriBuilder uriBuilder = new UriBuilder(url); // Remove final slash here as it can be added automatically. uriBuilder.Path = uriBuilder.Path.TrimEnd('/'); // Compute the hash. byte[] privateKey = Encoding.UTF8.GetBytes(appKey); HMACSHA1 algorithm = new HMACSHA1(privateKey); byte[] sequence = ASCIIEncoding.ASCII.GetBytes(uriBuilder.Uri.AbsoluteUri); byte[] hash = algorithm.ComputeHash(sequence); string signature = Convert.ToBase64String(hash); // Remove invalid symbols. signature = signature.TrimEnd('='); signature = HttpUtility.UrlEncode(signature); // Convert codes to upper case as they can be updated automatically. signature = Regex.Replace(signature, "%[0-9a-f]{2}", e => e.Value.ToUpper()); // Add the signature to query string. return string.Format("{0}&signature={1}", uriBuilder.Uri.AbsoluteUri, signature); } public static string serialize(object obj) { try { return obj != null ? JsonConvert.SerializeObject(obj) : null; } catch (Exception e) { throw new ApiException(500, e.Message); } } public string invokeAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; } public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; } public static void CopyTo(Stream source, Stream destination, int bufferSize = 81920) { byte[] array = new byte[bufferSize]; int count; while ((count = source.Read(array, 0, array.Length)) != 0) { destination.Write(array, 0, count); } } private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary<String, String> queryParams, object body, Dictionary<String, String> headerParams, Dictionary<String, object> formParams) { path = path.Replace("{appSid}", this.defaultHeaderMap[APP_SID]); path = Regex.Replace(path, @"{.+?}", ""); //var b = new StringBuilder(); host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; path = Sign(host + path, this.defaultHeaderMap[API_KEY]); var client = WebRequest.Create(path); client.Method = method; byte[] formData = null; if (formParams.Count > 0) { if (formParams.Count > 1) { string formDataBoundary = String.Format("Somthing"); client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; formData = GetMultipartFormData(formParams, formDataBoundary); } else { client.ContentType = "multipart/form-data"; formData = GetMultipartFormData(formParams, ""); } client.ContentLength = formData.Length; } else { client.ContentType = "application/json"; } foreach (var headerParamsItem in headerParams) { client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); } foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) { client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); } switch (method) { case "GET": break; case "POST": case "PUT": case "DELETE": using (Stream requestStream = client.GetRequestStream()) { if (formData != null) { requestStream.Write(formData, 0, formData.Length); } if (body != null) { var swRequestWriter = new StreamWriter(requestStream); swRequestWriter.Write(serialize(body)); swRequestWriter.Close(); } } break; default: throw new ApiException(500, "unknown method type " + method); } try { var webResponse = (HttpWebResponse)client.GetResponse(); if (webResponse.StatusCode != HttpStatusCode.OK) { webResponse.Close(); throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); } if (binaryResponse) { using (var memoryStream = new MemoryStream()) { CopyTo(webResponse.GetResponseStream(), memoryStream); return memoryStream.ToArray(); } } else { using (var responseReader = new StreamReader(webResponse.GetResponseStream())) { var responseData = responseReader.ReadToEnd(); return responseData; } } } catch (WebException ex) { var response = ex.Response as HttpWebResponse; int statusCode = 0; if (response != null) { statusCode = (int)response.StatusCode; response.Close(); } throw new ApiException(statusCode, ex.Message); } } private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary) { Stream formDataStream = new System.IO.MemoryStream(); bool needsCLRF = false; if (postParameters.Count > 1) { foreach (var param in postParameters) { // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. // Skip it on the first parameter, add it to subsequent parameters. if (needsCLRF) formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); needsCLRF = true; var fileInfo = (FileInfo)param.Value; if (param.Value is FileInfo) { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", boundary, param.Key, fileInfo.MimeType); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write((fileInfo.file as byte[]), 0, (fileInfo.file as byte[]).Length); } else { string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", boundary, param.Key, fileInfo.file); formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } // Add the end of the request. Start with a newline string footer = "\r\n--" + boundary + "--\r\n"; formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); } else { foreach (var param in postParameters) { if (param.Value is byte[]) { // Write the file data directly to the Stream, rather than serializing it to a string. formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length); } else { string postData = (string)param.Value; formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); } } } // Dump the Stream into a byte[] formDataStream.Position = 0; byte[] formData = new byte[formDataStream.Length]; formDataStream.Read(formData, 0, formData.Length); formDataStream.Close(); return formData; } /** * Overloaded method for returning the path value * For a string value an empty value is returned if the value is null * @param value * @return */ public String ToPathValue(String value) { return (value == null) ? "" : value; } public String ToPathValue(int value) { return value.ToString(); } public String ToPathValue(int? value) { return value.ToString(); } public String ToPathValue(float value) { return value.ToString(); } public String ToPathValue(float? value) { return value.ToString(); } public String ToPathValue(long value) { return value.ToString(); } public String ToPathValue(bool value) { return value.ToString(); } public String ToPathValue(Double value) { return value.ToString(); } public String ToPathValue(Com.Aspose.Storage.Model.DateTime value) { //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); //return format.format(value); return value.ToString(); } } }
using System; using System.Collections.Generic; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Services { /// <summary> /// Tag service to query for tags in the tags db table. The tags returned are only relevant for published content & saved media or members /// </summary> /// <remarks> /// If there is unpublished content with tags, those tags will not be contained /// </remarks> public class TagService : RepositoryService, ITagService { [Obsolete("Use the constructors that specify all dependencies instead")] public TagService() : this(new RepositoryFactory()) {} [Obsolete("Use the constructors that specify all dependencies instead")] public TagService(RepositoryFactory repositoryFactory) : this(new PetaPocoUnitOfWorkProvider(), repositoryFactory) { } [Obsolete("Use the constructors that specify all dependencies instead")] public TagService(IDatabaseUnitOfWorkProvider provider) : this(provider, new RepositoryFactory()) { } [Obsolete("Use the constructors that specify all dependencies instead")] public TagService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory) : this(provider, repositoryFactory, LoggerResolver.Current.Logger) { } public TagService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger) : base(provider, repositoryFactory, logger) { } /// <summary> /// Gets tagged Content by a specific 'Tag Group'. /// </summary> /// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Content, not the actual Content item.</remarks> /// <param name="tagGroup">Name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="TaggedEntity"/></returns> public IEnumerable<TaggedEntity> GetTaggedContentByTagGroup(string tagGroup) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Content, tagGroup); } } /// <summary> /// Gets tagged Content by a specific 'Tag' and optional 'Tag Group'. /// </summary> /// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Content, not the actual Content item.</remarks> /// <param name="tag">Tag</param> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="TaggedEntity"/></returns> public IEnumerable<TaggedEntity> GetTaggedContentByTag(string tag, string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Content, tag, tagGroup); } } /// <summary> /// Gets tagged Media by a specific 'Tag Group'. /// </summary> /// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Media, not the actual Media item.</remarks> /// <param name="tagGroup">Name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="TaggedEntity"/></returns> public IEnumerable<TaggedEntity> GetTaggedMediaByTagGroup(string tagGroup) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Media, tagGroup); } } /// <summary> /// Gets tagged Media by a specific 'Tag' and optional 'Tag Group'. /// </summary> /// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Media, not the actual Media item.</remarks> /// <param name="tag">Tag</param> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="TaggedEntity"/></returns> public IEnumerable<TaggedEntity> GetTaggedMediaByTag(string tag, string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Media, tag, tagGroup); } } /// <summary> /// Gets tagged Members by a specific 'Tag Group'. /// </summary> /// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Member, not the actual Member item.</remarks> /// <param name="tagGroup">Name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="TaggedEntity"/></returns> public IEnumerable<TaggedEntity> GetTaggedMembersByTagGroup(string tagGroup) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTaggedEntitiesByTagGroup(TaggableObjectTypes.Member, tagGroup); } } /// <summary> /// Gets tagged Members by a specific 'Tag' and optional 'Tag Group'. /// </summary> /// <remarks>The <see cref="TaggedEntity"/> contains the Id and Tags of the Member, not the actual Member item.</remarks> /// <param name="tag">Tag</param> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="TaggedEntity"/></returns> public IEnumerable<TaggedEntity> GetTaggedMembersByTag(string tag, string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTaggedEntitiesByTag(TaggableObjectTypes.Member, tag, tagGroup); } } /// <summary> /// Gets every tag stored in the database /// </summary> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="ITag"/></returns> public IEnumerable<ITag> GetAllTags(string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTagsForEntityType(TaggableObjectTypes.All, tagGroup); } } /// <summary> /// Gets all tags for content items /// </summary> /// <remarks>Use the optional tagGroup parameter to limit the /// result to a specific 'Tag Group'.</remarks> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="ITag"/></returns> public IEnumerable<ITag> GetAllContentTags(string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTagsForEntityType(TaggableObjectTypes.Content, tagGroup); } } /// <summary> /// Gets all tags for media items /// </summary> /// <remarks>Use the optional tagGroup parameter to limit the /// result to a specific 'Tag Group'.</remarks> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="ITag"/></returns> public IEnumerable<ITag> GetAllMediaTags(string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTagsForEntityType(TaggableObjectTypes.Media, tagGroup); } } /// <summary> /// Gets all tags for member items /// </summary> /// <remarks>Use the optional tagGroup parameter to limit the /// result to a specific 'Tag Group'.</remarks> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="ITag"/></returns> public IEnumerable<ITag> GetAllMemberTags(string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTagsForEntityType(TaggableObjectTypes.Member, tagGroup); } } /// <summary> /// Gets all tags attached to a property by entity id /// </summary> /// <remarks>Use the optional tagGroup parameter to limit the /// result to a specific 'Tag Group'.</remarks> /// <param name="contentId">The content item id to get tags for</param> /// <param name="propertyTypeAlias">Property type alias</param> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="ITag"/></returns> public IEnumerable<ITag> GetTagsForProperty(int contentId, string propertyTypeAlias, string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTagsForProperty(contentId, propertyTypeAlias, tagGroup); } } /// <summary> /// Gets all tags attached to an entity (content, media or member) by entity id /// </summary> /// <remarks>Use the optional tagGroup parameter to limit the /// result to a specific 'Tag Group'.</remarks> /// <param name="contentId">The content item id to get tags for</param> /// <param name="tagGroup">Optional name of the 'Tag Group'</param> /// <returns>An enumerable list of <see cref="ITag"/></returns> public IEnumerable<ITag> GetTagsForEntity(int contentId, string tagGroup = null) { using (var repository = RepositoryFactory.CreateTagRepository(UowProvider.GetUnitOfWork())) { return repository.GetTagsForEntity(contentId, tagGroup); } } } }
using EIDSS.Reports.Parameterized.Human.AJ.DataSets; using EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1InfectiousDataSetTableAdapters; namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { partial class FormN1Page3 { /// <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(FormN1Page3)); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand(); this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand(); this.tableInterval = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell8 = new DevExpress.XtraReports.UI.XRTableCell(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.Detail1 = new DevExpress.XtraReports.UI.DetailBand(); this.ReportHeader1 = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.m_Adapter1 = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1InfectiousDataSetTableAdapters.spRepHumFormN1InfectiousDiseasesTableAdapter(); this.formN1InfectiousDataSet1 = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1InfectiousDataSet(); this.m_Adapter2 = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.FormN1InfectiousDataSetTableAdapters.spRepHumFormN1InfectiousDiseases_IntrahospitalInfectionsTableAdapter(); this.labelFooterYear = new DevExpress.XtraReports.UI.XRLabel(); this.labelFooterPage3 = new DevExpress.XtraReports.UI.XRLabel(); this.IntrahospitalInfectionsDetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.IntrahospitalInfectionsDetail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell(); this.IntrahospitalInfectionsReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.xrTable8 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow16 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell33 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTable7 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell77 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell78 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell47 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell52 = new DevExpress.XtraReports.UI.XRTableCell(); this.PageFooter = new DevExpress.XtraReports.UI.PageFooterBand(); this.labelFooterInfo = new DevExpress.XtraReports.UI.XRLabel(); ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.formN1InfectiousDataSet1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable8)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // resources.ApplyResources(this.Detail, "Detail"); this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UseTextAlignment = false; // // TopMargin // resources.ApplyResources(this.TopMargin, "TopMargin"); this.TopMargin.Name = "TopMargin"; this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); // // BottomMargin // resources.ApplyResources(this.BottomMargin, "BottomMargin"); this.BottomMargin.Name = "BottomMargin"; this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.BottomMargin.StylePriority.UseTextAlignment = false; // // tableInterval // resources.ApplyResources(this.tableInterval, "tableInterval"); this.tableInterval.Name = "tableInterval"; this.tableInterval.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.tableInterval.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.tableInterval.StylePriority.UseBorders = false; this.tableInterval.StylePriority.UseFont = false; this.tableInterval.StylePriority.UsePadding = false; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell11, this.xrTableCell10, this.xrTableCell14, this.xrTableCell9, this.xrTableCell17, this.xrTableCell16, this.xrTableCell18, this.xrTableCell20, this.xrTableCell15, this.xrTableCell21, this.xrTableCell19, this.xrTableCell22, this.xrTableCell8}); this.xrTableRow2.Name = "xrTableRow2"; resources.ApplyResources(this.xrTableRow2, "xrTableRow2"); // // xrTableCell11 // this.xrTableCell11.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRowNumber")}); this.xrTableCell11.Name = "xrTableCell11"; resources.ApplyResources(this.xrTableCell11, "xrTableCell11"); // // xrTableCell10 // this.xrTableCell10.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.strDiseaseName")}); this.xrTableCell10.Name = "xrTableCell10"; this.xrTableCell10.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell10, "xrTableCell10"); // // xrTableCell14 // this.xrTableCell14.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.strICD10")}); resources.ApplyResources(this.xrTableCell14, "xrTableCell14"); this.xrTableCell14.Name = "xrTableCell14"; this.xrTableCell14.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.xrTableCell14.StylePriority.UseFont = false; this.xrTableCell14.StylePriority.UsePadding = false; // // xrTableCell9 // this.xrTableCell9.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intTotal")}); this.xrTableCell9.Name = "xrTableCell9"; resources.ApplyResources(this.xrTableCell9, "xrTableCell9"); // // xrTableCell17 // this.xrTableCell17.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intWomen")}); this.xrTableCell17.Name = "xrTableCell17"; resources.ApplyResources(this.xrTableCell17, "xrTableCell17"); // // xrTableCell16 // this.xrTableCell16.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_0_17")}); this.xrTableCell16.Name = "xrTableCell16"; resources.ApplyResources(this.xrTableCell16, "xrTableCell16"); // // xrTableCell18 // this.xrTableCell18.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_0_1")}); this.xrTableCell18.Name = "xrTableCell18"; resources.ApplyResources(this.xrTableCell18, "xrTableCell18"); // // xrTableCell20 // this.xrTableCell20.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_1_4")}); this.xrTableCell20.Name = "xrTableCell20"; resources.ApplyResources(this.xrTableCell20, "xrTableCell20"); // // xrTableCell15 // this.xrTableCell15.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_5_13")}); this.xrTableCell15.Name = "xrTableCell15"; resources.ApplyResources(this.xrTableCell15, "xrTableCell15"); // // xrTableCell21 // this.xrTableCell21.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_14_17")}); this.xrTableCell21.Name = "xrTableCell21"; resources.ApplyResources(this.xrTableCell21, "xrTableCell21"); // // xrTableCell19 // this.xrTableCell19.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intAge_18_more")}); this.xrTableCell19.Name = "xrTableCell19"; resources.ApplyResources(this.xrTableCell19, "xrTableCell19"); // // xrTableCell22 // this.xrTableCell22.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRuralTotal")}); this.xrTableCell22.Name = "xrTableCell22"; resources.ApplyResources(this.xrTableCell22, "xrTableCell22"); // // xrTableCell8 // this.xrTableCell8.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases.intRuralAge_0_17")}); this.xrTableCell8.Name = "xrTableCell8"; resources.ApplyResources(this.xrTableCell8, "xrTableCell8"); // // ReportHeader // resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Name = "ReportHeader"; this.ReportHeader.StylePriority.UseFont = false; this.ReportHeader.StylePriority.UseTextAlignment = false; // // xrTable1 // resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.xrTable1.StylePriority.UseBorders = false; this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UsePadding = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell1, this.xrTableCell2, this.xrTableCell3, this.xrTableCell4, this.xrTableCell5, this.xrTableCell6, this.xrTableCell7, this.xrTableCell12, this.xrTableCell13, this.xrTableCell23, this.xrTableCell24, this.xrTableCell25, this.xrTableCell26}); this.xrTableRow1.Name = "xrTableRow1"; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // xrTableCell1 // this.xrTableCell1.Name = "xrTableCell1"; resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); // // xrTableCell2 // this.xrTableCell2.Name = "xrTableCell2"; resources.ApplyResources(this.xrTableCell2, "xrTableCell2"); // // xrTableCell3 // this.xrTableCell3.Name = "xrTableCell3"; resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); // // xrTableCell4 // this.xrTableCell4.Name = "xrTableCell4"; resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); // // xrTableCell5 // this.xrTableCell5.Name = "xrTableCell5"; resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); // // xrTableCell6 // this.xrTableCell6.Name = "xrTableCell6"; resources.ApplyResources(this.xrTableCell6, "xrTableCell6"); // // xrTableCell7 // this.xrTableCell7.Name = "xrTableCell7"; resources.ApplyResources(this.xrTableCell7, "xrTableCell7"); // // xrTableCell12 // this.xrTableCell12.Name = "xrTableCell12"; resources.ApplyResources(this.xrTableCell12, "xrTableCell12"); // // xrTableCell13 // this.xrTableCell13.Name = "xrTableCell13"; resources.ApplyResources(this.xrTableCell13, "xrTableCell13"); // // xrTableCell23 // this.xrTableCell23.Name = "xrTableCell23"; resources.ApplyResources(this.xrTableCell23, "xrTableCell23"); // // xrTableCell24 // this.xrTableCell24.Name = "xrTableCell24"; resources.ApplyResources(this.xrTableCell24, "xrTableCell24"); // // xrTableCell25 // this.xrTableCell25.Name = "xrTableCell25"; resources.ApplyResources(this.xrTableCell25, "xrTableCell25"); // // xrTableCell26 // this.xrTableCell26.Name = "xrTableCell26"; resources.ApplyResources(this.xrTableCell26, "xrTableCell26"); // // DetailReport // this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail1, this.ReportHeader1}); this.DetailReport.DataAdapter = this.m_Adapter1; this.DetailReport.DataMember = "spRepHumFormN1InfectiousDiseases"; this.DetailReport.DataSource = this.formN1InfectiousDataSet1; this.DetailReport.Level = 0; this.DetailReport.Name = "DetailReport"; // // Detail1 // this.Detail1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.tableInterval}); resources.ApplyResources(this.Detail1, "Detail1"); this.Detail1.Name = "Detail1"; this.Detail1.StylePriority.UseBorders = false; this.Detail1.StylePriority.UseFont = false; this.Detail1.StylePriority.UseTextAlignment = false; // // ReportHeader1 // this.ReportHeader1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.ReportHeader1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); resources.ApplyResources(this.ReportHeader1, "ReportHeader1"); this.ReportHeader1.Name = "ReportHeader1"; this.ReportHeader1.StylePriority.UseBorders = false; this.ReportHeader1.StylePriority.UseFont = false; this.ReportHeader1.StylePriority.UseTextAlignment = false; // // m_Adapter1 // this.m_Adapter1.ClearBeforeFill = true; // // formN1InfectiousDataSet1 // this.formN1InfectiousDataSet1.DataSetName = "FormN1InfectiousDataSet"; this.formN1InfectiousDataSet1.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // m_Adapter2 // this.m_Adapter2.ClearBeforeFill = true; // // labelFooterYear // this.labelFooterYear.BorderWidth = 1F; this.labelFooterYear.CanGrow = false; resources.ApplyResources(this.labelFooterYear, "labelFooterYear"); this.labelFooterYear.Name = "labelFooterYear"; this.labelFooterYear.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.labelFooterYear.StylePriority.UseBorders = false; this.labelFooterYear.StylePriority.UseBorderWidth = false; this.labelFooterYear.StylePriority.UseFont = false; this.labelFooterYear.StylePriority.UsePadding = false; this.labelFooterYear.StylePriority.UseTextAlignment = false; // // labelFooterPage3 // this.labelFooterPage3.CanGrow = false; resources.ApplyResources(this.labelFooterPage3, "labelFooterPage3"); this.labelFooterPage3.Name = "labelFooterPage3"; this.labelFooterPage3.StylePriority.UseBorders = false; this.labelFooterPage3.StylePriority.UseBorderWidth = false; this.labelFooterPage3.StylePriority.UseFont = false; this.labelFooterPage3.StylePriority.UsePadding = false; this.labelFooterPage3.StylePriority.UseTextAlignment = false; // // IntrahospitalInfectionsDetailReport // this.IntrahospitalInfectionsDetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.IntrahospitalInfectionsDetail, this.IntrahospitalInfectionsReportHeader}); this.IntrahospitalInfectionsDetailReport.DataAdapter = this.m_Adapter2; this.IntrahospitalInfectionsDetailReport.DataMember = "spRepHumFormN1InfectiousDiseases_IntrahospitalInfections"; this.IntrahospitalInfectionsDetailReport.DataSource = this.formN1InfectiousDataSet1; this.IntrahospitalInfectionsDetailReport.Level = 1; this.IntrahospitalInfectionsDetailReport.Name = "IntrahospitalInfectionsDetailReport"; // // IntrahospitalInfectionsDetail // this.IntrahospitalInfectionsDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); resources.ApplyResources(this.IntrahospitalInfectionsDetail, "IntrahospitalInfectionsDetail"); this.IntrahospitalInfectionsDetail.Name = "IntrahospitalInfectionsDetail"; this.IntrahospitalInfectionsDetail.StylePriority.UseBorders = false; this.IntrahospitalInfectionsDetail.StylePriority.UseFont = false; this.IntrahospitalInfectionsDetail.StylePriority.UseTextAlignment = false; // // xrTable2 // this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable2, "xrTable2"); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow5}); this.xrTable2.StylePriority.UseBorders = false; // // xrTableRow5 // this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell32, this.xrTableCell29, this.xrTableCell30, this.xrTableCell41, this.xrTableCell37, this.xrTableCell43, this.xrTableCell31}); this.xrTableRow5.Name = "xrTableRow5"; resources.ApplyResources(this.xrTableRow5, "xrTableRow5"); // // xrTableCell32 // this.xrTableCell32.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases_IntrahospitalInfections.intRowNumber")}); resources.ApplyResources(this.xrTableCell32, "xrTableCell32"); this.xrTableCell32.Name = "xrTableCell32"; this.xrTableCell32.StylePriority.UseFont = false; // // xrTableCell29 // this.xrTableCell29.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases_IntrahospitalInfections.strDiseaseName")}); this.xrTableCell29.Name = "xrTableCell29"; this.xrTableCell29.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell29, "xrTableCell29"); // // xrTableCell30 // this.xrTableCell30.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases_IntrahospitalInfections.strICD10")}); this.xrTableCell30.Name = "xrTableCell30"; resources.ApplyResources(this.xrTableCell30, "xrTableCell30"); // // xrTableCell41 // this.xrTableCell41.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepHumFormN1InfectiousDiseases_IntrahospitalInfections.intTotal")}); this.xrTableCell41.Name = "xrTableCell41"; resources.ApplyResources(this.xrTableCell41, "xrTableCell41"); // // xrTableCell37 // this.xrTableCell37.Name = "xrTableCell37"; resources.ApplyResources(this.xrTableCell37, "xrTableCell37"); // // xrTableCell43 // this.xrTableCell43.Name = "xrTableCell43"; resources.ApplyResources(this.xrTableCell43, "xrTableCell43"); // // xrTableCell31 // this.xrTableCell31.Name = "xrTableCell31"; resources.ApplyResources(this.xrTableCell31, "xrTableCell31"); // // IntrahospitalInfectionsReportHeader // this.IntrahospitalInfectionsReportHeader.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.IntrahospitalInfectionsReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable8}); resources.ApplyResources(this.IntrahospitalInfectionsReportHeader, "IntrahospitalInfectionsReportHeader"); this.IntrahospitalInfectionsReportHeader.Name = "IntrahospitalInfectionsReportHeader"; this.IntrahospitalInfectionsReportHeader.StylePriority.UseBorders = false; this.IntrahospitalInfectionsReportHeader.StylePriority.UseFont = false; this.IntrahospitalInfectionsReportHeader.StylePriority.UseTextAlignment = false; // // xrTable8 // resources.ApplyResources(this.xrTable8, "xrTable8"); this.xrTable8.Name = "xrTable8"; this.xrTable8.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow16, this.xrTableRow4, this.xrTableRow7}); this.xrTable8.StylePriority.UseTextAlignment = false; // // xrTableRow16 // this.xrTableRow16.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell27}); this.xrTableRow16.Name = "xrTableRow16"; resources.ApplyResources(this.xrTableRow16, "xrTableRow16"); // // xrTableCell27 // resources.ApplyResources(this.xrTableCell27, "xrTableCell27"); this.xrTableCell27.Name = "xrTableCell27"; this.xrTableCell27.StylePriority.UseFont = false; this.xrTableCell27.StylePriority.UseTextAlignment = false; // // xrTableRow4 // this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell33, this.xrTableCell34, this.xrTableCell35, this.xrTableCell36, this.xrTableCell42}); resources.ApplyResources(this.xrTableRow4, "xrTableRow4"); this.xrTableRow4.Name = "xrTableRow4"; this.xrTableRow4.StylePriority.UseFont = false; // // xrTableCell33 // this.xrTableCell33.Angle = 90F; this.xrTableCell33.Name = "xrTableCell33"; this.xrTableCell33.StylePriority.UseBorders = false; this.xrTableCell33.StylePriority.UseFont = false; this.xrTableCell33.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell33, "xrTableCell33"); // // xrTableCell34 // this.xrTableCell34.Name = "xrTableCell34"; this.xrTableCell34.StylePriority.UseBorders = false; this.xrTableCell34.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell34, "xrTableCell34"); // // xrTableCell35 // this.xrTableCell35.Multiline = true; this.xrTableCell35.Name = "xrTableCell35"; this.xrTableCell35.StylePriority.UseBorders = false; this.xrTableCell35.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell35, "xrTableCell35"); // // xrTableCell36 // this.xrTableCell36.Name = "xrTableCell36"; resources.ApplyResources(this.xrTableCell36, "xrTableCell36"); // // xrTableCell42 // this.xrTableCell42.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable7}); this.xrTableCell42.Name = "xrTableCell42"; resources.ApplyResources(this.xrTableCell42, "xrTableCell42"); // // xrTable7 // this.xrTable7.Borders = DevExpress.XtraPrinting.BorderSide.None; resources.ApplyResources(this.xrTable7, "xrTable7"); this.xrTable7.Name = "xrTable7"; this.xrTable7.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow15, this.xrTableRow3, this.xrTableRow12}); this.xrTable7.StylePriority.UseBorders = false; this.xrTable7.StylePriority.UseFont = false; this.xrTable7.StylePriority.UseTextAlignment = false; // // xrTableRow15 // this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell77}); this.xrTableRow15.Name = "xrTableRow15"; resources.ApplyResources(this.xrTableRow15, "xrTableRow15"); // // xrTableCell77 // this.xrTableCell77.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.xrTableCell77.Name = "xrTableCell77"; this.xrTableCell77.StylePriority.UseBorders = false; this.xrTableCell77.StylePriority.UseFont = false; this.xrTableCell77.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell77, "xrTableCell77"); // // xrTableRow3 // this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell40, this.xrTableCell28}); this.xrTableRow3.Name = "xrTableRow3"; resources.ApplyResources(this.xrTableRow3, "xrTableRow3"); // // xrTableCell40 // this.xrTableCell40.Borders = DevExpress.XtraPrinting.BorderSide.Right; this.xrTableCell40.Name = "xrTableCell40"; this.xrTableCell40.StylePriority.UseBorders = false; this.xrTableCell40.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell40, "xrTableCell40"); // // xrTableCell28 // this.xrTableCell28.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell28.Name = "xrTableCell28"; this.xrTableCell28.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell28, "xrTableCell28"); // // xrTableRow12 // this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell38, this.xrTableCell39, this.xrTableCell78}); this.xrTableRow12.Name = "xrTableRow12"; resources.ApplyResources(this.xrTableRow12, "xrTableRow12"); // // xrTableCell38 // this.xrTableCell38.Borders = DevExpress.XtraPrinting.BorderSide.Right; this.xrTableCell38.Name = "xrTableCell38"; this.xrTableCell38.StylePriority.UseBorders = false; this.xrTableCell38.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell38, "xrTableCell38"); // // xrTableCell39 // this.xrTableCell39.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right))); this.xrTableCell39.Name = "xrTableCell39"; this.xrTableCell39.StylePriority.UseBorders = false; resources.ApplyResources(this.xrTableCell39, "xrTableCell39"); // // xrTableCell78 // this.xrTableCell78.Borders = DevExpress.XtraPrinting.BorderSide.Left; this.xrTableCell78.Multiline = true; this.xrTableCell78.Name = "xrTableCell78"; this.xrTableCell78.StylePriority.UseBorders = false; this.xrTableCell78.StylePriority.UsePadding = false; this.xrTableCell78.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableCell78, "xrTableCell78"); // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.xrTableCell45, this.xrTableCell46, this.xrTableCell47, this.xrTableCell48, this.xrTableCell49, this.xrTableCell50, this.xrTableCell52}); resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); this.xrTableRow7.Name = "xrTableRow7"; this.xrTableRow7.StylePriority.UseFont = false; // // xrTableCell45 // this.xrTableCell45.Name = "xrTableCell45"; resources.ApplyResources(this.xrTableCell45, "xrTableCell45"); // // xrTableCell46 // this.xrTableCell46.Name = "xrTableCell46"; resources.ApplyResources(this.xrTableCell46, "xrTableCell46"); // // xrTableCell47 // this.xrTableCell47.Name = "xrTableCell47"; resources.ApplyResources(this.xrTableCell47, "xrTableCell47"); // // xrTableCell48 // this.xrTableCell48.Name = "xrTableCell48"; resources.ApplyResources(this.xrTableCell48, "xrTableCell48"); // // xrTableCell49 // this.xrTableCell49.Name = "xrTableCell49"; resources.ApplyResources(this.xrTableCell49, "xrTableCell49"); // // xrTableCell50 // this.xrTableCell50.Name = "xrTableCell50"; resources.ApplyResources(this.xrTableCell50, "xrTableCell50"); // // xrTableCell52 // this.xrTableCell52.Name = "xrTableCell52"; resources.ApplyResources(this.xrTableCell52, "xrTableCell52"); // // PageFooter // this.PageFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.labelFooterYear, this.labelFooterInfo, this.labelFooterPage3}); resources.ApplyResources(this.PageFooter, "PageFooter"); this.PageFooter.Name = "PageFooter"; this.PageFooter.StylePriority.UseFont = false; // // labelFooterInfo // this.labelFooterInfo.CanGrow = false; resources.ApplyResources(this.labelFooterInfo, "labelFooterInfo"); this.labelFooterInfo.Name = "labelFooterInfo"; this.labelFooterInfo.StylePriority.UseBorders = false; this.labelFooterInfo.StylePriority.UseBorderWidth = false; this.labelFooterInfo.StylePriority.UseFont = false; this.labelFooterInfo.StylePriority.UsePadding = false; this.labelFooterInfo.StylePriority.UseTextAlignment = false; // // FormN1Page3 // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.TopMargin, this.BottomMargin, this.ReportHeader, this.DetailReport, this.IntrahospitalInfectionsDetailReport, this.PageFooter}); resources.ApplyResources(this, "$this"); this.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.Version = "14.1"; ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.formN1InfectiousDataSet1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable8)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.DetailBand Detail; private DevExpress.XtraReports.UI.TopMarginBand TopMargin; private DevExpress.XtraReports.UI.BottomMarginBand BottomMargin; protected DevExpress.XtraReports.UI.XRTable tableInterval; private DevExpress.XtraReports.UI.XRTableRow xrTableRow2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell11; private DevExpress.XtraReports.UI.XRTableCell xrTableCell10; private DevExpress.XtraReports.UI.XRTableCell xrTableCell14; private DevExpress.XtraReports.UI.XRTableCell xrTableCell9; private DevExpress.XtraReports.UI.XRTableCell xrTableCell17; private DevExpress.XtraReports.UI.XRTableCell xrTableCell16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell18; private DevExpress.XtraReports.UI.XRTableCell xrTableCell20; private DevExpress.XtraReports.UI.XRTableCell xrTableCell15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell21; private DevExpress.XtraReports.UI.XRTableCell xrTableCell19; private DevExpress.XtraReports.UI.XRTableCell xrTableCell22; private DevExpress.XtraReports.UI.XRTableCell xrTableCell8; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader; protected DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell xrTableCell2; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell6; private DevExpress.XtraReports.UI.XRTableCell xrTableCell7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell13; private DevExpress.XtraReports.UI.XRTableCell xrTableCell23; private DevExpress.XtraReports.UI.XRTableCell xrTableCell24; private DevExpress.XtraReports.UI.XRTableCell xrTableCell25; private DevExpress.XtraReports.UI.XRTableCell xrTableCell26; private DevExpress.XtraReports.UI.DetailReportBand DetailReport; private DevExpress.XtraReports.UI.DetailBand Detail1; private DevExpress.XtraReports.UI.ReportHeaderBand ReportHeader1; private DevExpress.XtraReports.UI.DetailReportBand IntrahospitalInfectionsDetailReport; private DevExpress.XtraReports.UI.DetailBand IntrahospitalInfectionsDetail; private FormN1InfectiousDataSet formN1InfectiousDataSet1; private spRepHumFormN1InfectiousDiseasesTableAdapter m_Adapter1; private spRepHumFormN1InfectiousDiseases_IntrahospitalInfectionsTableAdapter m_Adapter2; private DevExpress.XtraReports.UI.XRTable xrTable8; private DevExpress.XtraReports.UI.XRTableRow xrTableRow16; private DevExpress.XtraReports.UI.XRTableCell xrTableCell27; private DevExpress.XtraReports.UI.XRTableRow xrTableRow4; private DevExpress.XtraReports.UI.XRTableCell xrTableCell33; private DevExpress.XtraReports.UI.XRTableCell xrTableCell34; private DevExpress.XtraReports.UI.XRTableCell xrTableCell35; private DevExpress.XtraReports.UI.XRTableCell xrTableCell36; private DevExpress.XtraReports.UI.XRTableCell xrTableCell42; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell xrTableCell45; private DevExpress.XtraReports.UI.XRTableCell xrTableCell46; private DevExpress.XtraReports.UI.XRTableCell xrTableCell47; private DevExpress.XtraReports.UI.XRTableCell xrTableCell48; private DevExpress.XtraReports.UI.XRTableCell xrTableCell49; private DevExpress.XtraReports.UI.XRTableCell xrTableCell50; private DevExpress.XtraReports.UI.XRTableCell xrTableCell52; private DevExpress.XtraReports.UI.XRTable xrTable7; private DevExpress.XtraReports.UI.XRTableRow xrTableRow12; private DevExpress.XtraReports.UI.XRTableCell xrTableCell78; private DevExpress.XtraReports.UI.PageFooterBand PageFooter; private DevExpress.XtraReports.UI.XRTableRow xrTableRow15; private DevExpress.XtraReports.UI.XRTableCell xrTableCell77; private DevExpress.XtraReports.UI.XRTableRow xrTableRow3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell28; private DevExpress.XtraReports.UI.XRTableCell xrTableCell38; private DevExpress.XtraReports.UI.XRTableCell xrTableCell39; private DevExpress.XtraReports.UI.XRTableCell xrTableCell40; private DevExpress.XtraReports.UI.XRLabel labelFooterYear; private DevExpress.XtraReports.UI.XRLabel labelFooterPage3; private DevExpress.XtraReports.UI.XRLabel labelFooterInfo; private DevExpress.XtraReports.UI.ReportHeaderBand IntrahospitalInfectionsReportHeader; private DevExpress.XtraReports.UI.XRTable xrTable2; private DevExpress.XtraReports.UI.XRTableRow xrTableRow5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell32; private DevExpress.XtraReports.UI.XRTableCell xrTableCell29; private DevExpress.XtraReports.UI.XRTableCell xrTableCell30; private DevExpress.XtraReports.UI.XRTableCell xrTableCell41; private DevExpress.XtraReports.UI.XRTableCell xrTableCell37; private DevExpress.XtraReports.UI.XRTableCell xrTableCell43; private DevExpress.XtraReports.UI.XRTableCell xrTableCell31; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename { internal abstract partial class AbstractEditorInlineRenameService { /// <summary> /// Represents information about the ability to rename a particular location. /// </summary> private partial class SymbolInlineRenameInfo : IInlineRenameInfo { private const string AttributeSuffix = "Attribute"; private readonly object _gate = new object(); private readonly Document _document; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private Task<RenameLocations> _underlyingFindRenameLocationsTask; /// <summary> /// Whether or not we shortened the trigger span (say because we were renaming an attribute, /// and we didn't select the 'Attribute' portion of the name. /// </summary> private readonly bool _shortenedTriggerSpan; private readonly bool _isRenamingAttributePrefix; public bool CanRename { get; } public string LocalizedErrorMessage { get; } public TextSpan TriggerSpan { get; } public SymbolAndProjectId RenameSymbolAndProjectId { get; } public bool HasOverloads { get; } public bool ForceRenameOverloads { get; } public ISymbol RenameSymbol => RenameSymbolAndProjectId.Symbol; public SymbolInlineRenameInfo( IEnumerable<IRefactorNotifyService> refactorNotifyServices, Document document, TextSpan triggerSpan, SymbolAndProjectId renameSymbolAndProjectId, bool forceRenameOverloads, CancellationToken cancellationToken) { this.CanRename = true; _refactorNotifyServices = refactorNotifyServices; _document = document; this.RenameSymbolAndProjectId = renameSymbolAndProjectId; this.HasOverloads = RenameLocations.GetOverloadedSymbols(this.RenameSymbolAndProjectId).Any(); this.ForceRenameOverloads = forceRenameOverloads; _isRenamingAttributePrefix = CanRenameAttributePrefix(document, triggerSpan, cancellationToken); this.TriggerSpan = GetReferenceEditSpan(new InlineRenameLocation(document, triggerSpan), cancellationToken); _shortenedTriggerSpan = this.TriggerSpan != triggerSpan; } private bool CanRenameAttributePrefix(Document document, TextSpan triggerSpan, CancellationToken cancellationToken) { // if this isn't an attribute, or it doesn't have the 'Attribute' suffix, then clearly // we can't rename just the attribute prefix. if (!this.IsRenamingAttributeTypeWithAttributeSuffix()) { return false; } // Ok, the symbol is good. Now, make sure that the trigger text starts with the prefix // of the attribute. If it does, then we can rename just the attribute prefix (otherwise // we need to rename the entire attribute). var nameWithoutAttribute = this.RenameSymbol.Name.GetWithoutAttributeSuffix(isCaseSensitive: true); var triggerText = GetSpanText(document, triggerSpan, cancellationToken); return triggerText.StartsWith(triggerText); // TODO: Always true? What was it supposed to do? } /// <summary> /// Given a span of text, we need to return the subspan that is editable and /// contains the current replacementText. /// /// These cases are currently handled: /// - Escaped identifiers [foo] => foo /// - Type suffixes in VB foo$ => foo /// - Qualified names from complexification A.foo => foo /// - Optional Attribute suffixes XAttribute => X /// Careful here: XAttribute => XAttribute if renamesymbol is XAttributeAttribute /// - Compiler-generated EventHandler suffix XEventHandler => X /// - Compiler-generated get_ and set_ prefixes get_X => X /// </summary> public TextSpan GetReferenceEditSpan(InlineRenameLocation location, CancellationToken cancellationToken) { var searchName = this.RenameSymbol.Name; if (_isRenamingAttributePrefix) { // We're only renaming the attribute prefix part. We want to adjust the span of // the reference we've found to only update the prefix portion. searchName = GetWithoutAttributeSuffix(this.RenameSymbol.Name); } var spanText = GetSpanText(location.Document, location.TextSpan, cancellationToken); var index = spanText.LastIndexOf(searchName, StringComparison.Ordinal); if (index < 0) { // Couldn't even find the search text at this reference location. This might happen // if the user used things like unicode escapes. IN that case, we'll have to rename // the entire identifier. return location.TextSpan; } return new TextSpan(location.TextSpan.Start + index, searchName.Length); } public TextSpan? GetConflictEditSpan(InlineRenameLocation location, string replacementText, CancellationToken cancellationToken) { var spanText = GetSpanText(location.Document, location.TextSpan, cancellationToken); var position = spanText.LastIndexOf(replacementText, StringComparison.Ordinal); if (_isRenamingAttributePrefix) { // We're only renaming the attribute prefix part. We want to adjust the span of // the reference we've found to only update the prefix portion. var index = spanText.LastIndexOf(replacementText + AttributeSuffix, StringComparison.Ordinal); position = index >= 0 ? index : position; } if (position < 0) { return null; } return new TextSpan(location.TextSpan.Start + position, replacementText.Length); } private static string GetSpanText(Document document, TextSpan triggerSpan, CancellationToken cancellationToken) { var sourceText = document.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken); var triggerText = sourceText.ToString(triggerSpan); return triggerText; } private static string GetWithoutAttributeSuffix(string value) { return value.GetWithoutAttributeSuffix(isCaseSensitive: true); } internal bool IsRenamingAttributeTypeWithAttributeSuffix() { if (this.RenameSymbol.IsAttribute() || (this.RenameSymbol.Kind == SymbolKind.Alias && ((IAliasSymbol)this.RenameSymbol).Target.IsAttribute())) { var name = this.RenameSymbol.Name; if (name.TryGetWithoutAttributeSuffix(isCaseSensitive: true, result: out name)) { return true; } } return false; } public string DisplayName { get { return this.RenameSymbol.Name; } } public string FullDisplayName { get { return this.RenameSymbol.ToDisplayString(); } } public Glyph Glyph { get { return this.RenameSymbol.GetGlyph(); } } public string GetFinalSymbolName(string replacementText) { if (_isRenamingAttributePrefix) { return replacementText + AttributeSuffix; } return replacementText; } public Task<IInlineRenameLocationSet> FindRenameLocationsAsync(OptionSet optionSet, CancellationToken cancellationToken) { Task<RenameLocations> renameTask; lock (_gate) { if (_underlyingFindRenameLocationsTask == null) { // If this is the first call, then just start finding the initial set of rename // locations. _underlyingFindRenameLocationsTask = RenameLocations.FindAsync( this.RenameSymbolAndProjectId, _document.Project.Solution, optionSet, cancellationToken); renameTask = _underlyingFindRenameLocationsTask; // null out the option set. We don't need it anymore, and this will ensure // we don't call FindWithUpdatedOptionsAsync below. optionSet = null; } else { // We already have a task to figure out the set of rename locations. Let it // finish, then ask it to get the rename locations with the updated options. renameTask = _underlyingFindRenameLocationsTask; } } return GetLocationSet(renameTask, optionSet, cancellationToken); } private async Task<IInlineRenameLocationSet> GetLocationSet(Task<RenameLocations> renameTask, OptionSet optionSet, CancellationToken cancellationToken) { var locationSet = await renameTask.ConfigureAwait(false); if (optionSet != null) { locationSet = await locationSet.FindWithUpdatedOptionsAsync(optionSet, cancellationToken).ConfigureAwait(false); } return new InlineRenameLocationSet(this, locationSet); } public bool TryOnBeforeGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol, this.GetFinalSymbolName(replacementText), throwOnFailure: false); } public bool TryOnAfterGlobalSymbolRenamed(Workspace workspace, IEnumerable<DocumentId> changedDocumentIDs, string replacementText) { return _refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocumentIDs, RenameSymbol, this.GetFinalSymbolName(replacementText), throwOnFailure: false); } } } }
using BellRichM.Helpers.Test; using BellRichM.Logging; using BellRichM.Weather.Api.Configuration; using BellRichM.Weather.Api.Data; using BellRichM.Weather.Api.Repositories; using FluentAssertions; using Machine.Specifications; using Microsoft.Data.Sqlite; using Moq; using System.Collections.Generic; using System.Linq; using It = Machine.Specifications.It; namespace BellRichM { internal class ConditionRepositorySpecs { protected const int Offset = 0; protected const int Limit = 5; protected static LoggingData loggingData; protected static MinMaxCondition testCondition; protected static MinMaxCondition hourTestCondition; protected static Mock<ILoggerAdapter<ConditionRepository>> loggerMock; protected static ConditionRepository conditionRepository; protected static ConditionRepositoryDbProviderFactory conditionRepositoryDbProviderFactory; protected static ConditionRepositoryConfiguration conditionRepositoryConfiguration; Establish context = () => { // default to no logging loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData>(), ErrorLoggingMessages = new List<string>() }; testCondition = new MinMaxCondition { Year = 2018, Month = 9, Day = 1, Hour = 1, MaxTemp = "67.2", MinTemp = "65.6", MaxHumidity = "83.0", MinHumidity = "80.0", MaxDewpoint = "60.8725771445071", MinDewpoint = "60.0932637870109", MaxHeatIndex = "67.2", MinWindchill = "65.6", MaxBarometer = "29.694", MinBarometer = "29.687", MaxET = "0.001", MinET = "0.0", MaxUV = "0.0", MinUV = "0.0", MaxRadiation = "0.0", MinRadiation = "0.0", MaxRainRate = "0.0", RainTotal = "0.0", MaxWindGust = "4.00000994196379", AvgWindSpeed = "0.583334783203052" }; hourTestCondition = new MinMaxCondition { Year = 2018, Month = 9, Day = 1, Hour = 1, MaxTemp = "67.2", MinTemp = "65.6", MaxHumidity = "83.0", MinHumidity = "80.0", MaxDewpoint = "60.8725771445071", MinDewpoint = "60.0932637870109", MaxHeatIndex = "67.2", MinWindchill = "65.6", MaxBarometer = "29.694", MinBarometer = "29.687", MaxET = "0.001", MinET = "0.0", MaxUV = "0.0", MinUV = "0.0", MaxRadiation = "0.0", MinRadiation = "0.0", MaxRainRate = "0.0", MaxWindGust = "4.00000994196379", }; var dbProviderFactory = SqliteFactory.Instance; conditionRepositoryDbProviderFactory = new ConditionRepositoryDbProviderFactory(dbProviderFactory); conditionRepositoryConfiguration = new ConditionRepositoryConfiguration { ConnectionString = "Data Source=../../../testData.db" }; loggerMock = new Mock<ILoggerAdapter<ConditionRepository>>(); }; } internal class When_retrieving_condition_for_years : ConditionRepositorySpecs { protected static IEnumerable<MinMaxCondition> conditions; Establish context = () => { loggingData = new LoggingData { DebugTimes = 1, EventLoggingData = new List<EventLoggingData>(), ErrorLoggingMessages = new List<string>() }; conditionRepository = new ConditionRepository(loggerMock.Object, conditionRepositoryDbProviderFactory, conditionRepositoryConfiguration); }; Because of = () => conditions = conditionRepository.GetYear(Offset, Limit).Result; Behaves_like<LoggingBehaviors<ConditionRepository>> correct_logging = () => { }; It should_have_correct_number_of_records = () => conditions.Count().ShouldEqual(3); It should_not_have_months = () => conditions.Should().Contain(c => c.Month == null); It should_not_have_days = () => conditions.Should().Contain(c => c.Day == null); It should_not_have_hours = () => conditions.Should().Contain(c => c.Hour == null); } internal class When_retrieving_condition_for_years_fails : ConditionRepositorySpecs { protected static IEnumerable<MinMaxCondition> conditions; Establish context = () => { loggingData = new LoggingData { DebugTimes = 1, EventLoggingData = new List<EventLoggingData>(), ErrorLoggingMessages = new List<string>() }; conditionRepository = new ConditionRepository(loggerMock.Object, conditionRepositoryDbProviderFactory, conditionRepositoryConfiguration); }; Because of = () => conditions = conditionRepository.GetYear(4, Limit).Result; Behaves_like<LoggingBehaviors<ConditionRepository>> correct_logging = () => { }; It should_have_correct_number_of_records = () => conditions.ShouldBeEmpty(); } internal class When_retrieving_condition_detail_for_an_hour : ConditionRepositorySpecs { protected static MinMaxCondition condition; Establish context = () => { loggingData = new LoggingData { DebugTimes = 1, EventLoggingData = new List<EventLoggingData>(), ErrorLoggingMessages = new List<string>() }; conditionRepository = new ConditionRepository(loggerMock.Object, conditionRepositoryDbProviderFactory, conditionRepositoryConfiguration); }; Because of = () => condition = conditionRepository.GetHourDetail(2018, 9, 1, 1).Result; Behaves_like<LoggingBehaviors<ConditionRepository>> correct_logging = () => { }; It should_return_the_correct_data = () => condition.Should().BeEquivalentTo(testCondition); } internal class When_retrieving_condition_detail_for_an_hour_fails : ConditionRepositorySpecs { protected static MinMaxCondition condition; Establish context = () => { loggingData = new LoggingData { DebugTimes = 1, EventLoggingData = new List<EventLoggingData>(), ErrorLoggingMessages = new List<string>() }; conditionRepository = new ConditionRepository(loggerMock.Object, conditionRepositoryDbProviderFactory, conditionRepositoryConfiguration); }; Because of = () => condition = conditionRepository.GetHourDetail(1900, 9, 1, 1).Result; Behaves_like<LoggingBehaviors<ConditionRepository>> correct_logging = () => { }; It should_return_the_correct_data = () => condition.ShouldBeNull(); } internal class When_retrieving_year_count : ConditionRepositorySpecs { protected static int count; Establish context = () => { loggingData = new LoggingData { DebugTimes = 1, EventLoggingData = new List<EventLoggingData>(), ErrorLoggingMessages = new List<string>() }; conditionRepository = new ConditionRepository(loggerMock.Object, conditionRepositoryDbProviderFactory, conditionRepositoryConfiguration); }; Because of = () => count = conditionRepository.GetYearCount().Result; Behaves_like<LoggingBehaviors<ConditionRepository>> correct_logging = () => { }; It should_return_the_correct_count = () => count.ShouldEqual(3); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyDate { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Date operations. /// </summary> public partial class Date : IServiceOperations<AutoRestDateTestService>, IDate { /// <summary> /// Initializes a new instance of the Date class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Date(AutoRestDateTestService client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AutoRestDateTestService /// </summary> public AutoRestDateTestService Client { get; private set; } /// <summary> /// Get null date value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/null").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get invalid date value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetInvalidDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetInvalidDate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/invaliddate").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get overflow date value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetOverflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetOverflowDate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/overflowdate").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get underflow date value /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetUnderflowDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetUnderflowDate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/underflowdate").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put max date value 9999-12-31 /// </summary> /// <param name='dateBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutMaxDateWithHttpMessagesAsync(System.DateTime dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dateBody", dateBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMaxDate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get max date value 9999-12-31 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetMaxDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMaxDate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/max").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put min date value 0000-01-01 /// </summary> /// <param name='dateBody'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutMinDateWithHttpMessagesAsync(System.DateTime dateBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dateBody", dateBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutMinDate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get min date value 0000-01-01 /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<System.DateTime?>> GetMinDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetMinDate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "date/min").ToString(); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<System.DateTime?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<System.DateTime?>(_responseContent, new DateJsonConverter()); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using MagicOnion.Server.HttpGateway.Swagger.Schemas; using MagicOnion.Server; using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml.Linq; namespace MagicOnion.Server.HttpGateway.Swagger { public class SwaggerDefinitionBuilder { readonly SwaggerOptions options; readonly HttpContext httpContext; readonly IReadOnlyList<MethodHandler> handlers; ILookup<Tuple<string, string>, XmlCommentStructure> xDocLookup; public SwaggerDefinitionBuilder(SwaggerOptions options, HttpContext httpContext, IEnumerable<MethodHandler> handlers) { this.options = options; this.httpContext = httpContext; this.handlers = handlers.Where(x => x.MethodType == Grpc.Core.MethodType.Unary).ToArray(); } public byte[] BuildSwaggerJson() { try { if (options.XmlDocumentPath != null && !File.Exists(options.XmlDocumentPath)) { xDocLookup = null; } else { xDocLookup = (options.XmlDocumentPath != null) ? BuildXmlMemberCommentStructure(options.XmlDocumentPath) : null; } var doc = new SwaggerDocument(); doc.info = options.Info; doc.host = (options.CustomHost != null) ? options.CustomHost(httpContext) : httpContext.Request.Headers["Host"][0]; doc.basePath = options.ApiBasePath; doc.schemes = (options.ForceSchemas.Length == 0) ? new[] { httpContext.Request.IsHttps ? "https" : httpContext.Request.Scheme } : options.ForceSchemas; doc.paths = new Dictionary<string, PathItem>(); doc.definitions = new Dictionary<string, Schema>(); // tags. var xmlServiceName = (xDocLookup != null) ? BuildXmlTypeSummary(options.XmlDocumentPath) : null; doc.tags = handlers .Select(x => x.ServiceName) .Distinct() .Select(x => { string desc = null; if (xmlServiceName != null) { xmlServiceName.TryGetValue(x, out desc); } return new Tag() { name = x, description = desc }; }) .ToArray(); // Unary only foreach (var item in handlers) { XmlCommentStructure xmlComment = null; if (xDocLookup != null) { xmlComment = xDocLookup[Tuple.Create(item.ServiceName, item.MethodInfo.Name)].FirstOrDefault(); } var parameters = BuildParameters(doc.definitions, xmlComment, item.MethodInfo); var operation = new Operation { tags = new[] { item.ServiceName }, summary = (xmlComment != null) ? xmlComment.Summary : "", description = (xmlComment != null) ? xmlComment.Remarks : "", parameters = parameters, responses = new Dictionary<string, Response> { {"default", new Response { description = "done operation"} }, } }; doc.paths.Add("/" + item.ToString(), new PathItem { post = operation }); // everything post. } using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms, new UTF8Encoding(false))) { var serializer = new JsonSerializer() { NullValueHandling = NullValueHandling.Ignore, ContractResolver = IgnoreEmptyEnumerablesResolver.Instance // omit empty collection. }; serializer.Serialize(sw, doc); sw.Flush(); return ms.ToArray(); } } catch (Exception ex) { return Encoding.UTF8.GetBytes(ex.ToString()); } } Schemas.Parameter[] BuildParameters(IDictionary<string, Schema> definitions, XmlCommentStructure xmlComment, MethodInfo method) { var parameterInfos = method.GetParameters(); var parameters = parameterInfos .Select(x => { var parameterXmlComment = UnwrapTypeName(x.ParameterType); if (xmlComment != null) { xmlComment.Parameters.TryGetValue(x.Name, out parameterXmlComment); parameterXmlComment = UnwrapTypeName(x.ParameterType) + " " + parameterXmlComment; } var defaultValue = x.DefaultValue; if (defaultValue != null && x.ParameterType.GetTypeInfo().IsEnum) { defaultValue = defaultValue.ToString(); } var collectionType = GetCollectionType(x.ParameterType); var items = collectionType != null ? new PartialSchema { type = ToSwaggerDataType(collectionType) } : null; string defaultObjectExample = null; object[] enums = null; if (x.ParameterType.GetTypeInfo().IsEnum || (collectionType != null && collectionType.GetTypeInfo().IsEnum)) { var enumType = (x.ParameterType.GetTypeInfo().IsEnum) ? x.ParameterType : collectionType; var enumValues = Enum.GetNames(enumType); if (collectionType != null) { // Current Swagger-UI's enum array selector is too buggy... //items.@enum = enumValues; defaultObjectExample = string.Join("\r\n", Enum.GetNames(collectionType)); } else { enums = enumValues; } } var swaggerDataType = ToSwaggerDataType(x.ParameterType); Schema refSchema = null; if (swaggerDataType == "object") { BuildSchema(definitions, x.ParameterType); refSchema = new Schema { @ref = BuildSchema(definitions, x.ParameterType) }; var unknownObj = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(x.ParameterType); defaultObjectExample = JsonConvert.SerializeObject(unknownObj, new[] { new Newtonsoft.Json.Converters.StringEnumConverter() }); swaggerDataType = "string"; // object can not attach formData. } return new Schemas.Parameter { name = x.Name, @in = "formData", type = swaggerDataType, description = parameterXmlComment, required = !x.IsOptional, @default = defaultObjectExample ?? ((x.IsOptional) ? defaultValue : null), items = items, @enum = enums, collectionFormat = "multi", // csv or multi schema = refSchema }; }) .ToArray(); return parameters; } string BuildSchema(IDictionary<string, Schema> definitions, Type type) { var fullName = type.FullName; if (fullName == null) return ""; // safety(TODO:IDictionary<> is not supported) Schema schema; if (definitions.TryGetValue(fullName, out schema)) return "#/definitions/" + fullName; var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); var fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public); var props = properties.Cast<MemberInfo>().Concat(fields) .OrderBy(x => x.Name) .Select(x => { var memberType = GetMemberType(x); var swaggerDataType = ToSwaggerDataType(memberType); if (swaggerDataType == "object") { return new { Name = x.Name, Schema = new Schema { @ref = BuildSchema(definitions, memberType) } }; } else { Schema items = null; if (swaggerDataType == "array") { var collectionType = GetCollectionType(memberType); var dataType = ToSwaggerDataType(collectionType); if (dataType == "object") { items = new Schema { @ref = BuildSchema(definitions, collectionType) }; } else { if (collectionType.GetTypeInfo().IsEnum) { items = new Schema { type = "string", @enum = Enum.GetNames(collectionType) }; } else { items = new Schema { type = ToSwaggerDataType(collectionType) }; } } } IList<object> schemaEnum = null; if (memberType.GetTypeInfo().IsEnum) { schemaEnum = Enum.GetNames(memberType); } return new { Name = x.Name, Schema = new Schema { type = swaggerDataType, description = UnwrapTypeName(memberType), @enum = schemaEnum, items = items } }; } }) .ToDictionary(x => x.Name, x => x.Schema); schema = new Schema { type = "object", properties = props, }; definitions.Add(fullName, schema); return "#/definitions/" + fullName; } static Type GetMemberType(MemberInfo memberInfo) { var f = memberInfo as FieldInfo; if (f != null) return f.FieldType; var p = memberInfo as PropertyInfo; if (p != null) return p.PropertyType; throw new Exception(); } static Type GetCollectionType(Type type) { if (type.IsArray) return type.GetElementType(); if (type.GetTypeInfo().IsGenericType) { var genTypeDef = type.GetGenericTypeDefinition(); if (genTypeDef == typeof(IEnumerable<>) || genTypeDef == typeof(ICollection<>) || genTypeDef == typeof(IList<>) || genTypeDef == typeof(List<>) || genTypeDef == typeof(IReadOnlyCollection<>) || genTypeDef == typeof(IReadOnlyList<>)) { return genTypeDef.GetGenericArguments()[0]; } } return null; // not collection } static ILookup<Tuple<string, string>, XmlCommentStructure> BuildXmlMemberCommentStructure(string xmlDocumentPath) { var file = File.ReadAllText(xmlDocumentPath); var xDoc = XDocument.Parse(file); var xDocLookup = xDoc.Descendants("member") .Where(x => x.Attribute("name").Value.StartsWith("M:")) .Select(x => { var match = Regex.Match(x.Attribute("name").Value, @"(\w+)\.(\w+)?(\(.+\)|$)"); var summary = ((string)x.Element("summary")) ?? ""; var returns = ((string)x.Element("returns")) ?? ""; var remarks = ((string)x.Element("remarks")) ?? ""; var parameters = x.Elements("param") .Select(e => Tuple.Create(e.Attribute("name").Value, e)) .Distinct(new Item1EqualityCompaerer<string, XElement>()) .ToDictionary(e => e.Item1, e => e.Item2.Value.Trim()); return new XmlCommentStructure { ClassName = match.Groups[1].Value, MethodName = match.Groups[2].Value, Summary = summary.Trim(), Remarks = remarks.Trim(), Parameters = parameters, Returns = returns.Trim() }; }) .ToLookup(x => Tuple.Create(x.ClassName, x.MethodName)); return xDocLookup; } static IDictionary<string, string> BuildXmlTypeSummary(string xmlDocumentPath) { var file = File.ReadAllText(xmlDocumentPath); var xDoc = XDocument.Parse(file); var xDocLookup = xDoc.Descendants("member") .Where(x => x.Attribute("name").Value.StartsWith("T:")) .Select(x => { var match = Regex.Match(x.Attribute("name").Value, @"(\w+)\.(\w+)?(\(.+\)|$)"); var summary = ((string)x.Element("summary")) ?? ""; return new { name = match.Groups[2].Value, summary = summary.Trim() }; }) .ToDictionary(x => x.name, x => x.summary); return xDocLookup; } static string ToSwaggerDataType(Type type) { if (GetCollectionType(type) != null) { return "array"; } if (type.IsNullable()) { type = Nullable.GetUnderlyingType(type); } if (type.GetTypeInfo().IsEnum || type == typeof(DateTime) || type == typeof(DateTimeOffset)) { return "string"; } switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: return "boolean"; case TypeCode.Decimal: case TypeCode.Single: case TypeCode.Double: return "number"; case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: return "integer"; case TypeCode.Char: case TypeCode.String: return "string"; default: return "object"; } } static string UnwrapTypeName(Type t) { if (t == typeof(void)) return "void"; if (!t.GetTypeInfo().IsGenericType) return t.Name; var innerFormat = string.Join(", ", t.GetGenericArguments().Select(x => UnwrapTypeName(x))); return Regex.Replace(t.GetGenericTypeDefinition().Name, @"`.+$", "") + "&lt;" + innerFormat + "&gt;"; } class Item1EqualityCompaerer<T1, T2> : EqualityComparer<Tuple<T1, T2>> { public override bool Equals(Tuple<T1, T2> x, Tuple<T1, T2> y) { return x.Item1.Equals(y.Item1); } public override int GetHashCode(Tuple<T1, T2> obj) { return obj.Item1.GetHashCode(); } } class XmlCommentStructure { public string ClassName { get; set; } public string MethodName { get; set; } public string Summary { get; set; } public string Remarks { get; set; } public Dictionary<string, string> Parameters { get; set; } public string Returns { get; set; } } } // http://stackoverflow.com/questions/34903151/how-to-omit-empty-collections-when-serializing-with-json-net public class IgnoreEmptyEnumerablesResolver : DefaultContractResolver { public static readonly IgnoreEmptyEnumerablesResolver Instance = new IgnoreEmptyEnumerablesResolver(); protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var property = base.CreateProperty(member, memberSerialization); if (property.PropertyType != typeof(string) && typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) { property.ShouldSerialize = instance => { IEnumerable enumerable = null; // this value could be in a public field or public property switch (member.MemberType) { case MemberTypes.Property: enumerable = instance .GetType() .GetProperty(member.Name) .GetValue(instance, null) as IEnumerable; break; case MemberTypes.Field: enumerable = instance .GetType() .GetField(member.Name) .GetValue(instance) as IEnumerable; break; default: break; } if (enumerable != null) { // check to see if there is at least one item in the Enumerable return enumerable.GetEnumerator().MoveNext(); } else { // if the list is null, we defer the decision to NullValueHandling return true; } }; } return property; } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace Microsoft.Tools.ServiceModel.ComSvcConfig { using System; using System.ServiceModel.Channels; using System.Diagnostics; using System.Configuration; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Runtime.InteropServices; using System.Security; using System.ServiceModel; using System.ServiceModel.Configuration; using System.ServiceModel.Description; using Microsoft.Tools.ServiceModel; using Microsoft.Tools.ServiceModel.SvcUtil; using System.Web.Configuration; class WasEndpointConfigContainer : EndpointConfigContainer { bool closed; AtomicFile configFile; SvcFileManager svcFileManager; string webDirectoryName; string webDirectoryPath; string webServerName; RuntimeVersions runtimeVersion; bool modified = false; WasEndpointConfigContainer(string webServerName, string webDirectoryName, string webDirectoryPath, RuntimeVersions runtimeVersion) { if (string.IsNullOrEmpty(webDirectoryPath) || !Directory.Exists(webDirectoryPath)) { // We will not tolerate a webDir that does not exist throw Tool.CreateException(SR.GetString(SR.WebDirectoryPathNotFound, webDirectoryName, webDirectoryPath), null); } this.webDirectoryName = webDirectoryName; this.webDirectoryPath = webDirectoryPath; this.webServerName = webServerName; this.closed = false; this.configFile = new AtomicFile(this.webDirectoryPath + "\\web.config"); this.svcFileManager = new SvcFileManager(this.webDirectoryPath); this.runtimeVersion = runtimeVersion; } public override bool WasModified { get { return this.modified; } set { this.modified = value; } } public override void AbortChanges() { this.closed = true; this.configFile.Abort(); this.svcFileManager.Abort(); } internal AtomicFile ConfigFile { get { return this.configFile; } } public override void Add(IList<EndpointConfig> endpointConfigs) { ThrowIfClosed(); Configuration config = GetConfiguration(false); // not read only Debug.Assert(config != null, "config != null"); bool anyAdded = false; const string systemWebSection = "system.web"; foreach (EndpointConfig endpointConfig in endpointConfigs) { Guid appid; //verify that we someone did not delete and reinstall the app from underneath us if (this.svcFileManager.ResolveClsid(endpointConfig.Clsid, out appid)) { if (endpointConfig.Appid != appid) { ToolConsole.WriteError(SR.GetString(SR.AppIDsDontMatch), ""); return; } } } SystemWebSectionGroup swsg = (SystemWebSectionGroup)config.GetSectionGroup(systemWebSection); CompilationSection compilationSection = swsg.Compilation; if (string.IsNullOrEmpty(compilationSection.TargetFramework) && RuntimeVersions.V40 == this.runtimeVersion) { anyAdded = true; compilationSection.TargetFramework = ".NETFramework, Version=v4.0"; } foreach (EndpointConfig endpointConfig in endpointConfigs) { bool added = this.BaseAddEndpointConfig(config, endpointConfig); if (added) { this.svcFileManager.Add(endpointConfig.Appid, endpointConfig.Clsid); anyAdded = true; // the metadata exchange endpoint is not displayed as a regular endpoint if (endpointConfig.Iid == typeof(IMetadataExchange).GUID) { ToolConsole.WriteLine(SR.GetString(SR.MexEndpointAdded)); continue; } if (!Tool.Options.ShowGuids) { ToolConsole.WriteLine(SR.GetString(SR.InterfaceAdded, endpointConfig.ComponentProgID, endpointConfig.InterfaceName)); } else { ToolConsole.WriteLine(SR.GetString(SR.InterfaceAdded, endpointConfig.Clsid, endpointConfig.Iid)); } } else { // the metadata exchange endpoint is not displayed as a regular endpoint if (endpointConfig.Iid == typeof(IMetadataExchange).GUID) { if (!Tool.Options.ShowGuids) ToolConsole.WriteWarning(SR.GetString(SR.MexEndpointAlreadyExposed, endpointConfig.ComponentProgID)); else ToolConsole.WriteWarning(SR.GetString(SR.MexEndpointAlreadyExposed, endpointConfig.Clsid)); } else { if (!Tool.Options.ShowGuids) ToolConsole.WriteWarning(SR.GetString(SR.InterfaceAlreadyExposed, endpointConfig.ComponentProgID, endpointConfig.InterfaceName)); else ToolConsole.WriteWarning(SR.GetString(SR.InterfaceAlreadyExposed, endpointConfig.Clsid, endpointConfig.Iid)); } } } if (anyAdded) { WasModified = true; config.Save(); } } void EnsureWSProfileBindingAdded(Configuration config) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); if (!sg.Bindings.WSHttpBinding.Bindings.ContainsKey(this.DefaultBindingName)) { WSHttpBindingElement bindingConfig = new WSHttpBindingElement(this.DefaultBindingName); bindingConfig.ReliableSession.Enabled = true; sg.Bindings.WSHttpBinding.Bindings.Add(bindingConfig); } if (!sg.Bindings.WSHttpBinding.Bindings.ContainsKey(this.DefaultTransactionalBindingName)) { WSHttpBindingElement bindingConfig = new WSHttpBindingElement(this.DefaultTransactionalBindingName); bindingConfig.ReliableSession.Enabled = true; bindingConfig.TransactionFlow = true; sg.Bindings.WSHttpBinding.Bindings.Add(bindingConfig); } } protected override void AddBinding(Configuration config) { EnsureWSProfileBindingAdded(config); } const string defaultBindingType = "wsHttpBinding"; const string defaultTransactionBindingType = "wsHttpBinding"; const string defaultMexBindingType = "mexHttpBinding"; const string defaultBindingName = "comNonTransactionalBinding"; const string defaultTransactionalBindingName = "comTransactionalBinding"; public override string DefaultBindingType { get { return defaultBindingType; } } public override string DefaultBindingName { get { return defaultBindingName; } } public override string DefaultTransactionalBindingType { get { return defaultTransactionBindingType; } } public override string DefaultTransactionalBindingName { get { return defaultTransactionalBindingName; } } public override string DefaultMexBindingType { get { return defaultMexBindingType; } } public override string DefaultMexBindingName { get { return null; } } void EnsureBindingRemoved(Configuration config) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); if (sg.Bindings.WSHttpBinding.Bindings.ContainsKey(this.DefaultBindingName)) { WSHttpBindingElement element = sg.Bindings.WSHttpBinding.Bindings[this.DefaultBindingName]; sg.Bindings.WSHttpBinding.Bindings.Remove(element); } if (sg.Bindings.WSHttpBinding.Bindings.ContainsKey(this.DefaultTransactionalBindingName)) { WSHttpBindingElement element = sg.Bindings.WSHttpBinding.Bindings[this.DefaultTransactionalBindingName]; sg.Bindings.WSHttpBinding.Bindings.Remove(element); } } protected override void RemoveBinding(Configuration config) { EnsureBindingRemoved(config); } public override void CommitChanges() { this.configFile.Commit(); this.svcFileManager.Commit(); } public override string DefaultEndpointAddress(Guid appId, Guid clsid, Guid iid) { ComAdminAppInfo adminAppInfo = ComAdminWrapper.GetAppInfo(appId.ToString("B")); if (null == adminAppInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindAppInfo, appId.ToString("B")), null); } ComAdminClassInfo adminClassInfo = adminAppInfo.FindClass(clsid.ToString("B")); if (null == adminClassInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindClassInfo, clsid.ToString("B")), null); } ComAdminInterfaceInfo adminInterfaceInfo = adminClassInfo.FindInterface(iid.ToString("B")); if (null == adminInterfaceInfo) { throw Tool.CreateException(SR.GetString(SR.CannotFindInterfaceInfo, iid.ToString("B")), null); } string uri = Uri.EscapeUriString(adminInterfaceInfo.Name); if (Uri.IsWellFormedUriString(uri, UriKind.RelativeOrAbsolute)) return uri; return iid.ToString().ToUpperInvariant(); } public override List<string> GetBaseAddresses(EndpointConfig config) { return new List<string>(); } public override string BaseServiceAddress(Guid appId, Guid clsid, Guid iid) { return String.Empty; } public override string DefaultMexAddress(Guid appId, Guid clsid) { return EndpointConfig.MexEndpointSuffix; } public override Configuration GetConfiguration(bool readOnly) { string fileName = this.configFile.GetCurrentFileName(readOnly); if (string.IsNullOrEmpty(fileName)) { return null; } return GetConfigurationFromFile(fileName); } public override List<EndpointConfig> GetEndpointConfigs() { ThrowIfClosed(); Configuration config = GetConfiguration(true); // readonly if (config == null) { // null config means there is no config to read, return an empty list return new List<EndpointConfig>(); } Dictionary<string, List<EndpointConfig>> endpointConfigs = BaseGetEndpointsFromConfiguration(config); List<EndpointConfig> list = new List<EndpointConfig>(); // now, fix up the appid for all the endpoints foreach (List<EndpointConfig> endpoints in endpointConfigs.Values) { foreach (EndpointConfig endpoint in endpoints) { Guid appid; if (this.svcFileManager.ResolveClsid(endpoint.Clsid, out appid)) { endpoint.Appid = appid; list.Add(endpoint); } else { string appName = endpoint.ApplicationName; string componentID = endpoint.ComponentProgID; string interfaceName = endpoint.InterfaceName; if (!Tool.Options.ShowGuids && !string.IsNullOrEmpty(appName) && !string.IsNullOrEmpty(componentID) && !string.IsNullOrEmpty(interfaceName)) ToolConsole.WriteWarning(SR.GetString(SR.EndpointNotFoundInSvcFile, appName, componentID, interfaceName, endpoint.BindingName, endpoint.Address)); else ToolConsole.WriteWarning(SR.GetString(SR.EndpointNotFoundInSvcFile, endpoint.Appid.ToString("B"), endpoint.Clsid.ToString("B"), endpoint.Iid.ToString("B"), endpoint.BindingName, endpoint.Address)); } } } return list; } int NumEndpointsForClsid(Configuration config, Guid clsid, Guid appId) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); ServiceElementCollection serviceColl = sg.Services.Services; foreach (ServiceElement se in serviceColl) { string[] serviceParams = se.Name.Split(','); if (serviceParams.Length != 2) { continue; } Guid serviceAppId; Guid serviceClsid; try { serviceAppId = new Guid(serviceParams[0]); serviceClsid = new Guid(serviceParams[1]); } catch (FormatException) { // Only Guid serviceTypes are of interest to us - those are the ones our listener picks up continue; } if (serviceClsid == clsid && serviceAppId == appId) { return se.Endpoints.Count; } } return 0; } public override void PrepareChanges() { this.closed = true; bool workDone = this.configFile.HasBeenModified() && WasModified; this.configFile.Prepare(); if (workDone) { ToolConsole.WriteLine(SR.GetString((this.configFile.OriginalFileExists ? SR.FileUpdated : SR.FileCreated), configFile.OriginalFileName)); } this.svcFileManager.Prepare(); } public override void Remove(IList<EndpointConfig> endpointConfigs) { ThrowIfClosed(); Configuration config = GetConfiguration(false); // not read only Debug.Assert(config != null, "config != null"); bool anyRemoved = false; foreach (EndpointConfig endpointConfig in endpointConfigs) { bool removed = this.BaseRemoveEndpointConfig(config, endpointConfig); if (removed) { anyRemoved = true; if (NumEndpointsForClsid(config, endpointConfig.Clsid, endpointConfig.Appid) == 0) { // We can only Remove the SVC file when there are no more endpoints for the Clsid this.svcFileManager.Remove(endpointConfig.Appid, endpointConfig.Clsid); } if (!Tool.Options.ShowGuids) ToolConsole.WriteLine(SR.GetString(SR.InterfaceRemoved, endpointConfig.ComponentProgID, endpointConfig.InterfaceName)); else ToolConsole.WriteLine(SR.GetString(SR.InterfaceRemoved, endpointConfig.Clsid, endpointConfig.Iid)); } else if (!endpointConfig.IsMexEndpoint) { if (!Tool.Options.ShowGuids) ToolConsole.WriteWarning(SR.GetString(SR.InterfaceNotExposed, endpointConfig.ComponentProgID, endpointConfig.InterfaceName)); else ToolConsole.WriteWarning(SR.GetString(SR.InterfaceNotExposed, endpointConfig.Clsid, endpointConfig.Iid)); } } if (anyRemoved) { WasModified = true; config.Save(); } } void ThrowIfClosed() { if (this.closed) { Debug.Assert(false, "attempting operation after container is closed"); throw new InvalidOperationException(); } } public static string DefaultWebServer { get { return WasAdminWrapper.DefaultWebServer; } } public static List<WasEndpointConfigContainer> Get(string applicationIdOrName) { List<WasEndpointConfigContainer> containers = new List<WasEndpointConfigContainer>(); string[] webServers = WasAdminWrapper.GetWebServerNames(); if (webServers != null) { foreach (string webServer in webServers) { List<WasEndpointConfigContainer> cont = Get(webServer, applicationIdOrName); containers.AddRange(cont); } } return containers; } public static List<WasEndpointConfigContainer> Get(string webServer, string applicationIdOrName) { List<WasEndpointConfigContainer> containers = new List<WasEndpointConfigContainer>(); string[] webDirectories = WasAdminWrapper.GetWebDirectoryNames(webServer); if (webDirectories != null) { foreach (string webDirectory in webDirectories) { WasEndpointConfigContainer container = Get(webServer, webDirectory, applicationIdOrName); if (container != null) { containers.Add(container); } } } return containers; } public static WasEndpointConfigContainer Get(string webServer, string webDirectory, string applicationIdOrName) { string webDirectoryPath = null; RuntimeVersions runtimeVersion = RuntimeVersions.V40; if (!string.IsNullOrEmpty(applicationIdOrName)) { ComAdminAppInfo appInfo = ComAdminWrapper.GetAppInfo(applicationIdOrName); runtimeVersion = appInfo.RuntimeVersion; } if (WasAdminWrapper.GetWebDirectoryPath(webServer, webDirectory, out webDirectoryPath)) { try { return new WasEndpointConfigContainer(webServer, webDirectory, webDirectoryPath, runtimeVersion); } catch (Exception ex) { if (ex is NullReferenceException || ex is SEHException) { throw ex; } ToolConsole.WriteWarning(SR.GetString(SR.FailedToLoadConfigForWebDirectoryOnWebSite, webDirectory, webServer)); } return null; } else { return null; } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using Axiom.Core; using Axiom.Animating; namespace Axiom.SceneManagers.Multiverse { public delegate void ConfigChangeHandler(object sender, EventArgs e); public class OceanConfig : IAnimableObject { protected bool showOcean = true; protected float seaLevel = 10 * TerrainManager.oneMeter; protected float waveHeight = 1 * TerrainManager.oneMeter; protected ColorEx deepColor = new ColorEx(1, 0, 0, 0.1f); protected ColorEx shallowColor = new ColorEx(1, 0, 0.3f, 0.5f); protected float bumpScale = 0.5f; protected float textureScaleX = 0.015625f; protected float textureScaleZ = 0.0078125f; protected float bumpSpeedX = -0.005f; protected float bumpSpeedZ = 0; protected bool useParams = true; public event ConfigChangeHandler ConfigChange; public OceanConfig() { } protected void OnConfigChange() { ConfigChangeHandler handler = ConfigChange; if (handler != null) { handler(null, new EventArgs()); } } public bool UseParams { get { return useParams; } set { if (useParams != value) { useParams = value; OnConfigChange(); } } } public bool ShowOcean { get { return showOcean; } set { if (showOcean != value) { showOcean = value; OnConfigChange(); } } } public float SeaLevel { get { return seaLevel; } set { if (seaLevel != value) { seaLevel = value; OnConfigChange(); } } } public float WaveHeight { get { return waveHeight; } set { if (waveHeight != value) { waveHeight = value; OnConfigChange(); } } } public ColorEx DeepColor { get { return deepColor; } set { if (deepColor != value) { deepColor = value; OnConfigChange(); } } } public ColorEx ShallowColor { get { return shallowColor; } set { if (shallowColor != value) { shallowColor = value; OnConfigChange(); } } } public float BumpScale { get { return bumpScale; } set { if (bumpScale != value) { bumpScale = value; OnConfigChange(); } } } public float BumpSpeedX { get { return bumpSpeedX; } set { if (bumpSpeedX != value) { bumpSpeedX = value; OnConfigChange(); } } } public float BumpSpeedZ { get { return bumpSpeedZ; } set { if (bumpSpeedZ != value) { bumpSpeedZ = value; OnConfigChange(); } } } public float TextureScaleX { get { return textureScaleX; } set { if (textureScaleX != value) { textureScaleX = value; OnConfigChange(); } } } public float TextureScaleZ { get { return textureScaleZ; } set { if (textureScaleZ != value) { textureScaleZ = value; OnConfigChange(); } } } #region IAnimableObject Members public static string[] animableAttributes = { "SeaLevel", "WaveHeight", "DeepColor", "ShallowColor", "BumpScale", "BumpSpeedX", "BumpSpeedZ", "TextureScaleX", "TextureScaleZ" }; public AnimableValue CreateAnimableValue(string valueName) { switch (valueName) { case "SeaLevel": return new SeaLevelValue(this); case "WaveHeight": return new WaveHeightValue(this); case "DeepColor": return new DeepColorValue(this); case "ShallowColor": return new ShallowColorValue(this); case "BumpScale": return new BumpScaleValue(this); case "BumpSpeedX": return new BumpSpeedXValue(this); case "BumpSpeedZ": return new BumpSpeedZValue(this); case "TextureScaleX": return new TextureScaleXValue(this); case "TextureScaleZ": return new TextureScaleZValue(this); } throw new Exception(string.Format("Could not find animable attribute '{0}'", valueName)); } public string[] AnimableValueNames { get { return animableAttributes; } } protected class SeaLevelValue : AnimableValue { protected OceanConfig ocean; public SeaLevelValue(OceanConfig ocean) : base(AnimableType.Float) { this.ocean = ocean; SetAsBaseValue(0.0f); } public override void SetValue(float val) { ocean.SeaLevel = val; } public override void ApplyDeltaValue(float val) { SetValue(ocean.SeaLevel + val); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.SeaLevel); } } protected class WaveHeightValue : AnimableValue { protected OceanConfig ocean; public WaveHeightValue(OceanConfig ocean) : base(AnimableType.Float) { this.ocean = ocean; SetAsBaseValue(0.0f); } public override void SetValue(float val) { ocean.WaveHeight = val; } public override void ApplyDeltaValue(float val) { SetValue(ocean.WaveHeight + val); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.WaveHeight); } } protected class DeepColorValue : AnimableValue { protected OceanConfig ocean; public DeepColorValue(OceanConfig ocean) : base(AnimableType.ColorEx) { this.ocean = ocean; SetAsBaseValue(ColorEx.Black); } public override void SetValue(ColorEx val) { ocean.DeepColor = val; } public override void ApplyDeltaValue(ColorEx val) { SetValue(new ColorEx(ocean.DeepColor.r + val.r, ocean.DeepColor.g + val.g, ocean.DeepColor.b + val.b)); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.DeepColor); } } protected class ShallowColorValue : AnimableValue { protected OceanConfig ocean; public ShallowColorValue(OceanConfig ocean) : base(AnimableType.ColorEx) { this.ocean = ocean; SetAsBaseValue(ColorEx.Black); } public override void SetValue(ColorEx val) { ocean.ShallowColor = val; } public override void ApplyDeltaValue(ColorEx val) { SetValue(new ColorEx(ocean.ShallowColor.r + val.r, ocean.ShallowColor.g + val.g, ocean.ShallowColor.b + val.b)); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.ShallowColor); } } protected class BumpScaleValue : AnimableValue { protected OceanConfig ocean; public BumpScaleValue(OceanConfig ocean) : base(AnimableType.Float) { this.ocean = ocean; SetAsBaseValue(0.0f); } public override void SetValue(float val) { ocean.BumpScale = val; } public override void ApplyDeltaValue(float val) { SetValue(ocean.BumpScale + val); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.BumpScale); } } protected class BumpSpeedXValue : AnimableValue { protected OceanConfig ocean; public BumpSpeedXValue(OceanConfig ocean) : base(AnimableType.Float) { this.ocean = ocean; SetAsBaseValue(0.0f); } public override void SetValue(float val) { ocean.BumpSpeedX = val; } public override void ApplyDeltaValue(float val) { SetValue(ocean.BumpSpeedX + val); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.BumpSpeedX); } } protected class BumpSpeedZValue : AnimableValue { protected OceanConfig ocean; public BumpSpeedZValue(OceanConfig ocean) : base(AnimableType.Float) { this.ocean = ocean; SetAsBaseValue(0.0f); } public override void SetValue(float val) { ocean.BumpSpeedZ = val; } public override void ApplyDeltaValue(float val) { SetValue(ocean.BumpSpeedZ + val); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.BumpSpeedZ); } } protected class TextureScaleXValue : AnimableValue { protected OceanConfig ocean; public TextureScaleXValue(OceanConfig ocean) : base(AnimableType.Float) { this.ocean = ocean; SetAsBaseValue(0.0f); } public override void SetValue(float val) { ocean.TextureScaleX = val; } public override void ApplyDeltaValue(float val) { SetValue(ocean.TextureScaleX + val); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.TextureScaleX); } } protected class TextureScaleZValue : AnimableValue { protected OceanConfig ocean; public TextureScaleZValue(OceanConfig ocean) : base(AnimableType.Float) { this.ocean = ocean; SetAsBaseValue(0.0f); } public override void SetValue(float val) { ocean.TextureScaleZ = val; } public override void ApplyDeltaValue(float val) { SetValue(ocean.TextureScaleZ + val); } public override void SetCurrentStateAsBaseValue() { SetAsBaseValue(ocean.TextureScaleZ); } } #endregion } }
// *********************************************************************** // Copyright (c) 2006 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** #if !SILVERLIGHT && !PORTABLE using System.IO; using System.ComponentModel; using NUnit.Framework.Constraints; namespace NUnit.Framework { /// <summary> /// Asserts on Files /// </summary> public static class FileAssert { #region Equals and ReferenceEquals /// <summary> /// The Equals method throws an AssertionException. This is done /// to make sure there is no mistake by calling this function. /// </summary> /// <param name="a"></param> /// <param name="b"></param> [EditorBrowsable(EditorBrowsableState.Never)] public static new bool Equals(object a, object b) { throw new AssertionException("Assert.Equals should not be used for Assertions"); } /// <summary> /// override the default ReferenceEquals to throw an AssertionException. This /// implementation makes sure there is no mistake in calling this function /// as part of Assert. /// </summary> /// <param name="a"></param> /// <param name="b"></param> public static new void ReferenceEquals(object a, object b) { throw new AssertionException("Assert.ReferenceEquals should not be used for Assertions"); } #endregion #region AreEqual #region Streams /// <summary> /// Verifies that two Streams are equal. Two Streams are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreEqual(Stream expected, Stream actual, string message, params object[] args) { Assert.That(actual, Is.EqualTo(expected), message, args); } /// <summary> /// Verifies that two Streams are equal. Two Streams are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> static public void AreEqual(Stream expected, Stream actual) { AreEqual(expected, actual, string.Empty, null); } #endregion #region FileInfo /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreEqual(FileInfo expected, FileInfo actual, string message, params object[] args) { using (FileStream exStream = expected.OpenRead()) using (FileStream acStream = actual.OpenRead()) { AreEqual(exStream, acStream, message, args); } } /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> static public void AreEqual(FileInfo expected, FileInfo actual) { AreEqual(expected, actual, string.Empty, null); } #endregion #region String /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreEqual(string expected, string actual, string message, params object[] args) { using (FileStream exStream = File.OpenRead(expected)) using (FileStream acStream = File.OpenRead(actual)) { AreEqual(exStream, acStream, message, args); } } /// <summary> /// Verifies that two files are equal. Two files are considered /// equal if both are null, or if both have the same value byte for byte. /// If they are not equal an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> static public void AreEqual(string expected, string actual) { AreEqual(expected, actual, string.Empty, null); } #endregion #endregion #region AreNotEqual #region Streams /// <summary> /// Asserts that two Streams are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> /// <param name="message">The message to be displayed when the two Stream are the same.</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreNotEqual(Stream expected, Stream actual, string message, params object[] args) { Assert.That(actual, Is.Not.EqualTo(expected), message, args); } /// <summary> /// Asserts that two Streams are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The expected Stream</param> /// <param name="actual">The actual Stream</param> static public void AreNotEqual(Stream expected, Stream actual) { AreNotEqual(expected, actual, string.Empty, null); } #endregion #region FileInfo /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreNotEqual(FileInfo expected, FileInfo actual, string message, params object[] args) { using (FileStream exStream = expected.OpenRead()) using (FileStream acStream = actual.OpenRead()) { AreNotEqual(exStream, acStream, message, args); } } /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">A file containing the value that is expected</param> /// <param name="actual">A file containing the actual value</param> static public void AreNotEqual(FileInfo expected, FileInfo actual) { AreNotEqual(expected, actual, string.Empty, null); } #endregion #region String /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void AreNotEqual(string expected, string actual, string message, params object[] args) { using (FileStream exStream = File.OpenRead(expected)) using (FileStream acStream = File.OpenRead(actual)) { AreNotEqual(exStream, acStream, message, args); } } /// <summary> /// Asserts that two files are not equal. If they are equal /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="expected">The path to a file containing the value that is expected</param> /// <param name="actual">The path to a file containing the actual value</param> static public void AreNotEqual(string expected, string actual) { AreNotEqual(expected, actual, string.Empty, null); } #endregion #endregion #region Exists #region FileInfo /// <summary> /// Asserts that the file exists. If it does not exist /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="actual">A file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void Exists(FileInfo actual, string message, params object[] args) { Assert.That(actual, new FileOrDirectoryExistsConstraint().IgnoreDirectories, message, args); } /// <summary> /// Asserts that the file exists. If it does not exist /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="actual">A file containing the actual value</param> static public void Exists(FileInfo actual) { Exists(actual, string.Empty, null); } #endregion #region String /// <summary> /// Asserts that the file exists. If it does not exist /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="actual">The path to a file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void Exists(string actual, string message, params object[] args) { Assert.That(actual, new FileOrDirectoryExistsConstraint().IgnoreDirectories, message, args); } /// <summary> /// Asserts that the file exists. If it does not exist /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="actual">The path to a file containing the actual value</param> static public void Exists(string actual) { Exists(actual, string.Empty, null); } #endregion #endregion #region DoesNotExist #region FileInfo /// <summary> /// Asserts that the file does not exist. If it does exist /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="actual">A file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void DoesNotExist(FileInfo actual, string message, params object[] args) { Assert.That(actual, new NotConstraint(new FileOrDirectoryExistsConstraint().IgnoreDirectories), message, args); } /// <summary> /// Asserts that the file does not exist. If it does exist /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="actual">A file containing the actual value</param> static public void DoesNotExist(FileInfo actual) { DoesNotExist(actual, string.Empty, null); } #endregion #region String /// <summary> /// Asserts that the file does not exist. If it does exist /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="actual">The path to a file containing the actual value</param> /// <param name="message">The message to display if Streams are not equal</param> /// <param name="args">Arguments to be used in formatting the message</param> static public void DoesNotExist(string actual, string message, params object[] args) { Assert.That(actual, new NotConstraint(new FileOrDirectoryExistsConstraint().IgnoreDirectories), message, args); } /// <summary> /// Asserts that the file does not exist. If it does exist /// an <see cref="AssertionException"/> is thrown. /// </summary> /// <param name="actual">The path to a file containing the actual value</param> static public void DoesNotExist(string actual) { DoesNotExist(actual, string.Empty, null); } #endregion #endregion } } #endif
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Reflection; using Windows.ApplicationModel.Resources; namespace Prism.Windows.Validation { /// <summary> /// The BindableValidator class run validation rules of an entity, and stores a collection of errors of the properties that did not pass validation. /// The validation is run on each property change or whenever the ValidateProperties method is called. /// It also provides an indexer property, that uses the property names as keys and return the error list for the specified property. /// </summary> public class BindableValidator : INotifyPropertyChanged { private readonly INotifyPropertyChanged _entityToValidate; private IDictionary<string, ReadOnlyCollection<string>> _errors = new Dictionary<string, ReadOnlyCollection<string>>(); /// <summary> /// Represents a collection of empty error values. /// </summary> public static readonly ReadOnlyCollection<string> EmptyErrorsCollection = new ReadOnlyCollection<string>(new List<string>()); private Func<string, string, string> _getResourceDelegate; /// <summary> /// Initializes a new instance of the BindableValidator class with the entity to validate. /// </summary> /// <param name="entityToValidate">The entity to validate</param> /// <param name="getResourceDelegate">A delegate that returns a string resource given a resource map Id and resource Id</param> /// <exception cref="ArgumentNullException">When <paramref name="entityToValidate"/> is <see langword="null" />.</exception> public BindableValidator(INotifyPropertyChanged entityToValidate, Func<string, string, string> getResourceDelegate) : this(entityToValidate) { _getResourceDelegate = getResourceDelegate; } /// <summary> /// Initializes a new instance of the BindableValidator class with the entity to validate. /// </summary> /// <param name="entityToValidate">The entity to validate</param> /// <exception cref="ArgumentNullException">When <paramref name="entityToValidate"/> is <see langword="null" />.</exception> public BindableValidator(INotifyPropertyChanged entityToValidate) { if (entityToValidate == null) { throw new ArgumentNullException(nameof(entityToValidate)); } _entityToValidate = entityToValidate; IsValidationEnabled = true; _getResourceDelegate = (mapId, key) => { var resourceLoader = ResourceLoader.GetForCurrentView(mapId); return resourceLoader.GetString(key); }; } /// <summary> /// Multicast event for errors change notifications. /// </summary> public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; /// <summary> /// Multicast event for property change notifications. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Returns the errors of the property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <returns>The errors of the property, if it has errors. Otherwise, the BindableValidator.EmptyErrorsCollection.</returns> public ReadOnlyCollection<string> this[string propertyName] { get { return _errors.ContainsKey(propertyName) ? _errors[propertyName] : EmptyErrorsCollection; } } /// <summary> /// Gets the list of errors per property. /// </summary> /// <value> /// The dictionary of property names and errors collection pairs. /// </value> public IDictionary<string, ReadOnlyCollection<string>> Errors { get { return _errors; } } /// <summary> /// Returns true if the Validation functionality is enabled. Otherwise, false. /// </summary> public bool IsValidationEnabled { get; set; } /// <summary> /// Returns a new ReadOnlyDictionary containing all the errors of the Entity, separated by property. /// </summary> /// <returns> /// A ReadOnlyDictionary that contains a KeyValuePair for each property with errors. /// Each KeyValuePair has a property name as the key, and the value is the collection of errors of that property. /// </returns> public ReadOnlyDictionary<string, ReadOnlyCollection<string>> GetAllErrors() { return new ReadOnlyDictionary<string, ReadOnlyCollection<string>>(_errors); } /// <summary> /// Updates the errors collection of the entity, notifying if the errors collection has changed. /// </summary> /// <param name="entityErrors">The collection of errors for the entity.</param> public void SetAllErrors(IDictionary<string, ReadOnlyCollection<string>> entityErrors) { if (entityErrors == null) { throw new ArgumentNullException(nameof(entityErrors)); } _errors.Clear(); foreach (var item in entityErrors) { SetPropertyErrors(item.Key, item.Value); } OnPropertyChanged("Item[]"); OnErrorsChanged(string.Empty); } /// <summary> /// Validates the property, based on the rules set in the property ValidationAttributes attributes. /// It updates the errors collection with the new validation results (notifying if necessary). /// </summary> /// <param name="propertyName">The name of the property to validate.</param> /// <returns>True if the property is valid. Otherwise, false.</returns> /// <exception cref="ArgumentNullException">When <paramref name="propertyName"/> is <see langword="null" /> or an empty string value.</exception> /// <exception cref="ArgumentException">When the <paramref name="propertyName"/> parameter does not match any property name.</exception> public bool ValidateProperty(string propertyName) { if (string.IsNullOrEmpty(propertyName)) { throw new ArgumentNullException(nameof(propertyName)); } var propertyInfo = _entityToValidate.GetType().GetRuntimeProperty(propertyName); if (propertyInfo == null) { var errorString = _getResourceDelegate(Constants.InfrastructureResourceMapId, "InvalidPropertyNameException"); throw new ArgumentException(errorString, propertyName); } var propertyErrors = new List<string>(); bool isValid = TryValidateProperty(propertyInfo, propertyErrors); bool errorsChanged = SetPropertyErrors(propertyInfo.Name, propertyErrors); if (errorsChanged) { OnErrorsChanged(propertyName); OnPropertyChanged(string.Format(CultureInfo.CurrentCulture, "Item[{0}]", propertyName)); } return isValid; } /// <summary> /// Validates all the properties decorated with the ValidationAttribute attribute. /// It updates each property errors collection with the new validation results (notifying if necessary). /// </summary> /// <returns>True if the property is valid. Otherwise, false.</returns> public bool ValidateProperties() { var propertiesWithChangedErrors = new List<string>(); // Get all the properties decorated with the ValidationAttribute attribute. var propertiesToValidate = _entityToValidate.GetType() .GetRuntimeProperties() .Where(c => c.GetCustomAttributes(typeof(ValidationAttribute)).Any()); foreach (PropertyInfo propertyInfo in propertiesToValidate) { var propertyErrors = new List<string>(); TryValidateProperty(propertyInfo, propertyErrors); // If the errors have changed, save the property name to notify the update at the end of this method. bool errorsChanged = SetPropertyErrors(propertyInfo.Name, propertyErrors); if (errorsChanged && !propertiesWithChangedErrors.Contains(propertyInfo.Name)) { propertiesWithChangedErrors.Add(propertyInfo.Name); } } // Notify each property whose set of errors has changed since the last validation. foreach (string propertyName in propertiesWithChangedErrors) { OnErrorsChanged(propertyName); OnPropertyChanged(string.Format(CultureInfo.CurrentCulture, "Item[{0}]", propertyName)); } return _errors.Values.Count == 0; } /// <summary> /// Performs a validation of a property, adding the results in the propertyErrors list. /// </summary> /// <param name="propertyInfo">The PropertyInfo of the property to validate</param> /// <param name="propertyErrors">A list containing the current error messages of the property.</param> /// <returns>True if the property is valid. Otherwise, false.</returns> private bool TryValidateProperty(PropertyInfo propertyInfo, List<string> propertyErrors) { var results = new List<ValidationResult>(); var context = new ValidationContext(_entityToValidate) { MemberName = propertyInfo.Name }; var propertyValue = propertyInfo.GetValue(_entityToValidate); // Validate the property bool isValid = Validator.TryValidateProperty(propertyValue, context, results); if (results.Any()) { propertyErrors.AddRange(results.Select(c => c.ErrorMessage)); } return isValid; } /// <summary> /// Updates the errors collection of the property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="propertyNewErrors">The new collection of property errors.</param> /// <returns>True if the property errors have changed. Otherwise, false.</returns> private bool SetPropertyErrors(string propertyName, IList<string> propertyNewErrors) { bool errorsChanged = false; // If the property does not have errors, simply add them if (!_errors.ContainsKey(propertyName)) { if (propertyNewErrors.Count > 0) { _errors.Add(propertyName, new ReadOnlyCollection<string>(propertyNewErrors)); errorsChanged = true; } } else { // If the property has errors, check if the number of errors are different. // If the number of errors is the same, check if there are new ones if (propertyNewErrors.Count != _errors[propertyName].Count || _errors[propertyName].Intersect(propertyNewErrors).Count() != propertyNewErrors.Count) { if (propertyNewErrors.Count > 0) { _errors[propertyName] = new ReadOnlyCollection<string>(propertyNewErrors); } else { _errors.Remove(propertyName); } errorsChanged = true; } } return errorsChanged; } /// <summary> /// Notifies listeners that a property value has changed. /// </summary> /// <param name="propertyName">Name of the property used to notify listeners.</param> private void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Notifies listeners that the errors of a property have changed. /// </summary> /// <param name="propertyName">Name of the property used to notify listeners.</param> private void OnErrorsChanged(string propertyName) { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } } }
// 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 Internal.NativeCrypto; namespace System.Security.Cryptography { #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS internal static partial class ECDsaImplementation { #endif public sealed partial class ECDsaCng : ECDsa { /// <summary> /// ImportParameters will replace the existing key that ECDsaCng is working with by creating a /// new CngKey. If the parameters contains only Q, then only a public key will be imported. /// If the parameters also contains D, then a full key pair will be imported. /// The parameters Curve value specifies the type of the curve to import. /// </summary> /// <exception cref="CryptographicException"> /// if <paramref name="parameters" /> does not contain valid values. /// </exception> /// <exception cref="NotSupportedException"> /// if <paramref name="parameters" /> references a curve that cannot be imported. /// </exception> /// <exception cref="PlatformNotSupportedException"> /// if <paramref name="parameters" /> references a curve that is not supported by this platform. /// </exception> public override void ImportParameters(ECParameters parameters) { parameters.Validate(); ThrowIfDisposed(); ECCurve curve = parameters.Curve; bool includePrivateParameters = (parameters.D != null); if (curve.IsPrime) { byte[] ecExplicitBlob = ECCng.GetPrimeCurveBlob(ref parameters, ecdh: false); ImportFullKeyBlob(ecExplicitBlob, includePrivateParameters); } else if (curve.IsNamed) { // FriendlyName is required; an attempt was already made to default it in ECCurve if (string.IsNullOrEmpty(curve.Oid.FriendlyName)) throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_InvalidCurveOid, curve.Oid.Value.ToString())); byte[] ecNamedCurveBlob = ECCng.GetNamedCurveBlob(ref parameters, ecdh: false); ImportKeyBlob(ecNamedCurveBlob, curve.Oid.FriendlyName, includePrivateParameters); } else { throw new PlatformNotSupportedException(SR.Format(SR.Cryptography_CurveNotSupported, curve.CurveType.ToString())); } } /// <summary> /// Exports the key and explicit curve parameters used by the ECC object into an <see cref="ECParameters"/> object. /// </summary> /// <exception cref="CryptographicException"> /// if there was an issue obtaining the curve values. /// </exception> /// <exception cref="PlatformNotSupportedException"> /// if explicit export is not supported by this platform. Windows 10 or higher is required. /// </exception> /// <returns>The key and explicit curve parameters used by the ECC object.</returns> public override ECParameters ExportExplicitParameters(bool includePrivateParameters) { byte[] blob = ExportFullKeyBlob(includePrivateParameters); ECParameters ecparams = new ECParameters(); ECCng.ExportPrimeCurveParameters(ref ecparams, blob, includePrivateParameters); return ecparams; } /// <summary> /// Exports the key used by the ECC object into an <see cref="ECParameters"/> object. /// If the curve has a name, the Curve property will contain named curve parameters otherwise it will contain explicit parameters. /// </summary> /// <exception cref="CryptographicException"> /// if there was an issue obtaining the curve values. /// </exception> /// <returns>The key and named curve parameters used by the ECC object.</returns> public override ECParameters ExportParameters(bool includePrivateParameters) { ECParameters ecparams = new ECParameters(); string curveName = GetCurveName(out string oidValue); if (string.IsNullOrEmpty(curveName)) { byte[] fullKeyBlob = ExportFullKeyBlob(includePrivateParameters); ECCng.ExportPrimeCurveParameters(ref ecparams, fullKeyBlob, includePrivateParameters); } else { byte[] keyBlob = ExportKeyBlob(includePrivateParameters); ECCng.ExportNamedCurveParameters(ref ecparams, keyBlob, includePrivateParameters); ecparams.Curve = ECCurve.CreateFromOid(new Oid(oidValue, curveName)); } return ecparams; } public override void ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); CngPkcs8.Pkcs8Response response = CngPkcs8.ImportPkcs8PrivateKey(source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey( passwordBytes, source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } public override void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { ThrowIfDisposed(); CngPkcs8.Pkcs8Response response = CngPkcs8.ImportEncryptedPkcs8PrivateKey( password, source, out int localRead); ProcessPkcs8Response(response); bytesRead = localRead; } private void ProcessPkcs8Response(CngPkcs8.Pkcs8Response response) { // Wrong algorithm? switch (response.GetAlgorithmGroup()) { // CNG ECDH and ECDSA keys can both do ECDSA. case BCryptNative.AlgorithmName.ECDsa: case BCryptNative.AlgorithmName.ECDH: AcceptImport(response); return; } response.FreeKey(); throw new CryptographicException(SR.Cryptography_NotValidPublicOrPrivateKey); } public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, passwordBytes, pbeParameters); } public override byte[] ExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters) { if (pbeParameters == null) { throw new ArgumentNullException(nameof(pbeParameters)); } PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return ExportEncryptedPkcs8(password, pbeParameters.IterationCount); } return CngPkcs8.ExportEncryptedPkcs8PrivateKey( this, password, pbeParameters); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); return CngPkcs8.TryExportEncryptedPkcs8PrivateKey( this, passwordBytes, pbeParameters, destination, out bytesWritten); } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); if (CngPkcs8.IsPlatformScheme(pbeParameters)) { return TryExportEncryptedPkcs8( password, pbeParameters.IterationCount, destination, out bytesWritten); } return CngPkcs8.TryExportEncryptedPkcs8PrivateKey( this, password, pbeParameters, destination, out bytesWritten); } #if INTERNAL_ASYMMETRIC_IMPLEMENTATIONS } #endif } }
/* Copyright 2019 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.Data; using System.Drawing; using System.Runtime.InteropServices; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; namespace MyDynamicLayer { /// <summary> /// Summary description for AddMyDynamicLayerCmd. /// </summary> [Guid("0ddfd2b0-45ba-416a-93c8-c7db41de30e4")] [ClassInterface(ClassInterfaceType.None)] [ComVisible(true)] [ProgId("MyDynamicLayer.AddMyDynamicLayerCmd")] public sealed class AddMyDynamicLayerCmd : BaseCommand { #region COM Registration Function(s) [ComRegisterFunction()] [ComVisible(false)] static void RegisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryRegistration(registerType); // // TODO: Add any COM registration code here // } [ComUnregisterFunction()] [ComVisible(false)] static void UnregisterFunction(Type registerType) { // Required for ArcGIS Component Category Registrar support ArcGISCategoryUnregistration(registerType); // // TODO: Add any COM unregistration code here // } #region ArcGIS Component Category Registrar generated code /// <summary> /// Required method for ArcGIS Component Category registration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryRegistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Register(regKey); } /// <summary> /// Required method for ArcGIS Component Category unregistration - /// Do not modify the contents of this method with the code editor. /// </summary> private static void ArcGISCategoryUnregistration(Type registerType) { string regKey = string.Format("HKEY_CLASSES_ROOT\\CLSID\\{{{0}}}", registerType.GUID); ControlsCommands.Unregister(regKey); } #endregion #endregion private IHookHelper m_hookHelper = null; private MyDynamicLayerClass m_dynamicLayer = null; private bool m_bIsConnected = false; private bool m_bOnce = true; public AddMyDynamicLayerCmd() { base.m_category = ".NET Samples"; base.m_caption = "Add Dynamic Layer"; base.m_message = "Add Dynamic Layer"; base.m_toolTip = "Add Dynamic Layer"; base.m_name = "MyDynamicLayer_AddMyDynamicLayerCmd"; try { string bitmapResourceName = GetType().Name + ".bmp"; base.m_bitmap = new Bitmap(GetType(), bitmapResourceName); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message, "Invalid Bitmap"); } } #region Overriden Class Methods /// <summary> /// Occurs when this command is created /// </summary> /// <param name="hook">Instance of the application</param> public override void OnCreate(object hook) { if (hook == null) return; if (m_hookHelper == null) m_hookHelper = new HookHelperClass(); m_hookHelper.Hook = hook; } /// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { //make sure to switch into dynamic mode IDynamicMap dynamicMap = m_hookHelper.FocusMap as IDynamicMap; //make sure that the current Map supports the DynamicDisplay if (null == dynamicMap) return; if (!m_bIsConnected) { //make sure to switch into dynamic mode if (!dynamicMap.DynamicMapEnabled) dynamicMap.DynamicMapEnabled = true; //do some initializations... if (m_bOnce) { //initialize the dynamic layer m_dynamicLayer = new MyDynamicLayerClass(); m_dynamicLayer.Name = "Dynamic Layer"; m_bOnce = false; } //make sure that the layer did not get added to the map bool bLayerHasBeenAdded = false; if (m_hookHelper.FocusMap.LayerCount > 0) { IEnumLayer layers = m_hookHelper.FocusMap.get_Layers(null, false); layers.Reset(); ILayer layer = layers.Next(); while (layer != null) { if (layer is MyDynamicLayerClass) { bLayerHasBeenAdded = true; break; } layer = layers.Next(); } } if (!bLayerHasBeenAdded) { //add the dynamic layer to the map m_hookHelper.FocusMap.AddLayer(m_dynamicLayer); } //connect to the synthetic data source m_dynamicLayer.Connect(); } else { //disconnect to the synthetic data source m_dynamicLayer.Disconnect(); //delete the layer from the map m_hookHelper.FocusMap.DeleteLayer(m_dynamicLayer); //disable the dynamic display if (dynamicMap.DynamicMapEnabled) dynamicMap.DynamicMapEnabled = false; } //set the connected flag m_bIsConnected = !m_bIsConnected; } /// <summary> /// set the state of the button of the command /// </summary> public override bool Checked { get { return m_bIsConnected; } } #endregion } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using ALinq.SqlClient; namespace ALinq.EffiProz { class EfzDataType : SqlDataType<DbType>, IProviderType { public EfzDataType(Dictionary<TypeCode, DbType> typeMapping) : base(typeMapping) { } public EfzDataType(Dictionary<TypeCode, DbType> typeMapping, DbType dbType) : base(typeMapping, dbType) { if(dbType == DbType.UInt64) { Precision = 29; Scale = 4; } else if(dbType == DbType.Decimal) { Precision = DEFAULT_DECIMAL_PRECISION; Scale = DEFAULT_DECIMAL_SCALE; } } public EfzDataType(Dictionary<TypeCode, DbType> typeMapping, DbType dbType, int precision, int scale) : base(typeMapping, dbType, precision, scale) { } public EfzDataType(Dictionary<TypeCode, DbType> typeMapping, DbType dbType, int size) : base(typeMapping, dbType, size) { } public override string ToQueryString(QueryFormatOptions formatFlags) { switch(this.SqlDbType) { case DbType.Int32: case DbType.Int16: return "INT"; case DbType.Boolean: return "BIT"; case DbType.Byte: case DbType.SByte: return "TINYINT"; case DbType.Int64: return "BIGINT"; case DbType.Single: return "FLOAT"; case DbType.Double: return "DOUBLE"; } return base.ToQueryString(formatFlags); } protected override int GetTypeCoercionPrecedence(DbType type) { switch ((DbType)type) { case DbType.Binary: return 0; case DbType.AnsiString: return 1; case DbType.AnsiStringFixedLength: return 2; case DbType.String: return 3; case DbType.StringFixedLength: return 4; case DbType.Guid: return 5; case DbType.Boolean: return 6; case DbType.SByte: return 7; case DbType.Byte: return 8; case DbType.Int16: return 9; case DbType.Int32: return 10; case DbType.UInt16: return 11; case DbType.Int64: return 12; case DbType.UInt32: return 13; case DbType.UInt64: return 14; case DbType.Currency: return 15; case DbType.Decimal: return 16; case DbType.Single: return 17; case DbType.Double: return 18; case DbType.VarNumeric: return 19; case DbType.Date: return 20; case DbType.Time: return 21; case DbType.DateTimeOffset: return 22; case DbType.DateTime: return 23; case DbType.DateTime2: return 24; case DbType.Xml: return 25; case DbType.Object: return 26; } //FbDbType.Array throw SqlClient.Error.UnexpectedTypeCode(type); } private bool IsTypeKnownByProvider { get { return (!IsApplicationType && !IsRuntimeOnlyType); } } public override Type GetClosestRuntimeType() { if (RuntimeOnlyType != null) { return RuntimeOnlyType; } //if (this == EfzDataTypeProvider.Instance.GuidType) // return typeof(Guid); switch ((DbType)SqlDbType) { case DbType.AnsiString: case DbType.AnsiStringFixedLength: case DbType.String: case DbType.StringFixedLength: case DbType.Xml: return typeof(string); case DbType.Binary: return typeof(Byte[]); case DbType.Boolean: return typeof(bool); case DbType.Byte: return typeof(byte); case DbType.Currency: case DbType.Decimal: case DbType.VarNumeric: return typeof(decimal); case DbType.Date: case DbType.DateTime: case DbType.DateTime2: case DbType.DateTimeOffset: case DbType.Time: return typeof(DateTime); case DbType.Double: return typeof(double); case DbType.Guid: return typeof(Guid); case DbType.Int16: return typeof(short); case DbType.Int32: return typeof(int); case DbType.Int64: return typeof(long); case DbType.Object: return typeof(object); case DbType.SByte: return typeof(sbyte); case DbType.Single: return typeof(Single); case DbType.UInt16: return typeof(UInt16); case DbType.UInt32: return typeof(UInt32); case DbType.UInt64: return typeof(UInt64); } return typeof(object); } internal override DBTypeCategory Category { get { switch (SqlDbType) { case DbType.Binary: return DBTypeCategory.Binary; case DbType.AnsiString: case DbType.AnsiStringFixedLength: case DbType.String: case DbType.StringFixedLength: return DBTypeCategory.Text; case DbType.Date: case DbType.DateTime: case DbType.DateTime2: case DbType.DateTimeOffset: return DBTypeCategory.DateTime; //return TypeCategory.Image; case DbType.Boolean: case DbType.Byte: case DbType.Currency: case DbType.Decimal: case DbType.Double: case DbType.Int16: case DbType.Int32: case DbType.Int64: case DbType.SByte: case DbType.Single: case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: case DbType.VarNumeric: return DBTypeCategory.Numeric; //return TypeCategory.Text; //return TypeCategory.Udt; case DbType.Guid: return DBTypeCategory.Binary; //return TypeCategory.Variant; case DbType.Xml: return DBTypeCategory.Text; } throw SqlClient.Error.UnexpectedTypeCode(this); } } public override bool HasPrecisionAndScale { get { switch (SqlDbType) { case DbType.Currency: case DbType.Decimal: //case DbType.Double: return true; } return false; } } public override bool IsFixedSize { get { switch (SqlDbType) { case DbType.AnsiString: case DbType.Binary: case DbType.String: case DbType.VarNumeric: case DbType.Xml: return false; } return true; } } public override bool IsLargeType { get { switch ((DbType)SqlDbType) { case DbType.Binary: case DbType.Object: case DbType.Xml: return true; case DbType.String: case DbType.AnsiString: if (Size <= 0) return true; break; } return false; } } public override bool IsNumeric { get { switch ((DbType)SqlDbType) { case DbType.Boolean: case DbType.Byte: case DbType.Currency: case DbType.Decimal: case DbType.Double: case DbType.Int16: case DbType.Int32: case DbType.Int64: case DbType.SByte: case DbType.Single: case DbType.UInt16: case DbType.UInt32: case DbType.UInt64: return true; } return false; } } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors using System; using System.Collections.Generic; using System.Linq; using Generator.Constants; using Generator.Constants.Rust; using Generator.Enums; using Generator.Enums.InstructionInfo; using Generator.Enums.Rust; using Generator.IO; using Generator.Tables; namespace Generator.InstructionInfo.Rust { [Generator(TargetLanguage.Rust)] sealed class RustInstrInfoGenerator : InstrInfoGenerator { readonly IdentifierConverter idConverter; readonly RustEnumsGenerator enumGenerator; readonly RustConstantsGenerator constantsGenerator; readonly GeneratorContext generatorContext; readonly EnumType opAccessType; readonly EnumType registerType; readonly EnumType codeSizeType; public RustInstrInfoGenerator(GeneratorContext generatorContext) : base(generatorContext.Types) { idConverter = RustIdentifierConverter.Create(); enumGenerator = new RustEnumsGenerator(generatorContext); constantsGenerator = new RustConstantsGenerator(generatorContext); this.generatorContext = generatorContext; opAccessType = generatorContext.Types[TypeIds.OpAccess]; registerType = generatorContext.Types[TypeIds.Register]; codeSizeType = generatorContext.Types[TypeIds.CodeSize]; } protected override void Generate(EnumType enumType) => enumGenerator.Generate(enumType); protected override void Generate(ConstantsType constantsType) => constantsGenerator.Generate(constantsType); protected override void Generate((InstructionDef def, uint dword1, uint dword2)[] infos) { var filename = generatorContext.Types.Dirs.GetRustFilename("info", "info_table.rs"); using (var writer = new FileWriter(TargetLanguage.Rust, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.WriteLine($"pub(crate) static TABLE: [u32; {infos.Length * 2}] = ["); using (writer.Indent()) { foreach (var info in infos) writer.WriteLine($"{NumberFormatter.FormatHexUInt32WithSep(info.dword1)}, {NumberFormatter.FormatHexUInt32WithSep(info.dword2)},// {info.def.Code.Name(idConverter)}"); } writer.WriteLine("];"); } } protected override void Generate(EnumValue[] enumValues, RflagsBits[] read, RflagsBits[] undefined, RflagsBits[] written, RflagsBits[] cleared, RflagsBits[] set, RflagsBits[] modified) { var filename = generatorContext.Types.Dirs.GetRustFilename("info", "rflags_table.rs"); using (var writer = new FileWriter(TargetLanguage.Rust, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); var infos = new (RflagsBits[] rflags, string name)[] { (read, "read"), (undefined, "undefined"), (written, "written"), (cleared, "cleared"), (set, "set"), (modified, "modified"), }; foreach (var info in infos) { var rflags = info.rflags; if (rflags.Length != infos[0].rflags.Length) throw new InvalidOperationException(); var name = idConverter.Static("flags" + info.name[0..1].ToUpperInvariant() + info.name[1..]); writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.WriteLine($"pub(crate) static {name}: [u16; {rflags.Length}] = ["); using (writer.Indent()) { for (int i = 0; i < rflags.Length; i++) { var rfl = rflags[i]; uint value = (uint)rfl; if (value > ushort.MaxValue) throw new InvalidOperationException(); writer.WriteLine($"{NumberFormatter.FormatHexUInt32WithSep(value)},// {enumValues[i].Name(idConverter)}"); } } writer.WriteLine("];"); } } } protected override void Generate((EnumValue cpuidInternal, EnumValue[] cpuidFeatures)[] cpuidFeatures) { var filename = generatorContext.Types.Dirs.GetRustFilename("info", "cpuid_table.rs"); using (var writer = new FileWriter(TargetLanguage.Rust, FileUtils.OpenWrite(filename))) { writer.WriteFileHeader(); var cpuidFeatureTypeStr = genTypes[TypeIds.CpuidFeature].Name(idConverter); writer.WriteLine($"use super::super::{cpuidFeatureTypeStr};"); writer.WriteLine(); writer.WriteLine(RustConstants.AttributeNoRustFmt); writer.WriteLine($"pub(crate) static CPUID: [&[{cpuidFeatureTypeStr}]; {cpuidFeatures.Length}] = ["); using (writer.Indent()) { foreach (var info in cpuidFeatures) writer.WriteLine($"&[{string.Join(", ", info.cpuidFeatures.Select(a => $"{cpuidFeatureTypeStr}::{a.Name(idConverter)}"))}],// {info.cpuidInternal.Name(idConverter)}"); } writer.WriteLine("];"); } } protected override void GenerateCore() => GenerateOpAccesses(); void GenerateOpAccesses() { var filename = generatorContext.Types.Dirs.GetRustFilename("info", "enums.rs"); new FileUpdater(TargetLanguage.Rust, "OpAccesses", filename).Generate(writer => GenerateOpAccesses(writer)); } void GenerateOpAccesses(FileWriter writer) { var opInfos = instrInfoTypes.EnumOpInfos; // We assume max op count is 5, update the code if not Static.Assert(IcedConstants.MaxOpCount == 5 ? 0 : -1); var indexes = new int[] { 1, 2 }; var opAccessTypeStr = genTypes[TypeIds.OpAccess].Name(idConverter); foreach (var index in indexes) { var opInfo = opInfos[index]; writer.WriteLine(RustConstants.AttributeNoRustFmt); var name = idConverter.Constant($"OpAccess_{index}"); writer.WriteLine($"pub(super) static {name}: [{opAccessTypeStr}; {opInfo.Values.Length}] = ["); using (writer.Indent()) { foreach (var value in opInfo.Values) { var v = ToOpAccess(value); writer.WriteLine($"{opAccessTypeStr}::{v.Name(idConverter)},"); } } writer.WriteLine("];"); } } protected override void GenerateImpliedAccesses(ImpliedAccessesDef[] defs) { var filename = genTypes.Dirs.GetRustFilename("info", "factory.rs"); new FileUpdater(TargetLanguage.Rust, "ImpliedAccessHandler", filename).Generate(writer => GenerateImpliedAccesses(writer, defs)); } void GenerateImpliedAccesses(FileWriter writer, ImpliedAccessesDef[] defs) { foreach (var def in defs) { writer.WriteLine($"{GetEnumName(def.EnumValue)} => {{"); using (writer.Indent()) { foreach (var cond in def.ImpliedAccesses.Conditions) { var condStr = GetConditionString(cond.Kind); if (condStr is null) { if (cond.FalseStatements.Count > 0) throw new InvalidOperationException(); GenerateImpliedAccesses(writer, cond.TrueStatements); } else { writer.WriteLine($"if {condStr} {{"); using (writer.Indent()) GenerateImpliedAccesses(writer, cond.TrueStatements); writer.WriteLine("}"); if (cond.FalseStatements.Count > 0) { writer.WriteLine("else {"); using (writer.Indent()) GenerateImpliedAccesses(writer, cond.FalseStatements); writer.WriteLine("}"); } } } } writer.WriteLine("}"); } static string? GetConditionString(ImplAccConditionKind kind) => kind switch { ImplAccConditionKind.None => null, ImplAccConditionKind.Bit64 => "(flags & Flags::IS_64BIT) != 0", ImplAccConditionKind.NotBit64 => "(flags & Flags::IS_64BIT) == 0", _ => throw new InvalidOperationException(), }; } void GenerateImpliedAccesses(FileWriter writer, List<ImplAccStatement> stmts) { var stmtState = new StmtState( "if (flags & Flags::NO_REGISTER_USAGE) == 0 {", "}", "if (flags & Flags::NO_MEMORY_USAGE) == 0 {", "}"); foreach (var stmt in stmts) { IntArgImplAccStatement arg1; IntX2ArgImplAccStatement arg2; stmtState.SetKind(writer, stmt.Kind); switch (stmt.Kind) { case ImplAccStatementKind.MemoryAccess: var mem = (MemoryImplAccStatement)stmt; writer.WriteLine($"Self::add_memory(info, {GetRegisterString(mem.Segment)}, {GetRegisterString(mem.Base)}, {GetRegisterString(mem.Index)}, {mem.Scale}, 0x{mem.Displacement}, {GetMemorySizeString(mem.MemorySize)}, {GetOpAccessString(mem.Access)}, {GetCodeSizeString(mem.AddressSize)}, {mem.VsibSize});"); break; case ImplAccStatementKind.RegisterAccess: var reg = (RegisterImplAccStatement)stmt; if (reg.IsMemOpSegRead && CouldBeNullSegIn64BitMode(reg.Register, out var definitelyNullSeg)) { if (definitelyNullSeg) { writer.WriteLine("if (flags & Flags::IS_64BIT) == 0 {"); using (writer.Indent()) writer.WriteLine($"Self::add_register(flags, info, {GetRegisterString(reg.Register)}, {GetOpAccessString(reg.Access)});"); writer.WriteLine("}"); } else writer.WriteLine($"Self::add_memory_segment_register(flags, info, {GetRegisterString(reg.Register)}, {GetOpAccessString(reg.Access)});"); } else writer.WriteLine($"Self::add_register(flags, info, {GetRegisterString(reg.Register)}, {GetOpAccessString(reg.Access)});"); break; case ImplAccStatementKind.RegisterRangeAccess: var rreg = (RegisterRangeImplAccStatement)stmt; writer.WriteLine($"for reg_num in ({GetEnumName(rreg.RegisterFirst)} as u32)..(({GetEnumName(rreg.RegisterLast)} as u32) + 1) {{"); using (writer.Indent()) writer.WriteLine($"Self::add_register(flags, info, unsafe {{ mem::transmute(reg_num as u8) }}, {GetOpAccessString(rreg.Access)});"); writer.WriteLine("}"); break; case ImplAccStatementKind.ShiftMask: arg1 = (IntArgImplAccStatement)stmt; writer.WriteLine($"Self::command_shift_mask(instruction, info, 0x{arg1.Arg:X});"); break; case ImplAccStatementKind.ShiftMask1FMod: arg1 = (IntArgImplAccStatement)stmt; writer.WriteLine($"Self::command_shift_mask_mod(instruction, info, {Verify_9_or_17(arg1.Arg)});"); break; case ImplAccStatementKind.ZeroRegRflags: writer.WriteLine("Self::command_clear_rflags(instruction, info, flags);"); break; case ImplAccStatementKind.ZeroRegRegmem: writer.WriteLine("Self::command_clear_reg_regmem(instruction, info, flags);"); break; case ImplAccStatementKind.ZeroRegRegRegmem: writer.WriteLine("Self::command_clear_reg_reg_regmem(instruction, info, flags);"); break; case ImplAccStatementKind.Arpl: writer.WriteLine("Self::command_arpl(instruction, info, flags);"); break; case ImplAccStatementKind.LastGpr8: writer.WriteLine($"Self::command_last_gpr(instruction, info, flags, {GetEnumName(registerType[nameof(Register.AL)])});"); break; case ImplAccStatementKind.LastGpr16: writer.WriteLine($"Self::command_last_gpr(instruction, info, flags, {GetEnumName(registerType[nameof(Register.AX)])});"); break; case ImplAccStatementKind.LastGpr32: writer.WriteLine($"Self::command_last_gpr(instruction, info, flags, {GetEnumName(registerType[nameof(Register.EAX)])});"); break; case ImplAccStatementKind.EmmiReg: var emmi = (EmmiImplAccStatement)stmt; writer.WriteLine($"Self::command_emmi(instruction, info, flags, {GetEnumName(GetOpAccess(opAccessType, emmi.Access))});"); break; case ImplAccStatementKind.Enter: arg1 = (IntArgImplAccStatement)stmt; writer.WriteLine($"Self::command_enter(instruction, info, flags, {Verify_2_4_or_8(arg1.Arg)});"); break; case ImplAccStatementKind.Leave: arg1 = (IntArgImplAccStatement)stmt; writer.WriteLine($"Self::command_leave(instruction, info, flags, {Verify_2_4_or_8(arg1.Arg)});"); break; case ImplAccStatementKind.Push: arg2 = (IntX2ArgImplAccStatement)stmt; if (arg2.Arg1 != 0) writer.WriteLine($"Self::command_push(instruction, info, flags, {arg2.Arg1}, {Verify_2_4_or_8(arg2.Arg2)});"); break; case ImplAccStatementKind.Pop: arg2 = (IntX2ArgImplAccStatement)stmt; if (arg2.Arg1 != 0) writer.WriteLine($"Self::command_pop(instruction, info, flags, {arg2.Arg1}, {Verify_2_4_or_8(arg2.Arg2)});"); break; case ImplAccStatementKind.PopRm: arg1 = (IntArgImplAccStatement)stmt; writer.WriteLine($"Self::command_pop_rm(instruction, info, flags, {Verify_2_4_or_8(arg1.Arg)});"); break; case ImplAccStatementKind.Pusha: arg1 = (IntArgImplAccStatement)stmt; writer.WriteLine($"Self::command_pusha(instruction, info, flags, {Verify_2_or_4(arg1.Arg)});"); break; case ImplAccStatementKind.Popa: arg1 = (IntArgImplAccStatement)stmt; writer.WriteLine($"Self::command_popa(instruction, info, flags, {Verify_2_or_4(arg1.Arg)});"); break; case ImplAccStatementKind.lea: writer.WriteLine("Self::command_lea(instruction, info, flags);"); break; case ImplAccStatementKind.Cmps: writer.WriteLine("Self::command_cmps(instruction, info, flags);"); break; case ImplAccStatementKind.Ins: writer.WriteLine("Self::command_ins(instruction, info, flags);"); break; case ImplAccStatementKind.Lods: writer.WriteLine("Self::command_lods(instruction, info, flags);"); break; case ImplAccStatementKind.Movs: writer.WriteLine("Self::command_movs(instruction, info, flags);"); break; case ImplAccStatementKind.Outs: writer.WriteLine("Self::command_outs(instruction, info, flags);"); break; case ImplAccStatementKind.Scas: writer.WriteLine("Self::command_scas(instruction, info, flags);"); break; case ImplAccStatementKind.Stos: writer.WriteLine("Self::command_stos(instruction, info, flags);"); break; case ImplAccStatementKind.Xstore: arg1 = (IntArgImplAccStatement)stmt; writer.WriteLine($"Self::command_xstore(instruction, info, flags, {Verify_2_4_or_8(arg1.Arg)});"); break; default: throw new InvalidOperationException(); } } stmtState.Done(writer); } string GetMemorySizeString(ImplAccMemorySize memorySize) { switch (memorySize.Kind) { case ImplAccMemorySizeKind.MemorySize: if (memorySize.MemorySize is null) throw new InvalidOperationException(); return GetEnumName(memorySize.MemorySize); case ImplAccMemorySizeKind.Default: return "instruction.memory_size()"; default: throw new InvalidOperationException(); } } string GetRegisterString(ImplAccRegister? register) { if (register == null) return GetEnumName(registerType[nameof(Register.None)]); var reg = register.GetValueOrDefault(); switch (reg.Kind) { case ImplAccRegisterKind.Register: if (reg.Register is null) throw new InvalidOperationException(); return GetEnumName(reg.Register); case ImplAccRegisterKind.SegmentDefaultDS: return "Self::get_seg_default_ds(instruction)"; case ImplAccRegisterKind.a_rDI: return "Self::get_a_rdi(instruction)"; case ImplAccRegisterKind.Op0: return "instruction.op0_register()"; case ImplAccRegisterKind.Op1: return "instruction.op1_register()"; case ImplAccRegisterKind.Op2: return "instruction.op2_register()"; case ImplAccRegisterKind.Op3: return "instruction.op3_register()"; case ImplAccRegisterKind.Op4: return "instruction.op4_register()"; default: throw new InvalidOperationException(); } } string GetOpAccessString(OpAccess access) => GetEnumName(opAccessType[access.ToString()]); string GetCodeSizeString(CodeSize codeSize) => GetEnumName(codeSizeType[codeSize.ToString()]); string GetEnumName(EnumValue value) => value.DeclaringType.Name(idConverter) + "::" + value.Name(idConverter); void GenerateTable((EncodingKind encoding, InstructionDef[] defs)[] tdefs, string id, string filename) { new FileUpdater(TargetLanguage.Rust, id, filename).Generate(writer => { foreach (var (encoding, defs) in tdefs) { if (RustConstants.GetFeature(encoding) is string feature) writer.WriteLine(feature); var bar = string.Empty; foreach (var def in defs) { writer.WriteLine($"{bar}{def.Code.DeclaringType.Name(idConverter)}::{def.Code.Name(idConverter)}"); bar = "| "; } writer.WriteLine("=> true,"); } }); } protected override void GenerateIgnoresSegmentTable((EncodingKind encoding, InstructionDef[] defs)[] defs) { var filename = genTypes.Dirs.GetRustFilename("code.rs"); GenerateTable(defs, "IgnoresSegmentTable", filename); } protected override void GenerateIgnoresIndexTable((EncodingKind encoding, InstructionDef[] defs)[] defs) { var filename = genTypes.Dirs.GetRustFilename("code.rs"); GenerateTable(defs, "IgnoresIndexTable", filename); } protected override void GenerateTileStrideIndexTable((EncodingKind encoding, InstructionDef[] defs)[] defs) { var filename = genTypes.Dirs.GetRustFilename("code.rs"); GenerateTable(defs, "TileStrideIndexTable", filename); } protected override void GenerateFpuStackIncrementInfoTable((FpuStackInfo info, InstructionDef[] defs)[] tdefs) { var filename = genTypes.Dirs.GetRustFilename("instruction.rs"); new FileUpdater(TargetLanguage.Rust, "FpuStackIncrementInfoTable", filename).Generate(writer => { foreach (var (info, defs) in tdefs) { var bar = string.Empty; foreach (var def in defs) { writer.WriteLine($"{bar}{def.Code.DeclaringType.Name(idConverter)}::{def.Code.Name(idConverter)}"); bar = "| "; } var conditionalStr = info.Conditional ? "true" : "false"; var writesTopStr = info.WritesTop ? "true" : "false"; writer.WriteLine($"=> FpuStackIncrementInfo {{ increment: {info.Increment}, conditional: {conditionalStr}, writes_top: {writesTopStr} }},"); } }); } protected override void GenerateStackPointerIncrementTable((EncodingKind encoding, StackInfo info, InstructionDef[] defs)[] tdefs) { var filename = genTypes.Dirs.GetRustFilename("instruction.rs"); new FileUpdater(TargetLanguage.Rust, "StackPointerIncrementTable", filename).Generate(writer => { foreach (var (encoding, info, defs) in tdefs) { var expr = info.Kind switch { StackInfoKind.Increment => $" => {info.Value},", StackInfoKind.Enter => $" => -({info.Value} + (self.immediate8_2nd() as i32 & 0x1F) * {info.Value} + self.immediate16() as i32),", StackInfoKind.Iret => $" => if self.code_size() == CodeSize::Code64 {{ {info.Value} * 5 }} else {{ {info.Value} * 3 }},", StackInfoKind.PopImm16 => $" => {info.Value} + self.immediate16() as i32,", _ => throw new InvalidOperationException(), }; if (RustConstants.GetFeature(encoding) is string feature) writer.WriteLine(feature); var bar = string.Empty; for (int i = 0; i < defs.Length; i++) { var def = defs[i]; var finalExpr = i + 1 == defs.Length ? expr : string.Empty; writer.WriteLine($"{bar}{def.Code.DeclaringType.Name(idConverter)}::{def.Code.Name(idConverter)}{finalExpr}"); bar = "| "; } } }); } } }
/* * 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 NodaTime; using ProtoBuf; using System.IO; using System.Linq; using Newtonsoft.Json; using QuantConnect.Util; using QuantConnect.Data.Market; using System.Collections.Generic; using QuantConnect.Data.Custom.AlphaStreams; namespace QuantConnect.Data { /// <summary> /// Abstract base data class of QuantConnect. It is intended to be extended to define /// generic user customizable data types while at the same time implementing the basics of data where possible /// </summary> [ProtoContract(SkipConstructor = true)] [ProtoInclude(8, typeof(Tick))] [ProtoInclude(100, typeof(TradeBar))] [ProtoInclude(200, typeof(QuoteBar))] [ProtoInclude(300, typeof(Dividend))] [ProtoInclude(400, typeof(Split))] [ProtoInclude(555, typeof(AlphaStreamsPortfolioState))] [ProtoInclude(556, typeof(AlphaStreamsOrderEvent))] public abstract class BaseData : IBaseData { private decimal _value; /// <summary> /// A list of all <see cref="Resolution"/> /// </summary> protected static readonly List<Resolution> AllResolutions = Enum.GetValues(typeof(Resolution)).Cast<Resolution>().ToList(); /// <summary> /// A list of <see cref="Resolution.Daily"/> /// </summary> protected static readonly List<Resolution> DailyResolution = new List<Resolution> { Resolution.Daily }; /// <summary> /// A list of <see cref="Resolution.Minute"/> /// </summary> protected static readonly List<Resolution> MinuteResolution = new List<Resolution> { Resolution.Minute }; /// <summary> /// A list of high <see cref="Resolution"/>, including minute, second, and tick. /// </summary> protected static readonly List<Resolution> HighResolution = new List<Resolution> { Resolution.Minute, Resolution.Second, Resolution.Tick }; /// <summary> /// Market Data Type of this data - does it come in individual price packets or is it grouped into OHLC. /// </summary> /// <remarks>Data is classed into two categories - streams of instantaneous prices and groups of OHLC data.</remarks> [ProtoMember(1)] public MarketDataType DataType { get; set; } = MarketDataType.Base; /// <summary> /// True if this is a fill forward piece of data /// </summary> public bool IsFillForward { get; private set; } /// <summary> /// Current time marker of this data packet. /// </summary> /// <remarks>All data is timeseries based.</remarks> [ProtoMember(2)] public DateTime Time { get; set; } /// <summary> /// The end time of this data. Some data covers spans (trade bars) and as such we want /// to know the entire time span covered /// </summary> public virtual DateTime EndTime { get { return Time; } set { Time = value; } } /// <summary> /// Symbol representation for underlying Security /// </summary> public Symbol Symbol { get; set; } = Symbol.Empty; /// <summary> /// Value representation of this data packet. All data requires a representative value for this moment in time. /// For streams of data this is the price now, for OHLC packets this is the closing price. /// </summary> [ProtoMember(4)] public virtual decimal Value { get { return _value; } set { _value = value; } } /// <summary> /// As this is a backtesting platform we'll provide an alias of value as price. /// </summary> public decimal Price => Value; /// <summary> /// Constructor for initialising the dase data class /// </summary> public BaseData() { //Empty constructor required for fast-reflection initialization } /// <summary> /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object /// each time it is called. The returned object is assumed to be time stamped in the config.ExchangeTimeZone. /// </summary> /// <param name="config">Subscription data config setup object</param> /// <param name="line">Line of the source document</param> /// <param name="date">Date of the requested data</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns> public virtual BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, bool isLiveMode) { // stub implementation to prevent compile errors in user algorithms var dataFeed = isLiveMode ? DataFeedEndpoint.LiveTrading : DataFeedEndpoint.Backtesting; #pragma warning disable 618 // This implementation is left here for backwards compatibility of the BaseData API return Reader(config, line, date, dataFeed); #pragma warning restore 618 } /// <summary> /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object /// each time it is called. The returned object is assumed to be time stamped in the config.ExchangeTimeZone. /// </summary> /// <param name="config">Subscription data config setup object</param> /// <param name="stream">The data stream</param> /// <param name="date">Date of the requested data</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns> public virtual BaseData Reader(SubscriptionDataConfig config, StreamReader stream, DateTime date, bool isLiveMode) { throw new NotImplementedException("Each data types has to implement is own Stream reader"); } /// <summary> /// Return the URL string source of the file. This will be converted to a stream /// </summary> /// <param name="config">Configuration object</param> /// <param name="date">Date of this source file</param> /// <param name="isLiveMode">true if we're in live mode, false for backtesting mode</param> /// <returns>String URL of source file.</returns> public virtual SubscriptionDataSource GetSource(SubscriptionDataConfig config, DateTime date, bool isLiveMode) { // stub implementation to prevent compile errors in user algorithms var dataFeed = isLiveMode ? DataFeedEndpoint.LiveTrading : DataFeedEndpoint.Backtesting; #pragma warning disable 618 // This implementation is left here for backwards compatibility of the BaseData API var source = GetSource(config, date, dataFeed); #pragma warning restore 618 if (isLiveMode) { // live trading by default always gets a rest endpoint return new SubscriptionDataSource(source, SubscriptionTransportMedium.Rest); } // construct a uri to determine if we have a local or remote file var uri = new Uri(source, UriKind.RelativeOrAbsolute); if (uri.IsAbsoluteUri && !uri.IsLoopback) { return new SubscriptionDataSource(source, SubscriptionTransportMedium.RemoteFile); } return new SubscriptionDataSource(source, SubscriptionTransportMedium.LocalFile); } /// <summary> /// Indicates if there is support for mapping /// </summary> /// <remarks>Relies on the <see cref="Symbol"/> property value</remarks> /// <returns>True indicates mapping should be used</returns> public virtual bool RequiresMapping() { return Symbol.SecurityType.RequiresMapping(); } /// <summary> /// Indicates that the data set is expected to be sparse /// </summary> /// <remarks>Relies on the <see cref="Symbol"/> property value</remarks> /// <remarks>This is a method and not a property so that python /// custom data types can override it</remarks> /// <returns>True if the data set represented by this type is expected to be sparse</returns> public virtual bool IsSparseData() { // by default, we'll assume all custom data is sparse data return Symbol.SecurityType == SecurityType.Base; } /// <summary> /// Gets the default resolution for this data and security type /// </summary> /// <remarks>This is a method and not a property so that python /// custom data types can override it</remarks> public virtual Resolution DefaultResolution() { return Resolution.Minute; } /// <summary> /// Gets the supported resolution for this data and security type /// </summary> /// <remarks>Relies on the <see cref="Symbol"/> property value</remarks> /// <remarks>This is a method and not a property so that python /// custom data types can override it</remarks> public virtual List<Resolution> SupportedResolutions() { if (Symbol.SecurityType.IsOption() || Symbol.SecurityType == SecurityType.Index) { return MinuteResolution; } if (Symbol.SecurityType == SecurityType.Future) { return HighResolution; } return AllResolutions; } /// <summary> /// Specifies the data time zone for this data type. This is useful for custom data types /// </summary> /// <remarks>Will throw <see cref="InvalidOperationException"/> for security types /// other than <see cref="SecurityType.Base"/></remarks> /// <returns>The <see cref="DateTimeZone"/> of this data type</returns> public virtual DateTimeZone DataTimeZone() { if (Symbol.SecurityType != SecurityType.Base) { throw new InvalidOperationException("BaseData.DataTimeZone(): is only valid for base data types"); } return TimeZones.NewYork; } /// <summary> /// Updates this base data with a new trade /// </summary> /// <param name="lastTrade">The price of the last trade</param> /// <param name="tradeSize">The quantity traded</param> public void UpdateTrade(decimal lastTrade, decimal tradeSize) { Update(lastTrade, 0, 0, tradeSize, 0, 0); } /// <summary> /// Updates this base data with new quote information /// </summary> /// <param name="bidPrice">The current bid price</param> /// <param name="bidSize">The current bid size</param> /// <param name="askPrice">The current ask price</param> /// <param name="askSize">The current ask size</param> public void UpdateQuote(decimal bidPrice, decimal bidSize, decimal askPrice, decimal askSize) { Update(0, bidPrice, askPrice, 0, bidSize, askSize); } /// <summary> /// Updates this base data with the new quote bid information /// </summary> /// <param name="bidPrice">The current bid price</param> /// <param name="bidSize">The current bid size</param> public void UpdateBid(decimal bidPrice, decimal bidSize) { Update(0, bidPrice, 0, 0, bidSize, 0); } /// <summary> /// Updates this base data with the new quote ask information /// </summary> /// <param name="askPrice">The current ask price</param> /// <param name="askSize">The current ask size</param> public void UpdateAsk(decimal askPrice, decimal askSize) { Update(0, 0, askPrice, 0, 0, askSize); } /// <summary> /// Update routine to build a bar/tick from a data update. /// </summary> /// <param name="lastTrade">The last trade price</param> /// <param name="bidPrice">Current bid price</param> /// <param name="askPrice">Current asking price</param> /// <param name="volume">Volume of this trade</param> /// <param name="bidSize">The size of the current bid, if available</param> /// <param name="askSize">The size of the current ask, if available</param> public virtual void Update(decimal lastTrade, decimal bidPrice, decimal askPrice, decimal volume, decimal bidSize, decimal askSize) { Value = lastTrade; } /// <summary> /// Return a new instance clone of this object, used in fill forward /// </summary> /// <remarks> /// This base implementation uses reflection to copy all public fields and properties /// </remarks> /// <param name="fillForward">True if this is a fill forward clone</param> /// <returns>A clone of the current object</returns> public virtual BaseData Clone(bool fillForward) { var clone = Clone(); clone.IsFillForward = fillForward; return clone; } /// <summary> /// Return a new instance clone of this object, used in fill forward /// </summary> /// <remarks> /// This base implementation uses reflection to copy all public fields and properties /// </remarks> /// <returns>A clone of the current object</returns> public virtual BaseData Clone() { return (BaseData) ObjectActivator.Clone((object)this); } /// <summary> /// Formats a string with the symbol and value. /// </summary> /// <returns>string - a string formatted as SPY: 167.753</returns> public override string ToString() { return $"{Symbol}: {Value.ToStringInvariant("C")}"; } /// <summary> /// Reader converts each line of the data source into BaseData objects. Each data type creates its own factory method, and returns a new instance of the object /// each time it is called. /// </summary> /// <remarks>OBSOLETE:: This implementation is added for backward/forward compatibility purposes. This function is no longer called by the LEAN engine.</remarks> /// <param name="config">Subscription data config setup object</param> /// <param name="line">Line of the source document</param> /// <param name="date">Date of the requested data</param> /// <param name="datafeed">Type of datafeed we're requesting - a live or backtest feed.</param> /// <returns>Instance of the T:BaseData object generated by this line of the CSV</returns> [Obsolete("Reader(SubscriptionDataConfig, string, DateTime, DataFeedEndpoint) method has been made obsolete, use Reader(SubscriptionDataConfig, string, DateTime, bool) instead.")] public virtual BaseData Reader(SubscriptionDataConfig config, string line, DateTime date, DataFeedEndpoint datafeed) { throw new InvalidOperationException( $"Please implement Reader(SubscriptionDataConfig, string, DateTime, bool) on your custom data type: {GetType().Name}" ); } /// <summary> /// Return the URL string source of the file. This will be converted to a stream /// </summary> /// <remarks>OBSOLETE:: This implementation is added for backward/forward compatibility purposes. This function is no longer called by the LEAN engine.</remarks> /// <param name="config">Configuration object</param> /// <param name="date">Date of this source file</param> /// <param name="datafeed">Type of datafeed we're reqesting - backtest or live</param> /// <returns>String URL of source file.</returns> [Obsolete("GetSource(SubscriptionDataConfig, DateTime, DataFeedEndpoint) method has been made obsolete, use GetSource(SubscriptionDataConfig, DateTime, bool) instead.")] public virtual string GetSource(SubscriptionDataConfig config, DateTime date, DataFeedEndpoint datafeed) { throw new InvalidOperationException( $"Please implement GetSource(SubscriptionDataConfig, DateTime, bool) on your custom data type: {GetType().Name}" ); } /// <summary> /// Deserialize the message from the data server /// </summary> /// <param name="serialized">The data server's message</param> /// <returns>An enumerable of base data, if unsuccessful, returns an empty enumerable</returns> public static IEnumerable<BaseData> DeserializeMessage(string serialized) { var deserialized = JsonConvert.DeserializeObject(serialized, JsonSerializerSettings); var enumerable = deserialized as IEnumerable<BaseData>; if (enumerable != null) { return enumerable; } var data = deserialized as BaseData; if (data != null) { return new[] { data }; } return Enumerable.Empty<BaseData>(); } private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.ComponentModel.DataAnnotations.Tests { public class ValidatorTests { public static readonly ValidationContext s_estValidationContext = new ValidationContext(new object()); #region TryValidateObject [Fact] public static void TryValidateObjectThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null)); Assert.Throws<ArgumentNullException>( () => Validator.TryValidateObject(new object(), validationContext: null, validationResults: null, validateAllProperties: false)); } [Fact] public static void TryValidateObjectThrowsIf_instance_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null)); Assert.Throws<ArgumentNullException>( () => Validator.TryValidateObject(null, s_estValidationContext, validationResults: null, validateAllProperties: false)); } // TryValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance [Fact] public static void TestTryValidateObjectThrowsIfInstanceNotMatch() { AssertExtensions.Throws<ArgumentException>("instance", () => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null)); AssertExtensions.Throws<ArgumentException>("instance", () => Validator.TryValidateObject(new object(), s_estValidationContext, validationResults: null, validateAllProperties: true)); } [Fact] public static void TryValidateObject_returns_true_if_no_errors() { var objectToBeValidated = "ToBeValidated"; var validationContext = new ValidationContext(objectToBeValidated); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null)); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults: null, validateAllProperties: true)); } [Fact] public static void TryValidateObject_returns_false_if_errors() { var objectToBeValidated = new ToBeValidated() { PropertyToBeTested = "Invalid Value", PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, null, true)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); } [Fact] public static void TryValidateObject_collection_can_have_multiple_results() { HasDoubleFailureProperty objectToBeValidated = new HasDoubleFailureProperty(); ValidationContext validationContext = new ValidationContext(objectToBeValidated); List<ValidationResult> results = new List<ValidationResult>(); Assert.False(Validator.TryValidateObject(objectToBeValidated, validationContext, results, true)); Assert.Equal(2, results.Count); } [Fact] public static void TryValidateObject_collection_can_have_multiple_results_from_type_attributes() { DoublyInvalid objectToBeValidated = new DoublyInvalid(); ValidationContext validationContext = new ValidationContext(objectToBeValidated); List<ValidationResult> results = new List<ValidationResult>(); Assert.False(Validator.TryValidateObject(objectToBeValidated, validationContext, results, true)); Assert.Equal(2, results.Count); } // TryValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors() [Fact] public static void TestTryValidateObjectSuccessEvenWithOtherErrors() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, null, false)); var validationResults = new List<ValidationResult>(); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, false)); Assert.Equal(0, validationResults.Count); } [Fact] public static void TryValidateObject_returns_false_if_validateAllProperties_is_true_and_Required_test_fails() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null }; var validationContext = new ValidationContext(objectToBeValidated); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, null, true)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true)); Assert.Equal(1, validationResults.Count); // cannot check error message - not defined on ret builds } [Fact] public static void TryValidateObject_returns_true_if_validateAllProperties_is_true_and_all_attributes_are_valid() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, null, true)); var validationResults = new List<ValidationResult>(); Assert.True( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true)); Assert.Equal(0, validationResults.Count); } [Fact] public static void TryValidateObject_returns_false_if_all_properties_are_valid_but_class_is_invalid() { var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, null, true)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateObject(objectToBeValidated, validationContext, validationResults, true)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName, validationResults[0].ErrorMessage); } [Fact] public void TryValidateObject_IValidatableObject_Success() { var instance = new ValidatableSuccess(); var context = new ValidationContext(instance); var results = new List<ValidationResult>(); Assert.True(Validator.TryValidateObject(instance, context, results)); Assert.Empty(results); } public class ValidatableSuccess : IValidatableObject { public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { return new ValidationResult[] { ValidationResult.Success }; } } [Fact] public void TryValidateObject_IValidatableObject_Error() { var instance = new ValidatableError(); var context = new ValidationContext(instance); var results = new List<ValidationResult>(); Assert.False(Validator.TryValidateObject(instance, context, results)); Assert.Equal("error", Assert.Single(results).ErrorMessage); } public class ValidatableError : IValidatableObject { public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { return new ValidationResult[] { new ValidationResult("error") }; } } [Fact] public void TryValidateObject_RequiredNonNull_Success() { var instance = new RequiredFailure { Required = "Text" }; var context = new ValidationContext(instance); var results = new List<ValidationResult>(); Assert.True(Validator.TryValidateObject(instance, context, results)); Assert.Empty(results); } [Fact] public void TryValidateObject_RequiredNull_Error() { var instance = new RequiredFailure(); var context = new ValidationContext(instance); var results = new List<ValidationResult>(); Assert.False(Validator.TryValidateObject(instance, context, results)); Assert.Equal("The Required field is required.", Assert.Single(results).ErrorMessage); } public class RequiredFailure { [Required] public string Required { get; set; } } #endregion TryValidateObject #region ValidateObject [Fact] public static void ValidateObjectThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateObject(new object(), validationContext: null)); Assert.Throws<ArgumentNullException>( () => Validator.ValidateObject(new object(), validationContext: null, validateAllProperties: false)); } [Fact] public static void ValidateObjectThrowsIf_instance_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateObject(null, s_estValidationContext)); Assert.Throws<ArgumentNullException>( () => Validator.ValidateObject(null, s_estValidationContext, false)); } [Fact] public static void ValidateObjectThrowsIf_instance_does_not_match_ValidationContext_ObjectInstance() { AssertExtensions.Throws<ArgumentException>("instance", () => Validator.ValidateObject(new object(), s_estValidationContext)); AssertExtensions.Throws<ArgumentException>("instance", () => Validator.ValidateObject(new object(), s_estValidationContext, true)); } [Fact] public static void ValidateObject_succeeds_if_no_errors() { var objectToBeValidated = "ToBeValidated"; var validationContext = new ValidationContext(objectToBeValidated); Validator.ValidateObject(objectToBeValidated, validationContext); Validator.ValidateObject(objectToBeValidated, validationContext, true); } [Fact] public static void ValidateObject_throws_ValidationException_if_errors() { var objectToBeValidated = new ToBeValidated() { PropertyToBeTested = "Invalid Value", PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); var exception = Assert.Throws<ValidationException>( () => Validator.ValidateObject(objectToBeValidated, validationContext, true)); Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); } // ValidateObject_returns_true_if_validateAllProperties_is_false_and_Required_test_passes_even_if_there_are_other_errors [Fact] public static void TestValidateObjectNotThrowIfvalidateAllPropertiesFalse() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Invalid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Validator.ValidateObject(objectToBeValidated, validationContext, false); } // ValidateObject_throws_ValidationException_if_validateAllProperties_is_true_and_Required_test_fails [Fact] public static void TestValidateObjectThrowsIfRequiredTestFails() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = null }; var validationContext = new ValidationContext(objectToBeValidated); var exception = Assert.Throws<ValidationException>( () => Validator.ValidateObject(objectToBeValidated, validationContext, true)); Assert.IsType<RequiredAttribute>(exception.ValidationAttribute); // cannot check error message - not defined on ret builds Assert.Null(exception.Value); } [Fact] public static void ValidateObject_succeeds_if_validateAllProperties_is_true_and_all_attributes_are_valid() { var objectToBeValidated = new ToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); Validator.ValidateObject(objectToBeValidated, validationContext, true); } [Fact] public static void ValidateObject_throws_ValidationException_if_all_properties_are_valid_but_class_is_invalid() { var objectToBeValidated = new InvalidToBeValidated() { PropertyWithRequiredAttribute = "Valid Value" }; var validationContext = new ValidationContext(objectToBeValidated); var exception = Assert.Throws<ValidationException>( () => Validator.ValidateObject(objectToBeValidated, validationContext, true)); Assert.IsType<ValidClassAttribute>(exception.ValidationAttribute); Assert.Equal( "ValidClassAttribute.IsValid failed for class of type " + typeof(InvalidToBeValidated).FullName, exception.ValidationResult.ErrorMessage); Assert.Equal(objectToBeValidated, exception.Value); } #endregion ValidateObject #region TryValidateProperty [Fact] public static void TryValidatePropertyThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateProperty(new object(), validationContext: null, validationResults: null)); } [Fact] public static void TryValidatePropertyThrowsIf_value_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateProperty(null, s_estValidationContext, validationResults: null)); } // TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty() [Fact] public static void TestTryValidatePropertyThrowsIfNullOrEmptyValidationContextMemberName() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = null; Assert.Throws<ArgumentNullException>( () => Validator.TryValidateProperty(null, validationContext, null)); validationContext.MemberName = string.Empty; Assert.Throws<ArgumentNullException>( () => Validator.TryValidateProperty(null, validationContext, null)); } [Fact] public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NonExist"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null)); } [Fact] public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "InternalProperty"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null)); validationContext.MemberName = "ProtectedProperty"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null)); validationContext.MemberName = "PrivateProperty"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, null)); } [Fact] public static void TryValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "Item"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.TryValidateProperty(null, validationContext, validationResults: null)); } [Fact] public static void TryValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(123, validationContext, validationResults: null)); } [Fact] public static void TryValidatePropertyThrowsIf_null_passed_to_non_nullable_property() { var validationContext = new ValidationContext(new ToBeValidated()); // cannot assign null to a non-value-type property validationContext.MemberName = "EnumProperty"; AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(null, validationContext, validationResults: null)); // cannot assign null to a non-nullable property validationContext.MemberName = "NonNullableProperty"; AssertExtensions.Throws<ArgumentException>("value", () => Validator.TryValidateProperty(null, validationContext, validationResults: null)); } [Fact] public static void TryValidateProperty_returns_true_if_null_passed_to_nullable_property() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NullableProperty"; Assert.True(Validator.TryValidateProperty(null, validationContext, validationResults: null)); } [Fact] public static void TryValidateProperty_returns_true_if_no_attributes_to_validate() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; Assert.True( Validator.TryValidateProperty("Any Value", validationContext, validationResults: null)); } [Fact] public static void TryValidateProperty_returns_false_if_errors() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; Assert.False( Validator.TryValidateProperty("Invalid Value", validationContext, null)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateProperty("Invalid Value", validationContext, validationResults)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); } [Fact] public static void TryValidateProperty_returns_false_if_Required_attribute_test_fails() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; Assert.False( Validator.TryValidateProperty(null, validationContext, null)); var validationResults = new List<ValidationResult>(); Assert.False( Validator.TryValidateProperty(null, validationContext, validationResults)); Assert.Equal(1, validationResults.Count); // cannot check error message - not defined on ret builds } [Fact] public static void TryValidateProperty_collection_can_have_multiple_results() { ValidationContext validationContext = new ValidationContext(new HasDoubleFailureProperty()); validationContext.MemberName = nameof(HasDoubleFailureProperty.WillAlwaysFailTwice); List<ValidationResult> results = new List<ValidationResult>(); Assert.False(Validator.TryValidateProperty("Nope", validationContext, results)); Assert.Equal(2, results.Count); } [Fact] public static void TryValidateProperty_returns_true_if_all_attributes_are_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; Assert.True( Validator.TryValidateProperty("Valid Value", validationContext, null)); var validationResults = new List<ValidationResult>(); Assert.True( Validator.TryValidateProperty("Valid Value", validationContext, validationResults)); Assert.Equal(0, validationResults.Count); } #endregion TryValidateProperty #region ValidateProperty [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateProperty(new object(), validationContext: null)); } [Fact] public static void ValidatePropertyThrowsIf_value_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateProperty(null, s_estValidationContext)); } [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_null_or_empty() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = null; Assert.Throws<ArgumentNullException>( () => Validator.ValidateProperty(null, validationContext)); validationContext.MemberName = string.Empty; Assert.Throws<ArgumentNullException>( () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_does_not_exist_on_object() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NonExist"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_not_public() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "InternalProperty"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext)); validationContext.MemberName = "ProtectedProperty"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext)); validationContext.MemberName = "PrivateProperty"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_ValidationContext_MemberName_is_for_a_public_indexer() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "Item"; AssertExtensions.Throws<ArgumentException>("propertyName", () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_value_passed_is_of_wrong_type_to_be_assigned_to_property() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(123, validationContext)); } [Fact] public static void ValidatePropertyThrowsIf_null_passed_to_non_nullable_property() { var validationContext = new ValidationContext(new ToBeValidated()); // cannot assign null to a non-value-type property validationContext.MemberName = "EnumProperty"; AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(null, validationContext)); // cannot assign null to a non-nullable property validationContext.MemberName = "NonNullableProperty"; AssertExtensions.Throws<ArgumentException>("value", () => Validator.ValidateProperty(null, validationContext)); } [Fact] public static void ValidateProperty_succeeds_if_null_passed_to_nullable_property() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NullableProperty"; Validator.ValidateProperty(null, validationContext); } [Fact] public static void ValidateProperty_succeeds_if_no_attributes_to_validate() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; Validator.ValidateProperty("Any Value", validationContext); } [Fact] public static void ValidateProperty_throws_ValidationException_if_errors() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateProperty("Invalid Value", validationContext)); Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); } [Fact] public static void ValidateProperty_throws_ValidationException_if_Required_attribute_test_fails() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateProperty(null, validationContext)); Assert.IsType<RequiredAttribute>(exception.ValidationAttribute); // cannot check error message - not defined on ret builds Assert.Null(exception.Value); } [Fact] public static void ValidateProperty_succeeds_if_all_attributes_are_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; Validator.ValidateProperty("Valid Value", validationContext); } #endregion ValidateProperty #region TryValidateValue [Fact] public static void TryValidateValueThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.TryValidateValue(new object(), validationContext: null, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>())); } [Fact] public static void TryValidateValueThrowsIf_ValidationAttributeEnumerable_is_null() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = null; Assert.Throws<ArgumentNullException>( () => Validator.TryValidateValue(new object(), validationContext, validationResults: null, validationAttributes: null)); } [Fact] public static void TryValidateValue_returns_true_if_no_attributes_to_validate_regardless_of_value() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; Assert.True(Validator.TryValidateValue(null, validationContext, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>())); Assert.True(Validator.TryValidateValue(new object(), validationContext, validationResults: null, validationAttributes: Enumerable.Empty<ValidationAttribute>())); } [Fact] public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_null() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; Assert.False(Validator.TryValidateValue(null, validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue(null, validationContext, validationResults, attributesToValidate)); Assert.Equal(1, validationResults.Count); // cannot check error message - not defined on ret builds } [Fact] public static void TryValidateValue_returns_false_if_Property_has_RequiredAttribute_and_value_is_invalid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); } [Fact] public static void TryValidateValue_collection_can_have_multiple_results() { ValidationContext validationContext = new ValidationContext(new HasDoubleFailureProperty()); validationContext.MemberName = nameof(HasDoubleFailureProperty.WillAlwaysFailTwice); ValidationAttribute[] attributesToValidate = {new ValidValueStringPropertyAttribute(), new ValidValueStringPropertyDuplicateAttribute()}; List<ValidationResult> results = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue("Not Valid", validationContext, results, attributesToValidate)); Assert.Equal(2, results.Count); } [Fact] public static void TryValidateValue_returns_true_if_Property_has_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(0, validationResults.Count); } [Fact] public static void TryValidateValue_returns_false_if_Property_has_no_RequiredAttribute_and_value_is_invalid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.False(Validator.TryValidateValue("Invalid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(1, validationResults.Count); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", validationResults[0].ErrorMessage); } [Fact] public static void TryValidateValue_returns_true_if_Property_has_no_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; Assert.True(Validator.TryValidateValue("Valid Value", validationContext, null, attributesToValidate)); var validationResults = new List<ValidationResult>(); Assert.True(Validator.TryValidateValue("Valid Value", validationContext, validationResults, attributesToValidate)); Assert.Equal(0, validationResults.Count); } #endregion TryValidateValue #region ValidateValue [Fact] public static void ValidateValueThrowsIf_ValidationContext_is_null() { Assert.Throws<ArgumentNullException>( () => Validator.ValidateValue(new object(), validationContext: null, validationAttributes: Enumerable.Empty<ValidationAttribute>())); } [Fact] public static void ValidateValueThrowsIf_ValidationAttributeEnumerable_is_null() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = null; Assert.Throws<ArgumentNullException>( () => Validator.ValidateValue(new object(), validationContext, validationAttributes: null)); } [Fact] public static void ValidateValue_succeeds_if_no_attributes_to_validate_regardless_of_value() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "NoAttributesProperty"; Validator.ValidateValue(null, validationContext, Enumerable.Empty<ValidationAttribute>()); Validator.ValidateValue(new object(), validationContext, Enumerable.Empty<ValidationAttribute>()); } // ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_null() [Fact] public static void TestValidateValueThrowsIfNullRequiredAttribute() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateValue(null, validationContext, attributesToValidate)); Assert.IsType<RequiredAttribute>(exception.ValidationAttribute); // cannot check error message - not defined on ret builds Assert.Null(exception.Value); } // ValidateValue_throws_ValidationException_if_Property_has_RequiredAttribute_and_value_is_invalid() [Fact] public static void TestValidateValueThrowsIfRequiredAttributeInvalid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate)); Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); } [Fact] public static void ValidateValue_succeeds_if_Property_has_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new RequiredAttribute(), new ValidValueStringPropertyAttribute() }; Validator.ValidateValue("Valid Value", validationContext, attributesToValidate); } // ValidateValue_throws_ValidationException_if_Property_has_no_RequiredAttribute_and_value_is_invalid() [Fact] public static void TestValidateValueThrowsIfNoRequiredAttribute() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyWithRequiredAttribute"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; var exception = Assert.Throws<ValidationException>( () => Validator.ValidateValue("Invalid Value", validationContext, attributesToValidate)); Assert.IsType<ValidValueStringPropertyAttribute>(exception.ValidationAttribute); Assert.Equal("ValidValueStringPropertyAttribute.IsValid failed for value Invalid Value", exception.ValidationResult.ErrorMessage); Assert.Equal("Invalid Value", exception.Value); } [Fact] public static void ValidateValue_succeeds_if_Property_has_no_RequiredAttribute_and_value_is_valid() { var validationContext = new ValidationContext(new ToBeValidated()); validationContext.MemberName = "PropertyToBeTested"; var attributesToValidate = new ValidationAttribute[] { new ValidValueStringPropertyAttribute() }; Validator.ValidateValue("Valid Value", validationContext, attributesToValidate); } #endregion ValidateValue [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class ValidValueStringPropertyAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext _) { if (value == null) { return ValidationResult.Success; } var valueAsString = value as string; if ("Valid Value".Equals(valueAsString)) { return ValidationResult.Success; } return new ValidationResult("ValidValueStringPropertyAttribute.IsValid failed for value " + value); } } // Allows easy testing that multiple failures can be reported [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)] public class ValidValueStringPropertyDuplicateAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext _) { if (value == null) { return ValidationResult.Success; } var valueAsString = value as string; if ("Valid Value".Equals(valueAsString)) { return ValidationResult.Success; } return new ValidationResult("ValidValueStringPropertyAttribute.IsValid failed for value " + value); } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class ValidClassAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext _) { if (value == null) { return ValidationResult.Success; } if (value.GetType().Name.ToLowerInvariant().Contains("invalid")) { return new ValidationResult("ValidClassAttribute.IsValid failed for class of type " + value.GetType().FullName); } return ValidationResult.Success; } } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class ValidClassDuplicateAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext _) { if (value == null) { return ValidationResult.Success; } if (value.GetType().Name.ToLowerInvariant().Contains("invalid")) { return new ValidationResult("ValidClassAttribute.IsValid failed for class of type " + value.GetType().FullName); } return ValidationResult.Success; } } public class HasDoubleFailureProperty { [ValidValueStringProperty, ValidValueStringPropertyDuplicate] public string WillAlwaysFailTwice => "This is never valid."; } [ValidClass, ValidClassDuplicate] public class DoublyInvalid { } [ValidClass] public class ToBeValidated { [ValidValueStringProperty] public string PropertyToBeTested { get; set; } public string NoAttributesProperty { get; set; } [Required] [ValidValueStringProperty] public string PropertyWithRequiredAttribute { get; set; } internal string InternalProperty { get; set; } protected string ProtectedProperty { get; set; } private string PrivateProperty { get; set; } public string this[int index] { get { return null; } set { } } public TestEnum EnumProperty { get; set; } public int NonNullableProperty { get; set; } public int? NullableProperty { get; set; } } public enum TestEnum { A = 0 } [ValidClass] public class InvalidToBeValidated { [ValidValueStringProperty] public string PropertyToBeTested { get; set; } public string NoAttributesProperty { get; set; } [Required] [ValidValueStringProperty] public string PropertyWithRequiredAttribute { get; set; } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public enum _TileType{Hex, Square} public enum _TileState{Default, Selected, Walkable, Hostile, AbilityRange} public enum _ListState{Unassigned, Open, Close}; [System.Serializable] public class Wall{ public Transform wallObj; public Tile tile1; public Tile tile2; public float angle; public Wall(Transform obj, Tile t1, Tile t2, float ang){ wallObj=obj; tile1=t1; tile2=t2; if(ang>360) ang-=360; else if (ang<0) ang+=360; angle=ang; } public bool Contains(Tile t1, Tile t2){ if((t1==tile1 || t1==tile2) && (t2==tile1 || t2==tile2)){ return true; } return false; } } public class Tile : MonoBehaviour { public delegate void OnShowUnitInfoHandler(Tile tile); public static event OnShowUnitInfoHandler onShowUnitInfoE; public _TileType type; [HideInInspector] public bool walkable=true; [HideInInspector] public UnitTB unit=null; [HideInInspector] public _TileState state=_TileState.Default; //[HideInInspector] public Obstacle obstacle=null; public Material matNormal; //~ public Material matHighlight; public Material matWalkable; public Material matUnwalkable; public Material matHostile; public Material matAbilityRange; //~ public Material matFriendly; [HideInInspector] public Transform thisT; [HideInInspector] public Vector3 pos; [HideInInspector] [SerializeField] public List<Tile> neighbours=new List<Tile>(); [HideInInspector] [SerializeField] public List<Tile> disconnectedNeighbour=new List<Tile>(); [HideInInspector] public Tile parent; [HideInInspector] public _ListState listState=_ListState.Unassigned; [HideInInspector] public float scoreG; [HideInInspector] public float scoreH; [HideInInspector] public float scoreF; [HideInInspector] public float tempScoreG; [HideInInspector] public CollectibleTB collectible; [HideInInspector] public bool attackableToSelected=false; [HideInInspector] public bool walkableToSelected=false; [HideInInspector] public bool openForPlacement=false; [HideInInspector] public int placementID=-1; [HideInInspector] public int HPGainModifier=0; [HideInInspector] public int APGainModifier=0; [HideInInspector] public int damageModifier=0; [HideInInspector] public int attRangeModifier=0; [HideInInspector] public float attackModifier=0; [HideInInspector] public float defendModifier=0; [HideInInspector] public float criticalModifier=0; [HideInInspector] public float critDefModifier=0; [HideInInspector] public int sightModifier=0; [HideInInspector] public List<UnitAbility> activeUnitAbilityEffectList=new List<UnitAbility>(); [HideInInspector] public List<_CoverType> cover=new List<_CoverType>(); [HideInInspector] public List<Vector3> overlayPos=new List<Vector3>(); [HideInInspector] public List<GameObject> wall=new List<GameObject>(); //for AI analysis [HideInInspector] public List<UnitTB> AIHostileList=new List<UnitTB>(); [HideInInspector] public List<Wall> walls=new List<Wall>(); public virtual void Awake(){ thisT=transform; } // Use this for initialization public virtual void Start () { gameObject.layer=LayerManager.GetLayerTile(); pos=transform.position; //this has been assign right at grid generation, this line is for runtime grid generation if(!walkable){ renderer.material=matUnwalkable; } else{ //cover system, wip if(GameControlTB.EnableCover()){ if(Application.isPlaying) InitCover(); } } if(unit!=null) unit.occupiedTile=this; } //called in edit more to set tile to default public void SetToDefault(){ walkable=true; SetState(_TileState.Default); renderer.enabled=true; openForPlacement=false; } //called in edit more to set tile to openForPlacement public void SetToWalkable(){ walkable=true; SetState(_TileState.Walkable); renderer.enabled=true; openForPlacement=true; } //called in edit more to set tile to unwalkable public void SetToUnwalkable(bool flag){ walkable=false; renderer.material=matUnwalkable; if(flag) renderer.enabled=true; else renderer.enabled=false; openForPlacement=false; } // Update is called once per frame void Update () { } public void SetNeighbours(List<Tile> nn){ neighbours=nn; } public List<Tile> GetNeighbours(){ return neighbours; } public void RemoveNeighbour(Tile tile){ if(tile==null) return; if(neighbours.Contains(tile)){ neighbours.Remove(tile); disconnectedNeighbour.Add(tile); } if(tile.neighbours.Contains(this)){ tile.neighbours.Remove(this); tile.disconnectedNeighbour.Add(this); } } public void AddNeighbour(Tile tile){ if(tile==null) return; if(!neighbours.Contains(tile)){ neighbours.Add(tile); disconnectedNeighbour.Remove(tile); } if(!tile.neighbours.Contains(this)){ tile.neighbours.Add(this); tile.disconnectedNeighbour.Remove(this); } } public Tile AddWall(float angle){ return AddWall(angle, null); } public Tile AddWall(float angle, Obstacle wallPrefab){ Tile tile=null; for(int i=0; i<neighbours.Count; i++){ Vector2 dir=new Vector2(neighbours[i].pos.x-pos.x, neighbours[i].pos.z-pos.z); if(type==_TileType.Hex){ float angleN=((int)(Utility.VectorToAngle(dir))); if(Mathf.Abs(Mathf.DeltaAngle(angle, angleN))<30){ tile=neighbours[i]; break; } } else if(type==_TileType.Square){ float angleN=((int)(Utility.VectorToAngle(dir))); if(Mathf.Abs(Mathf.DeltaAngle(angle, angleN))<45){ tile=neighbours[i]; break; } } } for(int i=0; i<walls.Count; i++){ if(walls[i].Contains(tile, this)){ Debug.Log("wall existed "+tile+" "+this); return null; } } if(tile==null){ Debug.Log("no neighbour "+this); return null; } Vector2 dirV=new Vector2(tile.pos.x-pos.x, tile.pos.z-pos.z); float angleW=Utility.VectorToAngle(dirV); Transform wallT=null; if(wallPrefab!=null){ wallT=(Transform)Instantiate(wallPrefab.transform); Vector3 direction=tile.pos-pos; if(type==_TileType.Hex){ float gridSize=transform.localScale.x/1.1628f; wallT.position=pos+(direction.normalized)*gridSize*0.5f;//+new Vector3(0, gridSize*0.3f, 0); wallT.localScale=new Vector3(gridSize, gridSize, gridSize)*1.2f; } else if(type==_TileType.Square){ float gridSize=transform.localScale.x; wallT.position=pos+(direction.normalized)*gridSize*0.5f;//+new Vector3(0, gridSize*0.3f, 0); wallT.localScale=new Vector3(gridSize, gridSize, gridSize); } float rotOffset=90; wallT.rotation=Quaternion.Euler(0, -(angleW+rotOffset), 0); wallT.parent=transform; } walls.Add(new Wall(wallT, tile, this, angleW)); tile.walls.Add(new Wall(wallT, tile, this, angleW+180)); RemoveNeighbour(tile); return tile; } public Tile RemoveWall(float angle){ Wall wall=null; for(int i=0; i<walls.Count; i++){ if(type==_TileType.Hex){ if(Mathf.Abs(Mathf.DeltaAngle(angle, walls[i].angle))<30){ wall=walls[i]; walls.RemoveAt(i); break; } } else if(type==_TileType.Square){ if(Mathf.Abs(Mathf.DeltaAngle(angle, walls[i].angle))<45){ wall=walls[i]; walls.RemoveAt(i); break; } } } if(wall==null) return null; Tile newNeighbour=null; if(wall.tile1==this) newNeighbour=wall.tile2; else if(wall.tile2==this) newNeighbour=wall.tile1; AddNeighbour(newNeighbour); for(int i=0; i<newNeighbour.walls.Count; i++){ if(newNeighbour.walls[i].Contains(this, newNeighbour)){ newNeighbour.walls.RemoveAt(i); break; } } if(wall.wallObj!=null) DestroyImmediate(wall.wallObj.gameObject); return newNeighbour; } //disable in mobile so it wont interfere with touch input #if !UNITY_IPHONE && !UNITY_ANDROID //function called when mouse cursor enter the area of the tile, default MonoBehaviour method void OnMouseEnter(){ OnTouchMouseEnter(); } //function called when mouse cursor leave the area of the tile, default MonoBehaviour method void OnMouseExit(){ OnTouchMouseExit(); } //function called when mouse cursor enter the area of the tile, default MonoBehaviour method public void OnMouseDown(){ OnTouchMouseDown(); } //onMouseDown for right click //function called when mouse cursor enter the area of the tile, default MonoBehaviour method //used to detech right mouse click on the tile void OnMouseOver(){ if(GameControlTB.IsUnitPlacementState()) return; if(Input.GetMouseButtonDown(1)){ OnRightClick(); } } public void OnRightClick(){ if(onShowUnitInfoE!=null) onShowUnitInfoE(this); } #endif //code execution for when a mouse enter a tile or when a touch first tap on a tile public void OnTouchMouseEnter(){ #if !UNITY_IPHONE && !UNITY_ANDROID if(GameControlTB.IsCursorOnUI(Input.mousePosition)) return; //if(GameControlTB.IsObjectOnUI(pos)) return; #endif if(!walkable && !GridManager.IsInTargetTileSelectMode()) return; GridManager.OnHoverEnter(this); if(unit!=null) UnitControl.hoveredUnit=unit; } //code execution for when a mouse exit a tile and when a touch is land on a previously un-touched tile or an empty space public void OnTouchMouseExit(){ //if(GameControlTB.IsCursorOnUI(Input.mousePosition)) return; //if(GameControlTB.IsObjectOnUI(pos)) return; GridManager.OnHoverExit(); if(!walkable && !GridManager.IsInTargetTileSelectMode()) return; SetToDefaultMat(); if(unit!=null) UnitControl.hoveredUnit=null; } //code execution for when a left mouse click happen on a tile and when a touch is double tap on a tile public void OnTouchMouseDown(){ #if !UNITY_IPHONE && !UNITY_ANDROID if(GameControlTB.IsCursorOnUI(Input.mousePosition)) return; //if(GameControlTB.IsObjectOnUI(pos)) return; #endif if(GameControlTB.IsUnitPlacementState()){ PlaceUnit(); return; } if(GameControlTB.GetTurnMode()!=_TurnMode.SingleUnitPerTurn){ if(!GameControlTB.IsPlayerTurn()){ //if(GameControlTB.turnID!=GameControlTB.GetPlayerFactionTurnID()){ return; } } if(GameControlTB.IsActionInProgress()) return; if(!walkable && !GridManager.IsInTargetTileSelectMode()) return; UnitTB sUnit=UnitControl.selectedUnit; //if a friendly unit has been selected //if(sUnit!=null && sUnit.IsControllable(GameControlTB.GetPlayerFactionID())){ if(sUnit!=null && sUnit.IsControllable()){ //if HexFridManager is actively looking for a target for current selectedUnit if(GridManager.IsInTargetTileSelectMode()){ ManualSelect(); } else{ if(!walkableToSelected && !attackableToSelected){ ManualSelect(); } else{ if(attackableToSelected && unit!=null) sUnit.Attack(unit); else if(walkableToSelected){ sUnit.Move(this); } else Debug.Log("error"); } } return; } else{ ManualSelect(); } } //function called when tile is clicked in unit placement phase void PlaceUnit(){ if(!openForPlacement){ GameControlTB.DisplayMessage("Invalid position"); return; } if(unit==null){ if(placementID==UnitControl.GetPlayerUnitsBeingPlaced().factionID){ UnitControl.PlaceUnitAt(this); } } else if(unit.factionID==UnitControl.GetPlayerUnitsBeingPlaced().factionID) UnitControl.RemoveUnit(unit); } public void SetToDefaultMat(){ SetState(state); } //set the tile state and change the renderer material to match public void SetState(_TileState ts){ if(!walkable){ return; } state=ts; if(!walkable){ renderer.material=matUnwalkable; return; } if(state==_TileState.Default && matNormal!=null) renderer.material=matNormal; else if(state==_TileState.Selected && matNormal!=null) renderer.material=matNormal; else if(state==_TileState.Walkable && matWalkable!=null) renderer.material=matWalkable; else if(state==_TileState.Hostile && matHostile!=null) renderer.material=matHostile; else if(state==_TileState.AbilityRange && matAbilityRange!=null) renderer.material=matAbilityRange; //else if(state==_TileState.Friendly) renderer.material=matFriendly; //else if(state==_TileState.Selected) renderer.material=matHighlight; } //buffer function for select when the selection is initiated by player, check turn mode condition before proceed public void ManualSelect(){ //if not in target select phase for unitAbility if(!GridManager.IsInTargetTileSelectMode()){ if(!GameControlTB.AllowUnitSwitching()){ //Debug.Log("unit swtiching is lock"); return; } _MoveOrder moveOrder=GameControlTB.GetMoveOrder(); //if turn mode and turnOrder doesnt not support unit switching, return if(moveOrder!=_MoveOrder.Free) return; _TurnMode turnMode=GameControlTB.GetTurnMode(); if(turnMode==_TurnMode.FactionSingleUnitPerTurnAll){ if(unit.MovedForTheRound()){ Debug.Log("unit has been moved"); return; } } else if(turnMode==_TurnMode.SingleUnitPerTurn){ //Debug.Log("turn mode not allow switching"); return; } } Select(); } public void Select(){ if(!walkable) return; GridManager.Select(this); } public void SetWalkableToSelectedFlag(){ walkableToSelected=true; } public void ClearUnit(){ unit=null; SetState(_TileState.Default); if(attackableToSelected){ GridManager.ClearIndicatorH(this); attackableToSelected=false; } } public void SetUnit(UnitTB newUnit){ unit=newUnit; if(collectible!=null){ collectible.Trigger(newUnit); } } private int countTillNextTurn=0; void OnNextTurn(){ for(int i=0; i<activeUnitAbilityEffectList.Count; i++){ UnitAbility uAB=activeUnitAbilityEffectList[i]; uAB.countTillNextTurn-=1; if(uAB.countTillNextTurn==0){ if(GameControlTB.GetTurnMode()==_TurnMode.FactionAllUnitPerTurn){ uAB.countTillNextTurn=UnitControl.activeFactionCount; } else{ uAB.countTillNextTurn=UnitControl.GetAllUnitCount(); } bool flag=CalulateEffect(uAB); //false means no more effect active for the ability, remove the ability if(!flag){ activeUnitAbilityEffectList.RemoveAt(i); i-=1; //if not more ability, stop listening to any event if(activeUnitAbilityEffectList.Count==0) UnsubscribeEvent(); } } } //apply the effect, this is placed here so it only runs when there are active effect countTillNextTurn-=1; if(countTillNextTurn==0){ //apply the effect on unit if(unit!=null){ if(HPGainModifier>0) unit.ApplyHeal(HPGainModifier); else if(HPGainModifier<0) unit.ApplyDamage(HPGainModifier); if(APGainModifier!=0) unit.GainAP(APGainModifier); } if(GameControlTB.GetTurnMode()==_TurnMode.FactionAllUnitPerTurn){ countTillNextTurn=UnitControl.activeFactionCount; } else{ countTillNextTurn=UnitControl.GetAllUnitCount(); } } } void OnUnitDestroyed(UnitTB unit){ for(int i=0; i<activeUnitAbilityEffectList.Count; i++){ activeUnitAbilityEffectList[i].countTillNextTurn-=1; } } //calculate the active effect on the tile, called in every new round event bool CalulateEffect(UnitAbility ability){ //loop through all the active effect list for(int j=0; j<ability.effectAttrs.Count; j++){ EffectAttr effectAttr=ability.effectAttrs[j]; effectAttr.duration-=1; //if the effect duration has reach zero, cancel it by changing the modifier if(effectAttr.duration==0){ //commented effect are disabled for tile if(effectAttr.type==_EffectAttrType.HPDamage){ HPGainModifier+=(int)effectAttr.value; } else if(effectAttr.type==_EffectAttrType.HPGain){ HPGainModifier-=(int)effectAttr.value; } else if(effectAttr.type==_EffectAttrType.APDamage){ APGainModifier+=(int)effectAttr.value; } else if(effectAttr.type==_EffectAttrType.APGain){ APGainModifier-=(int)effectAttr.value; } else if(effectAttr.type==_EffectAttrType.Damage){ damageModifier-=(int)effectAttr.value; } //~ else if(effectAttr.type==_EffectAttrType.MovementRange){ //~ movementModifier-=(int)effectAttr.value; //~ } else if(effectAttr.type==_EffectAttrType.AttackRange){ attRangeModifier-=(int)effectAttr.value; } //~ else if(effectAttr.type==_EffectAttrType.Speed){ //~ speedModifier-=(int)effectAttr.value; //~ } else if(effectAttr.type==_EffectAttrType.HitChance){ attackModifier-=effectAttr.value; } else if(effectAttr.type==_EffectAttrType.DodgeChance){ defendModifier-=effectAttr.value; } else if(effectAttr.type==_EffectAttrType.CriticalChance){ criticalModifier-=effectAttr.value; } else if(effectAttr.type==_EffectAttrType.CriticalImmunity){ critDefModifier-=effectAttr.value; } /* //~ else if(effectAttr.type==_EffectAttrType.ExtraAttack){ //~ extraAttackModifier-=1; //~ } //~ else if(effectAttr.type==_EffectAttrType.ExtraCounterAttack){ //~ counterAttackModifier-=1; //~ } //~ else if(effectAttr.type==_EffectAttrType.Stun){ //~ stun-=1; //~ } //~ else if(effectAttr.type==_EffectAttrType.DisableAttack){ //~ attackDisabled-=1; //~ } //~ else if(effectAttr.type==_EffectAttrType.DisableMovement){ //~ movementDisabled-=1; //~ } //~ else if(effectAttr.type==_EffectAttrType.DisableAbility){ //~ abilityDisabled-=1; //~ } */ //remove the effect from the ability ability.effectAttrs.RemoveAt(j); j-=1; } } //if there's no more effect active for the ability, return false, the ability will be removed if(ability.effectAttrs.Count==0){ return false; } return true; } //apply a unit ability to the tile public void ApplyAbility(UnitAbility ability){ //spawn effect if any if(ability.effectTarget!=null){ StartCoroutine(SpawnAbilityEffect(ability.effectTarget, ability.effectTargetDelay, pos)); } //loop through the effect list and change the modifier //commented effect are disabled for tile foreach(EffectAttr effectAttr in ability.effectAttrs){ if(effectAttr.type==_EffectAttrType.HPDamage){ effectAttr.value=Random.Range(effectAttr.value, effectAttr.valueAlt); HPGainModifier-=(int)effectAttr.value; if(unit!=null) unit.ApplyDamage((int)effectAttr.value); } else if(effectAttr.type==_EffectAttrType.HPGain){ effectAttr.value=Random.Range(effectAttr.value, effectAttr.valueAlt); HPGainModifier+=(int)effectAttr.value; if(unit!=null) unit.ApplyHeal((int)effectAttr.value); } else if(effectAttr.type==_EffectAttrType.APDamage){ effectAttr.value=Random.Range(effectAttr.value, effectAttr.valueAlt); APGainModifier+=(int)effectAttr.value; if(unit!=null) unit.GainAP(-(int)effectAttr.value); } else if(effectAttr.type==_EffectAttrType.APGain){ effectAttr.value=Random.Range(effectAttr.value, effectAttr.valueAlt); APGainModifier-=(int)effectAttr.value; if(unit!=null) unit.GainAP((int)effectAttr.value); } else if(effectAttr.type==_EffectAttrType.Damage){ damageModifier+=(int)effectAttr.value; } //~ else if(effectAttr.type==_EffectAttrType.MovementRange){ //~ movementModifier+=(int)effectAttr.value; //~ } else if(effectAttr.type==_EffectAttrType.AttackRange){ attRangeModifier+=(int)effectAttr.value; } //~ else if(effectAttr.type==_EffectAttrType.Speed){ //~ speedModifier+=(int)effectAttr.value; //~ } else if(effectAttr.type==_EffectAttrType.HitChance){ attackModifier+=effectAttr.value; } else if(effectAttr.type==_EffectAttrType.DodgeChance){ defendModifier+=effectAttr.value; } else if(effectAttr.type==_EffectAttrType.CriticalChance){ criticalModifier+=effectAttr.value; } else if(effectAttr.type==_EffectAttrType.CriticalImmunity){ critDefModifier+=effectAttr.value; } //~ else if(effectAttr.type==_EffectAttrType.ExtraAttack){ //~ } //~ else if(effectAttr.type==_EffectAttrType.ExtraCounterAttack){ //~ } //~ else if(effectAttr.type==_EffectAttrType.Stun){ //~ } //~ else if(effectAttr.type==_EffectAttrType.DisableAttack){ //~ } //~ else if(effectAttr.type==_EffectAttrType.DisableMovement){ //~ } //~ else if(effectAttr.type==_EffectAttrType.DisableAbility){ //~ } //~ else if(effectAttr.type==_EffectAttrType.Teleport){ //~ } } if(activeUnitAbilityEffectList.Count==0){ SubscribeEvent(); if(GameControlTB.GetTurnMode()==_TurnMode.FactionAllUnitPerTurn){ countTillNextTurn=UnitControl.activeFactionCount; } else{ countTillNextTurn=UnitControl.GetAllUnitCount(); } } if(GameControlTB.GetTurnMode()==_TurnMode.FactionAllUnitPerTurn){ ability.countTillNextTurn=UnitControl.activeFactionCount; } else{ ability.countTillNextTurn=UnitControl.GetAllUnitCount(); } //add the ability to the list so it can be keep tracked activeUnitAbilityEffectList.Add(ability); } IEnumerator SpawnAbilityEffect(GameObject effect, float delay, Vector3 pos){ yield return new WaitForSeconds(delay); Instantiate(effect, pos, effect.transform.rotation); } void SubscribeEvent(){ //GameControlTB.onNewRoundE += OnNewRound; GameControlTB.onNextTurnE += OnNextTurn; UnitTB.onUnitDestroyedE += OnUnitDestroyed; } void UnsubscribeEvent(){ //GameControlTB.onNewRoundE -= OnNewRound; GameControlTB.onNextTurnE -= OnNextTurn; UnitTB.onUnitDestroyedE -= OnUnitDestroyed; } //******************************************************************************************************************************// //A* related code section //call during a serach to scan through neighbour, check their score against the position passed //process walkable neighbours only, used to search for a walkable path via A* public void ProcessWalkableNeighbour(Tile tile){ for(int i=0; i<neighbours.Count; i++){ if((neighbours[i].walkable && neighbours[i].unit==null) || neighbours[i]==tile){ //if the neightbour state is clean (never evaluated so far in the search) if(neighbours[i].listState==_ListState.Unassigned){ //check the score of G and H and update F, also assign the parent to currentNode neighbours[i].scoreG=scoreG+1; neighbours[i].scoreH=Vector3.Distance(neighbours[i].thisT.position, tile.thisT.position); neighbours[i].UpdateScoreF(); neighbours[i].parent=this; } //if the neighbour state is open (it has been evaluated and added to the open list) else if(neighbours[i].listState==_ListState.Open){ //calculate if the path if using this neighbour node through current node would be shorter compare to previous assigned parent node tempScoreG=scoreG+1; if(neighbours[i].scoreG>tempScoreG){ //if so, update the corresponding score and and reassigned parent neighbours[i].parent=this; neighbours[i].scoreG=tempScoreG; neighbours[i].UpdateScoreF(); } } } } } //call during a serach to scan through neighbour tile, check their score against the position passed //process all neighbours regardless of status, used to calculate distance via A* public void ProcessAllNeighbours(Tile tile){ Vector3 pos=tile.pos; for(int i=0; i<neighbours.Count; i++){ //if the neightbour state is clean (never evaluated so far in the search) if(neighbours[i].listState==_ListState.Unassigned){ //check the score of G and H and update F, also assign the parent to currentNode neighbours[i].scoreG=scoreG+1; neighbours[i].scoreH=Vector3.Distance(neighbours[i].thisT.position, pos); neighbours[i].UpdateScoreF(); neighbours[i].parent=this; } //if the neighbour state is open (it has been evaluated and added to the open list) else if(neighbours[i].listState==_ListState.Open){ //calculate if the path if using this neighbour node through current node would be shorter compare to previous assigned parent node tempScoreG=scoreG+1; if(neighbours[i].scoreG>tempScoreG){ //if so, update the corresponding score and and reassigned parent neighbours[i].parent=this; neighbours[i].scoreG=tempScoreG; neighbours[i].UpdateScoreF(); } } } } void UpdateScoreF(){ scoreF=scoreG+scoreH; } //******************************************************************************************************************************// //cover system related code section void InitCover(){ if(type==_TileType.Square) InitCoverSquare(); else if(type==_TileType.Hex) InitCoverHex(); } void InitCoverHex(){ if(cover.Count!=6){ cover=new List<_CoverType>(); for(int i=0; i<6; i++) cover.Add(_CoverType.None); overlayPos=new List<Vector3>(); for(int i=0; i<6; i++) overlayPos.Add(new Vector3(50000, 50000, 50000)); } if(gameObject.name=="HexTile60" || gameObject.name=="HexTile61"){ Debug.Log(name+" "+neighbours.Count); } List<Tile> adjacentTile=new List<Tile>(); foreach(Tile tile in neighbours) adjacentTile.Add(tile); foreach(Tile tile in disconnectedNeighbour) adjacentTile.Add(tile); LayerMask mask=1<<LayerManager.GetLayerObstacle(); foreach(Tile tile in adjacentTile){ int neighbourID=0; Vector2 dir=new Vector2(tile.transform.position.x-pos.x, tile.transform.position.z-pos.z); float angle=Utility.VectorToAngle(dir); if(angle>0 && angle<60) neighbourID=0; else if(angle>60 && angle<120) neighbourID=1; else if(angle>120 && angle<180) neighbourID=2; else if(angle>180 && angle<240) neighbourID=3; else if(angle>240 && angle<300) neighbourID=4; else if(angle>300 && angle<360) neighbourID=5; float dist=Vector3.Distance(pos, tile.pos); Vector3 direction=tile.pos-pos; float gridSize=GridManager.GetTileSize(); overlayPos[neighbourID]=pos+(direction.normalized)*gridSize*0.475f+new Vector3(0, gridSize*0.3f, 0); RaycastHit hit; if(Physics.Raycast(pos, direction.normalized, out hit, dist, mask)){ Obstacle obs=hit.collider.gameObject.GetComponent<Obstacle>(); if(obs!=null){ cover[neighbourID]=obs.coverType; } } } } void InitCoverSquare(){ if(cover.Count!=4){ cover=new List<_CoverType>(); for(int i=0; i<4; i++) cover.Add(_CoverType.None); overlayPos=new List<Vector3>(); for(int i=0; i<4; i++) overlayPos.Add(new Vector3(50000, 50000, 50000)); } List<Tile> adjacentTile=new List<Tile>(); foreach(Tile tile in neighbours) adjacentTile.Add(tile); foreach(Tile tile in disconnectedNeighbour) adjacentTile.Add(tile); LayerMask mask=1<<LayerManager.GetLayerObstacle(); foreach(Tile tile in adjacentTile){ int neighbourID=0; Vector2 dir=new Vector2(tile.transform.position.x-pos.x, tile.transform.position.z-pos.z); float angle=Utility.VectorToAngle(dir); if(angle>45 && angle<135) neighbourID=1; else if(angle>135 && angle<225) neighbourID=2; else if(angle>225 && angle<315) neighbourID=3; else neighbourID=0; float dist=Vector3.Distance(pos, tile.pos); Vector3 direction=tile.pos-pos; float gridSize=GridManager.GetTileSize(); overlayPos[neighbourID]=pos+(direction.normalized)*gridSize*0.475f+new Vector3(0, gridSize*0.3f, 0); RaycastHit hit; if(Physics.Raycast(pos, direction.normalized, out hit, dist, mask)){ Obstacle obs=hit.collider.gameObject.GetComponent<Obstacle>(); if(obs!=null){ cover[neighbourID]=obs.coverType; } } } } public float GetCoverDefendBonus(Vector3 posS){ if(type==_TileType.Square) return GetCoverDefendBonusSquare(posS); else if(type==_TileType.Hex) return GetCoverDefendBonusHex(posS); return 0; } public float GetCoverDefendBonusHex(Vector3 posS){ if(cover.Count<6){ Debug.Log("error getting cover, cover value not setup properly"); return 0; } Vector2 dir=new Vector2(posS.x-pos.x, posS.z-pos.z); float angle=Utility.VectorToAngle(dir); int coverType=0; if(angle==0) coverType=Mathf.Max((int)cover[0], (int)cover[5]); else if(angle==60) coverType=Mathf.Max((int)cover[0], (int)cover[1]); else if(angle==120) coverType=Mathf.Max((int)cover[1], (int)cover[2]); else if(angle==180) coverType=Mathf.Max((int)cover[2], (int)cover[3]); else if(angle==240) coverType=Mathf.Max((int)cover[3], (int)cover[4]); else if(angle==300) coverType=Mathf.Max((int)cover[4], (int)cover[5]); else if(angle>0 && angle<60) coverType=(int)cover[0]; else if(angle>60 && angle<120) coverType=(int)cover[1]; else if(angle>120 && angle<180) coverType=(int)cover[2]; else if(angle>180 && angle<240) coverType=(int)cover[3]; else if(angle>240 && angle<300) coverType=(int)cover[4]; else if(angle>300 && angle<360) coverType=(int)cover[5]; else Debug.Log("error getting cover, angle exceed 360"); if((_CoverType)coverType==_CoverType.BlockHalf) return GameControlTB.GetCoverHalf(); else if((_CoverType)coverType==_CoverType.BlockFull) return GameControlTB.GetCoverFull(); return 0; } public float GetCoverDefendBonusSquare(Vector3 posS){ if(cover.Count<4){ Debug.Log("error getting cover, cover value not setup properly"); return 0; } Vector2 dir=new Vector2(posS.x-pos.x, posS.z-pos.z); float angle=Utility.VectorToAngle(dir); int coverType=0; if(angle==45) coverType=Mathf.Max((int)cover[0], (int)cover[1]); else if(angle==135) coverType=Mathf.Max((int)cover[1], (int)cover[2]); else if(angle==225) coverType=Mathf.Max((int)cover[2], (int)cover[3]); else if(angle==315) coverType=Mathf.Max((int)cover[3], (int)cover[0]); else if(angle>45 && angle<135) coverType=(int)cover[1]; else if(angle>135 && angle<225) coverType=(int)cover[2]; else if(angle>225 && angle<315) coverType=(int)cover[3]; else if(angle>=0 && angle<45 || angle>315 && angle<360) coverType=(int)cover[0]; else Debug.Log("error getting cover, angle exceed 360"); if((_CoverType)coverType==_CoverType.BlockHalf) return GameControlTB.GetCoverHalf(); else if((_CoverType)coverType==_CoverType.BlockFull) return GameControlTB.GetCoverFull(); return 0; } public _CoverType GetCoverType(Vector3 posS){ if(type==_TileType.Square) return GetCoverTypeSquare(posS); else if(type==_TileType.Hex) return GetCoverTypeHex(posS); return _CoverType.None; } public _CoverType GetCoverTypeHex(Vector3 posS){ if(cover.Count<6){ Debug.Log("error getting cover, cover value not setup properly"); return 0; } Vector2 dir=new Vector2(posS.x-pos.x, posS.z-pos.z); float angle=Utility.VectorToAngle(dir); int coverType=0; if(angle==0) coverType=Mathf.Max((int)cover[0], (int)cover[5]); else if(angle==60) coverType=Mathf.Max((int)cover[0], (int)cover[1]); else if(angle==120) coverType=Mathf.Max((int)cover[1], (int)cover[2]); else if(angle==180) coverType=Mathf.Max((int)cover[2], (int)cover[3]); else if(angle==240) coverType=Mathf.Max((int)cover[3], (int)cover[4]); else if(angle==300) coverType=Mathf.Max((int)cover[4], (int)cover[5]); else if(angle>0 && angle<60) coverType=(int)cover[0]; else if(angle>60 && angle<120) coverType=(int)cover[1]; else if(angle>120 && angle<180) coverType=(int)cover[2]; else if(angle>180 && angle<240) coverType=(int)cover[3]; else if(angle>240 && angle<300) coverType=(int)cover[4]; else if(angle>300 && angle<360) coverType=(int)cover[5]; else Debug.Log("error getting cover, angle exceed 360"); return (_CoverType)coverType; } public _CoverType GetCoverTypeSquare(Vector3 posS){ if(cover.Count<4){ Debug.Log("error getting cover, cover value not setup properly"); return 0; } Vector2 dir=new Vector2(posS.x-pos.x, posS.z-pos.z); float angle=Utility.VectorToAngle(dir); int coverType=0; if(angle==45) coverType=Mathf.Max((int)cover[0], (int)cover[1]); else if(angle==135) coverType=Mathf.Max((int)cover[1], (int)cover[2]); else if(angle==225) coverType=Mathf.Max((int)cover[2], (int)cover[3]); else if(angle==315) coverType=Mathf.Max((int)cover[3], (int)cover[0]); else if(angle>45 && angle<135) coverType=(int)cover[1]; else if(angle>135 && angle<225) coverType=(int)cover[2]; else if(angle>225 && angle<315) coverType=(int)cover[3]; else if(angle>=0 && angle<45 || angle>315 && angle<360) coverType=(int)cover[0]; else Debug.Log("error getting cover, angle exceed 360"); return (_CoverType)coverType; } public bool GotCover(){ bool covered=false; for(int i=0; i<cover.Count; i++){ if(cover[i]!=_CoverType.None){ covered=true; break; } } return covered; } }
// JsonNumber.cs // // Copyright (C) 2006 Andy Kernahan // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // 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 using System; using System.Diagnostics; using System.Globalization; namespace NetServ.Net.Json { /// <summary> /// Represents a JavaScript Object Notation Number data type. This class cannot /// be inherited. /// </summary> [Serializable()] [DebuggerDisplay("{_value}")] public sealed class JsonNumber : JsonTypeSkeleton, IJsonNumber { #region Private Fields. private double _value; #endregion #region Public Interface. /// <summary> /// Defines the smallest Json number. This field is readonly. /// </summary> public static readonly JsonNumber MinValue = new JsonNumber(double.MinValue); /// <summary> /// Defines a Json number with a value of zero. This field is readonly. /// </summary> public static readonly JsonNumber Zero = new JsonNumber(0D); /// <summary> /// Defines the lasrgest Json number. This field is readonly. /// </summary> public static readonly JsonNumber MaxValue = new JsonNumber(double.MaxValue); /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> public JsonNumber(byte value) : this((double)value) { } /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> [CLSCompliant(false)] public JsonNumber(sbyte value) : this((double)value) { } /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> public JsonNumber(short value) : this((double)value) { } /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> [CLSCompliant(false)] public JsonNumber(ushort value) : this((double)value) { } /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> public JsonNumber(int value) : this((double)value) { } /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> [CLSCompliant(false)] public JsonNumber(uint value) : this((double)value) { } /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> public JsonNumber(long value) : this((double)value) { } /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> [CLSCompliant(false)] public JsonNumber(ulong value) : this((double)value) { } /// <summary> /// Initialises a new instance of the JsonNumber class and specifies the /// value. /// </summary> /// <param name="value">The value of the new instance.</param> public JsonNumber(double value) : base(JsonTypeCode.Number) { if(double.IsInfinity(value) || double.IsNegativeInfinity(value) || double.IsNaN(value)) throw new ArgumentOutOfRangeException("value"); _value = value; } /// <summary> /// Writes the contents of this Json type using the specified /// <see cref="NetServ.Net.Json.IJsonWriter"/>. /// </summary> /// <param name="writer">The Json writer.</param> public override void Write(IJsonWriter writer) { if(writer == null) throw new ArgumentNullException("writer"); writer.WriteValue(ToString()); } /// <summary> /// Returns a <see cref="System.String"/> representation of this JsonNumber instance. /// </summary> /// <returns> <see cref="System.String"/> representation of this JsonNumber instance</returns> public override string ToString() { return this.Value.ToString(CultureInfo.InvariantCulture); } /// <summary> /// Returns a <see cref="System.String"/> representation of this JsonNumber instance. /// </summary> /// <param name="format">The format.</param> /// <param name="formatProvider">The culture specific format provider.</param> /// <returns> <see cref="System.String"/> representation of this JsonNumber instance</returns> public string ToString(string format, IFormatProvider formatProvider) { return this.Value.ToString(format, formatProvider); } /// <summary> /// Returns a indicating whether this instance is equal to the specified /// <see cref="System.Object"/>. /// </summary> /// <param name="obj">The object to compare.</param> /// <returns>True if the specified object is equal to this instance, otherwise; /// false.</returns> public override bool Equals(object obj) { if(obj == null) return false; if(obj.GetType() != GetType()) return false; return Equals((JsonNumber)obj); } /// <summary> /// Returns a indicating whether this instance is equal to the specified /// JsonNumber. /// </summary> /// <param name="other">The value to compare.</param> /// <returns>True if the specified instance is equal to this instance, otherwise; /// false.</returns> public bool Equals(JsonNumber other) { return other != null && this.Value == other.Value; } /// <summary> /// Returns a indicating whether this instance is equal to the specified /// <see cref="NetServ.Net.Json.IJsonNumber"/>. /// </summary> /// <param name="other">The value to compare.</param> /// <returns>True if the specified instance is equal to this instance, otherwise; /// false.</returns> public bool Equals(IJsonNumber other) { return other != null && this.Value == other.Value; } /// <summary> /// Returns a indicating whether this instance is equal to the specified /// <see cref="System.Double"/>. /// </summary> /// <param name="other">The value to compare.</param> /// <returns>True if the specified double is equal to this instance, otherwise; /// false.</returns> public bool Equals(double other) { return this.Value == other; } /// <summary> /// Returns a value indicating equality with the specified instance. /// </summary> /// <param name="other">The JsonNumber to compare.</param> /// <returns></returns> public int CompareTo(JsonNumber other) { return other != null ? this.Value.CompareTo(other.Value) : -1; } /// <summary> /// Returns a value indicating equality with the specified instance. /// </summary> /// <param name="other">The <see cref="NetServ.Net.Json.IJsonNumber"/> to compare.</param> /// <returns></returns> public int CompareTo(IJsonNumber other) { return other != null ? this.Value.CompareTo(other.Value) : -1; } /// <summary> /// Returns a value indicating equality with the specified <see cref="System.Double"/>. /// </summary> /// <param name="other">The Double to compare.</param> /// <returns></returns> public int CompareTo(double other) { return this.Value.CompareTo(other); } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>A hash code for this instance.</returns> public override int GetHashCode() { return this.Value.GetHashCode(); } /// <summary> /// Gets the value of this JsonNumber. /// </summary> public double Value { get { return _value; } } /// <summary> /// Determines if the two <see cref="NetServ.Net.Json.JsonNumber"/>s are /// equal. /// </summary> /// <param name="a">The first JsonNumber.</param> /// <param name="b">The second JsonNumber.</param> /// <returns>True if the JsonNumbers are equal, otherwise; false.</returns> public static bool Equals(JsonNumber a, JsonNumber b) { object ao = a; object bo = b; if(ao == bo) return true; if(ao == null || bo == null) return false; return a.Value == b.Value; } /// <summary> /// Equality operator. /// </summary> /// <param name="a">The first JsonNumber.</param> /// <param name="b">The second JsonNumber.</param> /// <returns>True if the JsonNumbers are equal, otherwise; false.</returns> public static bool operator ==(JsonNumber a, JsonNumber b) { return JsonNumber.Equals(a, b); } /// <summary> /// Inequality operator. /// </summary> /// <param name="a">The first JsonNumber.</param> /// <param name="b">The second JsonNumber.</param> /// <returns>True if the JsonNumbers are not equal, otherwise; false.</returns> public static bool operator !=(JsonNumber a, JsonNumber b) { return !JsonNumber.Equals(a, b); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static implicit operator JsonNumber(byte value) { return new JsonNumber(value); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> [CLSCompliant(false)] public static implicit operator JsonNumber(sbyte value) { return new JsonNumber(value); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static implicit operator JsonNumber(short value) { return new JsonNumber(value); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> [CLSCompliant(false)] public static implicit operator JsonNumber(ushort value) { return new JsonNumber(value); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static implicit operator JsonNumber(int value) { return new JsonNumber(value); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> [CLSCompliant(false)] public static implicit operator JsonNumber(uint value) { return new JsonNumber(value); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static implicit operator JsonNumber(long value) { return new JsonNumber(value); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> [CLSCompliant(false)] public static implicit operator JsonNumber(ulong value) { return new JsonNumber(value); } /// <summary> /// Implict conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static implicit operator JsonNumber(double value) { return new JsonNumber(value); } /// <summary> /// Implicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns>This method always returns null.</returns> public static implicit operator JsonNumber(JsonNull value) { return null; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static explicit operator double(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return value.Value; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static explicit operator byte(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return (byte)value.Value; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> [CLSCompliant(false)] public static explicit operator sbyte(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return (sbyte)value.Value; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static explicit operator short(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return (short)value.Value; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> [CLSCompliant(false)] public static explicit operator ushort(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return (ushort)value.Value; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static explicit operator int(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return (int)value.Value; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> [CLSCompliant(false)] public static explicit operator uint(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return (uint)value.Value; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> public static explicit operator long(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return (long)value.Value; } /// <summary> /// Explicit conversion operator. /// </summary> /// <param name="value"></param> /// <returns></returns> [CLSCompliant(false)] public static explicit operator ulong(JsonNumber value) { if(value == null) throw new ArgumentNullException(); return (ulong)value.Value; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.Caching; using Umbraco.Core.Persistence.Factories; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Relators; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Persistence.Repositories { /// <summary> /// Represents a repository for doing CRUD operations for <see cref="DictionaryItem"/> /// </summary> internal class DictionaryRepository : PetaPocoRepositoryBase<int, IDictionaryItem>, IDictionaryRepository { private readonly ILanguageRepository _languageRepository; public DictionaryRepository(IDatabaseUnitOfWork work, ILanguageRepository languageRepository) : base(work) { _languageRepository = languageRepository; } public DictionaryRepository(IDatabaseUnitOfWork work, IRepositoryCacheProvider cache, ILanguageRepository languageRepository) : base(work, cache) { _languageRepository = languageRepository; } #region Overrides of RepositoryBase<int,DictionaryItem> protected override IDictionaryItem PerformGet(int id) { var sql = GetBaseQuery(false) .Where(GetBaseWhereClause(), new {Id = id}) .OrderBy<DictionaryDto>(x => x.UniqueId); var dto = Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql).FirstOrDefault(); if (dto == null) return null; var factory = new DictionaryItemFactory(); var entity = factory.BuildEntity(dto); var list = new List<IDictionaryTranslation>(); foreach (var textDto in dto.LanguageTextDtos) { var language = _languageRepository.Get(textDto.LanguageId); var translationFactory = new DictionaryTranslationFactory(dto.UniqueId, language); list.Add(translationFactory.BuildEntity(textDto)); } entity.Translations = list; //on initial construction we don't want to have dirty properties tracked // http://issues.umbraco.org/issue/U4-1946 ((Entity)entity).ResetDirtyProperties(false); return entity; } protected override IEnumerable<IDictionaryItem> PerformGetAll(params int[] ids) { if (ids.Any()) { foreach (var id in ids) { yield return Get(id); } } else { var dtos = Database.Fetch<DictionaryDto>("WHERE pk > 0"); foreach (var dto in dtos) { yield return Get(dto.PrimaryKey); } } } protected override IEnumerable<IDictionaryItem> PerformGetByQuery(IQuery<IDictionaryItem> query) { var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator<IDictionaryItem>(sqlClause, query); var sql = translator.Translate(); sql.OrderBy<DictionaryDto>(x => x.UniqueId); var dtos = Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql); foreach (var dto in dtos) { yield return Get(dto.PrimaryKey); } } #endregion #region Overrides of PetaPocoRepositoryBase<int,DictionaryItem> protected override Sql GetBaseQuery(bool isCount) { var sql = new Sql(); if(isCount) { sql.Select("COUNT(*)") .From<DictionaryDto>(); } else { sql.Select("*") .From<DictionaryDto>() .InnerJoin<LanguageTextDto>() .On<DictionaryDto, LanguageTextDto>(left => left.UniqueId, right => right.UniqueId); } return sql; } protected override string GetBaseWhereClause() { return "cmsDictionary.pk = @Id"; } protected override IEnumerable<string> GetDeleteClauses() { return new List<string>(); } /// <summary> /// Returns the Top Level Parent Guid Id /// </summary> protected override Guid NodeObjectTypeId { get { return new Guid("41c7638d-f529-4bff-853e-59a0c2fb1bde"); } } #endregion #region Unit of Work Implementation protected override void PersistNewItem(IDictionaryItem entity) { ((DictionaryItem)entity).AddingEntity(); var factory = new DictionaryItemFactory(); var dto = factory.BuildDto(entity); var id = Convert.ToInt32(Database.Insert(dto)); entity.Id = id; var translationFactory = new DictionaryTranslationFactory(entity.Key, null); foreach (var translation in entity.Translations) { var textDto = translationFactory.BuildDto(translation); translation.Id = Convert.ToInt32(Database.Insert(textDto)); translation.Key = entity.Key; } ((ICanBeDirty)entity).ResetDirtyProperties(); } protected override void PersistUpdatedItem(IDictionaryItem entity) { ((Entity)entity).UpdatingEntity(); var factory = new DictionaryItemFactory(); var dto = factory.BuildDto(entity); Database.Update(dto); var translationFactory = new DictionaryTranslationFactory(entity.Key, null); foreach (var translation in entity.Translations) { var textDto = translationFactory.BuildDto(translation); if(translation.HasIdentity) { Database.Update(textDto); } else { translation.Id = Convert.ToInt32(Database.Insert(dto)); translation.Key = entity.Key; } } ((ICanBeDirty)entity).ResetDirtyProperties(); } protected override void PersistDeletedItem(IDictionaryItem entity) { RecursiveDelete(entity.Key); Database.Delete<LanguageTextDto>("WHERE UniqueId = @Id", new { Id = entity.Key}); Database.Delete<DictionaryDto>("WHERE id = @Id", new { Id = entity.Key }); } private void RecursiveDelete(Guid parentId) { var list = Database.Fetch<DictionaryDto>("WHERE parent = @ParentId", new {ParentId = parentId}); foreach (var dto in list) { RecursiveDelete(dto.UniqueId); Database.Delete<LanguageTextDto>("WHERE UniqueId = @Id", new { Id = dto.UniqueId }); Database.Delete<DictionaryDto>("WHERE id = @Id", new { Id = dto.UniqueId }); } } #endregion } }
// 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 Microsoft.Azure.Management.RecoveryServices.Backup { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// ProtectionContainerOperationResultsOperations operations. /// </summary> internal partial class ProtectionContainerOperationResultsOperations : Microsoft.Rest.IServiceOperations<RecoveryServicesBackupClient>, IProtectionContainerOperationResultsOperations { /// <summary> /// Initializes a new instance of the ProtectionContainerOperationResultsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ProtectionContainerOperationResultsOperations(RecoveryServicesBackupClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the RecoveryServicesBackupClient /// </summary> public RecoveryServicesBackupClient Client { get; private set; } /// <summary> /// Fetches the result of any operation on the container. /// </summary> /// <param name='vaultName'> /// The name of the recovery services vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the recovery services vault is /// present. /// </param> /// <param name='fabricName'> /// Fabric name associated with the container. /// </param> /// <param name='containerName'> /// Container name whose information should be fetched. /// </param> /// <param name='operationId'> /// Operation ID which represents the operation whose result needs to be /// fetched. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<ProtectionContainerResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string fabricName, string containerName, string operationId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (vaultName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.SubscriptionId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (fabricName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "fabricName"); } if (containerName == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "containerName"); } if (operationId == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "operationId"); } string apiVersion = "2016-06-01"; // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("fabricName", fabricName); tracingParameters.Add("containerName", containerName); tracingParameters.Add("operationId", operationId); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupFabrics/{fabricName}/protectionContainers/{containerName}/operationResults/{operationId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId)); _url = _url.Replace("{fabricName}", System.Uri.EscapeDataString(fabricName)); _url = _url.Replace("{containerName}", System.Uri.EscapeDataString(containerName)); _url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId)); System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.Azure.AzureOperationResponse<ProtectionContainerResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ProtectionContainerResource>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Xunit; #pragma warning disable 0414 namespace System.Reflection.Tests { public class ConstructorInfoTests { [Fact] public void ConstructorName() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Equal(3, constructors.Length); foreach (ConstructorInfo constructorInfo in constructors) { Assert.Equal(ConstructorInfo.ConstructorName, constructorInfo.Name); } } public static IEnumerable<object[]> Equals_TestData() { ConstructorInfo[] methodSampleConstructors1 = GetConstructors(typeof(ClassWith3Constructors)); ConstructorInfo[] methodSampleConstructors2 = GetConstructors(typeof(ClassWith3Constructors)); yield return new object[] { methodSampleConstructors1[0], methodSampleConstructors2[0], true }; yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[1], true }; yield return new object[] { methodSampleConstructors1[2], methodSampleConstructors2[2], true }; yield return new object[] { methodSampleConstructors1[1], methodSampleConstructors2[2], false }; } [Theory] [MemberData(nameof(Equals_TestData))] public void Equals(ConstructorInfo constructorInfo1, ConstructorInfo constructorInfo2, bool expected) { Assert.Equal(expected, constructorInfo1.Equals(constructorInfo2)); Assert.NotEqual(expected, constructorInfo1 != constructorInfo2); } [Fact] public void GetHashCodeTest() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); foreach (ConstructorInfo constructorInfo in constructors) { Assert.NotEqual(0, constructorInfo.GetHashCode()); } } [Fact] public void Invoke() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Equal(constructors.Length, 3); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[0].Invoke(null); Assert.NotNull(obj); } [Fact] public void Invoke_StaticConstructor_NullObject_NullParameters() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWithStaticConstructor)); Assert.Equal(1, constructors.Length); object obj = constructors[0].Invoke(null, new object[] { }); Assert.Null(obj); } [Fact] public void Invoke_StaticConstructor_ThrowsMemberAccessException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWithStaticConstructor)); Assert.Equal(1, constructors.Length); Assert.Throws<MemberAccessException>(() => constructors[0].Invoke(new object[0])); } [Fact] public void Invoke_OneDimensionalArray() { ConstructorInfo[] constructors = GetConstructors(typeof(object[])); int[] arraylength = { 1, 2, 99, 65535 }; // Try to invoke Array ctors with different lengths foreach (int length in arraylength) { // Create big Array with elements object[] arr = (object[])constructors[0].Invoke(new object[] { length }); Assert.Equal(arr.Length, length); } } [Fact] public void Invoke_OneDimensionalArray_NegativeLengths_ThrowsOverflowException() { ConstructorInfo[] constructors = GetConstructors(typeof(object[])); int[] arraylength = new int[] { -1, -2, -99 }; // Try to invoke Array ctors with different lengths foreach (int length in arraylength) { // Create big Array with elements Assert.Throws<OverflowException>(() => (object[])constructors[0].Invoke(new object[] { length })); } } [Fact] public void Invoke_OneParameter() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[1].Invoke(new object[] { 100 }); Assert.Equal(obj.intValue, 100); } [Fact] public void Invoke_TwoParameters() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj = (ClassWith3Constructors)constructors[2].Invoke(new object[] { 101, "hello" }); Assert.Equal(obj.intValue, 101); Assert.Equal(obj.stringValue, "hello"); } [Fact] public void Invoke_NoParameters_ThowsTargetParameterCountException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Throws<TargetParameterCountException>(() => constructors[2].Invoke(new object[0])); } [Fact] public void Invoke_ParameterMismatch_ThrowsTargetParameterCountException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.Throws<TargetParameterCountException>(() => (ClassWith3Constructors)constructors[2].Invoke(new object[] { 121 })); } [Fact] public void Invoke_ParameterWrongType_ThrowsArgumentException() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); AssertExtensions.Throws<ArgumentException>(null, () => (ClassWith3Constructors)constructors[1].Invoke(new object[] { "hello" })); } [Fact] public void Invoke_ExistingInstance() { // Should not produce a second object. ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); ClassWith3Constructors obj1 = new ClassWith3Constructors(100, "hello"); ClassWith3Constructors obj2 = (ClassWith3Constructors)constructors[2].Invoke(obj1, new object[] { 999, "initialized" }); Assert.Null(obj2); Assert.Equal(obj1.intValue, 999); Assert.Equal(obj1.stringValue, "initialized"); } [Fact] public void Invoke_AbstractClass_ThrowsMemberAccessException() { ConstructorInfo[] constructors = GetConstructors(typeof(ConstructorInfoAbstractBase)); Assert.Throws<MemberAccessException>(() => (ConstructorInfoAbstractBase)constructors[0].Invoke(new object[0])); } [Fact] public void Invoke_SubClass() { ConstructorInfo[] constructors = GetConstructors(typeof(ConstructorInfoDerived)); ConstructorInfoDerived obj = null; obj = (ConstructorInfoDerived)constructors[0].Invoke(new object[] { }); Assert.NotNull(obj); } [Fact] public void Invoke_Struct() { ConstructorInfo[] constructors = GetConstructors(typeof(StructWith1Constructor)); StructWith1Constructor obj; obj = (StructWith1Constructor)constructors[0].Invoke(new object[] { 1, 2 }); Assert.Equal(1, obj.x); Assert.Equal(2, obj.y); } [Fact] public void IsConstructor_ReturnsTrue() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.All(constructors, constructorInfo => Assert.True(constructorInfo.IsConstructor)); } [Fact] public void IsPublic() { ConstructorInfo[] constructors = GetConstructors(typeof(ClassWith3Constructors)); Assert.True(constructors[0].IsPublic); } public static ConstructorInfo[] GetConstructors(Type type) { return type.GetTypeInfo().DeclaredConstructors.ToArray(); } } // Metadata for Reflection public abstract class ConstructorInfoAbstractBase { public ConstructorInfoAbstractBase() { } } public class ConstructorInfoDerived : ConstructorInfoAbstractBase { public ConstructorInfoDerived() { } } public class ClassWith3Constructors { public int intValue = 0; public string stringValue = ""; public ClassWith3Constructors() { } public ClassWith3Constructors(int intValue) { this.intValue = intValue; } public ClassWith3Constructors(int intValue, string stringValue) { this.intValue = intValue; this.stringValue = stringValue; } public string Method1(DateTime dt) => ""; } public static class ClassWithStaticConstructor { static ClassWithStaticConstructor() { } } public struct StructWith1Constructor { public int x; public int y; public StructWith1Constructor(int x, int y) { this.x = x; this.y = y; } } }
#region Disclaimer/Info /////////////////////////////////////////////////////////////////////////////////////////////////// // Subtext WebLog // // Subtext is an open source weblog system that is a fork of the .TEXT // weblog system. // // For updated news and information please visit http://subtextproject.com/ // Subtext is hosted at Google Code at http://code.google.com/p/subtext/ // The development mailing list is at subtext@googlegroups.com // // This project is licensed under the BSD license. See the License.txt file for more information. /////////////////////////////////////////////////////////////////////////////////////////////////// #endregion using System; using System.Globalization; using System.Net; using System.Text; using System.Web; using System.Web.Security; using Subtext.Framework.Security; using Subtext.Framework.Syndication.Compression; using Subtext.Framework.Web.Handlers; namespace Subtext.Framework.Syndication { /// <summary> /// Abstract base class used to respond to requests for /// syndicated feeds such as RSS and ATOM. /// </summary> public abstract class BaseSyndicationHandler : SubtextHttpHandler { const int HttpImUsed = 226; protected BaseSyndicationHandler(ISubtextContext subtextContext) : base(subtextContext) { } protected CachedFeed Feed { get; set; } // TODO: Why is the private setter not used? protected virtual bool RequiresAdminRole { get; private set; } // TODO: Why is the private setter not used? protected virtual bool RequiresHostAdminRole { get; private set; } protected HttpContextBase HttpContext { get { return SubtextContext.HttpContext; } } /// <summary> /// Returns the "If-Modified-Since" HTTP header. This indicates /// the last time the client requested data and is used to /// determine whether new data is to be sent. /// </summary> /// <value></value> protected string LastModifiedHeader { get { return HttpContext.Request.Headers["If-Modified-Since"]; } } /// <summary> /// Returns the "If-None-Match" HTTP header. This is used to indicate /// a conditional GET and is used to implement RFC3229 with feeds /// <see href="http://bobwyman.pubsub.com/main/2004/09/using_rfc3229_w.html"/>. /// </summary> /// <value></value> protected string IfNonMatchHeader { get { return HttpContext.Request.Headers["If-None-Match"]; } } /// <summary> /// Gets the Publish Date of the last feed item received by the client. /// This is used to determine whether the client is up to date /// or whether the client is ready to receive new feed items. /// We will then send just the difference. /// </summary> /// <value></value> protected DateTime PublishDateOfLastFeedItemReceived { get { if (!string.IsNullOrEmpty(IfNonMatchHeader)) { try { return DateTime.Parse(IfNonMatchHeader, CultureInfo.InvariantCulture); } catch (FormatException) { //Swallow it. } } return NullValue.NullDateTime; } } /// <summary> /// Gets a value indicating whether use delta encoding within this request. /// </summary> /// <value> /// <c>true</c> if use delta encoding; otherwise, <c>false</c>. /// </value> protected bool UseDeltaEncoding { get { return Blog.RFC3229DeltaEncodingEnabled && AcceptDeltaEncoding; } } /// <summary> /// Gets the syndication writer. /// </summary> /// <returns></returns> protected abstract BaseSyndicationWriter SyndicationWriter { get; } /// <summary> /// Returns the "Accept-Encoding" value from the HTTP Request header. /// This is a list of encodings that may be sent to the browser. /// </summary> /// <remarks> /// Specifically we're looking for gzip. /// </remarks> /// <value></value> protected string AcceptEncoding { get { string header = HttpContext.Request.Headers["Accept-Encoding"]; if (header != null) { return header; } return string.Empty; } } /// <summary> /// Gets the accept IM header from the request. /// </summary> /// <value></value> protected string AcceptImHeader { get { string header = HttpContext.Request.Headers["A-IM"]; if (header != null) { return header; } return string.Empty; } } /// <summary> /// Gets a value indicating whether the client accepts /// <see href="http://bobwyman.pubsub.com/main/2004/09/using_rfc3229_w.html">RFC3229 Feed Delta /// Encoding</see>. /// </summary> /// <value> /// <c>true</c> if [accepts delta encoding]; otherwise, <c>false</c>. /// </value> protected bool AcceptDeltaEncoding { get { return AcceptImHeader.IndexOf("feed") >= 0; } } /// <summary> /// Gets a value indicating whether the client accepts gzip compression. /// </summary> /// <value> /// <c>true</c> if accepts gzip compression; otherwise, <c>false</c>. /// </value> protected bool AcceptGzipCompression { get { return AcceptEncoding.IndexOf("gzip") >= 0 || AcceptImHeader.IndexOf("gzip") >= 0; } } /// <summary> /// Returns true if the feed is the main feed. False for category feeds and comment feeds. /// </summary> protected abstract bool IsMainfeed { get; } /// <summary> /// Compares the requesting clients <see cref="LastModifiedHeader"/> against /// the date the feed was last updated. If the feed hasn't been updated, then /// it sends a 304 HTTP header indicating such. /// </summary> /// <returns></returns> protected virtual bool IsLocalCacheOk() { string dt = LastModifiedHeader; if (dt != null) { try { DateTime feedDt = DateTime.Parse(dt, CultureInfo.InvariantCulture); DateTime lastUpdated = Blog.DateModifiedUtc; TimeSpan ts = feedDt - lastUpdated; //We need to allow some margin of error. return Math.Abs(ts.TotalMilliseconds) <= 500; } catch (FormatException) { //TODO: Review //swallow it for now. //Some browsers send a funky last modified header. //We don't want to throw an exception in those cases. } } return false; } /// <summary> /// Returns whether or not the http cache is OK. /// </summary> /// <returns></returns> protected virtual bool IsHttpCacheOk() { if (HttpContext.Cache == null) { Feed = null; return false; } Feed = HttpContext.Cache[CacheKey(PublishDateOfLastFeedItemReceived)] as CachedFeed; if (Feed == null) { return false; } return Feed.LastModifiedUtc == Blog.DateModifiedUtc; } /// <summary> /// Send the HTTP status code 304 to the response this instance. /// </summary> private void Send304() { HttpContext.Response.StatusCode = 304; } /// <summary> /// Processs the feed. Responds to the incoming request with the /// contents of the feed. /// </summary> protected virtual void ProcessFeed() { if (RedirectToFeedBurnerIfNecessary()) { return; } // Checks Last Modified Header. if (IsLocalCacheOk()) { Send304(); return; } // Checks our cache against last modified header. if (!IsHttpCacheOk()) { Feed = BuildFeed(); if (Feed != null) { if (UseDeltaEncoding && Feed.ClientHasAllFeedItems) { Send304(); return; } Cache(Feed); } } WriteFeed(); } /// <summary> /// Returns the key used to cache this feed. /// </summary> /// <param name="dateLastViewedFeedItemPublished">Date last viewed feed item published.</param> /// <returns></returns> protected abstract string CacheKey(DateTime dateLastViewedFeedItemPublished); protected abstract void Cache(CachedFeed feed); protected virtual CachedFeed BuildFeed() { var feed = new CachedFeed { LastModifiedUtc = Blog.DateModifiedUtc }; BaseSyndicationWriter writer = SyndicationWriter; feed.Xml = writer.Xml; feed.ClientHasAllFeedItems = writer.ClientHasAllFeedItems; feed.Etag = writer.DateLastViewedFeedItemPublishedUtc.ToString(CultureInfo.InvariantCulture); feed.LatestFeedItemPublishDate = writer.DateLastViewedFeedItemPublishedUtc; return feed; } /// <summary> /// Writes the feed to the response. /// </summary> protected virtual void WriteFeed() { string encoding = null; if (Feed != null) { if (Blog.UseSyndicationCompression && AcceptGzipCompression) { // We're GZip Encoding! SyndicationCompressionFilter filter = SyndicationCompressionHelper.GetFilterForScheme( AcceptEncoding, HttpContext.Response.Filter); if (filter != null) { encoding = filter.ContentEncoding; HttpContext.Response.Filter = filter.Filter; } } if (encoding == null) { HttpContext.Response.ContentEncoding = Encoding.UTF8; } HttpContext.Response.ContentType = "text/xml"; HttpContext.Response.Cache.SetCacheability(HttpCacheability.Public); HttpContext.Response.Cache.SetLastModified(Feed.LastModifiedUtc); HttpContext.Response.Cache.SetETag(Feed.Etag); if (AcceptGzipCompression) { HttpContext.Response.AddHeader("IM", "feed, gzip"); } else { HttpContext.Response.AddHeader("IM", "feed"); } if (UseDeltaEncoding) { HttpContext.Response.StatusCode = HttpImUsed; //IM Used } else { HttpContext.Response.StatusCode = (int)HttpStatusCode.OK; } HttpContext.Response.Write(Feed.Xml); } } /// <summary> /// Processs the request and sends the feed to the response. /// </summary> public override void ProcessRequest() { if ((RequiresAdminRole && !SubtextContext.User.IsAdministrator()) || (RequiresHostAdminRole && !SubtextContext.User.IsHostAdministrator())) { FormsAuthentication.RedirectToLoginPage(); return; } ProcessFeed(); } // Adapted from DasBlog private bool RedirectToFeedBurnerIfNecessary() { //If we are using FeedBurner, only allow them to get our feed... if (!String.IsNullOrEmpty(Blog.RssProxyUrl)) { string userAgent = HttpContext.Request.UserAgent; if (!String.IsNullOrEmpty(userAgent)) { // If they aren't FeedBurner and they aren't asking for a category or comment rss, redirect them! if (!userAgent.StartsWith("FeedBurner") && IsMainfeed) { HttpContext.Response.RedirectPermanent(SubtextContext.UrlHelper.RssProxyUrl(SubtextContext.Blog).ToString()); return true; } } } return false; } } }
// <copyright file="By.cs" company="WebDriver Committers"> // Copyright 2015 Software Freedom Conservancy // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.ObjectModel; using System.Text.RegularExpressions; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium { /// <summary> /// Provides a mechanism by which to find elements within a document. /// </summary> /// <remarks>It is possible to create your own locating mechanisms for finding documents. /// In order to do this,subclass this class and override the protected methods. However, /// it is expected that that all subclasses rely on the basic finding mechanisms provided /// through static methods of this class. An example of this can be found in OpenQA.Support.ByIdOrName /// </remarks> [Serializable] public class By { private string description = "OpenQA.Selenium.By"; private Func<ISearchContext, IWebElement> findElementMethod; private Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod; /// <summary> /// Initializes a new instance of the <see cref="By"/> class. /// </summary> protected By() { } /// <summary> /// Initializes a new instance of the <see cref="By"/> class using the given functions to find elements. /// </summary> /// <param name="findElementMethod">A function that takes an object implementing <see cref="ISearchContext"/> /// and returns the found <see cref="IWebElement"/>.</param> /// <param name="findElementsMethod">A function that takes an object implementing <see cref="ISearchContext"/> /// and returns a <see cref="ReadOnlyCollection{T}"/> of the found<see cref="IWebElement">IWebElements</see>. /// <see cref="IWebElement">IWebElements</see>/>.</param> protected By(Func<ISearchContext, IWebElement> findElementMethod, Func<ISearchContext, ReadOnlyCollection<IWebElement>> findElementsMethod) { this.findElementMethod = findElementMethod; this.findElementsMethod = findElementsMethod; } /// <summary> /// Gets or sets the value of the description for this <see cref="By"/> class instance. /// </summary> protected string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Gets or sets the method used to find a single element matching specified criteria. /// </summary> protected Func<ISearchContext, IWebElement> FindElementMethod { get { return this.findElementMethod; } set { this.findElementMethod = value; } } /// <summary> /// Gets or sets the method used to find all elements matching specified criteria. /// </summary> protected Func<ISearchContext, ReadOnlyCollection<IWebElement>> FindElementsMethod { get { return this.findElementsMethod; } set { this.findElementsMethod = value; } } /// <summary> /// Gets a mechanism to find elements by their ID. /// </summary> /// <param name="idToFind">The ID to find.</param> /// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns> public static By Id(string idToFind) { if (idToFind == null) { throw new ArgumentNullException("idToFind", "Cannot find elements with a null id attribute."); } By by = new By(); by.findElementMethod = (ISearchContext context) => ((IFindsById)context).FindElementById(idToFind); by.findElementsMethod = (ISearchContext context) => ((IFindsById)context).FindElementsById(idToFind); by.description = "By.Id: " + idToFind; return by; } /// <summary> /// Gets a mechanism to find elements by their link text. /// </summary> /// <param name="linkTextToFind">The link text to find.</param> /// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns> public static By LinkText(string linkTextToFind) { if (linkTextToFind == null) { throw new ArgumentNullException("linkTextToFind", "Cannot find elements when link text is null."); } By by = new By(); by.findElementMethod = (ISearchContext context) => ((IFindsByLinkText)context).FindElementByLinkText(linkTextToFind); by.findElementsMethod = (ISearchContext context) => ((IFindsByLinkText)context).FindElementsByLinkText(linkTextToFind); by.description = "By.LinkText: " + linkTextToFind; return by; } /// <summary> /// Gets a mechanism to find elements by their name. /// </summary> /// <param name="nameToFind">The name to find.</param> /// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns> public static By Name(string nameToFind) { if (nameToFind == null) { throw new ArgumentNullException("nameToFind", "Cannot find elements when name text is null."); } By by = new By(); by.findElementMethod = (ISearchContext context) => ((IFindsByName)context).FindElementByName(nameToFind); by.findElementsMethod = (ISearchContext context) => ((IFindsByName)context).FindElementsByName(nameToFind); by.description = "By.Name: " + nameToFind; return by; } /// <summary> /// Gets a mechanism to find elements by an XPath query. /// When searching within a WebElement using xpath be aware that WebDriver follows standard conventions: /// a search prefixed with "//" will search the entire document, not just the children of this current node. /// Use ".//" to limit your search to the children of this WebElement. /// </summary> /// <param name="xpathToFind">The XPath query to use.</param> /// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns> public static By XPath(string xpathToFind) { if (xpathToFind == null) { throw new ArgumentNullException("xpathToFind", "Cannot find elements when the XPath expression is null."); } By by = new By(); by.findElementMethod = (ISearchContext context) => ((IFindsByXPath)context).FindElementByXPath(xpathToFind); by.findElementsMethod = (ISearchContext context) => ((IFindsByXPath)context).FindElementsByXPath(xpathToFind); by.description = "By.XPath: " + xpathToFind; return by; } /// <summary> /// Gets a mechanism to find elements by their CSS class. /// </summary> /// <param name="classNameToFind">The CSS class to find.</param> /// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns> /// <remarks>If an element has many classes then this will match against each of them. /// For example if the value is "one two onone", then the following values for the /// className parameter will match: "one" and "two".</remarks> public static By ClassName(string classNameToFind) { if (classNameToFind == null) { throw new ArgumentNullException("classNameToFind", "Cannot find elements when the class name expression is null."); } if (new Regex(".*\\s+.*").IsMatch(classNameToFind)) { throw new IllegalLocatorException("Compound class names are not supported. Consider searching for one class name and filtering the results."); } By by = new By(); by.findElementMethod = (ISearchContext context) => ((IFindsByClassName)context).FindElementByClassName(classNameToFind); by.findElementsMethod = (ISearchContext context) => ((IFindsByClassName)context).FindElementsByClassName(classNameToFind); by.description = "By.ClassName[Contains]: " + classNameToFind; return by; } /// <summary> /// Gets a mechanism to find elements by a partial match on their link text. /// </summary> /// <param name="partialLinkTextToFind">The partial link text to find.</param> /// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns> public static By PartialLinkText(string partialLinkTextToFind) { By by = new By(); by.findElementMethod = (ISearchContext context) => ((IFindsByPartialLinkText)context).FindElementByPartialLinkText(partialLinkTextToFind); by.findElementsMethod = (ISearchContext context) => ((IFindsByPartialLinkText)context).FindElementsByPartialLinkText(partialLinkTextToFind); by.description = "By.PartialLinkText: " + partialLinkTextToFind; return by; } /// <summary> /// Gets a mechanism to find elements by their tag name. /// </summary> /// <param name="tagNameToFind">The tag name to find.</param> /// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns> public static By TagName(string tagNameToFind) { if (tagNameToFind == null) { throw new ArgumentNullException("tagNameToFind", "Cannot find elements when name tag name is null."); } By by = new By(); by.findElementMethod = (ISearchContext context) => ((IFindsByTagName)context).FindElementByTagName(tagNameToFind); by.findElementsMethod = (ISearchContext context) => ((IFindsByTagName)context).FindElementsByTagName(tagNameToFind); by.description = "By.TagName: " + tagNameToFind; return by; } /// <summary> /// Gets a mechanism to find elements by their cascading style sheet (CSS) selector. /// </summary> /// <param name="cssSelectorToFind">The CSS selector to find.</param> /// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns> public static By CssSelector(string cssSelectorToFind) { if (cssSelectorToFind == null) { throw new ArgumentNullException("cssSelectorToFind", "Cannot find elements when name CSS selector is null."); } By by = new By(); by.findElementMethod = (ISearchContext context) => ((IFindsByCssSelector)context).FindElementByCssSelector(cssSelectorToFind); by.findElementsMethod = (ISearchContext context) => ((IFindsByCssSelector)context).FindElementsByCssSelector(cssSelectorToFind); by.description = "By.CssSelector: " + cssSelectorToFind; return by; } /// <summary> /// Determines if two <see cref="By"/> instances are equal. /// </summary> /// <param name="one">One instance to compare.</param> /// <param name="two">The other instance to compare.</param> /// <returns><see langword="true"/> if the two instances are equal; otherwise, <see langword="false"/>.</returns> public static bool operator ==(By one, By two) { // If both are null, or both are same instance, return true. if (object.ReferenceEquals(one, two)) { return true; } // If one is null, but not both, return false. if (((object)one == null) || ((object)two == null)) { return false; } return one.Equals(two); } /// <summary> /// Determines if two <see cref="By"/> instances are unequal. /// </summary>s /// <param name="one">One instance to compare.</param> /// <param name="two">The other instance to compare.</param> /// <returns><see langword="true"/> if the two instances are not equal; otherwise, <see langword="false"/>.</returns> public static bool operator !=(By one, By two) { return !(one == two); } /// <summary> /// Finds the first element matching the criteria. /// </summary> /// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param> /// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns> public virtual IWebElement FindElement(ISearchContext context) { return this.findElementMethod(context); } /// <summary> /// Finds all elements matching the criteria. /// </summary> /// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param> /// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see> /// matching the current criteria, or an empty list if nothing matches.</returns> public virtual ReadOnlyCollection<IWebElement> FindElements(ISearchContext context) { return this.findElementsMethod(context); } /// <summary> /// Gets a string representation of the finder. /// </summary> /// <returns>The string displaying the finder content.</returns> public override string ToString() { return this.description; } /// <summary> /// Determines whether the specified <see cref="System.Object">Object</see> is equal /// to the current <see cref="System.Object">Object</see>. /// </summary> /// <param name="obj">The <see cref="System.Object">Object</see> to compare with the /// current <see cref="System.Object">Object</see>.</param> /// <returns><see langword="true"/> if the specified <see cref="System.Object">Object</see> /// is equal to the current <see cref="System.Object">Object</see>; otherwise, /// <see langword="false"/>.</returns> public override bool Equals(object obj) { var other = obj as By; // TODO(dawagner): This isn't ideal return other != null && this.description.Equals(other.description); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns>A hash code for the current <see cref="System.Object">Object</see>.</returns> public override int GetHashCode() { return this.description.GetHashCode(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Xml; using System.Xml.Linq; using Rhino.ServiceBus.Exceptions; using Rhino.ServiceBus.Internal; using System.Linq; using Rhino.ServiceBus.DataStructures; namespace Rhino.ServiceBus.Serializers { public class XmlMessageSerializer : IMessageSerializer { private const int MaxNumberOfAllowedItemsInCollection = 256; private readonly IReflection reflection; private readonly IServiceLocator serviceLocator; private readonly Hashtable<Type, bool> typeHasConvertorCache = new Hashtable<Type, bool>(); private ICustomElementSerializer[] customElementSerializers; private IElementSerializationBehavior[] elementSerializationBehaviors; public XmlMessageSerializer(IReflection reflection, IServiceLocator serviceLocator ) { this.reflection = reflection; this.serviceLocator = serviceLocator; customElementSerializers = this.serviceLocator.ResolveAll<ICustomElementSerializer>().ToArray(); elementSerializationBehaviors = this.serviceLocator.ResolveAll<IElementSerializationBehavior>().ToArray(); } public void Serialize(object[] messages, Stream messageStream) { if(messages.Length> MaxNumberOfAllowedItemsInCollection) throw new UnboundedResultSetException("A message batch is limited to 256 messages"); var namespaces = GetNamespaces(messages); var messagesElement = new XElement(namespaces["esb"] + "messages"); var xml = new XDocument(messagesElement); foreach (var m in messages) { if (m == null) continue; try { WriteObject(reflection.GetNameForXml(m.GetType()), m, messagesElement, namespaces); } catch (Exception e) { throw new SerializationException("Could not serialize " + m.GetType() + ".", e); } } messagesElement.Add( namespaces.Select(x => new XAttribute(XNamespace.Xmlns + x.Key, x.Value)) ); var streamWriter = new StreamWriter(messageStream); var writer = XmlWriter.Create(streamWriter, new XmlWriterSettings { Indent = true, Encoding = Encoding.UTF8 }); if (writer == null) throw new InvalidOperationException("Could not create xml writer from stream"); xml.WriteTo(writer); writer.Flush(); streamWriter.Flush(); } private void WriteObject(string name, object value, XContainer parent, IDictionary<string, XNamespace> namespaces) { if(HaveCustomValueConvertor(value.GetType())) { var valueConvertorType = reflection.GetGenericTypeOf(typeof (IValueConvertor<>), value); var convertor = serviceLocator.Resolve(valueConvertorType); var elementName = GetXmlNamespace(namespaces, value.GetType()) + name; var convertedValue = reflection.InvokeToElement(convertor, value, v => GetXmlNamespace(namespaces, v)); convertedValue = ApplyMessageSerializationBehaviorIfNecessary(value.GetType(), convertedValue); parent.Add(new XElement(elementName, convertedValue)); } else if(HaveCustomSerializer(value.GetType())) { var customSerializer = customElementSerializers.First(s => s.CanSerialize(value.GetType())); var elementName = GetXmlNamespace(namespaces, value.GetType()) + name; var element = customSerializer.ToElement(value, v => GetXmlNamespace(namespaces, v)); var customElement = new XElement(elementName, element); customElement = ApplyMessageSerializationBehaviorIfNecessary(value.GetType(), customElement); parent.Add(customElement); } else if (ShouldPutAsString(value)) { var elementName = GetXmlNamespace(namespaces, value.GetType()) + name; parent.Add(new XElement(elementName, FormatAsString(value))); } else if (value is byte[]) { var elementName = GetXmlNamespace(namespaces, typeof(byte[])) + name; parent.Add(new XElement(elementName, Convert.ToBase64String((byte[]) value))); } else if (ShouldTreatAsDictionary(value.GetType())) { XElement list = GetContentWithNamespace(value, namespaces, name); parent.Add(list); var itemCount = 0; foreach (var item in ((IEnumerable)value)) { if (item == null) continue; itemCount += 1; if (itemCount > MaxNumberOfAllowedItemsInCollection) throw new UnboundedResultSetException("You cannot send collections with more than 256 items (" + value + " " + name + ")"); var entry = new XElement("entry"); var keyProp = reflection.Get(item, "Key"); if (keyProp == null) continue; WriteObject("Key", keyProp, entry, namespaces); var propVal = reflection.Get(item, "Value"); if (propVal != null) { WriteObject("Value", propVal, entry, namespaces); } list.Add(entry); } } else if (value is IEnumerable) { XElement list = GetContentWithNamespace(value, namespaces, name); parent.Add(list); var itemCount = 0; foreach (var item in ((IEnumerable)value)) { if (item == null) continue; itemCount += 1; if (itemCount > MaxNumberOfAllowedItemsInCollection) throw new UnboundedResultSetException("You cannot send collections with more than 256 items (" + value + " " + name + ")"); WriteObject("value", item, list, namespaces); } } else { XElement content = GetContentWithNamespace(value, namespaces, name); foreach (var property in reflection.GetProperties(value)) { var propVal = reflection.Get(value, property); if (propVal == null) continue; WriteObject(property, propVal, content, namespaces); } content = ApplyMessageSerializationBehaviorIfNecessary(value.GetType(), content); parent.Add(content); } } private static bool ShouldTreatAsDictionary(Type type) { if (type.IsGenericType == false) return false; var genericArguments = type.GetGenericArguments(); if (genericArguments.Length != 2) return false; var interfaceType = typeof (IDictionary<,>).MakeGenericType(genericArguments); if (interfaceType.IsAssignableFrom(type) == false) return false; return true; } private XElement ApplyMessageSerializationBehaviorIfNecessary(Type messageType, XElement element) { foreach (var afterSerializedBehavior in elementSerializationBehaviors) { if (afterSerializedBehavior.ShouldApplyBehavior(messageType)) return afterSerializedBehavior.ApplyElementBehavior(element); } return element; } private XElement ApplyMessageDeserializationBehaviorIfNecessary(Type messageType, XElement element) { foreach (var afterSerializedBehavior in elementSerializationBehaviors) { if (afterSerializedBehavior.ShouldApplyBehavior(messageType)) return afterSerializedBehavior.RemoveElementBehavior(element); } return element; } private XNamespace GetXmlNamespace(IDictionary<string, XNamespace> namespaces, Type type) { var ns = reflection.GetNamespacePrefixForXml(type); XNamespace xmlNs; if (namespaces.TryGetValue(ns, out xmlNs) == false) { namespaces[ns] = xmlNs = reflection.GetNamespaceForXml(type); } return xmlNs; } private bool HaveCustomSerializer(Type type) { return customElementSerializers .Any(s => s.CanSerialize(type)); } private bool HaveCustomValueConvertor(Type type) { bool? hasConvertor = null; typeHasConvertorCache.Read( reader => { bool val; if (reader.TryGetValue(type, out val)) hasConvertor = val; }); if (hasConvertor != null) return hasConvertor.Value; var convertorType = reflection.GetGenericTypeOf(typeof(IValueConvertor<>),type); var component = serviceLocator.CanResolve(convertorType); typeHasConvertorCache.Write(writer => writer.Add(type, component)); return component; } private XElement GetContentWithNamespace(object value, IDictionary<string, XNamespace> namespaces, string name) { var type = value.GetType(); var xmlNsAlias = reflection.GetNamespacePrefixForXml(type); XNamespace xmlNs; if (namespaces.TryGetValue(xmlNsAlias, out xmlNs) == false) { namespaces[xmlNsAlias] = xmlNs = reflection.GetNamespaceForXml(type); } return new XElement(xmlNs + name); } private static bool ShouldPutAsString(object value) { return value is ValueType || value is string || value is Uri; } public static object FromString(Type type, string value) { if (type == typeof(string)) return value; if (type == typeof(Uri)) return new Uri(value); if (type.IsPrimitive) return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); if (type == typeof(Guid)) return new Guid(value); if (type == typeof(DateTime)) return DateTime.Parse(value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); if (type == typeof(DateTimeOffset)) return XmlConvert.ToDateTimeOffset(value); if (type == typeof(TimeSpan)) return XmlConvert.ToTimeSpan(value); if (type.IsEnum) return Enum.Parse(type, value); if (type == typeof(decimal)) return decimal.Parse(value, CultureInfo.InvariantCulture); throw new SerializationException("Don't know how to deserialize type: " + type + " from '" + value + "'"); } private static string FormatAsString(object value) { if (value == null) return string.Empty; if (value is bool) return value.ToString().ToLower(); if (value is string) return value as string; if (value is Uri) return value.ToString(); if (value is DateTime) return ((DateTime)value).ToString("o", CultureInfo.InvariantCulture); if(value is DateTimeOffset) return XmlConvert.ToString((DateTimeOffset)value); if (value is TimeSpan) { var ts = (TimeSpan)value; return string.Format("P0Y0M{0}DT{1}H{2}M{3}S", ts.Days, ts.Hours, ts.Minutes, ts.Seconds); } if (value is Guid) return ((Guid)value).ToString(); if (value is decimal) return ((decimal) value).ToString(CultureInfo.InvariantCulture); if (value is double) return ((double)value).ToString(CultureInfo.InvariantCulture); if (value is float) return ((float)value).ToString(CultureInfo.InvariantCulture); return value.ToString(); } private IDictionary<string, XNamespace> GetNamespaces(object[] mesages) { var namespaces = new Dictionary<string, XNamespace> { {"esb", "http://servicebus.hibernatingrhinos.com/2008/12/20/esb"}, }; foreach (var msg in mesages) { if (msg == null) continue; var type = msg.GetType(); namespaces[reflection.GetNamespacePrefixForXml(type)] = reflection.GetNamespaceForXml(type); } return namespaces; } public object[] Deserialize(Stream message) { var namespaces = GetNamespaces(new object[0]); var document = XDocument.Load(XmlReader.Create(message)); if (document.Root == null) throw new SerializationException("document doesn't have root element"); if (document.Root.Name != namespaces["esb"] + "messages") throw new SerializationException("message doesn't have root element named 'messages'"); var msgs = new List<object>(); foreach (var element in document.Root.Elements()) { var type = reflection.GetTypeFromXmlNamespace(element.Name.NamespaceName); if (type==null) { throw new SerializationException("Cannot find root message type: " + element.Name.Namespace); } var msg = ReadObject(type, element); msgs.Add(msg); } return msgs.ToArray(); } private object ReadObject(Type type, XElement element) { if (type == null) throw new ArgumentNullException("type"); element = ApplyMessageDeserializationBehaviorIfNecessary(type, element); if(HaveCustomValueConvertor(type)) { var convertorType = reflection.GetGenericTypeOf(typeof(IValueConvertor<>),type); var convertor = serviceLocator.Resolve(convertorType); return reflection.InvokeFromElement(convertor, element); } if(HaveCustomSerializer(type)) { var customSerializer = customElementSerializers.First(s => s.CanSerialize(type)); return customSerializer.FromElement(type, element); } if(type == typeof(byte[])) { return Convert.FromBase64String(element.Value); } if (CanParseFromString(type)) { return FromString(type, element.Value); } if(ShouldTreatAsDictionary(type)) { return ReadDictionary(type, element); } if (typeof(IEnumerable).IsAssignableFrom(type)) { return ReadList(type, element); } object instance = reflection.CreateInstance(type); foreach (var prop in element.Elements()) { var property = prop; reflection.Set(instance, prop.Name.LocalName, typeFromProperty => { var propType = reflection.GetTypeFromXmlNamespace(property.Name.NamespaceName); return ReadObject(propType ?? typeFromProperty, property); }); } return instance; } private static bool CanParseFromString(Type type) { if (type.IsPrimitive) return true; if (type == typeof(string)) return true; if (type == typeof(Uri)) return true; if (type == typeof(DateTime)) return true; if (type == typeof(DateTimeOffset)) return true; if (type == typeof(TimeSpan)) return true; if (type == typeof(Guid)) return true; if (type.IsEnum) return true; if (type == typeof(decimal)) return true; return false; } private object ReadList(Type type, XContainer element) { object instance; Type elementType; if (type.IsArray) { instance = reflection.CreateInstance(type, element.Elements().Count()); elementType = type.GetElementType(); } else { instance = reflection.CreateInstance(type); elementType = type.GetGenericArguments()[0]; } int index = 0; var array = instance as Array; foreach (var value in element.Elements()) { var itemType = reflection.GetTypeFromXmlNamespace(value.Name.NamespaceName); object o = ReadObject(itemType ?? elementType, value); if (array != null) array.SetValue(o, index); else reflection.InvokeAdd(instance, o); index += 1; } return instance; } private object ReadDictionary(Type type, XContainer element) { object instance = reflection.CreateInstance(type); var genericArguments = type.GetGenericArguments(); var keyType = genericArguments[0]; var valueType = genericArguments[1]; foreach (var entry in element.Elements()) { var elements = entry.Elements().ToArray(); var itemKeyType = reflection.GetTypeFromXmlNamespace(elements[0].Name.NamespaceName); object key = ReadObject(itemKeyType ?? keyType, elements[0]); object value = null; if (elements.Length > 1) { var itemValueType = reflection.GetTypeFromXmlNamespace(elements[1].Name.NamespaceName); value = ReadObject(itemValueType ?? valueType, elements[1]); } reflection.InvokeAdd(instance, key, value); } return instance; } } }
// 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.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { public abstract class ExpressionCompiler : IDkmClrExpressionCompiler, IDkmClrExpressionCompilerCallback, IDkmModuleModifiedNotification, IDkmModuleInstanceUnloadNotification { static ExpressionCompiler() { FatalError.Handler = FailFast.OnFatalException; } DkmCompiledClrLocalsQuery IDkmClrExpressionCompiler.GetClrLocalVariableQuery( DkmInspectionContext inspectionContext, DkmClrInstructionAddress instructionAddress, bool argumentsOnly) { try { var moduleInstance = instructionAddress.ModuleInstance; var runtimeInstance = instructionAddress.RuntimeInstance; var aliases = argumentsOnly ? ImmutableArray<Alias>.Empty : GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying. string error; var r = this.CompileWithRetry( moduleInstance, runtimeInstance.GetMetadataBlocks(moduleInstance.AppDomain), (blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly), (context, diagnostics) => { var builder = ArrayBuilder<LocalAndMethod>.GetInstance(); string typeName; var assembly = context.CompileGetLocals( builder, argumentsOnly, aliases, diagnostics, out typeName, testData: null); Debug.Assert((builder.Count == 0) == (assembly.Count == 0)); var locals = new ReadOnlyCollection<DkmClrLocalVariableInfo>(builder.SelectAsArray(ToLocalVariableInfo)); builder.Free(); return new GetLocalsResult(typeName, locals, assembly); }, out error); return DkmCompiledClrLocalsQuery.Create(runtimeInstance, null, this.CompilerId, r.Assembly, r.TypeName, r.Locals); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } private static ImmutableArray<Alias> GetAliases(DkmClrRuntimeInstance runtimeInstance, DkmInspectionContext inspectionContext) { var dkmAliases = runtimeInstance.GetAliases(inspectionContext); if (dkmAliases == null) { return ImmutableArray<Alias>.Empty; } var builder = ArrayBuilder<Alias>.GetInstance(dkmAliases.Count); foreach (var dkmAlias in dkmAliases) { builder.Add(new Alias( dkmAlias.Kind, dkmAlias.Name, dkmAlias.FullName, dkmAlias.Type, dkmAlias.CustomTypeInfoPayloadTypeId, dkmAlias.CustomTypeInfoPayload)); } return builder.ToImmutableAndFree(); } void IDkmClrExpressionCompiler.CompileExpression( DkmLanguageExpression expression, DkmClrInstructionAddress instructionAddress, DkmInspectionContext inspectionContext, out string error, out DkmCompiledClrInspectionQuery result) { try { var moduleInstance = instructionAddress.ModuleInstance; var runtimeInstance = instructionAddress.RuntimeInstance; var aliases = GetAliases(runtimeInstance, inspectionContext); // NB: Not affected by retrying. var r = this.CompileWithRetry( moduleInstance, runtimeInstance.GetMetadataBlocks(moduleInstance.AppDomain), (blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly), (context, diagnostics) => { ResultProperties resultProperties; var compileResult = context.CompileExpression( expression.Text, expression.CompilationFlags, aliases, diagnostics, out resultProperties, testData: null); return new CompileExpressionResult(compileResult, resultProperties); }, out error); result = r.CompileResult.ToQueryResult(this.CompilerId, r.ResultProperties, runtimeInstance); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } void IDkmClrExpressionCompiler.CompileAssignment( DkmLanguageExpression expression, DkmClrInstructionAddress instructionAddress, DkmEvaluationResult lValue, out string error, out DkmCompiledClrInspectionQuery result) { try { var moduleInstance = instructionAddress.ModuleInstance; var runtimeInstance = instructionAddress.RuntimeInstance; var aliases = GetAliases(runtimeInstance, lValue.InspectionContext); // NB: Not affected by retrying. var r = this.CompileWithRetry( moduleInstance, runtimeInstance.GetMetadataBlocks(moduleInstance.AppDomain), (blocks, useReferencedModulesOnly) => CreateMethodContext(instructionAddress, blocks, useReferencedModulesOnly), (context, diagnostics) => { ResultProperties resultProperties; var compileResult = context.CompileAssignment( lValue.FullName, expression.Text, aliases, diagnostics, out resultProperties, testData: null); return new CompileExpressionResult(compileResult, resultProperties); }, out error); Debug.Assert((r.ResultProperties.Flags & DkmClrCompilationResultFlags.PotentialSideEffect) == DkmClrCompilationResultFlags.PotentialSideEffect); result = r.CompileResult.ToQueryResult(this.CompilerId, r.ResultProperties, runtimeInstance); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } void IDkmClrExpressionCompilerCallback.CompileDisplayAttribute( DkmLanguageExpression expression, DkmClrModuleInstance moduleInstance, int token, out string error, out DkmCompiledClrInspectionQuery result) { try { var runtimeInstance = moduleInstance.RuntimeInstance; var appDomain = moduleInstance.AppDomain; var compileResult = this.CompileWithRetry( moduleInstance, runtimeInstance.GetMetadataBlocks(appDomain), (blocks, useReferencedModulesOnly) => CreateTypeContext(appDomain, blocks, moduleInstance.Mvid, token, useReferencedModulesOnly), (context, diagnostics) => { ResultProperties unusedResultProperties; return context.CompileExpression( expression.Text, DkmEvaluationFlags.TreatAsExpression, ImmutableArray<Alias>.Empty, diagnostics, out unusedResultProperties, testData: null); }, out error); result = compileResult.ToQueryResult(this.CompilerId, default(ResultProperties), runtimeInstance); } catch (Exception e) when (ExpressionEvaluatorFatalError.CrashIfFailFastEnabled(e)) { throw ExceptionUtilities.Unreachable; } } /// <remarks> /// Internal for testing. /// </remarks> internal static bool ShouldTryAgainWithMoreMetadataBlocks(DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtrFunction, ImmutableArray<AssemblyIdentity> missingAssemblyIdentities, ref ImmutableArray<MetadataBlock> references) { var newReferences = DkmUtilities.GetMetadataBlocks(getMetaDataBytesPtrFunction, missingAssemblyIdentities); if (newReferences.Length > 0) { references = references.AddRange(newReferences); return true; } return false; } void IDkmModuleModifiedNotification.OnModuleModified(DkmModuleInstance moduleInstance) { RemoveDataItemIfNecessary(moduleInstance); } void IDkmModuleInstanceUnloadNotification.OnModuleInstanceUnload(DkmModuleInstance moduleInstance, DkmWorkList workList, DkmEventDescriptor eventDescriptor) { RemoveDataItemIfNecessary(moduleInstance); } private void RemoveDataItemIfNecessary(DkmModuleInstance moduleInstance) { // If the module is not a managed module, the module change has no effect. var module = moduleInstance as DkmClrModuleInstance; if (module == null) { return; } // Drop any context cached on the AppDomain. var appDomain = module.AppDomain; RemoveDataItem(appDomain); } internal abstract DiagnosticFormatter DiagnosticFormatter { get; } internal abstract DkmCompilerId CompilerId { get; } internal abstract EvaluationContextBase CreateTypeContext( DkmClrAppDomain appDomain, ImmutableArray<MetadataBlock> metadataBlocks, Guid moduleVersionId, int typeToken, bool useReferencedModulesOnly); internal abstract EvaluationContextBase CreateMethodContext( DkmClrAppDomain appDomain, ImmutableArray<MetadataBlock> metadataBlocks, Lazy<ImmutableArray<AssemblyReaders>> lazyAssemblyReaders, object symReader, Guid moduleVersionId, int methodToken, int methodVersion, uint ilOffset, int localSignatureToken, bool useReferencedModulesOnly); internal abstract void RemoveDataItem(DkmClrAppDomain appDomain); private EvaluationContextBase CreateMethodContext( DkmClrInstructionAddress instructionAddress, ImmutableArray<MetadataBlock> metadataBlocks, bool useReferencedModulesOnly) { var moduleInstance = instructionAddress.ModuleInstance; var methodToken = instructionAddress.MethodId.Token; int localSignatureToken; try { localSignatureToken = moduleInstance.GetLocalSignatureToken(methodToken); } catch (InvalidOperationException) { // No local signature. May occur when debugging .dmp. localSignatureToken = 0; } catch (FileNotFoundException) { // No local signature. May occur when debugging heapless dumps. localSignatureToken = 0; } return this.CreateMethodContext( moduleInstance.AppDomain, metadataBlocks, new Lazy<ImmutableArray<AssemblyReaders>>(() => instructionAddress.MakeAssemblyReaders(), LazyThreadSafetyMode.None), symReader: moduleInstance.GetSymReader(), moduleVersionId: moduleInstance.Mvid, methodToken: methodToken, methodVersion: (int)instructionAddress.MethodId.Version, ilOffset: instructionAddress.ILOffset, localSignatureToken: localSignatureToken, useReferencedModulesOnly: useReferencedModulesOnly); } internal delegate EvaluationContextBase CreateContextDelegate(ImmutableArray<MetadataBlock> metadataBlocks, bool useReferencedModulesOnly); internal delegate TResult CompileDelegate<TResult>(EvaluationContextBase context, DiagnosticBag diagnostics); private TResult CompileWithRetry<TResult>( DkmClrModuleInstance moduleInstance, ImmutableArray<MetadataBlock> metadataBlocks, CreateContextDelegate createContext, CompileDelegate<TResult> compile, out string errorMessage) { return CompileWithRetry( metadataBlocks, this.DiagnosticFormatter, createContext, compile, (AssemblyIdentity assemblyIdentity, out uint size) => moduleInstance.AppDomain.GetMetaDataBytesPtr(assemblyIdentity.GetDisplayName(), out size), out errorMessage); } internal static TResult CompileWithRetry<TResult>( ImmutableArray<MetadataBlock> metadataBlocks, DiagnosticFormatter formatter, CreateContextDelegate createContext, CompileDelegate<TResult> compile, DkmUtilities.GetMetadataBytesPtrFunction getMetaDataBytesPtr, out string errorMessage) { TResult compileResult; PooledHashSet<AssemblyIdentity> assembliesLoadedInRetryLoop = null; bool tryAgain; var linqLibrary = EvaluationContextBase.SystemLinqIdentity; do { errorMessage = null; var context = createContext(metadataBlocks, useReferencedModulesOnly: false); var diagnostics = DiagnosticBag.GetInstance(); compileResult = compile(context, diagnostics); tryAgain = false; if (diagnostics.HasAnyErrors()) { bool useReferencedModulesOnly; ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; errorMessage = context.GetErrorMessageAndMissingAssemblyIdentities( diagnostics, formatter, preferredUICulture: null, linqLibrary: linqLibrary, useReferencedModulesOnly: out useReferencedModulesOnly, missingAssemblyIdentities: out missingAssemblyIdentities); // If there were LINQ-related errors, we'll initially add System.Linq (set above). // If that doesn't work, we'll fall back to System.Core for subsequent retries. linqLibrary = EvaluationContextBase.SystemCoreIdentity; if (useReferencedModulesOnly) { Debug.Assert(missingAssemblyIdentities.IsEmpty); var otherContext = createContext(metadataBlocks, useReferencedModulesOnly: true); var otherDiagnostics = DiagnosticBag.GetInstance(); var otherResult = compile(otherContext, otherDiagnostics); if (!otherDiagnostics.HasAnyErrors()) { errorMessage = null; compileResult = otherResult; } otherDiagnostics.Free(); } else { if (!missingAssemblyIdentities.IsEmpty) { if (assembliesLoadedInRetryLoop == null) { assembliesLoadedInRetryLoop = PooledHashSet<AssemblyIdentity>.GetInstance(); } // If any identities failed to add (they were already in the list), then don't retry. if (assembliesLoadedInRetryLoop.AddAll(missingAssemblyIdentities)) { tryAgain = ShouldTryAgainWithMoreMetadataBlocks(getMetaDataBytesPtr, missingAssemblyIdentities, ref metadataBlocks); } } } } diagnostics.Free(); } while (tryAgain); assembliesLoadedInRetryLoop?.Free(); return compileResult; } private static DkmClrLocalVariableInfo ToLocalVariableInfo(LocalAndMethod local) { ReadOnlyCollection<byte> customTypeInfo; Guid customTypeInfoId = local.GetCustomTypeInfo(out customTypeInfo); return DkmClrLocalVariableInfo.Create( local.LocalDisplayName, local.LocalName, local.MethodName, local.Flags, DkmEvaluationResultCategory.Data, customTypeInfo.ToCustomTypeInfo(customTypeInfoId)); } private struct GetLocalsResult { internal readonly string TypeName; internal readonly ReadOnlyCollection<DkmClrLocalVariableInfo> Locals; internal readonly ReadOnlyCollection<byte> Assembly; internal GetLocalsResult(string typeName, ReadOnlyCollection<DkmClrLocalVariableInfo> locals, ReadOnlyCollection<byte> assembly) { this.TypeName = typeName; this.Locals = locals; this.Assembly = assembly; } } private struct CompileExpressionResult { internal readonly CompileResult CompileResult; internal readonly ResultProperties ResultProperties; internal CompileExpressionResult(CompileResult compileResult, ResultProperties resultProperties) { this.CompileResult = compileResult; this.ResultProperties = resultProperties; } } } }
using System; using System.Linq; using Toucan.Data.Model; using Toucan.Contract; using Toucan.Contract.Security; namespace Toucan.Data { public static partial class Extensions { private const string AdminEmail = "webmaster@toucan.org"; public static void EnsureSeedData(this DbContextBase db, ICryptoService crypto) { EnsureLocalProvider(db); EnsureExternalProviders(db); User admin = EnsureAdmin(db, crypto); EnsureAuthorizationClaims(db, admin); EnsureSystemRoles(db, admin); } private static void EnsureAuthorizationClaims(DbContextBase db, User admin) { string[] claims = new string[] { SecurityClaimTypes.Example }; foreach (string claim in claims) { var securityClaim = db.SecurityClaim.FirstOrDefault(o => o.SecurityClaimId == claim); if (securityClaim == null) { securityClaim = new SecurityClaim() { CreatedBy = admin.UserId, CreatedOn = DateTime.UtcNow, Description = claim, Enabled = true, Origin = "System", ValidationPattern = SecurityClaimTypes.AllowedValuesPattern, SecurityClaimId = claim }; db.SecurityClaim.Add(securityClaim); db.SaveChanges(); } } } private static Provider EnsureExternalProviders(DbContextBase db) { Provider provider = db.Provider.FirstOrDefault(o => o.ProviderId == ProviderTypes.Google); if (provider == null) { provider = new Provider() { ProviderId = ProviderTypes.Google, Name = "Google", Description = "Logon using your google account", Enabled = true }; db.Provider.Add(provider); db.SaveChanges(); } provider = db.Provider.FirstOrDefault(o => o.ProviderId == ProviderTypes.Microsoft); if (provider == null) { provider = new Provider() { ProviderId = ProviderTypes.Microsoft, Name = "Microsoft", Description = "Logon using your microsoft account", Enabled = true }; db.Provider.Add(provider); db.SaveChanges(); } return provider; } private static Provider EnsureLocalProvider(DbContextBase db) { Provider provider = db.Provider.FirstOrDefault(o => o.ProviderId == ProviderTypes.Local); if (provider == null) { provider = new Provider() { ProviderId = ProviderTypes.Local, Name = "Site", Description = "Authenticate with a username/password provider by this site", Enabled = true }; db.Provider.Add(provider); db.SaveChanges(); } return provider; } private static void EnsureSystemRoles(DbContextBase db, User admin) { foreach (var systemRole in RoleTypes.System) { Role role = db.Role.FirstOrDefault(o => o.RoleId == systemRole.Key); if (role == null) { role = new Role() { CreatedBy = admin.UserId, Enabled = true, Name = systemRole.Value, RoleId = systemRole.Key }; if (systemRole.Key == RoleTypes.User) { var claim = db.SecurityClaim.SingleOrDefault(o => o.SecurityClaimId == SecurityClaimTypes.Example); if (claim != null) role.SecurityClaims.Add(new RoleSecurityClaim() { Role = role, SecurityClaimId = SecurityClaimTypes.Example, Value = SecurityClaimValueTypes.Read.ToString() }); } db.Role.Add(role); db.SaveChanges(); } } } private static User EnsureAdmin(DbContextBase db, ICryptoService crypto) { User admin = db.User.SingleOrDefault(o => o.Username == AdminEmail); if (admin == null) { admin = new User() { CultureName = "en", DisplayName = "Webmaster", Enabled = true, TimeZoneId = Globalization.DefaultTimeZoneId, Username = AdminEmail }; db.User.Add(admin); db.SaveChanges(); } Role role = db.Role.FirstOrDefault(o => o.RoleId == RoleTypes.Admin); if (role == null) { string name = RoleTypes.System.FirstOrDefault(o => o.Key == RoleTypes.Admin).Value; role = new Role() { CreatedByUser = admin, Enabled = true, Name = name, RoleId = RoleTypes.Admin }; db.Role.Add(role); db.SaveChanges(); } if (!db.UserRole.Any()) { var userRole = new UserRole() { Role = role, User = admin }; string salt = crypto.CreateSalt(); string hash = crypto.CreateKey(salt, "P@ssw0rd"); var userProvider = new UserProviderLocal { ProviderId = ProviderTypes.Local, PasswordSalt = salt, PasswordHash = hash, User = admin, }; db.UserRole.Add(userRole); db.UserProvider.Add(userProvider); db.SaveChanges(); } return admin; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.UnitTests; using Xunit; namespace System.Runtime.Analyzers.UnitTests { public class DisposableTypesShouldDeclareFinalizerTests : DiagnosticAnalyzerTestBase { [Fact] public void CSharpDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndNoFinalizerExists() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern IntPtr AllocateResource(); } public class A : IDisposable { private readonly IntPtr _pi; public A() { _pi = NativeMethods.AllocateResource(); } public void Dispose() { } } "; VerifyCSharp(code, GetCSharpDiagnostic(11, 14)); } [Fact] public void BasicDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndNoFinalizerExists() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As IntPtr End Function End Class Public Class A Implements IDisposable Private ReadOnly _pi As IntPtr Public Sub New() _pi = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; VerifyBasic(code, GetBasicDiagnostic(11, 14)); } [Fact] public void CSharpNoDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndFinalizerExists() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern IntPtr AllocateResource(); } public class A : IDisposable { private readonly IntPtr _pi; public A() { _pi = NativeMethods.AllocateResource(); } public void Dispose() { } ~A() { } } "; VerifyCSharp(code); } [Fact] public void BasicNoDiagnosticIfIntPtrFieldIsAssignedFromNativeCodeAndFinalizerExists() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As IntPtr End Function End Class Public Class A Implements IDisposable Private ReadOnly _pi As IntPtr Public Sub New() _pi = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub Protected Overrides Sub Finalize() End Sub End Class "; VerifyBasic(code); } [Fact] public void CSharpNoDiagnosticIfIntPtrFieldInValueTypeIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern IntPtr AllocateResource(); } public struct A : IDisposable // Although disposable structs are evil { private readonly IntPtr _pi; public A() { _pi = NativeMethods.AllocateResource(); } public void Dispose() { } } "; VerifyCSharp(code); } [Fact] public void BasicNoDiagnosticIfIntPtrFieldInValueTypeIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As IntPtr End Function End Class Public Structure A Implements IDisposable ' Although disposable structs are evil Private ReadOnly _pi As IntPtr Public Sub New() _pi = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Structure "; VerifyBasic(code); } [Fact] public void CSharpNoDiagnosticIfIntPtrFieldInNonDisposableTypeIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern IntPtr AllocateResource(); } public class A { private readonly IntPtr _pi; public A() { _pi = NativeMethods.AllocateResource(); } } "; VerifyCSharp(code); } [Fact] public void BasicNoDiagnosticIfIntPtrFieldInNonDisposableTypeIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As IntPtr End Function End Class Public Class A Private ReadOnly _pi As IntPtr Public Sub New() _pi = NativeMethods.AllocateResource() End Sub Public Sub Dispose() End Sub End Class "; VerifyBasic(code); } [Fact] public void CSharpNoDiagnosticIfIntPtrFieldIsAssignedFromManagedCode() { var code = @" using System; internal static class ManagedMethods { internal static IntPtr AllocateIntPtr() { return IntPtr.Zero; } } public class A : IDisposable { private readonly IntPtr _pi; public A() { _pi = ManagedMethods.AllocateResource(); } public void Dispose() { } } "; VerifyCSharp(code); } [Fact] public void BasicNoDiagnosticIfIntPtrFieldIsAssignedFromManagedCode() { var code = @" Imports System Friend Shared Class ManagedMethods Friend Shared Function AllocateIntPtr() As IntPtr Return IntPtr.Zero; End Function End Class Public Class A Implements IDisposable Private ReadOnly I_pi As IntPtr Public Sub New() _pi = ManagedMethods.AllocateResource() End Sub Public Overloads Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; VerifyBasic(code); } [Fact] public void CSharpDiagnosticIfUIntPtrFieldIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern UIntPtr AllocateResource(); } public class A : IDisposable { private readonly UIntPtr _pu; public A() { _pu = NativeMethods.AllocateResource(); } public void Dispose() { } } "; VerifyCSharp(code, GetCSharpDiagnostic(11, 14)); } [Fact] public void BasicDiagnosticIfUIntPtrFieldIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As UIntPtr End Function End Class Public Class A Implements IDisposable Private ReadOnly _pu As UIntPtr Public Sub New() _pu = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; VerifyBasic(code, GetBasicDiagnostic(11, 14)); } [Fact] public void CSharpDiagnosticIfHandleRefFieldIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern HandleRef AllocateResource(); } public class A : IDisposable { private readonly HandleRef _hr; public A() { _hr = NativeMethods.AllocateResource(); } public void Dispose() { } } "; VerifyCSharp(code, GetCSharpDiagnostic(11, 14)); } [Fact] public void BasicDiagnosticIfHandleRefFieldIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As HandleRef End Function End Class Public Class A Implements IDisposable Private ReadOnly _hr As HandleRef Public Sub New() _hr = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; VerifyBasic(code, GetBasicDiagnostic(11, 14)); } [Fact] public void CSharpNoDiagnosticIfNonNativeResourceFieldIsAssignedFromNativeCode() { var code = @" using System; using System.Runtime.InteropServices; internal static class NativeMethods { [DllImport(""native.dll"")] internal static extern int AllocateResource(); } public class A : IDisposable { private readonly int _i; public A() { _i = NativeMethods.AllocateResource(); } public void Dispose() { } } "; VerifyCSharp(code); } [Fact] public void BasicNoDiagnosticIfNonNativeResourceFieldIsAssignedFromNativeCode() { var code = @" Imports System Imports System.Runtime.InteropServices Friend Class NativeMethods <DllImport(""native.dll"")> Friend Shared Function AllocateResource() As Integer End Function End Class Public Class A Implements IDisposable Private ReadOnly _i As Integer Public Sub New() _i = NativeMethods.AllocateResource() End Sub Public Sub Dispose() Implements IDisposable.Dispose End Sub End Class "; VerifyBasic(code); } protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new DisposableTypesShouldDeclareFinalizerAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new DisposableTypesShouldDeclareFinalizerAnalyzer(); } private static DiagnosticResult GetCSharpDiagnostic(int line, int column) { return GetExpectedDiagnostic(LanguageNames.CSharp, line, column); } private static DiagnosticResult GetBasicDiagnostic(int line, int column) { return GetExpectedDiagnostic(LanguageNames.VisualBasic, line, column); } private static DiagnosticResult GetExpectedDiagnostic(string language, int line, int column) { string fileName = language == LanguageNames.CSharp ? "Test0.cs" : "Test0.vb"; return new DiagnosticResult { Id = DisposableTypesShouldDeclareFinalizerAnalyzer.RuleId, Message = SystemRuntimeAnalyzersResources.DisposableTypesShouldDeclareFinalizerMessage, Severity = DisposableTypesShouldDeclareFinalizerAnalyzer.Rule.DefaultSeverity, Locations = new[] { new DiagnosticResultLocation(fileName, line, column) } }; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.PetstoreV2NoSync { using Models; /// <summary> /// This is a sample server Petstore server. You can find out more about /// Swagger at &lt;a /// href="http://swagger.io"&gt;http://swagger.io&lt;/a&gt; or on /// irc.freenode.net, #swagger. For this sample, you can use the api key /// "special-key" to test the authorization filters /// </summary> public partial interface ISwaggerPetstoreV2 : System.IDisposable { /// <summary> /// The base URI of the service. /// </summary> System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; } /// <summary> /// Add a new pet to the store /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Pet>> AddPetWithHttpMessagesAsync(Pet body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Update an existing pet /// </summary> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Finds Pets by status /// </summary> /// <remarks> /// Multiple status values can be provided with comma seperated strings /// </remarks> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(System.Collections.Generic.IList<string> status, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Finds Pets by tags /// </summary> /// <remarks> /// Muliple tags can be provided with comma seperated strings. Use /// tag1, tag2, tag3 for testing. /// </remarks> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(System.Collections.Generic.IList<string> tags, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Find pet by Id /// </summary> /// <remarks> /// Returns a single pet /// </remarks> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Updates a pet in the store with form data /// </summary> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(long petId, System.IO.Stream fileContent, string fileName = default(string), string status = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Deletes a pet /// </summary> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = "", System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Returns pet inventories by status /// </summary> /// <remarks> /// Returns a map of status codes to quantities /// </remarks> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Place an order for a pet /// </summary> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Find purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. /// Other values will generated exceptions /// </remarks> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Delete purchase order by Id /// </summary> /// <remarks> /// For valid response try integer IDs with value &lt; 1000. Anything /// above 1000 or nonintegers will generate API errors /// </remarks> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Create user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='body'> /// Created user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(System.Collections.Generic.IList<User> body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Creates list of users with given input array /// </summary> /// <param name='body'> /// List of user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(System.Collections.Generic.IList<User> body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Logs user into the system /// </summary> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<string,LoginUserHeaders>> LoginUserWithHttpMessagesAsync(string username, string password, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Logs out current logged in user session /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> LogoutUserWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get user by user name /// </summary> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Updated user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Delete user /// </summary> /// <remarks> /// This can only be done by the logged in user. /// </remarks> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
// // 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. // #if !SILVERLIGHT && !__ANDROID__ && !__IOS__ // Unfortunately, Xamarin Android and Xamarin iOS don't support mutexes (see https://github.com/mono/mono/blob/3a9e18e5405b5772be88bfc45739d6a350560111/mcs/class/corlib/System.Threading/Mutex.cs#L167) so the BaseFileAppender class now throws an exception in the constructor. #define SupportsMutex #endif namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Threading; /// <summary> /// Maintains a collection of file appenders usually associated with file targets. /// </summary> internal sealed class FileAppenderCache { private BaseFileAppender[] appenders; #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ private string archiveFilePatternToWatch = null; private readonly MultiFileWatcher externalFileArchivingWatcher = new MultiFileWatcher(NotifyFilters.FileName); private bool logFileWasArchived = false; #endif /// <summary> /// An "empty" instance of the <see cref="FileAppenderCache"/> class with zero size and empty list of appenders. /// </summary> public static readonly FileAppenderCache Empty = new FileAppenderCache(); /// <summary> /// Initializes a new "empty" instance of the <see cref="FileAppenderCache"/> class with zero size and empty /// list of appenders. /// </summary> private FileAppenderCache() : this(0, null, null) { } /// <summary> /// Initializes a new instance of the <see cref="FileAppenderCache"/> class. /// </summary> /// <remarks> /// The size of the list should be positive. No validations are performed during initialisation as it is an /// intenal class. /// </remarks> /// <param name="size">Total number of appenders allowed in list.</param> /// <param name="appenderFactory">Factory used to create each appender.</param> /// <param name="createFileParams">Parameters used for creating a file.</param> public FileAppenderCache(int size, IFileAppenderFactory appenderFactory, ICreateFileParameters createFileParams) { Size = size; Factory = appenderFactory; CreateFileParameters = createFileParams; appenders = new BaseFileAppender[Size]; #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ externalFileArchivingWatcher.OnChange += ExternalFileArchivingWatcher_OnChange; #endif } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ private void ExternalFileArchivingWatcher_OnChange(object sender, FileSystemEventArgs e) { if ((e.ChangeType & WatcherChangeTypes.Created) == WatcherChangeTypes.Created) logFileWasArchived = true; } /// <summary> /// The archive file path pattern that is used to detect when archiving occurs. /// </summary> public string ArchiveFilePatternToWatch { get { return archiveFilePatternToWatch; } set { if (archiveFilePatternToWatch != value) { archiveFilePatternToWatch = value; logFileWasArchived = false; externalFileArchivingWatcher.StopWatching(); } } } /// <summary> /// Invalidates appenders for all files that were archived. /// </summary> public void InvalidateAppendersForInvalidFiles() { if (logFileWasArchived) { CloseAppenders(); logFileWasArchived = false; } } #endif /// <summary> /// Gets the parameters which will be used for creating a file. /// </summary> public ICreateFileParameters CreateFileParameters { get; private set; } /// <summary> /// Gets the file appender factory used by all the appenders in this list. /// </summary> public IFileAppenderFactory Factory { get; private set; } /// <summary> /// Gets the number of appenders which the list can hold. /// </summary> public int Size { get; private set; } /// <summary> /// It allocates the first slot in the list when the file name does not already in the list and clean up any /// unused slots. /// </summary> /// <param name="fileName">File name associated with a single appender.</param> /// <returns>The allocated appender.</returns> /// <exception cref="NullReferenceException"> /// Thrown when <see cref="M:AllocateAppender"/> is called on an <c>Empty</c><see cref="FileAppenderCache"/> instance. /// </exception> public BaseFileAppender AllocateAppender(string fileName) { // // BaseFileAppender.Write is the most expensive operation here // so the in-memory data structure doesn't have to be // very sophisticated. It's a table-based LRU, where we move // the used element to become the first one. // The number of items is usually very limited so the // performance should be equivalent to the one of the hashtable. // BaseFileAppender appenderToWrite = null; int freeSpot = appenders.Length - 1; for (int i = 0; i < appenders.Length; ++i) { // Use empty slot in recent appender list, if there is one. if (appenders[i] == null) { freeSpot = i; break; } if (appenders[i].FileName == fileName) { // found it, move it to the first place on the list // (MRU) // file open has a chance of failure // if it fails in the constructor, we won't modify any data structures BaseFileAppender app = appenders[i]; for (int j = i; j > 0; --j) { appenders[j] = appenders[j - 1]; } appenders[0] = app; appenderToWrite = app; break; } } if (appenderToWrite == null) { BaseFileAppender newAppender = Factory.Open(fileName, CreateFileParameters); if (appenders[freeSpot] != null) { CloseAppender(appenders[freeSpot]); appenders[freeSpot] = null; } for (int j = freeSpot; j > 0; --j) { appenders[j] = appenders[j - 1]; } appenders[0] = newAppender; appenderToWrite = newAppender; #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ if (!string.IsNullOrEmpty(archiveFilePatternToWatch)) { string directoryPath = Path.GetDirectoryName(archiveFilePatternToWatch); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); externalFileArchivingWatcher.Watch(archiveFilePatternToWatch); } #endif } return appenderToWrite; } /// <summary> /// Close all the allocated appenders. /// </summary> public void CloseAppenders() { if (appenders != null) { for (int i = 0; i < appenders.Length; ++i) { if (appenders[i] == null) { break; } CloseAppender(appenders[i]); appenders[i] = null; } } } /// <summary> /// Close the allocated appenders initialised before the supplied time. /// </summary> /// <param name="expireTime">The time which prior the appenders considered expired</param> public void CloseAppenders(DateTime expireTime) { for (int i = 0; i < this.appenders.Length; ++i) { if (this.appenders[i] == null) { break; } if (this.appenders[i].OpenTime < expireTime) { for (int j = i; j < this.appenders.Length; ++j) { if (this.appenders[j] == null) { break; } CloseAppender(this.appenders[j]); this.appenders[j] = null; } break; } } } /// <summary> /// Fluch all the allocated appenders. /// </summary> public void FlushAppenders() { foreach (BaseFileAppender appender in appenders) { if (appender == null) { break; } appender.Flush(); } } private BaseFileAppender GetAppender(string fileName) { foreach (BaseFileAppender appender in appenders) { if (appender == null) break; if (appender.FileName == fileName) return appender; } return null; } #if SupportsMutex public Mutex GetArchiveMutex(string fileName) { var appender = GetAppender(fileName); return appender == null ? null : appender.ArchiveMutex; } #endif public DateTime? GetFileCreationTimeUtc(string filePath, bool fallback) { var appender = GetAppender(filePath); DateTime? result = null; if (appender != null) result = appender.GetFileCreationTimeUtc(); if (result == null && fallback) { var fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { return fileInfo.GetCreationTimeUtc(); } } return result; } public DateTime? GetFileLastWriteTimeUtc(string filePath, bool fallback) { var appender = GetAppender(filePath); DateTime? result = null; if (appender != null) result = appender.GetFileLastWriteTimeUtc(); if (result == null && fallback) { var fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { return fileInfo.GetLastWriteTimeUtc(); } } return result; } public long? GetFileLength(string filePath, bool fallback) { var appender = GetAppender(filePath); long? result = null; if (appender != null) result = appender.GetFileLength(); if (result == null && fallback) { var fileInfo = new FileInfo(filePath); if (fileInfo.Exists) { return fileInfo.Length; } } return result; } /// <summary> /// Closes the specified appender and removes it from the list. /// </summary> /// <param name="filePath">File name of the appender to be closed.</param> public void InvalidateAppender(string filePath) { for (int i = 0; i < appenders.Length; ++i) { if (appenders[i] == null) { break; } if (appenders[i].FileName == filePath) { CloseAppender(appenders[i]); for (int j = i; j < appenders.Length - 1; ++j) { appenders[j] = appenders[j + 1]; } appenders[appenders.Length - 1] = null; break; } } } private void CloseAppender(BaseFileAppender appender) { appender.Close(); #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ externalFileArchivingWatcher.StopWatching(); #endif } } }
using System; using System.Linq; using System.Text; using System.IO; using System.Collections.Generic; //this would be a good place for structural validation //after this step, we won't want to have to do stuff like that (it will gunk up already sticky code) namespace BizHawk.Emulation.DiscSystem.CUE { internal class CompiledCDText { public string Songwriter; public string Performer; public string Title; public string ISRC; } internal class CompiledCueIndex { public int Number; /// <summary> /// this is annoying, it should just be an integer /// </summary> public Timestamp FileMSF; public override string ToString() { return $"I#{Number:D2} {FileMSF}"; } } /// <summary> /// What type of file we're looking at.. each one would require a different ingestion handler /// </summary> public enum CompiledCueFileType { Unknown, /// <summary> /// a raw BIN that can be mounted directly /// </summary> BIN, /// <summary> /// a raw WAV that can be mounted directly /// </summary> WAVE, /// <summary> /// an ECM file that can be mounted directly (once the index is generated) /// </summary> ECM, /// <summary> /// An encoded audio file which can be seeked on the fly, therefore roughly mounted on the fly /// THIS ISN'T SUPPORTED YET /// </summary> SeekAudio, /// <summary> /// An encoded audio file which can't be seeked on the fly. It must be decoded to a temp buffer, or pre-discohawked /// </summary> DecodeAudio, } internal class CompiledCueFile { public string FullPath; public CompiledCueFileType Type; public override string ToString() { return $"{Type}: {Path.GetFileName(FullPath)}"; } } internal class CompiledDiscInfo { public int FirstRecordedTrackNumber, LastRecordedTrackNumber; public SessionFormat SessionFormat; } internal class CompiledCueTrack { public int BlobIndex; public int Number; /// <summary> /// A track that's final in a file gets its length from the length of the file; other tracks lengths are determined from the succeeding track /// </summary> public bool IsFinalInFile; /// <summary> /// A track that's first in a file has an implicit index 0 at 00:00:00 /// Otherwise it has an implicit index 0 at the placement of the index 1 /// </summary> public bool IsFirstInFile; public CompiledCDText CDTextData = new CompiledCDText(); public Timestamp PregapLength, PostgapLength; public CueTrackFlags Flags = CueTrackFlags.None; public CueTrackType TrackType = CueTrackType.Unknown; public List<CompiledCueIndex> Indexes = new List<CompiledCueIndex>(); public override string ToString() { var idx = Indexes.Find((i) => i.Number == 1); if (idx == null) return $"T#{Number:D2} NO INDEX 1"; else { var indexlist = string.Join("|", Indexes); return $"T#{Number:D2} {BlobIndex}:{idx.FileMSF} ({indexlist})"; } } } internal class CompileCueJob : DiscJob { /// <summary> /// input: the CueFile to analyze /// </summary> public CUE_File IN_CueFile; /// <summary> /// The context used for this compiling job /// TODO - rename something like context /// </summary> public CUE_Context IN_CueContext; /// <summary> /// output: high level disc info /// </summary> public CompiledDiscInfo OUT_CompiledDiscInfo; /// <summary> /// output: CD-Text set at the global level (before any track commands) /// </summary> public CompiledCDText OUT_GlobalCDText; /// <summary> /// output: The compiled file info /// </summary> public List<CompiledCueFile> OUT_CompiledCueFiles; /// <summary> /// output: The compiled track info /// </summary> public List<CompiledCueTrack> OUT_CompiledCueTracks; /// <summary> /// output: An integer between 0 and 10 indicating how costly it will be to load this disc completely. /// Activites like decoding non-seekable media will increase the load time. /// 0 - Requires no noticeable time /// 1 - Requires minimal processing (indexing ECM) /// 10 - Requires ages, decoding audio data, etc. /// </summary> public int OUT_LoadTime; //----------------------------------------------------------------- CompiledCDText curr_cdtext; int curr_blobIndex = -1; CompiledCueTrack curr_track = null; CompiledCueFile curr_file = null; bool discinfo_session1Format_determined = false; bool curr_fileHasTrack = false; void UpdateDiscInfo(CUE_File.Command.TRACK trackCommand) { if (OUT_CompiledDiscInfo.FirstRecordedTrackNumber == 0) OUT_CompiledDiscInfo.FirstRecordedTrackNumber = trackCommand.Number; OUT_CompiledDiscInfo.LastRecordedTrackNumber = trackCommand.Number; if (!discinfo_session1Format_determined) { switch (trackCommand.Type) { case CueTrackType.Mode2_2336: case CueTrackType.Mode2_2352: OUT_CompiledDiscInfo.SessionFormat = SessionFormat.Type20_CDXA; discinfo_session1Format_determined = true; break; case CueTrackType.CDI_2336: case CueTrackType.CDI_2352: OUT_CompiledDiscInfo.SessionFormat = SessionFormat.Type10_CDI; discinfo_session1Format_determined = true; break; default: break; } } } void CloseFile() { if (curr_track != null) { //flag this track as the final one in the file curr_track.IsFinalInFile = true; } curr_file = null; } void OpenFile(CUE_File.Command.FILE f) { if (curr_file != null) CloseFile(); curr_blobIndex++; curr_fileHasTrack = false; var Resolver = IN_CueContext.Resolver; //TODO - smart audio file resolving only for AUDIO types. not BINARY or MOTOROLA or AIFF or ECM or what have you var options = Resolver.Resolve(f.Path); string choice = null; if (options.Count == 0) { Error($"Couldn't resolve referenced cue file: {f.Path} ; you can commonly repair the cue file yourself, or a file might be missing"); //add a null entry to keep the count from being wrong later (quiets a warning) OUT_CompiledCueFiles.Add(null); return; } else { choice = options[0]; if (options.Count > 1) Warn($"Multiple options resolving referenced cue file; choosing: {Path.GetFileName(choice)}"); } var cfi = new CompiledCueFile(); curr_file = cfi; OUT_CompiledCueFiles.Add(cfi); cfi.FullPath = choice; //determine the CueFileInfo's type, based on extension and extra checking //TODO - once we reorganize the file ID stuff, do legit checks here (this is completely redundant with the fileID system //TODO - decode vs stream vs unpossible policies in input policies object (including ffmpeg availability-checking callback (results can be cached)) string blobPathExt = Path.GetExtension(choice).ToUpperInvariant(); if (blobPathExt == ".BIN" || blobPathExt == ".IMG") cfi.Type = CompiledCueFileType.BIN; else if (blobPathExt == ".ISO") cfi.Type = CompiledCueFileType.BIN; else if (blobPathExt == ".WAV") { //quickly, check the format. turn it to DecodeAudio if it can't be supported //TODO - fix exception-throwing inside //TODO - verify stream-disposing semantics var fs = File.OpenRead(choice); using (var blob = new Disc.Blob_WaveFile()) { try { blob.Load(fs); cfi.Type = CompiledCueFileType.WAVE; } catch { cfi.Type = CompiledCueFileType.DecodeAudio; } } } else if (blobPathExt == ".APE") cfi.Type = CompiledCueFileType.DecodeAudio; else if (blobPathExt == ".MP3") cfi.Type = CompiledCueFileType.DecodeAudio; else if (blobPathExt == ".MPC") cfi.Type = CompiledCueFileType.DecodeAudio; else if (blobPathExt == ".FLAC") cfi.Type = CompiledCueFileType.DecodeAudio; else if (blobPathExt == ".ECM") { cfi.Type = CompiledCueFileType.ECM; if (!Disc.Blob_ECM.IsECM(choice)) { Error($"an ECM file was specified or detected, but it isn't a valid ECM file: {Path.GetFileName(choice)}"); cfi.Type = CompiledCueFileType.Unknown; } } else { Error($"Unknown cue file type. Since it's likely an unsupported compression, this is an error: {Path.GetFileName(choice)}"); cfi.Type = CompiledCueFileType.Unknown; } //TODO - check for mismatches between track types and file types, or is that best done when interpreting the commands? } void CreateTrack1Pregap() { if (OUT_CompiledCueTracks[1].PregapLength.Sector == 0) { } else if (OUT_CompiledCueTracks[1].PregapLength.Sector == 150) { } else { Error("Track 1 specified an illegal pregap. It's being ignored and replaced with a 00:02:00 pregap"); } OUT_CompiledCueTracks[1].PregapLength = new Timestamp(150); } void FinalAnalysis() { //some quick checks: if (OUT_CompiledCueFiles.Count == 0) Error("Cue file doesn't specify any input files!"); //we can't reliably analyze the length of files here, because we might have to be decoding to get lengths (VBR mp3s) //REMINDER: we could actually scan the mp3 frames in software //So, it's not really worth the trouble. We'll cope with lengths later //we could check the format of the wav file here, though //score the cost of loading the file bool needsCodec = false; OUT_LoadTime = 0; foreach (var cfi in OUT_CompiledCueFiles) { if (cfi == null) continue; if (cfi.Type == CompiledCueFileType.DecodeAudio) { needsCodec = true; OUT_LoadTime = Math.Max(OUT_LoadTime, 10); } if (cfi.Type == CompiledCueFileType.SeekAudio) needsCodec = true; if (cfi.Type == CompiledCueFileType.ECM) OUT_LoadTime = Math.Max(OUT_LoadTime, 1); } //check whether processing was available if (needsCodec) { FFMpeg ffmpeg = new FFMpeg(); if (!ffmpeg.QueryServiceAvailable()) Warn("Decoding service will be required for further processing, but is not available"); } } void CloseTrack() { if (curr_track == null) return; //normalize: if an index 0 is missing, add it here if (curr_track.Indexes[0].Number != 0) { var index0 = new CompiledCueIndex(); var index1 = curr_track.Indexes[0]; index0.Number = 0; index0.FileMSF = index1.FileMSF; //same MSF as index 1 will make it effectively nonexistent //well now, if it's the first in the file, an implicit index will take its value from 00:00:00 in the file //this is the kind of thing I sought to solve originally by 'interpreting' the file, but it seems easy enough to handle this way //my carlin.cue tests this but test cases shouldnt be hard to find if (curr_track.IsFirstInFile) index0.FileMSF = new Timestamp(0); curr_track.Indexes.Insert(0, index0); } OUT_CompiledCueTracks.Add(curr_track); curr_track = null; } void OpenTrack(CUE_File.Command.TRACK trackCommand) { //assert that a file is open if(curr_file == null) { Error("Track command encountered with no active file"); throw new DiscJobAbortException(); } curr_track = new CompiledCueTrack(); //spill cdtext data into this track curr_cdtext = curr_track.CDTextData; curr_track.BlobIndex = curr_blobIndex; curr_track.Number = trackCommand.Number; curr_track.TrackType = trackCommand.Type; //default flags if (curr_track.TrackType != CueTrackType.Audio) curr_track.Flags = CueTrackFlags.DATA; if (!curr_fileHasTrack) { curr_fileHasTrack = curr_track.IsFirstInFile = true; } UpdateDiscInfo(trackCommand); } void AddIndex(CUE_File.Command.INDEX indexCommand) { var newindex = new CompiledCueIndex(); newindex.FileMSF = indexCommand.Timestamp; newindex.Number = indexCommand.Number; curr_track.Indexes.Add(newindex); } public void Run() { //in params var cue = IN_CueFile; //output state OUT_GlobalCDText = new CompiledCDText(); OUT_CompiledDiscInfo = new CompiledDiscInfo(); OUT_CompiledCueFiles = new List<CompiledCueFile>(); OUT_CompiledCueTracks = new List<CompiledCueTrack>(); //add a track 0, for addressing convenience. //note: for future work, track 0 may need emulation (accessible by very negative LBA--the TOC is stored there) var track0 = new CompiledCueTrack() { Number = 0, }; OUT_CompiledCueTracks.Add(track0); //global cd text will acquire the cdtext commands set before track commands curr_cdtext = OUT_GlobalCDText; for (int i = 0; i < cue.Commands.Count; i++) { var cmd = cue.Commands[i]; //these commands get dealt with globally. nothing to be done here //(but in the future we need to accumulate them into the compile pass output) if (cmd is CUE_File.Command.CATALOG || cmd is CUE_File.Command.CDTEXTFILE) continue; //nothing to be done for comments if (cmd is CUE_File.Command.REM) continue; if (cmd is CUE_File.Command.COMMENT) continue; //CD-text and related if (cmd is CUE_File.Command.PERFORMER) curr_cdtext.Performer = (cmd as CUE_File.Command.PERFORMER).Value; if (cmd is CUE_File.Command.SONGWRITER) curr_cdtext.Songwriter = (cmd as CUE_File.Command.SONGWRITER).Value; if (cmd is CUE_File.Command.TITLE) curr_cdtext.Title = (cmd as CUE_File.Command.TITLE).Value; if (cmd is CUE_File.Command.ISRC) curr_cdtext.ISRC = (cmd as CUE_File.Command.ISRC).Value; //flags can only be set when a track command is running if (cmd is CUE_File.Command.FLAGS) { if (curr_track == null) Warn("Ignoring invalid flag commands outside of a track command"); else //take care to |= it here, so the data flag doesn't get cleared curr_track.Flags |= (cmd as CUE_File.Command.FLAGS).Flags; } if (cmd is CUE_File.Command.TRACK) { CloseTrack(); OpenTrack(cmd as CUE_File.Command.TRACK); } if (cmd is CUE_File.Command.FILE) { CloseFile(); OpenFile(cmd as CUE_File.Command.FILE); } if (cmd is CUE_File.Command.INDEX) { //todo - validate no postgap specified AddIndex(cmd as CUE_File.Command.INDEX); } if (cmd is CUE_File.Command.PREGAP) { //validate track open //validate no indexes curr_track.PregapLength = (cmd as CUE_File.Command.PREGAP).Length; } if (cmd is CUE_File.Command.POSTGAP) { curr_track.PostgapLength = (cmd as CUE_File.Command.POSTGAP).Length; } } //it's a bit odd to close the file before closing the track, but... //we need to be sure to CloseFile first to make sure the track is marked as the final one in the file CloseFile(); CloseTrack(); CreateTrack1Pregap(); FinalAnalysis(); FinishLog(); } //Run() } //class CompileCueJob } //namespace BizHawk.Emulation.DiscSystem
// 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 Microsoft.CodeAnalysis.Editor.CSharp.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Roslyn.Test.Utilities; using Xunit; using Microsoft.CodeAnalysis.CSharp; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp { public class GenericNameSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests { public GenericNameSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture) { } internal override ISignatureHelpProvider CreateSignatureHelpProvider() { return new GenericNameSignatureHelpProvider(); } #region "Declaring generic type objects" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task NestedGenericTerminated() { var markup = @" class G<T> { }; class C { void Foo() { G<G<int>$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith1ParameterTerminated() { var markup = @" class G<T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1() { var markup = @" class G<S, T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2() { var markup = @" class G<S, T> { }; class C { void Foo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn1XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS. Also see <see cref=""T""/></typeparam> /// <typeparam name=""T"">TypeParamT</typeparam> class G<S, T> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamS. Also see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWith2ParametersOn2XmlDoc() { var markup = @" /// <summary> /// Summary for G /// </summary> /// <typeparam name=""S"">TypeParamS</typeparam> /// <typeparam name=""T"">TypeParamT. Also see <see cref=""S""/></typeparam> class G<S, T> { }; class C { void Foo() { [|G<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", "Summary for G", "TypeParamT. Also see S", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Constraints on generic types" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsStruct() { var markup = @" class G<S> where S : struct { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : struct", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsClass() { var markup = @" class G<S> where S : class { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : class", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsNew() { var markup = @" class G<S> where S : new() { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : new()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBase() { var markup = @" class Base { } class G<S> where S : Base { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<S> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<S>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericWithNonGeneric() { var markup = @" class Base<T> { } class G<S> where S : Base<int> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<int>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsBaseGenericNested() { var markup = @" class Base<T> { } class G<S> where S : Base<Base<int>> { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S> where S : Base<Base<int>>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsDeriveFromAnotherGenericParameter() { var markup = @" class G<S, T> where S : T { }; class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : T", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed1() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IFoo, new() { }; internal interface IFoo { } internal class Base { } class C { void Foo() { [|G<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where S : Base, new()", "Summary1", "SummaryS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithConstraintsMixed2() { var markup = @" /// <summary> /// Summary1 /// </summary> /// <typeparam name=""S"">SummaryS</typeparam> /// <typeparam name=""T"">SummaryT</typeparam> class G<S, T> where S : Base, new() where T : class, S, IFoo, new() { }; internal interface IFoo { } internal class Base { } class C { void Foo() { [|G<bar, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T> where T : class, S, IFoo, new()", "Summary1", "SummaryT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Generic member invocation" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith1ParameterTerminated() { var markup = @" class C { void Foo<T>() { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1() { var markup = @" class C { /// <summary> /// Method summary /// </summary> /// <typeparam name=""S"" > type param S. see <see cref=""T""/> </typeparam> /// <typeparam name=""T"">type param T. </typeparam> /// <param name=""s"">parameter s</param> /// <param name=""t"">parameter t</param> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "Method summary", "type param S. see T", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2() { var markup = @" class C { void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", string.Empty, string.Empty, currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn1XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForFoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "SummaryForFoo", "SummaryForS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWith2ParametersOn2XmlDoc() { var markup = @" class C { /// <summary> /// SummaryForFoo /// </summary> /// <typeparam name=""S"">SummaryForS</typeparam> /// <typeparam name=""T"">SummaryForT</typeparam> void Foo<S, T>(S s, T t) { } void Bar() { [|Foo<int, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<S, T>(S s, T t)", "SummaryForFoo", "SummaryForT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task CallingGenericExtensionMethod() { var markup = @" class G { }; class C { void Bar() { G g = null; g.[|Foo<$$|]> } } static class FooClass { public static void Foo<T>(this G g) { } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.Extension}) void G.Foo<T>()", string.Empty, string.Empty, currentParameterIndex: 0)); // TODO: Enable the script case when we have support for extension methods in scripts await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular); } #endregion #region "Constraints on generic methods" [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed1() { var markup = @" class Base { } interface IFoo { } class C { /// <summary> /// FooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Foo<S, T>(S s, T t) where S : Base, new() where T : class, S, IFoo, new() { return null; } void Bar() { [|Foo<$$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Foo<S, T>(S s, T t) where S : Base, new()", "FooSummary", "ParamS", currentParameterIndex: 0)); await TestAsync(markup, expectedOrderedItems); } [WorkItem(544091)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task InvokingGenericMethodWithConstraintsMixed2() { var markup = @" class Base { } interface IFoo { } class C { /// <summary> /// FooSummary /// </summary> /// <typeparam name=""S"">ParamS</typeparam> /// <typeparam name=""T"">ParamT</typeparam> S Foo<S, T>(S s, T t) where S : Base, new() where T : class, S, IFoo, new() { return null; } void Bar() { [|Foo<Base, $$|]> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("S C.Foo<S, T>(S s, T t) where T : class, S, IFoo, new()", "FooSummary", "ParamT", currentParameterIndex: 1)); await TestAsync(markup, expectedOrderedItems); } #endregion #region "Trigger tests" [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public void TestTriggerCharacters() { char[] expectedCharacters = { ',', '<' }; char[] unexpectedCharacters = { ' ', '[', '(' }; VerifyTriggerCharacters(expectedCharacters, unexpectedCharacters); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task FieldUnavailableInOneLinkedFile() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D<T> { } #endif void foo() { var x = new D<$$ } } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj2", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task ExcludeFilesWithInactiveRegions() { var markup = @"<Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""FOO,BAR""> <Document FilePath=""SourceDocument""><![CDATA[ class C { #if FOO class D<T> { } #endif #if BAR void foo() { var x = new D<$$ } #endif } ]]> </Document> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" /> </Project> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR""> <Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/> </Project> </Workspace>"; var expectedDescription = new SignatureHelpTestItem($"D<T>\r\n\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources.ProjectAvailability, "Proj3", FeaturesResources.NotAvailable)}\r\n\r\n{FeaturesResources.UseTheNavigationBarToSwitchContext}", currentParameterIndex: 0); await VerifyItemWithReferenceWorkerAsync(markup, new[] { expectedDescription }, false); } #endregion #region "EditorBrowsable tests" [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAlways() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableNever() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp); } [WorkItem(7336, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task EditorBrowsable_GenericType_BrowsableAdvanced() { var markup = @" class Program { void M() { var c = new C<$$ } }"; var referencedCode = @" [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)] public class C<T> { }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); expectedOrderedItems.Add(new SignatureHelpTestItem("C<T>", string.Empty, string.Empty, currentParameterIndex: 0)); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(), expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: true); await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup, referencedCode: referencedCode, expectedOrderedItemsMetadataReference: expectedOrderedItems, expectedOrderedItemsSameSolution: expectedOrderedItems, sourceLanguage: LanguageNames.CSharp, referencedLanguage: LanguageNames.CSharp, hideAdvancedMembers: false); } #endregion [WorkItem(1083601)] [WpfFact, Trait(Traits.Feature, Traits.Features.SignatureHelp)] public async Task DeclaringGenericTypeWithBadTypeArgumentList() { var markup = @" class G<T> { }; class C { void Foo() { G{$$> } }"; var expectedOrderedItems = new List<SignatureHelpTestItem>(); await TestAsync(markup, expectedOrderedItems); } } }
using System; using System.Collections.Generic; using CocosSharp; using Random = CocosSharp.CCRandom; namespace tests { public class ParticleTestScene : TestScene { #region eIDClick enum public enum eIDClick { IDC_NEXT = 100, IDC_BACK, IDC_RESTART, IDC_TOGGLE }; #endregion internal static int TagLabelAtlas = 1; internal static int SceneIdx = -1; internal static int MAX_LAYER = 0; public ParticleTestScene () : base () { MAX_LAYER = particleCreateFunctions.Length; } static Func<CCLayer>[] particleCreateFunctions = { () => new ParticleReorder(), () => new DemoFlower(), () => new DemoGalaxy(), () => new DemoFirework(), () => new DemoSpiral(), () => new DemoSun(), () => new DemoMeteor(), () => new DemoFire(), () => new DemoSmoke(), () => new DemoExplosion(), () => new DemoSnow(), () => new DemoRain(), () => new DemoBigFlower(), () => new DemoRotFlower(), () => new DemoModernArt(), () => new DemoRing(), () => new ParallaxParticle(), () => new DemoParticleFromFile("BoilingFoam"), () => new DemoParticleFromFile("BurstPipe"), () => new DemoParticleFromFile("Comet"), () => new DemoParticleFromFile("Comet"), () => new DemoParticleFromFile("Comet"), () => new DemoParticleFromFile("debian"), () => new DemoParticleFromFile("ExplodingRing"), () => new DemoParticleFromFile("LavaFlow"), () => new DemoParticleFromFile("SpinningPeas"), () => new DemoParticleFromFile("SpookyPeas"), () => new DemoParticleFromFile("Upsidedown"), () => new DemoParticleFromFile("Flower"), () => new DemoParticleFromFile("Spiral"), () => new DemoParticleFromFile("Galaxy"), () => new DemoParticleFromFile("Phoenix"), () => new RadiusMode1(), () => new RadiusMode2(), () => new Issue704(), () => new Issue870(), () => new Issue1201(), // v1.1 tests () => new MultipleParticleSystems(), () => new MultipleParticleSystemsBatched(), () => new AddAndDeleteParticleSystems(), () => new ReorderParticleSystems(), () => new PremultipliedAlphaTest(), () => new PremultipliedAlphaTest2(), }; public static CCLayer CreateParticleLayer(int index) { return particleCreateFunctions[index](); } public static CCLayer NextParticleAction() { SceneIdx++; SceneIdx = SceneIdx % MAX_LAYER; CCLayer layer = CreateParticleLayer(SceneIdx); return layer; } public static CCLayer BackParticleAction() { SceneIdx--; int total = MAX_LAYER; if (SceneIdx < 0) SceneIdx += total; CCLayer layer = CreateParticleLayer(SceneIdx); return layer; } public static CCLayer RestartParticleAction() { CCLayer layer = CreateParticleLayer(SceneIdx); return layer; } protected override void NextTestCase() { NextParticleAction(); } protected override void PreviousTestCase() { BackParticleAction(); } protected override void RestTestCase() { RestartParticleAction(); } public override void runThisTest() { AddChild(NextParticleAction()); Director.ReplaceScene(this); } }; public class ParticleDemo : TestNavigationLayer { const int labelTag = 9000; protected CCPoint MidWindowPoint; protected CCParticleSystemQuad Emitter; protected CCSprite Background; CCLabelAtlas particleCounter; CCMenu particleMenu; CCMenuItemToggle toggleParticleMovMenuItem; #region Constructors public ParticleDemo() { toggleParticleMovMenuItem = new CCMenuItemToggle(ToggleCallback, new CCMenuItemFont("Free Movement"), new CCMenuItemFont("Relative Movement"), new CCMenuItemFont("Grouped Movement")); particleMenu = new CCMenu(toggleParticleMovMenuItem); AddChild(particleMenu, 100); particleCounter = new CCLabelAtlas("0000", "Images/fps_Images", 16, 64, '.'); AddChild(particleCounter, 100, ParticleTestScene.TagLabelAtlas); Background = new CCSprite(TestResource.s_back3); AddChild(Background, 5); // Add event listeners var listener = new CCEventListenerTouchAllAtOnce(); listener.OnTouchesBegan = OnTouchesBegan; listener.OnTouchesMoved = OnTouchesMoved; listener.OnTouchesEnded = OnTouchesEnded; AddEventListener(listener); Color = new CCColor3B(127, 127, 127); Opacity = 255; } #endregion Constructors #region Setup content static CCMoveBy move = new CCMoveBy (4, new CCPoint(300, 0)); static CCFiniteTimeAction move_back = move.Reverse(); protected override void AddedToScene() { base.AddedToScene(); var windowSize = VisibleBoundsWorldspace.Size; MidWindowPoint = windowSize.Center; // Laying out content based on window size particleMenu.Position = CCPoint.Zero; toggleParticleMovMenuItem.Position = new CCPoint(10, 100); toggleParticleMovMenuItem.AnchorPoint = CCPoint.AnchorLowerLeft; particleCounter.Position = new CCPoint(windowSize.Width - 70, 50); // Background could have been removed by overriding class if (Background != null) { Background.Position = windowSize.Center;// new CCPoint(windowSize.Width / 2, windowSize.Height - 180); // Run background animation Background.RepeatForever(move, move_back); } Schedule(Step); } #endregion Setup content #region Titles public override string Title { get { return base.Title; } } public override string Subtitle { get { return base.Subtitle; } } #endregion Titles #region Callbacks public override void RestartCallback(object sender) { if (Emitter != null) { Emitter.ResetSystem(); } } public override void NextCallback(object sender) { var s = new ParticleTestScene(); s.AddChild(ParticleTestScene.NextParticleAction()); Director.ReplaceScene(s); } public override void BackCallback(object sender) { var s = new ParticleTestScene(); s.AddChild(ParticleTestScene.BackParticleAction()); Director.ReplaceScene(s); } void ToggleCallback(object sender) { if (Emitter != null) { if (Emitter.PositionType == CCPositionType.Grouped) Emitter.PositionType = CCPositionType.Free; else if (Emitter.PositionType == CCPositionType.Free) Emitter.PositionType = CCPositionType.Relative; else if (Emitter.PositionType == CCPositionType.Relative) Emitter.PositionType = CCPositionType.Grouped; } } #endregion Callbacks #region Event handling void OnTouchesBegan(List<CCTouch> touches, CCEvent touchEvent) { OnTouchesEnded(touches, touchEvent); } void OnTouchesMoved(List<CCTouch> touches, CCEvent touchEvent) { OnTouchesEnded(touches, touchEvent); } void OnTouchesEnded(List<CCTouch> touches, CCEvent touchEvent) { var touch = touches [0]; var convertedLocation = touch.Location; var pos = CCPoint.Zero; if (Background != null) { pos = Background.ConvertToWorldspace(pos); } if (Emitter != null) { Emitter.Position = convertedLocation - pos; } } #endregion Event handling void Step(float dt) { var atlas = (CCLabelAtlas) GetChildByTag(ParticleTestScene.TagLabelAtlas); if (Emitter != null) { string str = string.Format("{0:0000}", Emitter.ParticleCount); atlas.Text = (str); } else { int count = 0; for (int i = 0; i < Children.Count; i++) { if (Children[i] is CCParticleSystem) { count += ((CCParticleSystem) Children[i]).ParticleCount; } } string str = string.Format("{0:0000}", count); atlas.Text = (str); } } protected void SetEmitterPosition() { if (Emitter != null) { var size = VisibleBoundsWorldspace.Size; Emitter.Position = new CCPoint(size.Width / 2, size.Height / 2 - 30); } } } //------------------------------------------------------------------ // // DemoFirework // //------------------------------------------------------------------ public class DemoFirework : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleFireworks(MidWindowPoint); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1); SetEmitterPosition(); } public override string Title { get { return "ParticleFireworks"; } } } //------------------------------------------------------------------ // // DemoFire // //------------------------------------------------------------------ public class DemoFire : ParticleDemo { public override void OnEnter() { base.OnEnter(); var windowSize = VisibleBoundsWorldspace.Size; CCPoint emitterPos = new CCPoint(windowSize.Width / 2, 100); Emitter = new CCParticleFire(emitterPos); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); //.pvr"]; SetEmitterPosition(); } public override string Title { get { return "ParticleFire"; } } }; //------------------------------------------------------------------ // // DemoSun // //------------------------------------------------------------------ public class DemoSun : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleSun(MidWindowPoint); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); SetEmitterPosition(); } public override string Title { get { return "ParticleSun"; } } } //------------------------------------------------------------------ // // DemoGalaxy // //------------------------------------------------------------------ public class DemoGalaxy : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleGalaxy(MidWindowPoint); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); SetEmitterPosition(); } public override string Title { get { return "ParticleGalaxy"; } } }; //------------------------------------------------------------------ // // DemoFlower // //------------------------------------------------------------------ public class DemoFlower : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleFlower(Background.ContentSize.Center); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1); SetEmitterPosition(); } public override string Title { get { return "ParticleFlower"; } } }; //------------------------------------------------------------------ // // DemoBigFlower // //------------------------------------------------------------------ public class DemoBigFlower : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleSystemQuad(50); //Emitter.autorelease(); Background.AddChild(Emitter, 10); ////Emitter.release(); // win32 : use this line or remove this line and use autorelease() Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1); Emitter.Duration = -1; // gravity Emitter.Gravity = CCPoint.Zero; // angle Emitter.Angle = 90; Emitter.AngleVar = 360; // speed of particles Emitter.Speed = (160); Emitter.SpeedVar = (20); // radial Emitter.RadialAccel = (-120); Emitter.RadialAccelVar = (0); // tagential Emitter.TangentialAccel = (30); Emitter.TangentialAccelVar = (0); // emitter position Emitter.Position = new CCPoint(160, 240); Emitter.PositionVar = new CCPoint(0, 0); // life of particles Emitter.Life = 4; Emitter.LifeVar = 1; // spin of particles Emitter.StartSpin = 0; Emitter.StartSizeVar = 0; Emitter.EndSpin = 0; Emitter.EndSpinVar = 0; // color of particles var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColor = startColor; var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColorVar = startColorVar; var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColor = endColor; var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColorVar = endColorVar; // size, in pixels Emitter.StartSize = 80.0f; Emitter.StartSizeVar = 40.0f; Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize; // emits per second Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life; // additive Emitter.BlendAdditive = true; SetEmitterPosition(); } public override string Title { get { return "ParticleBigFlower"; } } }; //------------------------------------------------------------------ // // DemoRotFlower // //------------------------------------------------------------------ public class DemoRotFlower : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleSystemQuad(300); //Emitter.autorelease(); Background.AddChild(Emitter, 10); ////Emitter.release(); // win32 : Remove this line Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars2); // duration Emitter.Duration = -1; // gravity Emitter.Gravity = (new CCPoint(0, 0)); // angle Emitter.Angle = 90; Emitter.AngleVar = 360; // speed of particles Emitter.Speed = (160); Emitter.SpeedVar = (20); // radial Emitter.RadialAccel = (-120); Emitter.RadialAccelVar = (0); // tagential Emitter.TangentialAccel = (30); Emitter.TangentialAccelVar = (0); // emitter position Emitter.Position = new CCPoint(160, 240); Emitter.PositionVar = new CCPoint(0, 0); // life of particles Emitter.Life = 3; Emitter.LifeVar = 1; // spin of particles Emitter.StartSpin = 0; Emitter.StartSpinVar = 0; Emitter.EndSpin = 0; Emitter.EndSpinVar = 2000; // color of particles var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColor = startColor; var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColorVar = startColorVar; var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColor = endColor; var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColorVar = endColorVar; // size, in pixels Emitter.StartSize = 30.0f; Emitter.StartSizeVar = 00.0f; Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize; // emits per second Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life; // additive Emitter.BlendAdditive = false; SetEmitterPosition(); } public override string Title { get { return "ParticleRotFlower"; } } }; public class DemoMeteor : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleMeteor(MidWindowPoint); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); SetEmitterPosition(); } public override string Title { get { return "ParticleMeteor"; } } }; public class DemoSpiral : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleSpiral(MidWindowPoint); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); SetEmitterPosition(); } public override string Title { get { return "ParticleSpiral"; } } }; public class DemoExplosion : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleExplosion(MidWindowPoint); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1); Emitter.AutoRemoveOnFinish = true; SetEmitterPosition(); } public override string Title { get { return "ParticleExplosion"; } } }; public class DemoSmoke : ParticleDemo { public override void OnEnter() { base.OnEnter(); var windowSize = VisibleBoundsWorldspace.Size; Emitter = new CCParticleSmoke(new CCPoint(windowSize.Width / 2.0f, 0)); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); CCPoint p = Emitter.Position; Emitter.Position = new CCPoint(p.X, 100); SetEmitterPosition(); } public override string Title { get { return "ParticleSmoke"; } } }; public class DemoSnow : ParticleDemo { public override void OnEnter() { base.OnEnter(); var windowSize = VisibleBoundsWorldspace.Size; Emitter = new CCParticleSnow(new CCPoint(windowSize.Width / 2, windowSize.Height + 10)); Background.AddChild(Emitter, 10); CCPoint p = Emitter.Position; Emitter.Position = new CCPoint(p.X, p.Y - 110); Emitter.Life = 3; Emitter.LifeVar = 1; // gravity Emitter.Gravity = (new CCPoint(0, -10)); // speed of particles Emitter.Speed = (130); Emitter.SpeedVar = (30); var startColor = Emitter.StartColor; startColor.R = 0.9f; startColor.G = 0.9f; startColor.B = 0.9f; Emitter.StartColor = startColor; var startColorVar = Emitter.StartColorVar; startColorVar.B = 0.1f; Emitter.StartColorVar = startColorVar; Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life; Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_snow); SetEmitterPosition(); } public override string Title { get { return "ParticleSnow"; } } }; public class DemoRain : ParticleDemo { public override void OnEnter() { base.OnEnter(); var windowSize = VisibleBoundsWorldspace.Size; Emitter = new CCParticleRain(new CCPoint (windowSize.Width / 2.0f, windowSize.Height)); Background.AddChild(Emitter, 10); CCPoint p = Emitter.Position; Emitter.Position = new CCPoint(p.X, p.Y - 100); Emitter.Life = 4; Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); } public override string Title { get { return "ParticleRain"; } } }; // todo: CCParticleSystemPoint::draw() hasn't been implemented. public class DemoModernArt : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleSystemQuad(1000); Background.AddChild(Emitter, 10); // duration Emitter.Duration = -1; // gravity Emitter.Gravity = (new CCPoint(0, 0)); // angle Emitter.Angle = 0; Emitter.AngleVar = 360; // radial Emitter.RadialAccel = (70); Emitter.RadialAccelVar = (10); // tagential Emitter.TangentialAccel = (80); Emitter.TangentialAccelVar = (0); // speed of particles Emitter.Speed = (50); Emitter.SpeedVar = (10); // emitter position Emitter.Position = MidWindowPoint; Emitter.PositionVar = new CCPoint(0, 0); // life of particles Emitter.Life = 2.0f; Emitter.LifeVar = 0.3f; // emits per frame Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life; // color of particles var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColor = startColor; var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColorVar = startColorVar; var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColor = endColor; var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColorVar = endColorVar; // size, in pixels Emitter.StartSize = 1.0f; Emitter.StartSizeVar = 1.0f; Emitter.EndSize = 32.0f; Emitter.EndSizeVar = 8.0f; // texture Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); // additive Emitter.BlendAdditive = false; SetEmitterPosition(); } public override string Title { get { return "Varying size"; } } }; public class DemoRing : ParticleDemo { public override void OnEnter() { base.OnEnter(); Emitter = new CCParticleFlower(MidWindowPoint); Background.AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_stars1); Emitter.LifeVar = 0; Emitter.Life = 10; Emitter.Speed = (100); Emitter.SpeedVar = (0); Emitter.EmissionRate = 10000; SetEmitterPosition(); } public override string Title { get { return "Ring Demo"; } } }; public class ParallaxParticle : ParticleDemo { public override void OnEnter() { base.OnEnter(); Background.Parent.RemoveChild(Background, true); Background = null; CCParallaxNode p = new CCParallaxNode(); AddChild(p, 5); CCSprite p1 = new CCSprite(TestResource.s_back3); CCSprite p2 = new CCSprite(TestResource.s_back3); p.AddChild(p1, 1, new CCPoint(0.5f, 1), new CCPoint(0, 250)); p.AddChild(p2, 2, new CCPoint(1.5f, 1), new CCPoint(0, 50)); Emitter = new CCParticleFlower(MidWindowPoint); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); p1.AddChild(Emitter, 10); Emitter.Position = new CCPoint(250, 200); CCParticleSun par = new CCParticleSun(MidWindowPoint); p2.AddChild(par, 10); par.Texture = CCTextureCache.SharedTextureCache.AddImage(TestResource.s_fire); CCFiniteTimeAction move = new CCMoveBy (4, new CCPoint(300, 0)); CCFiniteTimeAction move_back = move.Reverse(); CCFiniteTimeAction seq = new CCSequence(move, move_back); p.RunAction(new CCRepeatForever ((CCFiniteTimeAction) seq)); } public override string Title { get { return "Parallax + Particles"; } } }; public class DemoParticleFromFile : ParticleDemo { readonly string title; static Dictionary<string, CCParticleSystemConfig> particleConfigManager; public DemoParticleFromFile() { if (particleConfigManager == null) particleConfigManager = new Dictionary<string, CCParticleSystemConfig> (); } public DemoParticleFromFile(string file) : base() { if (particleConfigManager == null) particleConfigManager = new Dictionary<string, CCParticleSystemConfig> (); title = file; } public override void OnEnter() { base.OnEnter(); Color = new CCColor3B(0, 0, 0); RemoveChild(Background, true); Background = null; string filename = "Particles/" + title; CCParticleSystemConfig config; if (particleConfigManager.ContainsKey (filename)) config = particleConfigManager [filename]; else { config = new CCParticleSystemConfig(filename, null); particleConfigManager.Add (filename, config); } Emitter = new CCParticleSystemQuad(config); AddChild(Emitter, 10); Emitter.BlendAdditive = true; SetEmitterPosition(); } public override string Title { get { if (null != title) { return title; } else { return "ParticleFromFile"; } } } }; public class RadiusMode1 : ParticleDemo { public override void OnEnter() { base.OnEnter(); var size = VisibleBoundsWorldspace.Size; Color = new CCColor3B(0, 0, 0); RemoveChild(Background, true); Background = null; Emitter = new CCParticleSystemQuad(200, CCEmitterMode.Radius); AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/stars-grayscale"); // duration Emitter.Duration = CCParticleSystem.ParticleDurationInfinity; // radius mode: start and end radius in pixels Emitter.StartRadius = (0); Emitter.StartRadiusVar = (0); Emitter.EndRadius = (160); Emitter.EndRadiusVar = (0); // radius mode: degrees per second Emitter.RotatePerSecond = (180); Emitter.RotatePerSecondVar = (0); // angle Emitter.Angle = 90; Emitter.AngleVar = 0; // emitter position Emitter.Position = new CCPoint(size.Width / 2, size.Height / 2); Emitter.PositionVar = new CCPoint(0, 0); // life of particles Emitter.Life = 5; Emitter.LifeVar = 0; // spin of particles Emitter.StartSpin = 0; Emitter.StartSpinVar = 0; Emitter.EndSpin = 0; Emitter.EndSpinVar = 0; // color of particles var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColor = startColor; var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColorVar = startColorVar; var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColor = endColor; var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColorVar = endColorVar; // size, in pixels Emitter.StartSize = 32; Emitter.StartSizeVar = 0; Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize; // emits per second Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life; // additive Emitter.BlendAdditive = false; } public override string Title { get { return "Radius Mode: Spiral"; } } }; public class RadiusMode2 : ParticleDemo { public override void OnEnter() { base.OnEnter(); var size = VisibleBoundsWorldspace.Size; Color = new CCColor3B(0, 0, 0); RemoveChild(Background, true); Background = null; Emitter = new CCParticleSystemQuad(200, CCEmitterMode.Radius); AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/stars-grayscale"); // duration Emitter.Duration = CCParticleSystem.ParticleDurationInfinity; // radius mode: start and end radius in pixels Emitter.StartRadius = (100); Emitter.StartRadiusVar = (0); Emitter.EndRadius = (CCParticleSystem.ParticleStartRadiusEqualToEndRadius); Emitter.EndRadiusVar = (0); // radius mode: degrees per second Emitter.RotatePerSecond = (45); Emitter.RotatePerSecondVar = (0); // angle Emitter.Angle = 90; Emitter.AngleVar = 0; // emitter position Emitter.Position = new CCPoint(size.Width / 2, size.Height / 2); Emitter.PositionVar = new CCPoint(0, 0); // life of particles Emitter.Life = 4; Emitter.LifeVar = 0; // spin of particles Emitter.StartSpin = 0; Emitter.StartSpinVar = 0; Emitter.EndSpin = 0; Emitter.EndSpinVar = 0; // color of particles var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColor = startColor; var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColorVar = startColorVar; var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColor = endColor; var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColorVar = endColorVar; // size, in pixels Emitter.StartSize = 32; Emitter.StartSizeVar = 0; Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize; // emits per second Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life; // additive Emitter.BlendAdditive = false; } public override string Title { get { return "Radius Mode: Semi Circle"; } } } public class Issue704 : ParticleDemo { public override void OnEnter() { base.OnEnter(); var size = VisibleBoundsWorldspace.Size; Color = new CCColor3B(0, 0, 0); RemoveChild(Background, true); Background = null; Emitter = new CCParticleSystemQuad(100, CCEmitterMode.Radius); AddChild(Emitter, 10); Emitter.Texture = CCTextureCache.SharedTextureCache.AddImage("Images/fire"); // duration Emitter.Duration = CCParticleSystem.ParticleDurationInfinity; // radius mode: start and end radius in pixels Emitter.StartRadius = (50); Emitter.StartRadiusVar = (0); Emitter.EndRadius = (CCParticleSystem.ParticleStartRadiusEqualToEndRadius); Emitter.EndRadiusVar = (0); // radius mode: degrees per second Emitter.RotatePerSecond = (0); Emitter.RotatePerSecondVar = (0); // angle Emitter.Angle = 90; Emitter.AngleVar = 0; // emitter position Emitter.Position = new CCPoint(size.Width / 2, size.Height / 2); Emitter.PositionVar = new CCPoint(0, 0); // life of particles Emitter.Life = 5; Emitter.LifeVar = 0; // spin of particles Emitter.StartSpin = 0; Emitter.StartSpinVar = 0; Emitter.EndSpin = 0; Emitter.EndSpinVar = 0; // color of particles var startColor = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColor = startColor; var startColorVar = new CCColor4F(0.5f, 0.5f, 0.5f, 1.0f); Emitter.StartColorVar = startColorVar; var endColor = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColor = endColor; var endColorVar = new CCColor4F(0.1f, 0.1f, 0.1f, 0.2f); Emitter.EndColorVar = endColorVar; // size, in pixels Emitter.StartSize = 16; Emitter.StartSizeVar = 0; Emitter.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize; // emits per second Emitter.EmissionRate = Emitter.TotalParticles / Emitter.Life; // additive Emitter.BlendAdditive = false; CCRotateBy rot = new CCRotateBy (16, 360); Emitter.RunAction(new CCRepeatForever (rot)); } public override string Title { get { return "Issue 704. Free + Rot"; } } public override string Subtitle { get { return "Emitted particles should not rotate"; } } } public class Issue870 : ParticleDemo { int index; public override void OnEnter() { base.OnEnter(); Color = new CCColor3B(0, 0, 0); RemoveChild(Background, true); Background = null; var system = new CCParticleSystemQuad("Particles/SpinningPeas"); system.Texture = (CCTextureCache.SharedTextureCache.AddImage ("Images/particles")); system.TextureRect = new CCRect(0, 0, 32, 32); AddChild(system, 10); Emitter = system; index = 0; Schedule(UpdateQuads, 2.0f); } void UpdateQuads(float dt) { index = (index + 1) % 4; var rect = new CCRect(index * 32, 0, 32, 32); var system = (CCParticleSystemQuad) Emitter; system.Texture = Emitter.Texture; system.TextureRect = rect; } public override string Title { get { return "Issue 870. SubRect"; } } public override string Subtitle { get { return "Every 2 seconds the particle should change"; } } } public class LoadingLabel : CCLabel { static CCScaleBy scale = new CCScaleBy(0.3f, 2); static CCSequence textThrob = new CCSequence(scale, scale.Reverse()); static CCSequence delayedShow = new CCSequence(new CCDelayTime (0.0f), new CCShow ()); public LoadingLabel(float delayTime = 0.0f) : base ("Loading...", "Marker Felt", 32, CCLabelFormat.SpriteFont) { Visible = false; delayedShow.Actions[0].Duration = delayTime; } protected override void AddedToScene() { base.AddedToScene(); Position = VisibleBoundsWorldspace.Center; RunActions (delayedShow); RepeatForever (textThrob); } } public class ParticleReorder : ParticleDemo { int order; LoadingLabel label; public ParticleReorder () { order = 0; Color = CCColor3B.Black; RemoveChild(Background, true); Background = null; label = new LoadingLabel(2.0f); AddChild(label, 10); } public override void OnEnter() { base.OnEnter(); label.Position = MidWindowPoint; // Load the particle system asynchronously ScheduleOnce(LoadParticleSystem, 0.0f); } void LoadParticleSystem(float dt) { CCParticleSystemCache.SharedParticleSystemCache.AddParticleSystemAsync("Particles/SmallSun", ParticleSystemLoaded); } void ParticleSystemLoaded(CCParticleSystemConfig psConfig) { label.RemoveFromParent(true); CCParticleSystemQuad ignore = new CCParticleSystemQuad (psConfig); //ignore.TotalParticles = 200; CCNode parent1 = new CCNode (); CCNode parent2 = new CCNode(); parent1.ContentSize = new CCSize (300.0f, 300.0f); for (int i = 0; i < 2; i++) { CCNode parent = (i == 0 ? parent1 : parent2); CCParticleSystemQuad emitter1 = new CCParticleSystemQuad (psConfig); //emitter1.TotalParticles = 200; emitter1.StartColor = (new CCColor4F (1, 0, 0, 1)); emitter1.BlendAdditive = (false); CCParticleSystemQuad emitter2 = new CCParticleSystemQuad (psConfig); //emitter2.TotalParticles = 200; emitter2.StartColor = (new CCColor4F (0, 1, 0, 1)); emitter2.BlendAdditive = (false); CCParticleSystemQuad emitter3 = new CCParticleSystemQuad (psConfig); //emitter3.TotalParticles = 200; emitter3.StartColor = (new CCColor4F (0, 0, 1, 1)); emitter3.BlendAdditive = (false); CCSize s = VisibleBoundsWorldspace.Size; int neg = (i == 0 ? 1 : -1); emitter1.Position = (new CCPoint (s.Width / 2 - 30, s.Height / 2 + 60 * neg)); emitter2.Position = (new CCPoint (s.Width / 2, s.Height / 2 + 60 * neg)); emitter3.Position = (new CCPoint (s.Width / 2 + 30, s.Height / 2 + 60 * neg)); parent.AddChild (emitter1, 0, 1); parent.AddChild (emitter2, 0, 2); parent.AddChild (emitter3, 0, 3); AddChild (parent, 10, 1000 + i); } Schedule(ReorderParticles, 1.0f); } public override string Title { get { return "Reordering particles"; } } public override string Subtitle { get { return "Reordering particles with and without batches batches"; } } void ReorderParticles(float dt) { for (int i = 0; i < 2; i++) { CCNode parent = GetChildByTag(1000 + i); CCNode child1 = parent.GetChildByTag(1); CCNode child2 = parent.GetChildByTag(2); CCNode child3 = parent.GetChildByTag(3); if (order % 3 == 0) { parent.ReorderChild(child1, 1); parent.ReorderChild(child2, 2); parent.ReorderChild(child3, 3); } else if (order % 3 == 1) { parent.ReorderChild(child1, 3); parent.ReorderChild(child2, 1); parent.ReorderChild(child3, 2); } else if (order % 3 == 2) { parent.ReorderChild(child1, 2); parent.ReorderChild(child2, 3); parent.ReorderChild(child3, 1); } } order++; } } public class RainbowEffect : CCParticleSystemQuad { public bool init() { return true; } public RainbowEffect(int numOfParticles) : base(numOfParticles) { // additive BlendAdditive = (false); // duration Duration = (ParticleDurationInfinity);; // Gravity Mode: gravity Gravity = (new CCPoint(0, 0)); // Gravity mode: radial acceleration RadialAccel = (0); RadialAccelVar = (0); // Gravity mode: speed of particles Speed = (120); SpeedVar = (0); // angle Angle = (180); AngleVar = (0); // life of particles Life = (0.5f); LifeVar = (0); // size, in pixels StartSize = (25.0f); StartSizeVar = (0); EndSize = (ParticleStartSizeEqualToEndSize); // emits per seconds EmissionRate = (TotalParticles / Life); // color of particles StartColor = (new CCColor4F(50, 50, 50, 50)); EndColor = (new CCColor4F(0, 0, 0, 0)); StartColorVar = new CCColor4F(); EndColorVar = new CCColor4F(); Texture = (CCTextureCache.SharedTextureCache.AddImage("Images/particles")); } public override void OnEnter() { base.OnEnter(); // emitter position Position = VisibleBoundsWorldspace.Size.Center; PositionVar = CCPoint.Zero; } public override void Update(float dt) { EmitCounter = 0; base.Update(dt); } } public class Issue1201 : ParticleDemo { public override void OnEnter() { base.OnEnter(); Color = CCColor3B.Black; RemoveChild(Background, true); Background = null; var particle = new RainbowEffect(50); AddChild(particle); particle.Position = MidWindowPoint; Emitter = particle; } public override string Title { get { return "Issue 1201. Unfinished"; } } public override string Subtitle { get { return "Unfinished test. Ignore it"; } } } public class MultipleParticleSystems : ParticleDemo { public override void OnEnter() { base.OnEnter(); Color = CCColor3B.Black; RemoveChild(Background, true); Background = null; CCTextureCache.SharedTextureCache.AddImage("Images/particles"); for (int i = 0; i < 5; i++) { CCParticleSystemQuad particleSystem = new CCParticleSystemQuad("Particles/SpinningPeas"); particleSystem.Position = (new CCPoint(i * 50, i * 50)); particleSystem.PositionType = CCPositionType.Grouped; AddChild(particleSystem); } Emitter = null; } public override string Title { get { return "Multiple particle systems"; } } public override string Subtitle { get { return "v1.1 test: FPS should be lower than next test"; } } } public class MultipleParticleSystemsBatched : ParticleDemo { public override void OnEnter() { base.OnEnter(); Color = CCColor3B.Black; RemoveChild(Background, true); Background = null; for (int i = 0; i < 5; i++) { CCParticleSystemQuad particleSystem = new CCParticleSystemQuad("Particles/SpinningPeas"); particleSystem.PositionType = CCPositionType.Grouped; particleSystem.Position = (new CCPoint(i * 50, i * 50)); } Emitter = null; } public override string Title { get { return "Multiple particle systems"; } } public override string Subtitle { get { return "v1.1 test: FPS should be lower than next test"; } } } public class AddAndDeleteParticleSystems : ParticleDemo { public override void OnEnter() { base.OnEnter(); Color = CCColor3B.Black; RemoveChild(Background, true); Background = null; for (int i = 0; i < 6; i++) { CCParticleSystemQuad particleSystem = new CCParticleSystemQuad("Particles/Spiral"); particleSystem.PositionType = CCPositionType.Grouped; particleSystem.TotalParticles = 200; particleSystem.Position = (new CCPoint(i * 15 + 100, i * 15 + 100)); int randZ = CCRandom.Next(100); } Schedule(RemoveSystem, 0.5f); Emitter = null; } void RemoveSystem(float dt) { } public override string Title { get { return "Add and remove Particle System"; } } public override string Subtitle { get { return "v1.1 test: every 2 sec 1 system disappear, 1 appears"; } } } public class ReorderParticleSystems : ParticleDemo { public override void OnEnter() { base.OnEnter(); Color = CCColor3B.Black; RemoveChild(Background, true); Background = null; for (int i = 0; i < 3; i++) { var particleSystem = new CCParticleSystemQuad(200, CCEmitterMode.Radius); // duration particleSystem.Duration = CCParticleSystem.ParticleDurationInfinity; // radius mode: 100 pixels from center particleSystem.StartRadius = (100); particleSystem.StartRadiusVar = (0); particleSystem.EndRadius = (CCParticleSystem.ParticleStartRadiusEqualToEndRadius); particleSystem.EndRadiusVar = (0); // not used when start == end // radius mode: degrees per second // 45 * 4 seconds of life = 180 degrees particleSystem.RotatePerSecond = (45); particleSystem.RotatePerSecondVar = (0); // angle particleSystem.Angle = (90); particleSystem.AngleVar = (0); // emitter position particleSystem.PositionVar = (CCPoint.Zero); // life of particles particleSystem.Life = (4); particleSystem.LifeVar = (0); // spin of particles particleSystem.StartSpin = (0); particleSystem.StartSpinVar = (0); particleSystem.EndSpin = (0); particleSystem.EndSpinVar = (0); // color of particles var color = new float[3] {0, 0, 0}; color[i] = 1; var startColor = new CCColor4F(color[0], color[1], color[2], 1.0f); particleSystem.StartColor = (startColor); var startColorVar = new CCColor4F(0, 0, 0, 0); particleSystem.StartColorVar = (startColorVar); CCColor4F endColor = startColor; particleSystem.EndColor = (endColor); CCColor4F endColorVar = startColorVar; particleSystem.EndColorVar = (endColorVar); // size, in pixels particleSystem.StartSize = (32); particleSystem.StartSizeVar = (0); particleSystem.EndSize = CCParticleSystem.ParticleStartSizeEqualToEndSize; // emits per second particleSystem.EmissionRate = (particleSystem.TotalParticles / particleSystem.Life); // additive particleSystem.Position = (new CCPoint(i * 10 + 120, 200)); particleSystem.PositionType = CCPositionType.Free; } Schedule(ReorderSystem, 2.0f); Emitter = null; } void ReorderSystem(float dt) { } public override string Title { get { return "reorder systems"; } } public override string Subtitle { get { return "changes every 2 seconds"; } } } public class PremultipliedAlphaTest : ParticleDemo { public override void OnEnter() { base.OnEnter(); Color = CCColor3B.Black; RemoveChild(Background, true); Background = null; Emitter = new CCParticleSystemQuad("Particles/BoilingFoam"); // Particle Designer "normal" blend func causes black halo on premul textures (ignores multiplication) //this->emitter.blendFunc = (ccBlendFunc){ GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA }; // Cocos2d "normal" blend func for premul causes alpha to be ignored (oversaturates colors) var tBlendFunc = new CCBlendFunc(CCOGLES.GL_ONE, CCOGLES.GL_ONE_MINUS_SRC_ALPHA); Emitter.BlendFunc = tBlendFunc; //Debug.Assert(Emitter.OpacityModifyRGB, "Particle texture does not have premultiplied alpha, test is useless"); // Toggle next line to see old behavior // this->emitter.opacityModifyRGB = NO; Emitter.StartColor = new CCColor4F(1, 1, 1, 1); Emitter.EndColor = new CCColor4F(1, 1, 1, 0); Emitter.StartColorVar = new CCColor4F(0, 0, 0, 0); Emitter.EndColorVar = new CCColor4F(0, 0, 0, 0); AddChild(Emitter, 10); } public override string Title { get { return "premultiplied alpha"; } } public override string Subtitle { get { return "no black halo, particles should fade out"; } } } public class PremultipliedAlphaTest2 : ParticleDemo { public override void OnEnter() { base.OnEnter(); Color = CCColor3B.Black; RemoveChild(Background, true); Background = null; Emitter = new CCParticleSystemQuad("Particles/TestPremultipliedAlpha"); AddChild(Emitter, 10); } public override string Title { get { return "premultiplied alpha 2"; } } public override string Subtitle { get { return "Arrows should be faded"; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the GuardiaMedicosFuncione class. /// </summary> [Serializable] public partial class GuardiaMedicosFuncioneCollection : ActiveList<GuardiaMedicosFuncione, GuardiaMedicosFuncioneCollection> { public GuardiaMedicosFuncioneCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>GuardiaMedicosFuncioneCollection</returns> public GuardiaMedicosFuncioneCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { GuardiaMedicosFuncione o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Guardia_Medicos_Funciones table. /// </summary> [Serializable] public partial class GuardiaMedicosFuncione : ActiveRecord<GuardiaMedicosFuncione>, IActiveRecord { #region .ctors and Default Settings public GuardiaMedicosFuncione() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public GuardiaMedicosFuncione(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public GuardiaMedicosFuncione(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public GuardiaMedicosFuncione(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Guardia_Medicos_Funciones", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdMedico = new TableSchema.TableColumn(schema); colvarIdMedico.ColumnName = "idMedico"; colvarIdMedico.DataType = DbType.Int32; colvarIdMedico.MaxLength = 0; colvarIdMedico.AutoIncrement = false; colvarIdMedico.IsNullable = false; colvarIdMedico.IsPrimaryKey = true; colvarIdMedico.IsForeignKey = false; colvarIdMedico.IsReadOnly = false; colvarIdMedico.DefaultSetting = @""; colvarIdMedico.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMedico); TableSchema.TableColumn colvarIdFuncion = new TableSchema.TableColumn(schema); colvarIdFuncion.ColumnName = "idFuncion"; colvarIdFuncion.DataType = DbType.AnsiString; colvarIdFuncion.MaxLength = 50; colvarIdFuncion.AutoIncrement = false; colvarIdFuncion.IsNullable = false; colvarIdFuncion.IsPrimaryKey = false; colvarIdFuncion.IsForeignKey = false; colvarIdFuncion.IsReadOnly = false; colvarIdFuncion.DefaultSetting = @""; colvarIdFuncion.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdFuncion); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Guardia_Medicos_Funciones",schema); } } #endregion #region Props [XmlAttribute("IdMedico")] [Bindable(true)] public int IdMedico { get { return GetColumnValue<int>(Columns.IdMedico); } set { SetColumnValue(Columns.IdMedico, value); } } [XmlAttribute("IdFuncion")] [Bindable(true)] public string IdFuncion { get { return GetColumnValue<string>(Columns.IdFuncion); } set { SetColumnValue(Columns.IdFuncion, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varIdMedico,string varIdFuncion) { GuardiaMedicosFuncione item = new GuardiaMedicosFuncione(); item.IdMedico = varIdMedico; item.IdFuncion = varIdFuncion; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdMedico,string varIdFuncion) { GuardiaMedicosFuncione item = new GuardiaMedicosFuncione(); item.IdMedico = varIdMedico; item.IdFuncion = varIdFuncion; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdMedicoColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdFuncionColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdMedico = @"idMedico"; public static string IdFuncion = @"idFuncion"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
/******************************************************************************* * Copyright 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************************** * __ _ _ ___ * ( )( \/\/ )/ __) * /__\ \ / \__ \ * (_)(_) \/\/ (___/ * * AWS SDK for .NET */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; namespace Amazon.EC2.Model { /// <summary> /// A Spot Instance request /// </summary> [XmlRootAttribute(IsNullable = false)] public class SpotInstanceRequest { private string spotInstanceRequestIdField; private string spotPriceField; private string typeField; private string stateField; private SpotInstanceStateFault faultField; private SpotInstanceStatusMessage statusField; private string validFromField; private string validUntilField; private string launchGroupField; private string availabilityZoneGroupField; private LaunchSpecification launchSpecificationField; private string instanceIdField; private string createTimeField; private string productDescriptionField; private List<Tag> tagField; private string launchedAvailabilityZoneField; /// <summary> /// The ID of the SpotInstanceRequest. /// </summary> [XmlElementAttribute(ElementName = "SpotInstanceRequestId")] public string SpotInstanceRequestId { get { return this.spotInstanceRequestIdField; } set { this.spotInstanceRequestIdField = value; } } /// <summary> /// Sets the ID of the SpotInstanceRequest. /// </summary> /// <param name="spotInstanceRequestId">The ID of the SpotInstanceRequest.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithSpotInstanceRequestId(string spotInstanceRequestId) { this.spotInstanceRequestIdField = spotInstanceRequestId; return this; } /// <summary> /// Checks if SpotInstanceRequestId property is set /// </summary> /// <returns>true if SpotInstanceRequestId property is set</returns> public bool IsSetSpotInstanceRequestId() { return this.spotInstanceRequestIdField != null; } /// <summary> /// The maximum price you will pay to launch one or more Spot Instances. /// </summary> [XmlElementAttribute(ElementName = "SpotPrice")] public string SpotPrice { get { return this.spotPriceField; } set { this.spotPriceField = value; } } /// <summary> /// Sets the maximum price you will pay to launch one or more Spot Instances. /// </summary> /// <param name="spotPrice">Specifies the maximum price you will pay to /// launch one or more Spot Instances.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithSpotPrice(string spotPrice) { this.spotPriceField = spotPrice; return this; } /// <summary> /// Checks if SpotPrice property is set /// </summary> /// <returns>true if SpotPrice property is set</returns> public bool IsSetSpotPrice() { return this.spotPriceField != null; } /// <summary> /// The instance type (eg. m1.small) /// </summary> [XmlElementAttribute(ElementName = "Type")] public string Type { get { return this.typeField; } set { this.typeField = value; } } /// <summary> /// Sets the instance type (eg. m1.small) /// </summary> /// <param name="type">The instance type (eg. m1.small)</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithType(string type) { this.typeField = type; return this; } /// <summary> /// Checks if Type property is set /// </summary> /// <returns>true if Type property is set</returns> public bool IsSetType() { return this.typeField != null; } /// <summary> /// The state of the Spot Instance request. /// Valid values: open | closed | cancelled | failed /// </summary> [XmlElementAttribute(ElementName = "State")] public string State { get { return this.stateField; } set { this.stateField = value; } } /// <summary> /// Sets the state of the Spot Instance request. /// </summary> /// <param name="state">The state of the Spot Instance request. /// Valid values: open | closed | cancelled | failed</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithState(string state) { this.stateField = state; return this; } /// <summary> /// Checks if State property is set /// </summary> /// <returns>true if State property is set</returns> public bool IsSetState() { return this.stateField != null; } /// <summary> /// Fault details for the Spot Instance request, if any. /// </summary> [XmlElementAttribute(ElementName = "Fault")] public SpotInstanceStateFault Fault { get { return this.faultField; } set { this.faultField = value; } } /// <summary> /// Sets the fault details for the Spot Instance request. /// </summary> /// <param name="fault">Fault details for the Spot Instance request, if any.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithFault(SpotInstanceStateFault fault) { this.faultField = fault; return this; } /// <summary> /// Checks if Fault property is set /// </summary> /// <returns>true if Fault property is set</returns> public bool IsSetFault() { return this.faultField != null; } /// <summary> /// Status details for the Spot Instance request, if any. /// </summary> [XmlElementAttribute(ElementName = "Status")] public SpotInstanceStatusMessage Status { get { return this.statusField; } set { this.statusField = value; } } /// <summary> /// Sets the status details for the Spot Instance request. /// </summary> /// <param name="status">Status details for the Spot Instance request, if any.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithStatus(SpotInstanceStatusMessage status) { this.statusField = status; return this; } /// <summary> /// Checks if Status property is set /// </summary> /// <returns>true if Status property is set</returns> public bool IsSetStatus() { return this.statusField != null; } /// <summary> /// Start date of the request. /// If this is a one-time request, the request remains active until all instances /// launch, the request expires, or the request is canceled. If the request is /// persistent, it remains active until it expires or is canceled. /// </summary> [XmlElementAttribute(ElementName = "ValidFrom")] public string ValidFrom { get { return this.validFromField; } set { this.validFromField = value; } } /// <summary> /// Sets the start date of the request. /// </summary> /// <param name="validFrom">Start date of the request. If this is a /// one-time request, the request /// remains active until all instances /// launch, the request expires, or /// the request is canceled. If the /// request is persistent, it remains /// active until it expires or is /// canceled.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithValidFrom(string validFrom) { this.validFromField = validFrom; return this; } /// <summary> /// Checks if ValidFrom property is set /// </summary> /// <returns>true if ValidFrom property is set</returns> public bool IsSetValidFrom() { return this.validFromField != null; } /// <summary> /// End date of the request. /// If this is a one-time request, the request remains active until all /// instances launch, the request expires, or the request is canceled. /// If the request is persistent, it remains active until it expires or /// is canceled. /// </summary> [XmlElementAttribute(ElementName = "ValidUntil")] public string ValidUntil { get { return this.validUntilField; } set { this.validUntilField = value; } } /// <summary> /// Sets the end date of the request. /// </summary> /// <param name="validUntil">End date of the request. If this is a one-time /// request, the request /// remains active until all instances launch, /// the request expires, or /// the request is canceled. If the request is /// persistent, it remains /// active until it expires or is canceled.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithValidUntil(string validUntil) { this.validUntilField = validUntil; return this; } /// <summary> /// Checks if ValidUntil property is set /// </summary> /// <returns>true if ValidUntil property is set</returns> public bool IsSetValidUntil() { return this.validUntilField != null; } /// <summary> /// The instance launch group. /// Launch groups are Spot Instances that launch and terminate together. /// </summary> [XmlElementAttribute(ElementName = "LaunchGroup")] public string LaunchGroup { get { return this.launchGroupField; } set { this.launchGroupField = value; } } /// <summary> /// Sets the instance launch group. /// </summary> /// <param name="launchGroup">Sets the instance launch group. Launch /// groups are Spot Instances that launch and terminate together.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithLaunchGroup(string launchGroup) { this.launchGroupField = launchGroup; return this; } /// <summary> /// Checks if LaunchGroup property is set /// </summary> /// <returns>true if LaunchGroup property is set</returns> public bool IsSetLaunchGroup() { return this.launchGroupField != null; } /// <summary> /// The Availability Zone group. /// If you specify the same Availability Zone group for all Spot Instance /// requests, all Spot Instances are launched in the same Availability Zone. /// </summary> [XmlElementAttribute(ElementName = "AvailabilityZoneGroup")] public string AvailabilityZoneGroup { get { return this.availabilityZoneGroupField; } set { this.availabilityZoneGroupField = value; } } /// <summary> /// Sets the Availability Zone group. /// </summary> /// <param name="availabilityZoneGroup">Specifies the Availability Zone group. If you /// specify the same Availability Zone group for /// all Spot Instance requests, all Spot /// Instances are launched in the same /// Availability Zone.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithAvailabilityZoneGroup(string availabilityZoneGroup) { this.availabilityZoneGroupField = availabilityZoneGroup; return this; } /// <summary> /// Checks if AvailabilityZoneGroup property is set /// </summary> /// <returns>true if AvailabilityZoneGroup property is set</returns> public bool IsSetAvailabilityZoneGroup() { return this.availabilityZoneGroupField != null; } /// <summary> /// Additional launch instance information. /// </summary> [XmlElementAttribute(ElementName = "LaunchSpecification")] public LaunchSpecification LaunchSpecification { get { return this.launchSpecificationField; } set { this.launchSpecificationField = value; } } /// <summary> /// Sets the additional launch instance information. /// </summary> /// <param name="launchSpecification">Specifies additional launch instance /// information.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithLaunchSpecification(LaunchSpecification launchSpecification) { this.launchSpecificationField = launchSpecification; return this; } /// <summary> /// Checks if LaunchSpecification property is set /// </summary> /// <returns>true if LaunchSpecification property is set</returns> public bool IsSetLaunchSpecification() { return this.launchSpecificationField != null; } /// <summary> /// The instance associated with the Spot Instance Request. /// </summary> [XmlElementAttribute(ElementName = "InstanceId")] public string InstanceId { get { return this.instanceIdField; } set { this.instanceIdField = value; } } /// <summary> /// Sets the instance associated with the Spot Instance Request. /// </summary> /// <param name="instanceId">The instance associated with the Spot Instance /// Request.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithInstanceId(string instanceId) { this.instanceIdField = instanceId; return this; } /// <summary> /// Checks if InstanceId property is set /// </summary> /// <returns>true if InstanceId property is set</returns> public bool IsSetInstanceId() { return this.instanceIdField != null; } /// <summary> /// Time stamp when the Spot Instance request was fulfilled. /// </summary> [XmlElementAttribute(ElementName = "CreateTime")] public string CreateTime { get { return this.createTimeField; } set { this.createTimeField = value; } } /// <summary> /// Sets the time stamp when the Spot Instance request was fulfilled. /// </summary> /// <param name="createTime">Time stamp when the Spot Instance request was /// fulfilled.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithCreateTime(string createTime) { this.createTimeField = createTime; return this; } /// <summary> /// Checks if CreateTime property is set /// </summary> /// <returns>true if CreateTime property is set</returns> public bool IsSetCreateTime() { return this.createTimeField != null; } /// <summary> /// The product description associated with the Spot Instance. /// </summary> [XmlElementAttribute(ElementName = "ProductDescription")] public string ProductDescription { get { return this.productDescriptionField; } set { this.productDescriptionField = value; } } /// <summary> /// Sets the product description associated with the Spot Instance. /// </summary> /// <param name="productDescription">The product description associated with the /// Spot Instance.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithProductDescription(string productDescription) { this.productDescriptionField = productDescription; return this; } /// <summary> /// Checks if ProductDescription property is set /// </summary> /// <returns>true if ProductDescription property is set</returns> public bool IsSetProductDescription() { return this.productDescriptionField != null; } /// <summary> /// A list of tags for the specified resources. /// </summary> [XmlElementAttribute(ElementName = "Tag")] public List<Tag> Tag { get { if (this.tagField == null) { this.tagField = new List<Tag>(); } return this.tagField; } set { this.tagField = value; } } /// <summary> /// Sets the tags for the specified resources. /// </summary> /// <param name="list">A list of tags for the specified resources.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithTag(params Tag[] list) { foreach (Tag item in list) { Tag.Add(item); } return this; } /// <summary> /// Checks if Tag property is set /// </summary> /// <returns>true if Tag property is set</returns> public bool IsSetTag() { return (Tag.Count > 0); } /// <summary> /// The Availability Zone in which the bid is launched. /// </summary> public string LaunchedAvailabilityZone { get { return this.launchedAvailabilityZoneField; } set { this.launchedAvailabilityZoneField = value; } } /// <summary> /// Sets the Availability Zone in which the bid is launched. /// </summary> /// <param name="launchedAvailabilityZone">The Availability Zone in which the bid is launched.</param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public SpotInstanceRequest WithLaunchedAvailabilityZone(string launchedAvailabilityZone) { this.launchedAvailabilityZoneField = launchedAvailabilityZone; return this; } /// <summary> /// Checks if LaunchedAvailabilityZone property is set /// </summary> /// <returns>true if LaunchedAvailabilityZone property is set</returns> public bool IsSetLaunchedAvailabilityZone() { return this.launchedAvailabilityZoneField != null; } } }
#region Copyright (c) 2009 S. van Deursen /* The CuttingEdge.Conditions library enables developers to validate pre- and postconditions in a fluent * manner. * * To contact me, please visit my blog at http://www.cuttingedge.it/blogs/steven/ * * Copyright (c) 2009 S. van Deursen * * 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 // NOTE: This file a copy of ValidatorExtensionTests.Compare.Base.cs with all occurrences of 'xxx' replaced // with 'Decimal'. using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CuttingEdge.Conditions.UnitTests.CompareTests { [TestClass] public class CompareDecimalTests { private static readonly Decimal One = 1; private static readonly Decimal Two = 2; private static readonly Decimal Three = 3; private static readonly Decimal Four = 4; private static readonly Decimal Five = 5; #region IsDecimalInRange [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsInRange on Decimal x with 'lower bound > x < upper bound' should fail.")] public void IsDecimalInRangeTest01() { Decimal a = One; Condition.Requires(a).IsInRange(Two, Four); } [TestMethod] [Description("Calling IsInRange on Decimal x with 'lower bound = x < upper bound' should pass.")] public void IsDecimalInRangeTest02() { Decimal a = Two; Condition.Requires(a).IsInRange(Two, Four); } [TestMethod] [Description("Calling IsInRange on Decimal x with 'lower bound < x < upper bound' should pass.")] public void IsDecimalInRangeTest03() { Decimal a = Three; Condition.Requires(a).IsInRange(Two, Four); } [TestMethod] [Description("Calling IsInRange on Decimal x with 'lower bound < x = upper bound' should pass.")] public void IsDecimalInRangeTest04() { Decimal a = Four; Condition.Requires(a).IsInRange(Two, Four); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsInRange on Decimal x with 'lower bound < x > upper bound' should fail.")] public void IsDecimalInRangeTest05() { Decimal a = Five; Condition.Requires(a).IsInRange(Two, Four); } [TestMethod] [Description("Calling IsInRange on Decimal x with conditionDescription should pass.")] public void IsDecimalInRangeTest06() { Decimal a = Four; Condition.Requires(a).IsInRange(Two, Four, string.Empty); } [TestMethod] [Description("Calling a failing IsInRange on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalInRangeTest07() { Decimal a = Five; try { Condition.Requires(a, "a").IsInRange(Two, Four, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsInRange on Decimal x with 'lower bound > x < upper bound' should succeed when exceptions are suppressed.")] public void IsDecimalInRangeTest08() { Decimal a = One; Condition.Requires(a).SuppressExceptionsForTest().IsInRange(Two, Four); } #endregion // IsDecimalInRange #region IsDecimalNotInRange [TestMethod] [Description("Calling IsNotInRange on Decimal x with 'lower bound > x < upper bound' should pass.")] public void IsDecimalNotInRangeTest01() { Decimal a = One; Condition.Requires(a).IsNotInRange(Two, Four); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling IsNotInRange on Decimal x with 'lower bound = x < upper bound' should fail.")] public void IsDecimalNotInRangeTest02() { Decimal a = Two; Condition.Requires(a).IsNotInRange(Two, Four); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling IsNotInRange on Decimal x with 'lower bound < x < upper bound' should fail.")] public void IsDecimalNotInRangeTest03() { Decimal a = Three; Condition.Requires(a).IsNotInRange(Two, Four); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling IsNotInRange on Decimal x with 'lower bound < x = upper bound' should fail.")] public void IsDecimalNotInRangeTest04() { Decimal a = Four; Condition.Requires(a).IsNotInRange(Two, Four); } [TestMethod] [Description("Calling IsNotInRange on Decimal x with 'lower bound < x > upper bound' should pass.")] public void IsDecimalNotInRangeTest05() { Decimal a = Five; Condition.Requires(a).IsNotInRange(Two, Four); } [TestMethod] [Description("Calling IsNotInRange on Decimal x with conditionDescription should pass.")] public void IsDecimalNotInRangeTest06() { Decimal a = Five; Condition.Requires(a).IsNotInRange(Two, Four, string.Empty); } [TestMethod] [Description("Calling a failing IsNotInRange on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalNotInRangeTest07() { Decimal a = Four; try { Condition.Requires(a, "a").IsNotInRange(Two, Four, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsNotInRange on Decimal x with 'lower bound = x < upper bound' should succeed when exceptions are suppressed.")] public void IsDecimalNotInRangeTest08() { Decimal a = Two; Condition.Requires(a).SuppressExceptionsForTest().IsNotInRange(Two, Four); } #endregion // IsDecimalNotInRange #region IsDecimalGreaterThan [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsGreaterThan on Decimal x with 'lower bound < x' should fail.")] public void IsDecimalGreaterThanTest01() { Decimal a = One; Condition.Requires(a).IsGreaterThan(Two); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsGreaterThan on Decimal x with 'lower bound = x' should fail.")] public void IsDecimalGreaterThanTest02() { Decimal a = Two; Condition.Requires(a).IsGreaterThan(Two); } [TestMethod] [Description("Calling IsGreaterThan on Decimal x with 'lower bound < x' should pass.")] public void IsDecimalGreaterThanTest03() { Decimal a = Three; Condition.Requires(a).IsGreaterThan(Two); } [TestMethod] [Description("Calling IsGreaterThan on Decimal x with conditionDescription should pass.")] public void IsDecimalGreaterThanTest04() { Decimal a = Three; Condition.Requires(a).IsGreaterThan(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsGreaterThan on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalGreaterThanTest05() { Decimal a = Three; try { Condition.Requires(a, "a").IsGreaterThan(Three, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsGreaterThan on Decimal x with 'lower bound < x' should succeed when exceptions are suppressed.")] public void IsDecimalGreaterThanTest06() { Decimal a = One; Condition.Requires(a).SuppressExceptionsForTest().IsGreaterThan(Two); } #endregion // IsDecimalGreaterThan #region IsDecimalNotGreaterThan [TestMethod] [Description("Calling IsNotGreaterThan on Decimal x with 'x < upper bound' should pass.")] public void IsDecimalNotGreaterThanTest01() { Decimal a = One; Condition.Requires(a).IsNotGreaterThan(Two); } [TestMethod] [Description("Calling IsNotGreaterThan on Decimal x with 'x = upper bound' should pass.")] public void IsDecimalNotGreaterThanTest02() { Decimal a = Two; Condition.Requires(a).IsNotGreaterThan(Two); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsNotGreaterThan on Decimal x with 'x > upper bound' should fail.")] public void IsDecimalNotGreaterThanTest03() { Decimal a = Three; Condition.Requires(a).IsNotGreaterThan(Two); } [TestMethod] [Description("Calling IsNotGreaterThan on Decimal x with conditionDescription should pass.")] public void IsDecimalNotGreaterThanTest04() { Decimal a = Two; Condition.Requires(a).IsNotGreaterThan(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsNotGreaterThan on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalNotGreaterThanTest05() { Decimal a = Three; try { Condition.Requires(a, "a").IsNotGreaterThan(Two, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsNotGreaterThan on Decimal x with 'x > upper bound' should succeed when exceptions are suppressed.")] public void IsDecimalNotGreaterThanTest06() { Decimal a = Three; Condition.Requires(a).SuppressExceptionsForTest().IsNotGreaterThan(Two); } #endregion // IsDecimalNotGreaterThan #region IsDecimalGreaterOrEqual [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsGreaterOrEqual on Decimal x with 'lower bound > x' should fail.")] public void IsDecimalGreaterOrEqualTest01() { Decimal a = One; Condition.Requires(a).IsGreaterOrEqual(Two); } [TestMethod] [Description("Calling IsGreaterOrEqual on Decimal x with 'lower bound = x' should pass.")] public void IsDecimalGreaterOrEqualTest02() { Decimal a = Two; Condition.Requires(a).IsGreaterOrEqual(Two); } [TestMethod] [Description("Calling IsGreaterOrEqual on Decimal x with 'lower bound < x' should pass.")] public void IsDecimalGreaterOrEqualTest03() { Decimal a = Three; Condition.Requires(a).IsGreaterOrEqual(Two); } [TestMethod] [Description("Calling IsGreaterOrEqual on Decimal x with conditionDescription should pass.")] public void IsDecimalGreaterOrEqualTest04() { Decimal a = Three; Condition.Requires(a).IsGreaterOrEqual(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsGreaterOrEqual on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalGreaterOrEqualTest05() { Decimal a = One; try { Condition.Requires(a, "a").IsGreaterOrEqual(Two, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsGreaterOrEqual on Decimal x with 'lower bound > x' should succeed when exceptions are suppressed.")] public void IsDecimalGreaterOrEqualTest06() { Decimal a = One; Condition.Requires(a).SuppressExceptionsForTest().IsGreaterOrEqual(Two); } #endregion // IsDecimalGreaterOrEqual #region IsDecimalNotGreaterOrEqual [TestMethod] [Description("Calling IsNotGreaterOrEqual on Decimal x with 'x < upper bound' should pass.")] public void IsDecimalNotGreaterOrEqualTest01() { Decimal a = One; Condition.Requires(a).IsNotGreaterOrEqual(Two); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsNotGreaterOrEqual on Decimal x with 'x = upper bound' should fail.")] public void IsDecimalNotGreaterOrEqualTest02() { Decimal a = Two; Condition.Requires(a).IsNotGreaterOrEqual(Two); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsNotGreaterOrEqual on Decimal x with 'x > upper bound' should fail.")] public void IsDecimalNotGreaterOrEqualTest03() { Decimal a = Three; Condition.Requires(a).IsNotGreaterOrEqual(Two); } [TestMethod] [Description("Calling IsNotGreaterOrEqual on Decimal x with conditionDescription should pass.")] public void IsDecimalNotGreaterOrEqualTest04() { Decimal a = One; Condition.Requires(a).IsNotGreaterOrEqual(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsNotGreaterOrEqual on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalNotGreaterOrEqualTest05() { Decimal a = Three; try { Condition.Requires(a, "a").IsNotGreaterOrEqual(Two, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsNotGreaterOrEqual on Decimal x with 'x = upper bound' should succeed when exceptions are suppressed.")] public void IsDecimalNotGreaterOrEqualTest06() { Decimal a = Two; Condition.Requires(a).SuppressExceptionsForTest().IsNotGreaterOrEqual(Two); } #endregion // IsDecimalNotGreaterOrEqual #region IsDecimalLessThan [TestMethod] [Description("Calling IsLessThan on Decimal x with 'x < upper bound' should pass.")] public void IsDecimalLessThanTest01() { Decimal a = One; Condition.Requires(a).IsLessThan(Two); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsLessThan on Decimal x with 'x = upper bound' should fail.")] public void IsDecimalLessThanTest02() { Decimal a = Two; Condition.Requires(a).IsLessThan(Two); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsLessThan on Decimal x with 'x > upper bound' should fail.")] public void IsDecimalLessThanTest03() { Decimal a = Three; Condition.Requires(a).IsLessThan(Two); } [TestMethod] [Description("Calling IsLessThan on Decimal x with conditionDescription should pass.")] public void IsDecimalLessThanTest04() { Decimal a = Two; Condition.Requires(a).IsLessThan(Three, string.Empty); } [TestMethod] [Description("Calling a failing IsLessThan on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalLessThanTest05() { Decimal a = Three; try { Condition.Requires(a, "a").IsLessThan(Two, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsLessThan on Decimal x with 'x = upper bound' should succeed when exceptions are suppressed.")] public void IsDecimalLessThanTest06() { Decimal a = Two; Condition.Requires(a).SuppressExceptionsForTest().IsLessThan(Two); } #endregion // IsDecimalLessThan #region IsDecimalNotLessThan [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsNotLessThan on Decimal x with 'lower bound > x' should fail.")] public void IsDecimalNotLessThanTest01() { Decimal a = One; Condition.Requires(a).IsNotLessThan(Two); } [TestMethod] [Description("Calling IsNotLessThan on Decimal x with 'lower bound = x' should pass.")] public void IsDecimalNotLessThanTest02() { Decimal a = Two; Condition.Requires(a).IsNotLessThan(Two); } [TestMethod] [Description("Calling IsNotLessThan on Decimal x with 'lower bound < x' should pass.")] public void IsDecimalNotLessThanTest03() { Decimal a = Three; Condition.Requires(a).IsNotLessThan(Two); } [TestMethod] [Description("Calling IsNotLessThan on Decimal x with conditionDescription should pass.")] public void IsDecimalNotLessThanTest04() { Decimal a = Two; Condition.Requires(a).IsNotLessThan(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsNotLessThan on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalNotLessThanTest05() { Decimal a = Two; try { Condition.Requires(a, "a").IsNotLessThan(Three, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsNotLessThan on Decimal x with 'lower bound > x' should succeed when exceptions are suppressed.")] public void IsDecimalNotLessThanTest06() { Decimal a = One; Condition.Requires(a).SuppressExceptionsForTest().IsNotLessThan(Two); } #endregion // IsDecimalNotLessThan #region IsDecimalLessOrEqual [TestMethod] [Description("Calling IsLessOrEqual on Decimal x with 'x < upper bound' should pass.")] public void IsDecimalLessOrEqualTest01() { Decimal a = One; Condition.Requires(a).IsLessOrEqual(Two); } [TestMethod] [Description("Calling IsLessOrEqual on Decimal x with 'x = upper bound' should pass.")] public void IsDecimalLessOrEqualTest02() { Decimal a = Two; Condition.Requires(a).IsLessOrEqual(Two); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsLessOrEqual on Decimal x with 'x > upper bound' should fail.")] public void IsDecimalLessOrEqualTest03() { Decimal a = Three; Condition.Requires(a).IsLessOrEqual(Two); } [TestMethod] [Description("Calling IsLessOrEqual on Decimal x with conditionDescription should pass.")] public void IsDecimalLessOrEqualTest04() { Decimal a = Two; Condition.Requires(a).IsLessOrEqual(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsLessOrEqual on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalLessOrEqualTest05() { Decimal a = Three; try { Condition.Requires(a, "a").IsLessOrEqual(Two, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsLessOrEqual on Decimal x with 'x > upper bound' should succeed when exceptions are suppressed.")] public void IsDecimalLessOrEqualTest06() { Decimal a = Three; Condition.Requires(a).SuppressExceptionsForTest().IsLessOrEqual(Two); } #endregion // IsDecimalLessOrEqual #region IsDecimalNotLessOrEqual [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsNotLessOrEqual on Decimal x with 'lower bound > x' should fail.")] public void IsDecimalNotLessOrEqualTest01() { Decimal a = One; Condition.Requires(a).IsNotLessOrEqual(Two); } [TestMethod] [ExpectedException(typeof(ArgumentOutOfRangeException))] [Description("Calling IsNotLessOrEqual on Decimal x with 'lower bound = x' should fail.")] public void IsDecimalNotLessOrEqualTest02() { Decimal a = Two; Condition.Requires(a).IsNotLessOrEqual(Two); } [TestMethod] [Description("Calling IsNotLessOrEqual on Decimal x with 'lower bound < x' should pass.")] public void IsDecimalNotLessOrEqualTest03() { Decimal a = Three; Condition.Requires(a).IsNotLessOrEqual(Two); } [TestMethod] [Description("Calling IsNotLessOrEqual on Decimal x with conditionDescription should pass.")] public void IsDecimalNotLessOrEqualTest04() { Decimal a = Three; Condition.Requires(a).IsNotLessOrEqual(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsNotLessOrEqual on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalNotLessOrEqualTest05() { Decimal a = Two; try { Condition.Requires(a, "a").IsNotLessOrEqual(Two, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsNotLessOrEqual on Decimal x with 'lower bound > x' should succeed when exceptions are suppressed.")] public void IsDecimalNotLessOrEqualTest06() { Decimal a = One; Condition.Requires(a).SuppressExceptionsForTest().IsNotLessOrEqual(Two); } #endregion // IsNotLessOrEqual #region IsDecimalEqualTo [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling IsEqualTo on Decimal x with 'x < other' should fail.")] public void IsDecimalEqualToTest01() { Decimal a = One; Condition.Requires(a).IsEqualTo(Two); } [TestMethod] [Description("Calling IsEqualTo on Decimal x with 'x = other' should pass.")] public void IsDecimalEqualToTest02() { Decimal a = Two; Condition.Requires(a).IsEqualTo(Two); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling IsEqualTo on Decimal x with 'x > other' should fail.")] public void IsDecimalEqualToTest03() { Decimal a = Three; Condition.Requires(a).IsEqualTo(Two); } [TestMethod] [Description("Calling IsEqualTo on Decimal x with conditionDescription should pass.")] public void IsDecimalEqualToTest04() { Decimal a = Two; Condition.Requires(a).IsEqualTo(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsEqualTo on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalEqualToTest05() { Decimal a = Three; try { Condition.Requires(a, "a").IsEqualTo(Two, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsEqualTo on Decimal x with 'x < other' should succeed when exceptions are suppressed.")] public void IsDecimalEqualToTest06() { Decimal a = One; Condition.Requires(a).SuppressExceptionsForTest().IsEqualTo(Two); } #endregion // IsDecimalEqualTo #region IsDecimalNotEqualTo [TestMethod] [Description("Calling IsNotEqualTo on Decimal x with 'x < other' should pass.")] public void IsDecimalNotEqualToTest01() { Decimal a = One; Condition.Requires(a).IsNotEqualTo(Two); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling IsNotEqualTo on Decimal x with 'x = other' should fail.")] public void IsDecimalNotEqualToTest02() { Decimal a = Two; Condition.Requires(a).IsNotEqualTo(Two); } [TestMethod] [Description("Calling IsNotEqualTo on Decimal x with 'x > other' should pass.")] public void IsDecimalNotEqualToTest03() { Decimal a = Three; Condition.Requires(a).IsNotEqualTo(Two); } [TestMethod] [Description("Calling IsNotEqualTo on Decimal x with conditionDescription should pass.")] public void IsDecimalNotEqualToTest04() { Decimal a = Three; Condition.Requires(a).IsNotEqualTo(Two, string.Empty); } [TestMethod] [Description("Calling a failing IsNotEqualTo on Decimal should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void IsDecimalNotEqualToTest05() { Decimal a = Two; try { Condition.Requires(a, "a").IsNotEqualTo(Two, "abc {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("abc a xyz")); } } [TestMethod] [Description("Calling IsNotEqualTo on Decimal x with 'x = other' should succeed when exceptions are suppressed.")] public void IsDecimalNotEqualToTest06() { Decimal a = Two; Condition.Requires(a).SuppressExceptionsForTest().IsNotEqualTo(Two); } #endregion // IsDecimalNotEqualTo } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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 System.Globalization; namespace ASC.Web.Core.Helpers { /// <summary> /// Defines a type converter for enum values that converts enum values to /// and from string representations using resources /// </summary> /// <remarks> /// This class makes localization of display values for enums in a project easy. Simply /// derive a class from this class and pass the ResourceManagerin the constructor. /// /// Then define the enum values in the resource editor. The names of /// the resources are simply the enum value prefixed by the enum type name with an /// underscore separator eg MyEnum_MyValue. You can then use the TypeConverter attribute /// to make the LocalizedEnumConverter the default TypeConverter for the enums in your /// project. /// </remarks> public class ResourceEnumConverter : System.ComponentModel.EnumConverter { private class LookupTable : Dictionary<string, object> { } private readonly Dictionary<CultureInfo, LookupTable> _lookupTables = new Dictionary<CultureInfo, LookupTable>(); private readonly System.Resources.ResourceManager _resourceManager; private readonly bool _isFlagEnum = false; private readonly Array _flagValues; /// <summary> /// Get the lookup table for the given culture (creating if necessary) /// </summary> /// <param name="culture"></param> /// <returns></returns> private LookupTable GetLookupTable(CultureInfo culture) { LookupTable result = null; if (culture == null) culture = CultureInfo.CurrentCulture; if (!_lookupTables.TryGetValue(culture, out result)) { result = new LookupTable(); foreach (object value in GetStandardValues()) { string text = GetValueText(culture, value); if (text != null) { result.Add(text, value); } } _lookupTables.Add(culture, result); } return result; } /// <summary> /// Return the text to display for a simple value in the given culture /// </summary> /// <param name="culture">The culture to get the text for</param> /// <param name="value">The enum value to get the text for</param> /// <returns>The localized text</returns> private string GetValueText(CultureInfo culture, object value) { Type type = value.GetType(); string resourceName = string.Format("{0}_{1}", type.Name, value.ToString()); string result = _resourceManager.GetString(resourceName, culture); if (result == null) result = resourceName; return result; } /// <summary> /// Return true if the given value is can be represented using a single bit /// </summary> /// <param name="value"></param> /// <returns></returns> private bool IsSingleBitValue(ulong value) { switch (value) { case 0: return false; case 1: return true; } return ((value & (value - 1)) == 0); } /// <summary> /// Return the text to display for a flag value in the given culture /// </summary> /// <param name="culture">The culture to get the text for</param> /// <param name="value">The flag enum value to get the text for</param> /// <returns>The localized text</returns> private string GetFlagValueText(CultureInfo culture, object value) { // if there is a standard value then use it // if (Enum.IsDefined(value.GetType(), value)) { return GetValueText(culture, value); } // otherwise find the combination of flag bit values // that makes up the value // ulong lValue = Convert.ToUInt32(value); string result = null; foreach (object flagValue in _flagValues) { ulong lFlagValue = Convert.ToUInt32(flagValue); if (IsSingleBitValue(lFlagValue)) { if ((lFlagValue & lValue) == lFlagValue) { string valueText = GetValueText(culture, flagValue); if (result == null) { result = valueText; } else { result = string.Format("{0}, {1}", result, valueText); } } } } return result; } /// <summary> /// Return the Enum value for a simple (non-flagged enum) /// </summary> /// <param name="culture">The culture to convert using</param> /// <param name="text">The text to convert</param> /// <returns>The enum value</returns> private object GetValue(CultureInfo culture, string text) { LookupTable lookupTable = GetLookupTable(culture); object result = null; lookupTable.TryGetValue(text, out result); return result; } /// <summary> /// Return the Enum value for a flagged enum /// </summary> /// <param name="culture">The culture to convert using</param> /// <param name="text">The text to convert</param> /// <returns>The enum value</returns> private object GetFlagValue(CultureInfo culture, string text) { LookupTable lookupTable = GetLookupTable(culture); string[] textValues = text.Split(','); ulong result = 0; foreach (string textValue in textValues) { object value = null; string trimmedTextValue = textValue.Trim(); if (!lookupTable.TryGetValue(trimmedTextValue, out value)) { return null; } result |= Convert.ToUInt32(value); } return Enum.ToObject(EnumType, result); } /// <summary> /// Create a new instance of the converter using translations from the given resource manager /// </summary> /// <param name="type"></param> /// <param name="resourceManager"></param> public ResourceEnumConverter(Type type, System.Resources.ResourceManager resourceManager) : base(type) { _resourceManager = resourceManager; object[] flagAttributes = type.GetCustomAttributes(typeof(FlagsAttribute), true); _isFlagEnum = flagAttributes.Length > 0; if (_isFlagEnum) { _flagValues = Enum.GetValues(type); } } /// <summary> /// Convert string values to enum values /// </summary> /// <param name="context"></param> /// <param name="culture"></param> /// <param name="value"></param> /// <returns></returns> public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is string) { object result = (_isFlagEnum) ? GetFlagValue(culture, (string)value) : GetValue(culture, (string)value); if (result == null) { result = base.ConvertFrom(context, culture, value); } return result; } else { return base.ConvertFrom(context, culture, value); } } /// <summary> /// Convert the enum value to a string /// </summary> /// <param name="context"></param> /// <param name="culture"></param> /// <param name="value"></param> /// <param name="destinationType"></param> /// <returns></returns> public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (value != null && destinationType == typeof(string)) { object result = (_isFlagEnum) ? GetFlagValueText(culture, value) : GetValueText(culture, value); return result; } else { return base.ConvertTo(context, culture, value, destinationType); } } /// <summary> /// Convert the given enum value to string using the registered type converter /// </summary> /// <param name="value">The enum value to convert to string</param> /// <returns>The localized string value for the enum</returns> static public string ConvertToString(Enum value) { TypeConverter converter = TypeDescriptor.GetConverter(value.GetType()); return converter.ConvertToString(value); } /// <summary> /// Return a list of the enum values and their associated display text for the given enum type /// </summary> /// <param name="enumType">The enum type to get the values for</param> /// <param name="culture">The culture to get the text for</param> /// <returns> /// A list of KeyValuePairs where the key is the enum value and the value is the text to display /// </returns> /// <remarks> /// This method can be used to provide localized binding to enums in ASP.NET applications. Unlike /// windows forms the standard ASP.NET controls do not use TypeConverters to convert from enum values /// to the displayed text. You can bind an ASP.NET control to the list returned by this method by setting /// the DataValueField to "Key" and theDataTextField to "Value". /// </remarks> static public List<KeyValuePair<Enum, string>> GetValues(Type enumType, CultureInfo culture) { List<KeyValuePair<Enum, string>> result = new List<KeyValuePair<Enum, string>>(); TypeConverter converter = TypeDescriptor.GetConverter(enumType); foreach (Enum value in Enum.GetValues(enumType)) { KeyValuePair<Enum, string> pair = new KeyValuePair<Enum, string>(value, converter.ConvertToString(null, culture, value)); result.Add(pair); } return result; } /// <summary> /// Return a list of the enum values and their associated display text for the given enum type in the current UI Culture /// </summary> /// <param name="enumType">The enum type to get the values for</param> /// <returns> /// A list of KeyValuePairs where the key is the enum value and the value is the text to display /// </returns> /// <remarks> /// This method can be used to provide localized binding to enums in ASP.NET applications. Unlike /// windows forms the standard ASP.NET controls do not use TypeConverters to convert from enum values /// to the displayed text. You can bind an ASP.NET control to the list returned by this method by setting /// the DataValueField to "Key" and theDataTextField to "Value". /// </remarks> static public List<KeyValuePair<Enum, string>> GetValues(Type enumType) { return GetValues(enumType, CultureInfo.CurrentUICulture); } } }
//------------------------------------------------------------------------------ // <copyright file="SessionStateUtil.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * SessionStateUtil * */ namespace System.Web.SessionState { using System.Collections; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Runtime.Serialization; using System.Security.Permissions; using System.Web; using System.Web.Util; using System.Xml; public static class SessionStateUtility { internal const String SESSION_KEY = "AspSession"; // Used by AltSerialization's BinaryFormatter for session serialization customization public static ISurrogateSelector SerializationSurrogateSelector { [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] get; [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] set; } // Called by custom session state module if they want to raise Session_End. static public void RaiseSessionEnd(IHttpSessionState session, Object eventSource, EventArgs eventArgs) { HttpApplicationFactory.EndSession(new HttpSessionState(session), eventSource, eventArgs); } // Called by custom session state module static public void AddHttpSessionStateToContext(HttpContext context, IHttpSessionState container) { HttpSessionState sessionState = new HttpSessionState(container); try { context.Items.Add(SESSION_KEY, sessionState); } catch (ArgumentException) { throw new HttpException(SR.GetString(SR.Cant_have_multiple_session_module)); } } static internal void AddHttpSessionStateModuleToContext(HttpContext context, SessionStateModule module, bool delayed) { context.AddHttpSessionStateModule(module, delayed); } static internal void RemoveHttpSessionStateFromContext(HttpContext context, bool delayed) { if (!delayed) { context.Items.Remove(SESSION_KEY); } context.RemoveHttpSessionStateModule(); } // Called by custom session state module static public void RemoveHttpSessionStateFromContext(HttpContext context) { RemoveHttpSessionStateFromContext(context, false); } // Called by custom session state module static public IHttpSessionState GetHttpSessionStateFromContext(HttpContext context) { return context.Session.Container; } static public HttpStaticObjectsCollection GetSessionStaticObjects(HttpContext context) { return context.Application.SessionStaticObjects.Clone(); } internal static SessionStateStoreData CreateLegitStoreData(HttpContext context, ISessionStateItemCollection sessionItems, HttpStaticObjectsCollection staticObjects, int timeout) { if (sessionItems == null) { sessionItems = new SessionStateItemCollection(); } if (staticObjects == null && context != null) { staticObjects = SessionStateUtility.GetSessionStaticObjects(context); } return new SessionStateStoreData(sessionItems, staticObjects, timeout); } // This method will take an item and serialize it [SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)] internal static void Serialize(SessionStateStoreData item, Stream stream) { bool hasItems = true; bool hasStaticObjects = true; BinaryWriter writer = new BinaryWriter(stream); writer.Write(item.Timeout); if (item.Items == null || item.Items.Count == 0) { hasItems = false; } writer.Write(hasItems); if (item.StaticObjects == null || item.StaticObjects.NeverAccessed) { hasStaticObjects = false; } writer.Write(hasStaticObjects); if (hasItems) { ((SessionStateItemCollection)item.Items).Serialize(writer); } if (hasStaticObjects) { item.StaticObjects.Serialize(writer); } // Prevent truncation of the stream writer.Write(unchecked((byte)0xff)); } // This will deserialize and return an item. // This version uses the default classes for SessionStateItemCollection, HttpStaticObjectsCollection // and SessionStateStoreData [SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)] internal static SessionStateStoreData Deserialize(HttpContext context, Stream stream) { int timeout; SessionStateItemCollection sessionItems; bool hasItems; bool hasStaticObjects; HttpStaticObjectsCollection staticObjects; Byte eof; Debug.Assert(context != null); try { BinaryReader reader = new BinaryReader(stream); timeout = reader.ReadInt32(); hasItems = reader.ReadBoolean(); hasStaticObjects = reader.ReadBoolean(); if (hasItems) { sessionItems = SessionStateItemCollection.Deserialize(reader); } else { sessionItems = new SessionStateItemCollection(); } if (hasStaticObjects) { staticObjects = HttpStaticObjectsCollection.Deserialize(reader); } else { staticObjects = SessionStateUtility.GetSessionStaticObjects(context); } eof = reader.ReadByte(); if (eof != 0xff) { throw new HttpException(SR.GetString(SR.Invalid_session_state)); } } catch (EndOfStreamException) { throw new HttpException(SR.GetString(SR.Invalid_session_state)); } return new SessionStateStoreData(sessionItems, staticObjects, timeout); } static internal void SerializeStoreData(SessionStateStoreData item, int initialStreamSize, out byte[] buf, out int length, bool compressionEnabled) { using(MemoryStream s = new MemoryStream(initialStreamSize)) { SessionStateUtility.Serialize(item, s); if(compressionEnabled) { byte[] serializedBuffer = s.GetBuffer(); int serializedLength = (int)s.Length; // truncate the MemoryStream so we can write the compressed data in it s.SetLength(0); // compress the serialized bytes using(DeflateStream zipStream = new DeflateStream(s, CompressionMode.Compress, true)) { zipStream.Write(serializedBuffer, 0, serializedLength); } // if the session state tables have ANSI_PADDING disabled, last )s are trimmed. // This shouldn't happen, but to be sure, we are padding with an extra byte s.WriteByte((byte)0xff); } buf = s.GetBuffer(); length = (int) s.Length; } } static internal SessionStateStoreData DeserializeStoreData(HttpContext context, Stream stream, bool compressionEnabled) { if(compressionEnabled) { // apply the compression decorator on top of the stream // the data should not be bigger than 4GB - compression doesn't work for more than that using(DeflateStream zipStream = new DeflateStream(stream, CompressionMode.Decompress, true)) { return SessionStateUtility.Deserialize(context, zipStream); } } return SessionStateUtility.Deserialize(context, stream); } } }
using System; using System.Collections.Generic; using System.IO; using BTDB.KVDBLayer; using BTDB.ODBLayer; using System.Diagnostics; using ODbDump.Visitor; using BTDB.StreamLayer; using System.Linq; using System.Text; using System.Threading; using BTDB.Collections; using Microsoft.Extensions.Primitives; using ODbDump.TrlDump; namespace ODbDump { class Program { static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Need to have just one parameter with directory of ObjectDB"); Console.WriteLine( "Optional second parameter: nicedump, comparedump, diskdump, dump, dumpnull, stat, statm, fileheaders, compact, export, import, leaks, leakscode, size, frequency, interactive, check, findsplitbrain, fulldiskdump, trldump"); return; } var action = "nicedump"; if (args.Length > 1) { action = args[1].ToLowerInvariant(); } switch (action) { case "realpath": { var res = PlatformMethods.Instance.RealPath(args[0]); if (res == null) Console.WriteLine("Error resolving real path for " + args[0]); else Console.WriteLine(res); break; } case "nicedump": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var trkv = kdb.StartReadOnlyTransaction(); using var tr = odb.StartTransaction(); Console.WriteLine("CommitUlong: " + tr.GetCommitUlong()); Console.WriteLine("Ulong[0] oid: " + trkv.GetUlong(0)); Console.WriteLine("Ulong[1] dictid: " + trkv.GetUlong(1)); var visitor = new ToConsoleVisitorNice(); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(); break; } case "interactive": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var trkv = kdb.StartReadOnlyTransaction(); using var tr = odb.StartTransaction(); Console.WriteLine("CommitUlong: " + tr.GetCommitUlong()); Console.WriteLine("Ulong[0] oid: " + trkv.GetUlong(0)); Console.WriteLine("Ulong[1] dictid: " + trkv.GetUlong(1)); var visitor = new ToConsoleVisitorNice(); var iterator = new ODBIterator(tr, visitor); iterator.LoadGlobalInfo(true); Interactive(iterator, visitor); break; } case "comparedump": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var trkv = kdb.StartReadOnlyTransaction(); using var tr = odb.StartTransaction(); var visitor = new ToConsoleVisitorForComparison(); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(sortTableByNameAsc: true); break; } case "comparesplitdump": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var trkv = kdb.StartReadOnlyTransaction(); using var tr = odb.StartTransaction(); using var visitor = new ToFilesVisitorForComparison(HashType.Crc32); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(sortTableByNameAsc: true); break; } case "fulldiskdump": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var trkv = kdb.StartReadOnlyTransaction(); using var tr = odb.StartTransaction(); using var visitor = new ToFilesVisitorWithSecondaryKeys(); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(sortTableByNameAsc: true); break; } case "diskdump": { var dbDir = args[0]; var openUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null; var fileName = Path.Combine(dbDir, "dump"+(openUpToCommitUlong.HasValue?openUpToCommitUlong.ToString():"")+".txt"); DiskDump(dbDir, fileName, openUpToCommitUlong); break; } case "dump": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var trkv = kdb.StartReadOnlyTransaction(); using var tr = odb.StartTransaction(); Console.WriteLine("CommitUlong: " + tr.GetCommitUlong()); Console.WriteLine("Ulong[0] oid: " + trkv.GetUlong(0)); Console.WriteLine("Ulong[1] dictid: " + trkv.GetUlong(1)); var visitor = new ToConsoleVisitor(); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(); break; } case "dumpnull": case "null": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var tr = odb.StartTransaction(); var visitor = new ToNullVisitor(); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(); break; } case "check": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var transaction = kdb.StartReadOnlyTransaction(); var keyValueCount = transaction.GetKeyValueCount(); transaction.FindFirstKey(ReadOnlySpan<byte>.Empty); for (long kv = 0; kv < keyValueCount; kv++) { transaction.GetKey(); transaction.GetValue(); transaction.FindNextKey(ReadOnlySpan<byte>.Empty); } break; } case "stat": { var sw = new Stopwatch(); sw.Start(); using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new BTreeKeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, Compression = new SnappyCompressionStrategy(), OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); sw.Stop(); Console.WriteLine( $"Opened in {sw.Elapsed.TotalSeconds:F1}s Using {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024}MB RAM"); Console.WriteLine(kdb.CalcStats()); break; } case "statm": // Stat but by old managed implementation { var sw = new Stopwatch(); sw.Start(); using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, Compression = new SnappyCompressionStrategy(), OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); sw.Stop(); Console.WriteLine( $"Opened in {sw.Elapsed.TotalSeconds:F1}s Using {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024}MB RAM"); Console.WriteLine(kdb.CalcStats()); break; } case "kvi": { var sw = Stopwatch.StartNew(); using var dfc = new OnDiskFileCollection(args[0]); var options = new KeyValueDBOptions { FileCollection = dfc, Compression = new SnappyCompressionStrategy(), FileSplitSize = 100 * 1024 * 1024, CompactorScheduler = null, Logger = new ConsoleKvdbLogger(), }; using var kdb = new BTreeKeyValueDB(options); Console.WriteLine( $"Opened in {sw.Elapsed.TotalSeconds:F1}s Using {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024}MB RAM"); sw.Restart(); kdb.CreateKvi(CancellationToken.None); Console.WriteLine( $"Created kvi in {sw.Elapsed.TotalSeconds:F1}s Using {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024}MB RAM"); break; } case "kvim": // Kvi but by old managed implementation { var sw = Stopwatch.StartNew(); using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(dfc, new SnappyCompressionStrategy(), 100 * 1024 * 1024, null); Console.WriteLine( $"Opened in {sw.Elapsed.TotalSeconds:F1}s Using {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024}MB RAM"); sw.Restart(); kdb.CreateKvi(CancellationToken.None); Console.WriteLine( $"Created kvi in {sw.Elapsed.TotalSeconds:F1}s Using {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024}MB RAM"); break; } case "fileheaders": { using var dfc = new OnDiskFileCollection(args[0]); var fcfi = new FileCollectionWithFileInfos(dfc); foreach (var fi in fcfi.FileInfos) { var details = ""; switch (fi.Value) { case IKeyIndex keyIndex: { details = $"KVCount:{keyIndex.KeyValueCount} CommitUlong:{keyIndex.CommitUlong} TrLogFileId:{keyIndex.TrLogFileId} TrLogOffset:{keyIndex.TrLogOffset}\n"; details += LoadUsedFilesFromKvi(keyIndex, fcfi, fi.Key); break; } case IFileTransactionLog trlog: details = $"Previous File Id: {trlog.PreviousFileId}"; break; } Console.WriteLine("File {0} Guid:{3} Gen:{2} Type:{1} {4}", fi.Key, fi.Value.FileType.ToString(), fi.Value.Generation, fi.Value.Guid, details); } break; } case "compact": { var sw = new Stopwatch(); sw.Start(); using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(dfc, new SnappyCompressionStrategy(), 100 * 1024 * 1024, null); kdb.Logger = new ConsoleKvdbLogger(); sw.Stop(); Console.WriteLine( $"Opened in {sw.Elapsed.TotalSeconds:F1}s Using {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024}MB RAM"); sw.Restart(); while (kdb.Compact(new CancellationToken())) { sw.Stop(); Console.WriteLine($"Compaction iteration in {sw.Elapsed.TotalSeconds:F1}"); sw.Restart(); } sw.Stop(); Console.WriteLine( $"Final compaction in {sw.Elapsed.TotalSeconds:F1} Using {Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024}MB RAM"); Console.WriteLine(kdb.CalcStats()); break; } case "export": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, Compression = new SnappyCompressionStrategy(), OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var tr = kdb.StartReadOnlyTransaction(); using var st = File.Create(Path.Combine(args[0], "snapshot.dat")); KeyValueDBExportImporter.Export(tr, st); break; } case "import": { using var st = File.OpenRead(Path.Combine(args[0], "snapshot.dat")); using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(dfc); using var tr = kdb.StartTransaction(); KeyValueDBExportImporter.Import(tr, st); tr.Commit(); break; } case "leaks": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, Compression = new SnappyCompressionStrategy(), OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); Console.WriteLine("Leaks: "); odb.Open(kdb, false); odb.DumpLeaks(); break; } case "leakscode": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, Compression = new SnappyCompressionStrategy(), OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); odb.DumpLeaksCode(); break; } case "frequency": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, Compression = new SnappyCompressionStrategy(), OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var tr = odb.StartTransaction(); var visitor = new ToConsoleFrequencyVisitor(); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(); visitor.OutputStatistic(); } break; case "size": { using var dfc = new OnDiskFileCollection(args[0]); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, Compression = new SnappyCompressionStrategy(), OpenUpToCommitUlong = args.Length >= 3 ? (ulong?)ulong.Parse(args[2]) : null }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var tr = odb.StartTransaction(); var visitor = new ToConsoleSizeVisitor(); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(); } break; case "findsplitbrain": { if (args.Length != 6) { Console.WriteLine( "usage: ODBDump Eagle_0 findsplitbrain Eagle_1 1000 100000 INestedEventTable"); return; } var startEvent = ulong.Parse(args[3]); var endEvent = ulong.Parse(args[4]); var relationName = args[5]; var (found, lastGood, firstBad) = FindSplitBrain(args[0], args[2], relationName, startEvent, endEvent); if (found) { Console.WriteLine($"Split occured between {lastGood} and {firstBad}"); DiskDump(args[0], $"dump_{lastGood}_0.txt", lastGood); DiskDump(args[2], $"dump_{lastGood}_1.txt", lastGood); DiskDump(args[0], $"dump_{firstBad}_0.txt", firstBad); DiskDump(args[2], $"dump_{firstBad}_1.txt", firstBad); } } break; case "trldump": { using var outFile = File.CreateText("tlrdump.txt"); var visitor = new TrlVisitor(outFile); using var dfc = new OnDiskFileCollection(args[0]); foreach (var file in dfc.Enumerate()) { try { visitor.StartFile(file.Index, file.GetSize()); var reader = new TrlFileReader(file); reader.Iterate(visitor); } catch (Exception e) { visitor.OperationDetail("Failure " + e.Message); } visitor.EndOperation(); } } break; default: { Console.WriteLine($"Unknown action: {action}"); break; } } } static string LoadUsedFilesFromKvi(IKeyIndex keyIndex, FileCollectionWithFileInfos fcfi, uint fileId) { try { var file = fcfi.GetFile(fileId); var reader = new SpanReader(file.GetExclusiveReader()); FileKeyIndex.SkipHeader(ref reader); var keyCount = keyIndex.KeyValueCount; var usedFileIds = new RefDictionary<uint, ulong>(); if (keyIndex.Compression == KeyIndexCompression.Old) { for (var i = 0; i < keyCount; i++) { var keyLength = reader.ReadVInt32(); reader.SkipBlock(keyLength); var vFileId = reader.ReadVUInt32(); reader.SkipVUInt32(); var len = reader.ReadVInt32(); if (vFileId > 0) usedFileIds.GetOrAddValueRef(vFileId) += (ulong)Math.Abs(len); } } else { if (keyIndex.Compression != KeyIndexCompression.None) return ""; for (var i = 0; i < keyCount; i++) { reader.SkipVUInt32(); var keyLengthWithoutPrefix = (int)reader.ReadVUInt32(); reader.SkipBlock(keyLengthWithoutPrefix); var vFileId = reader.ReadVUInt32(); reader.SkipVUInt32(); var len = reader.ReadVInt32(); if (vFileId > 0) usedFileIds.GetOrAddValueRef(vFileId) += (ulong)Math.Abs(len); } } var used = usedFileIds.OrderBy(a => a.Key).ToArray(); var sb = new StringBuilder(); foreach (var keyValuePair in used) { sb.Append(" in "); sb.Append(keyValuePair.Key); sb.Append(" used "); sb.Append(keyValuePair.Value); sb.Append('\n'); } return sb.ToString(); } catch { // ignore } return ""; } static (bool found, ulong lastGood, ulong firstBad) FindSplitBrain(string dir1, string dir2, string relationName, ulong startEvent, ulong endEvent) { if (!CheckStartEquals()) return (false, 0, 0); bool CheckStartEquals() { var startContent0 = DumpRelationContent(dir1, relationName, startEvent); var startContent1 = DumpRelationContent(dir2, relationName, startEvent); if (startContent0 == startContent1) return true; Console.WriteLine("DBs differs already on start event."); return false; } if (!CheckEndDiffers()) return (false, 0, 0); bool CheckEndDiffers() { var endContent0 = DumpRelationContent(dir1, relationName, endEvent); var endContent1 = DumpRelationContent(dir2, relationName, endEvent); if (endContent0 != endContent1) return true; Console.WriteLine("DBs are same on end event."); return false; } var l = startEvent; var r = endEvent; while (l + 1 < r) { var m = (r + l) / 2; var content0 = DumpRelationContent(dir1, relationName, m); var content1 = DumpRelationContent(dir2, relationName, m); if (content0 == content1) l = m; else r = m; Console.WriteLine($"Narrowing to {l} .. {r}"); } return (true, l, r); } static string DumpRelationContent(string dbDir, string relationName, ulong? openUpToCommitUlong) { using var dfc = new OnDiskFileCollection(dbDir); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = openUpToCommitUlong }); using var odb = new ObjectDB(); odb.Open(kdb, false); using var trkv = kdb.StartReadOnlyTransaction(); using var tr = odb.StartTransaction(); var visitor = new ToStringFastVisitor(); var iterator = new ODBIterator(tr, visitor); iterator.LoadGlobalInfo(); var relationIdInfo = iterator.RelationId2Info.FirstOrDefault(kvp => kvp.Value.Name.EndsWith(relationName)); if (relationIdInfo.Value == null) return ""; iterator.IterateRelation(relationIdInfo.Value); return visitor.ToString(); } static void DiskDump(string dbDir, string fileName, ulong? openUpToCommitUlong) { using var dfc = new OnDiskFileCollection(dbDir); using var kdb = new KeyValueDB(new KeyValueDBOptions { FileCollection = dfc, ReadOnly = true, OpenUpToCommitUlong = openUpToCommitUlong }); using var odb = new ObjectDB(); using var tst = File.CreateText(fileName); odb.Open(kdb, false); using var trkv = kdb.StartReadOnlyTransaction(); using var tr = odb.StartTransaction(); tst.WriteLine("CommitUlong: " + tr.GetCommitUlong()); tst.WriteLine("Ulong[0] oid: " + trkv.GetUlong(0)); tst.WriteLine("Ulong[1] dictid: " + trkv.GetUlong(1)); var visitor = new ToFileVisitorNice(tst); var iterator = new ODBIterator(tr, visitor); iterator.Iterate(); } static void Interactive(ODBIterator iterator, ToConsoleVisitorNice visitor) { Console.WriteLine("Enter command:"); var currentRelationId = -1; while (true) { var line = Console.ReadLine(); if (line == null) break; var words = line.Split(' '); switch (words[0]) { default: Console.WriteLine("Unknown command " + words[0]); goto case "help"; case "": case "h": case "help": Console.WriteLine("Commands help:"); Console.WriteLine("l list"); Console.WriteLine("e exit"); continue; case "o": case "oid": if (words.Length == 2) { if (uint.TryParse(words[1], out var oid)) iterator.IterateOid(oid); } else { Console.WriteLine("oid command help:"); Console.WriteLine("oid id"); continue; } break; case "ri": case "relation-info": if (currentRelationId >= 0) { PrintRelationInfo(iterator, iterator.RelationId2Info[(uint)currentRelationId]); } else { Console.WriteLine("First do: select relation id"); } break; case "s": case "select": if (words.Length == 1) { Console.WriteLine("Select command help:"); Console.WriteLine("select relation id"); continue; } if (long.TryParse(words[1], out var selectId)) { if (currentRelationId >= 0) { iterator.IterateRelationRow(iterator.RelationId2Info[(uint)currentRelationId], selectId); } break; } switch (words[1]) { case "r": case "relation": if (words.Length == 3) { if (uint.TryParse(words[2], out var id) && iterator.RelationId2Info.ContainsKey(id)) { currentRelationId = (int)id; } } break; } break; case "l": case "list": if (words.Length == 1) { Console.WriteLine("List command help:"); Console.WriteLine("list relation"); Console.WriteLine("list nonempty relations"); continue; } switch (words[1]) { case "r": case "relation": if (words.Length == 2) { foreach (var rel in iterator.RelationId2Info.Values.OrderBy(r => r.Id)) { Console.WriteLine(rel.Id + " " + rel.Name + " " + rel.RowCount); } } break; case "n": case "nonempty": if (words.Length == 3) { switch (words[2]) { case "r": case "relations": foreach (var rel in iterator.RelationId2Info.Values .Where(r => r.RowCount > 0).OrderBy(r => r.RowCount)) { Console.WriteLine(rel.Id + " " + rel.Name + " " + rel.RowCount); } break; } } break; case "t": case "table": if (words.Length == 2) { foreach (var (id, name) in iterator.TableId2Name) { Console.WriteLine(id + " " + name); } } break; } break; case "e": case "exit": return; } } } static void PrintRelationInfo(ODBIterator iterator, ODBIteratorRelationInfo ri) { Console.WriteLine("Relation:" + ri.Id + " " + ri.Name + " " + ri.RowCount); Console.WriteLine("LastPersistedVersion:" + ri.LastPersistedVersion); foreach (var relationVersionInfo in ri.VersionInfos) { Console.WriteLine("Version:" + relationVersionInfo.Key); PrintFields(relationVersionInfo.Value.Fields); } foreach (var s in iterator.IterateRelationStats(ri)) { Console.WriteLine(s.Item1 + ":" + s.Item2); } } static void PrintFields(ReadOnlyMemory<TableFieldInfo> valueFields) { if (valueFields.IsEmpty) return; foreach (var fieldInfo in valueFields.Span) { if (fieldInfo.Handler == null) { Console.WriteLine(fieldInfo.Name + " : !!null!!"); } else { Console.WriteLine(fieldInfo.Name + " : " + fieldInfo.Handler.Name); } } } class ConsoleKvdbLogger : IKeyValueDBLogger { public void ReportTransactionLeak(IKeyValueDBTransaction transaction) { } public void CompactionStart(ulong totalWaste) { Console.WriteLine($"Starting compaction with {totalWaste} wasted bytes"); } public void CompactionCreatedPureValueFile(uint fileId, ulong size, uint itemsInMap, ulong roughMemory) { Console.WriteLine( $"Pvl file {fileId} with size {size} created. Items in map {itemsInMap} roughly {roughMemory} bytes."); } public void KeyValueIndexCreated(uint fileId, long keyValueCount, ulong size, TimeSpan duration, ulong beforeCompressionSize) { Console.WriteLine($"Kvi created {keyValueCount} keys with size {size} in {duration.TotalSeconds:F1} before compression size {beforeCompressionSize}"); } public void TransactionLogCreated(uint fileId) { Console.WriteLine($"Trl file {fileId} added to collection."); } public void FileMarkedForDelete(uint fileId) { Console.WriteLine($"File {fileId} marked for delete."); } public void LogWarning(string message) { Console.WriteLine("Warning: " + message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Concurrency; using Orleans.Runtime; namespace Orleans.Streams { internal class PersistentStreamPullingAgent : SystemTarget, IPersistentStreamPullingAgent { private static readonly IBackoffProvider DeliveryBackoffProvider = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1)); private static readonly IBackoffProvider ReadLoopBackoff = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1)); private static readonly IStreamFilterPredicateWrapper DefaultStreamFilter =new DefaultStreamFilterPredicateWrapper(); private const int StreamInactivityCheckFrequency = 10; private readonly string streamProviderName; private readonly IStreamPubSub pubSub; private readonly Dictionary<StreamId, StreamConsumerCollection> pubSubCache; private readonly SafeRandom safeRandom; private readonly PersistentStreamProviderConfig config; private readonly Logger logger; private readonly CounterStatistic numReadMessagesCounter; private readonly CounterStatistic numSentMessagesCounter; private int numMessages; private IQueueAdapter queueAdapter; private IQueueCache queueCache; private IQueueAdapterReceiver receiver; private IStreamFailureHandler streamFailureHandler; private DateTime lastTimeCleanedPubSubCache; private IDisposable timer; internal readonly QueueId QueueId; private Task receiverInitTask; private bool IsShutdown => timer == null; private string StatisticUniquePostfix => streamProviderName + "." + QueueId; internal PersistentStreamPullingAgent( GrainId id, string strProviderName, IStreamProviderRuntime runtime, IStreamPubSub streamPubSub, QueueId queueId, PersistentStreamProviderConfig config) : base(id, runtime.ExecutingSiloAddress, true) { if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null"); if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null"); QueueId = queueId; streamProviderName = strProviderName; pubSub = streamPubSub; pubSubCache = new Dictionary<StreamId, StreamConsumerCollection>(); safeRandom = new SafeRandom(); this.config = config; numMessages = 0; logger = runtime.GetLogger(GrainId + "-" + streamProviderName); logger.Info(ErrorCode.PersistentStreamPullingAgent_01, "Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.", GetType().Name, GrainId.ToDetailedString(), streamProviderName, Silo, QueueId.ToStringWithHashCode()); numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, StatisticUniquePostfix)); numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, StatisticUniquePostfix)); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix), () => pubSubCache.Count); // TODO: move queue cache size statistics tracking into queue cache implementation once Telemetry APIs and LogStatistics have been reconciled. //IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, statUniquePostfix), () => queueCache != null ? queueCache.Size : 0); } /// <summary> /// Take responsibility for a new queues that was assigned to me via a new range. /// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer. /// ERROR HANDLING: /// The resposibility to handle initializatoion and shutdown failures is inside the INewQueueAdapterReceiver code. /// The agent will call Initialize once and log an error. It will not call initiliaze again. /// The receiver itself may attempt later to recover from this error and do initialization again. /// The agent will assume initialization has succeeded and will subsequently start calling pumping receive. /// Same applies to shutdown. /// </summary> /// <param name="qAdapter"></param> /// <param name="queueAdapterCache"></param> /// <param name="failureHandler"></param> /// <returns></returns> public Task Initialize(Immutable<IQueueAdapter> qAdapter, Immutable<IQueueAdapterCache> queueAdapterCache, Immutable<IStreamFailureHandler> failureHandler) { if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null"); if (failureHandler.Value == null) throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null"); return OrleansTaskExtentions.WrapInTask(() => InitializeInternal(qAdapter.Value, queueAdapterCache.Value, failureHandler.Value)); } private void InitializeInternal(IQueueAdapter qAdapter, IQueueAdapterCache queueAdapterCache, IStreamFailureHandler failureHandler) { logger.Info(ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.", GetType().Name, GrainId.ToDetailedString(), Silo, QueueId.ToStringWithHashCode()); // Remove cast once we cleanup queueAdapter = qAdapter; streamFailureHandler = failureHandler; lastTimeCleanedPubSubCache = DateTime.UtcNow; try { receiver = queueAdapter.CreateReceiver(QueueId); } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingAgent_02, "Exception while calling IQueueAdapter.CreateNewReceiver.", exc); throw; } try { if (queueAdapterCache != null) { queueCache = queueAdapterCache.CreateQueueCache(QueueId); } } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingAgent_23, "Exception while calling IQueueAdapterCache.CreateQueueCache.", exc); throw; } try { receiverInitTask = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(config.InitQueueTimeout)) .LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, $"QueueAdapterReceiver {QueueId.ToStringWithHashCode()} failed to Initialize."); receiverInitTask.Ignore(); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Initialize. No need to log again. } // Setup a reader for a new receiver. // Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization. var randomTimerOffset = safeRandom.NextTimeSpan(config.GetQueueMsgsTimerPeriod); timer = RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, config.GetQueueMsgsTimerPeriod); logger.Info((int)ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode()); } public async Task Shutdown() { // Stop pulling from queues that are not in my range anymore. logger.Info(ErrorCode.PersistentStreamPullingAgent_05, "Shutdown of {0} responsible for queue: {1}", GetType().Name, QueueId.ToStringWithHashCode()); if (timer != null) { IDisposable tmp = timer; timer = null; Utils.SafeExecute(tmp.Dispose); } Task localReceiverInitTask = receiverInitTask; if (localReceiverInitTask != null) { try { await localReceiverInitTask; receiverInitTask = null; } catch (Exception) { receiverInitTask = null; // squelch } } try { var task = OrleansTaskExtentions.SafeExecute(() => receiver.Shutdown(config.InitQueueTimeout)); task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_07, $"QueueAdapterReceiver {QueueId} failed to Shutdown."); await task; } catch { // Just ignore this exception and proceed as if Shutdown has succeeded. // We already logged individual exceptions for individual calls to Shutdown. No need to log again. } var unregisterTasks = new List<Task>(); var meAsStreamProducer = this.AsReference<IStreamProducerExtension>(); foreach (var tuple in pubSubCache) { tuple.Value.DisposeAll(logger); var streamId = tuple.Key; logger.Info(ErrorCode.PersistentStreamPullingAgent_06, "Unregister PersistentStreamPullingAgent Producer for stream {0}.", streamId); unregisterTasks.Add(pubSub.UnregisterProducer(streamId, streamProviderName, meAsStreamProducer)); } try { await Task.WhenAll(unregisterTasks); } catch (Exception exc) { logger.Warn(ErrorCode.PersistentStreamPullingAgent_08, "Failed to unregister myself as stream producer to some streams that used to be in my responsibility.", exc); } pubSubCache.Clear(); IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix)); //IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, StatisticUniquePostfix)); } public Task AddSubscriber( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, IStreamFilterPredicateWrapper filter) { if (logger.IsVerbose) logger.Verbose(ErrorCode.PersistentStreamPullingAgent_09, "AddSubscriber: Stream={0} Subscriber={1}.", streamId, streamConsumer); // cannot await here because explicit consumers trigger this call, so it could cause a deadlock. AddSubscriber_Impl(subscriptionId, streamId, streamConsumer, null, filter) .LogException(logger, ErrorCode.PersistentStreamPullingAgent_26, $"Failed to add subscription for stream {streamId}.") .Ignore(); return TaskDone.Done; } // Called by rendezvous when new remote subscriber subscribes to this stream. private async Task AddSubscriber_Impl( GuidId subscriptionId, StreamId streamId, IStreamConsumerExtension streamConsumer, StreamSequenceToken cacheToken, IStreamFilterPredicateWrapper filter) { if (IsShutdown) return; StreamConsumerCollection streamDataCollection; if (!pubSubCache.TryGetValue(streamId, out streamDataCollection)) { streamDataCollection = new StreamConsumerCollection(DateTime.UtcNow); pubSubCache.Add(streamId, streamDataCollection); } StreamConsumerData data; if (!streamDataCollection.TryGetConsumer(subscriptionId, out data)) data = streamDataCollection.AddConsumer(subscriptionId, streamId, streamConsumer, filter ?? DefaultStreamFilter); if (await DoHandshakeWithConsumer(data, cacheToken)) { if (data.State == StreamConsumerDataState.Inactive) RunConsumerCursor(data, data.Filter).Ignore(); // Start delivering events if not actively doing so } } private async Task<bool> DoHandshakeWithConsumer( StreamConsumerData consumerData, StreamSequenceToken cacheToken) { StreamHandshakeToken requestedHandshakeToken = null; // if not cache, then we can't get cursor and there is no reason to ask consumer for token. if (queueCache != null) { Exception exceptionOccured = null; try { requestedHandshakeToken = await AsyncExecutorWithRetries.ExecuteWithRetries( i => consumerData.StreamConsumer.GetSequenceToken(consumerData.SubscriptionId), AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !(exception is ClientNotAvailableException), config.MaxEventDeliveryTime, DeliveryBackoffProvider); if (requestedHandshakeToken != null) { consumerData.SafeDisposeCursor(logger); consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, requestedHandshakeToken.Token); } else { if (consumerData.Cursor == null) // if the consumer did not ask for a specific token and we already have a cursor, jsut keep using it. consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken); } } catch (Exception exception) { exceptionOccured = exception; } if (exceptionOccured != null) { bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, false, null, requestedHandshakeToken?.Token); if (faultedSubscription) return false; } } consumerData.LastToken = requestedHandshakeToken; // use what ever the consumer asked for as LastToken for next handshake (even if he asked for null). // if we don't yet have a cursor (had errors in the handshake or data not available exc), get a cursor at the event that triggered that consumer subscription. if (consumerData.Cursor == null && queueCache != null) { try { consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken); } catch (Exception) { consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null); // just in case last GetCacheCursor failed. } } return true; } public Task RemoveSubscriber(GuidId subscriptionId, StreamId streamId) { RemoveSubscriber_Impl(subscriptionId, streamId); return TaskDone.Done; } public void RemoveSubscriber_Impl(GuidId subscriptionId, StreamId streamId) { if (IsShutdown) return; StreamConsumerCollection streamData; if (!pubSubCache.TryGetValue(streamId, out streamData)) return; // remove consumer bool removed = streamData.RemoveConsumer(subscriptionId, logger); if (removed && logger.IsVerbose) logger.Verbose(ErrorCode.PersistentStreamPullingAgent_10, "Removed Consumer: subscription={0}, for stream {1}.", subscriptionId, streamId); if (streamData.Count == 0) pubSubCache.Remove(streamId); } private async Task AsyncTimerCallback(object state) { try { Task localReceiverInitTask = receiverInitTask; if (localReceiverInitTask != null) { await localReceiverInitTask; receiverInitTask = null; } if (IsShutdown) return; // timer was already removed, last tick // loop through the queue until it is empty. while (!IsShutdown) // timer will be set to null when we are asked to shudown. { int maxCacheAddCount = queueCache?.GetMaxAddCount() ?? QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG; // If read succeeds and there is more data, we continue reading. // If read succeeds and there is no more data, we breack out of loop // If read fails, we try again, with backoff policy. // This prevents spamming backend queue which may be encountering transient errors. // We retry until the operation succeeds or we are shutdown. bool moreData = await AsyncExecutorWithRetries.ExecuteWithRetries( i => ReadFromQueue((QueueId)state, receiver, maxCacheAddCount), AsyncExecutorWithRetries.INFINITE_RETRIES, (e, i) => !IsShutdown, TimeSpan.MaxValue, ReadLoopBackoff); if (!moreData) return; } } catch (Exception exc) { receiverInitTask = null; logger.Error(ErrorCode.PersistentStreamPullingAgent_12, "Exception while PersistentStreamPullingAgentGrain.AsyncTimerCallback", exc); } } /// <summary> /// Read from queue. /// Returns true, if data was read, false if it was not /// </summary> /// <param name="myQueueId"></param> /// <param name="rcvr"></param> /// <param name="maxCacheAddCount"></param> /// <returns></returns> private async Task<bool> ReadFromQueue(QueueId myQueueId, IQueueAdapterReceiver rcvr, int maxCacheAddCount) { try { var now = DateTime.UtcNow; // Try to cleanup the pubsub cache at the cadence of 10 times in the configurable StreamInactivityPeriod. if ((now - lastTimeCleanedPubSubCache) >= config.StreamInactivityPeriod.Divide(StreamInactivityCheckFrequency)) { lastTimeCleanedPubSubCache = now; CleanupPubSubCache(now); } if (queueCache != null) { IList<IBatchContainer> purgedItems; if (queueCache.TryPurgeFromCache(out purgedItems)) { try { await rcvr.MessagesDeliveredAsync(purgedItems); } catch (Exception exc) { logger.Warn(ErrorCode.PersistentStreamPullingAgent_27, $"Exception calling MessagesDeliveredAsync on queue {myQueueId}. Ignoring.", exc); } } } if (queueCache != null && queueCache.IsUnderPressure()) { // Under back pressure. Exit the loop. Will attempt again in the next timer callback. logger.Info((int)ErrorCode.PersistentStreamPullingAgent_24, "Stream cache is under pressure. Backing off."); return false; } // Retrieve one multiBatch from the queue. Every multiBatch has an IEnumerable of IBatchContainers, each IBatchContainer may have multiple events. IList<IBatchContainer> multiBatch = await rcvr.GetQueueMessagesAsync(maxCacheAddCount); if (multiBatch == null || multiBatch.Count == 0) return false; // queue is empty. Exit the loop. Will attempt again in the next timer callback. queueCache?.AddToCache(multiBatch); numMessages += multiBatch.Count; numReadMessagesCounter.IncrementBy(multiBatch.Count); if (logger.IsVerbose2) logger.Verbose2(ErrorCode.PersistentStreamPullingAgent_11, "Got {0} messages from queue {1}. So far {2} msgs from this queue.", multiBatch.Count, myQueueId.ToStringWithHashCode(), numMessages); foreach (var group in multiBatch .Where(m => m != null) .GroupBy(container => new Tuple<Guid, string>(container.StreamGuid, container.StreamNamespace))) { var streamId = StreamId.GetStreamId(group.Key.Item1, queueAdapter.Name, group.Key.Item2); StreamConsumerCollection streamData; if (pubSubCache.TryGetValue(streamId, out streamData)) { streamData.RefreshActivity(now); StartInactiveCursors(streamData); // if this is an existing stream, start any inactive cursors } else { RegisterStream(streamId, group.First().SequenceToken, now).Ignore(); // if this is a new stream register as producer of stream in pub sub system } } return true; } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingAgent_28, "Exception while reading from queue.", exc); throw; } } private void CleanupPubSubCache(DateTime now) { if (pubSubCache.Count == 0) return; var toRemove = pubSubCache.Where(pair => pair.Value.IsInactive(now, config.StreamInactivityPeriod)) .ToList(); toRemove.ForEach(tuple => { pubSubCache.Remove(tuple.Key); tuple.Value.DisposeAll(logger); }); } private async Task RegisterStream(StreamId streamId, StreamSequenceToken firstToken, DateTime now) { var streamData = new StreamConsumerCollection(now); pubSubCache.Add(streamId, streamData); // Create a fake cursor to point into a cache. // That way we will not purge the event from the cache, until we talk to pub sub. // This will help ensure the "casual consistency" between pre-existing subscripton (of a potentially new already subscribed consumer) // and later production. var pinCursor = queueCache.GetCacheCursor(streamId, firstToken); try { await RegisterAsStreamProducer(streamId, firstToken); }finally { // Cleanup the fake pinning cursor. pinCursor.Dispose(); } } private void StartInactiveCursors(StreamConsumerCollection streamData) { foreach (StreamConsumerData consumerData in streamData.AllConsumers()) { if (consumerData.State == StreamConsumerDataState.Inactive) { // wake up inactive consumers RunConsumerCursor(consumerData, consumerData.Filter).Ignore(); } else { consumerData.Cursor?.Refresh(); } } } private async Task RunConsumerCursor(StreamConsumerData consumerData, IStreamFilterPredicateWrapper filterWrapper) { try { // double check in case of interleaving if (consumerData.State == StreamConsumerDataState.Active || consumerData.Cursor == null) return; consumerData.State = StreamConsumerDataState.Active; while (consumerData.Cursor != null) { IBatchContainer batch = null; Exception exceptionOccured = null; try { Exception ignore; if (!consumerData.Cursor.MoveNext()) { break; } batch = consumerData.Cursor.GetCurrent(out ignore); } catch (Exception exc) { exceptionOccured = exc; consumerData.SafeDisposeCursor(logger); consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null); } // Apply filtering to this batch, if applicable if (filterWrapper != null && batch != null) { try { // Apply batch filter to this input batch, to see whether we should deliver it to this consumer. if (!batch.ShouldDeliver( consumerData.StreamId, filterWrapper.FilterData, filterWrapper.ShouldReceive)) continue; // Skip this batch -- nothing to do } catch (Exception exc) { var message = $"Ignoring exception while trying to evaluate subscription filter function {filterWrapper} on stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor"; logger.Warn((int) ErrorCode.PersistentStreamPullingAgent_13, message, exc); } } try { numSentMessagesCounter.Increment(); if (batch != null) { StreamHandshakeToken newToken = await AsyncExecutorWithRetries.ExecuteWithRetries( i => DeliverBatchToConsumer(consumerData, batch), AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !(exception is ClientNotAvailableException), config.MaxEventDeliveryTime, DeliveryBackoffProvider); if (newToken != null) { consumerData.LastToken = newToken; IQueueCacheCursor newCursor = queueCache.GetCacheCursor(consumerData.StreamId, newToken.Token); consumerData.SafeDisposeCursor(logger); consumerData.Cursor = newCursor; } } } catch (Exception exc) { consumerData.Cursor?.RecordDeliveryFailure(); var message = $"Exception while trying to deliver msgs to stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor"; logger.Error(ErrorCode.PersistentStreamPullingAgent_14, message, exc); exceptionOccured = exc is ClientNotAvailableException ? exc : new StreamEventDeliveryFailureException(consumerData.StreamId); } // if we failed to deliver a batch if (exceptionOccured != null) { bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, true, batch, batch?.SequenceToken); if (faultedSubscription) return; } } consumerData.State = StreamConsumerDataState.Inactive; } catch (Exception exc) { // RunConsumerCursor is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception logger.Error(ErrorCode.PersistentStreamPullingAgent_15, "Ignored RunConsumerCursor Error", exc); consumerData.State = StreamConsumerDataState.Inactive; throw; } } private async Task<StreamHandshakeToken> DeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch) { StreamHandshakeToken prevToken = consumerData.LastToken; Task<StreamHandshakeToken> batchDeliveryTask; bool isRequestContextSet = batch.ImportRequestContext(); try { batchDeliveryTask = consumerData.StreamConsumer.DeliverBatch(consumerData.SubscriptionId, batch.AsImmutable(), prevToken); } finally { if (isRequestContextSet) { // clear RequestContext before await! RequestContext.Clear(); } } StreamHandshakeToken newToken = await batchDeliveryTask; consumerData.LastToken = StreamHandshakeToken.CreateDeliveyToken(batch.SequenceToken); // this is the currently delivered token return newToken; } private static async Task DeliverErrorToConsumer(StreamConsumerData consumerData, Exception exc, IBatchContainer batch) { Task errorDeliveryTask; bool isRequestContextSet = batch != null && batch.ImportRequestContext(); try { errorDeliveryTask = consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, exc); } finally { if (isRequestContextSet) { RequestContext.Clear(); // clear RequestContext before await! } } await errorDeliveryTask; } private async Task<bool> ErrorProtocol(StreamConsumerData consumerData, Exception exceptionOccured, bool isDeliveryError, IBatchContainer batch, StreamSequenceToken token) { // for loss of client, we just remove the subscription if (exceptionOccured is ClientNotAvailableException) { logger.Warn(ErrorCode.Stream_ConsumerIsDead, "Consumer {0} on stream {1} is no longer active - permanently removing Consumer.", consumerData.StreamConsumer, consumerData.StreamId); pubSub.UnregisterConsumer(consumerData.SubscriptionId, consumerData.StreamId, consumerData.StreamId.ProviderName).Ignore(); return true; } // notify consumer about the error or that the data is not available. await OrleansTaskExtentions.ExecuteAndIgnoreException( () => DeliverErrorToConsumer( consumerData, exceptionOccured, batch)); // record that there was a delivery failure if (isDeliveryError) { await OrleansTaskExtentions.ExecuteAndIgnoreException( () => streamFailureHandler.OnDeliveryFailure( consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token)); } else { await OrleansTaskExtentions.ExecuteAndIgnoreException( () => streamFailureHandler.OnSubscriptionFailure( consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token)); } // if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid)) { try { // notify consumer of faulted subscription, if we can. await OrleansTaskExtentions.ExecuteAndIgnoreException( () => DeliverErrorToConsumer( consumerData, new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId), batch)); // mark subscription as faulted. await pubSub.FaultSubscription(consumerData.StreamId, consumerData.SubscriptionId); } finally { // remove subscription RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId); } return true; } return false; } private async Task RegisterAsStreamProducer(StreamId streamId, StreamSequenceToken streamStartToken) { try { if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetreaveNewStream"); IStreamProducerExtension meAsStreamProducer = this.AsReference<IStreamProducerExtension>(); ISet<PubSubSubscriptionState> streamData = await pubSub.RegisterProducer(streamId, streamProviderName, meAsStreamProducer); if (logger.IsVerbose) logger.Verbose(ErrorCode.PersistentStreamPullingAgent_16, "Got back {0} Subscribers for stream {1}.", streamData.Count, streamId); var addSubscriptionTasks = new List<Task>(streamData.Count); foreach (PubSubSubscriptionState item in streamData) { addSubscriptionTasks.Add(AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, streamStartToken, item.Filter)); } await Task.WhenAll(addSubscriptionTasks); } catch (Exception exc) { // RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception logger.Error(ErrorCode.PersistentStreamPullingAgent_17, "Ignored RegisterAsStreamProducer Error", exc); throw; } } } }
#region Apache License // // 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. // #endregion // MONO 1.0 has no support for Win32 Error APIs #if !MONO // SSCLI 1.0 has no support for Win32 Error APIs #if !SSCLI // We don't want framework or platform specific code in the CLI version of log4net #if !CLI_1_0 using System; using System.Globalization; using System.Runtime.InteropServices; namespace log4net.Util { /// <summary> /// Represents a native error code and message. /// </summary> /// <remarks> /// <para> /// Represents a Win32 platform native error. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class NativeError { #region Protected Instance Constructors /// <summary> /// Create an instance of the <see cref="NativeError" /> class with the specified /// error number and message. /// </summary> /// <param name="number">The number of the native error.</param> /// <param name="message">The message of the native error.</param> /// <remarks> /// <para> /// Create an instance of the <see cref="NativeError" /> class with the specified /// error number and message. /// </para> /// </remarks> private NativeError(int number, string message) { m_number = number; m_message = message; } #endregion // Protected Instance Constructors #region Public Instance Properties /// <summary> /// Gets the number of the native error. /// </summary> /// <value> /// The number of the native error. /// </value> /// <remarks> /// <para> /// Gets the number of the native error. /// </para> /// </remarks> public int Number { get { return m_number; } } /// <summary> /// Gets the message of the native error. /// </summary> /// <value> /// The message of the native error. /// </value> /// <remarks> /// <para> /// </para> /// Gets the message of the native error. /// </remarks> public string Message { get { return m_message; } } #endregion // Public Instance Properties #region Public Static Methods /// <summary> /// Create a new instance of the <see cref="NativeError" /> class for the last Windows error. /// </summary> /// <returns> /// An instance of the <see cref="NativeError" /> class for the last windows error. /// </returns> /// <remarks> /// <para> /// The message for the <see cref="Marshal.GetLastWin32Error"/> error number is lookup up using the /// native Win32 <c>FormatMessage</c> function. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #elif !NETCF [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] #endif public static NativeError GetLastError() { int number = Marshal.GetLastWin32Error(); return new NativeError(number, NativeError.GetErrorMessage(number)); } /// <summary> /// Create a new instance of the <see cref="NativeError" /> class. /// </summary> /// <param name="number">the error number for the native error</param> /// <returns> /// An instance of the <see cref="NativeError" /> class for the specified /// error number. /// </returns> /// <remarks> /// <para> /// The message for the specified error number is lookup up using the /// native Win32 <c>FormatMessage</c> function. /// </para> /// </remarks> public static NativeError GetError(int number) { return new NativeError(number, NativeError.GetErrorMessage(number)); } /// <summary> /// Retrieves the message corresponding with a Win32 message identifier. /// </summary> /// <param name="messageId">Message identifier for the requested message.</param> /// <returns> /// The message corresponding with the specified message identifier. /// </returns> /// <remarks> /// <para> /// The message will be searched for in system message-table resource(s) /// using the native <c>FormatMessage</c> function. /// </para> /// </remarks> #if NET_4_0 [System.Security.SecuritySafeCritical] #elif !NETCF [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)] #endif public static string GetErrorMessage(int messageId) { // Win32 constants int FORMAT_MESSAGE_ALLOCATE_BUFFER = 0x00000100; // The function should allocates a buffer large enough to hold the formatted message int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; // Insert sequences in the message definition are to be ignored int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; // The function should search the system message-table resource(s) for the requested message string msgBuf = ""; // buffer that will receive the message IntPtr sourcePtr = new IntPtr(); // Location of the message definition, will be ignored IntPtr argumentsPtr = new IntPtr(); // Pointer to array of values to insert, not supported as it requires unsafe code if (messageId != 0) { // If the function succeeds, the return value is the number of TCHARs stored in the output buffer, excluding the terminating null character int messageSize = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, ref sourcePtr, messageId, 0, ref msgBuf, 255, argumentsPtr); if (messageSize > 0) { // Remove trailing null-terminating characters (\r\n) from the message msgBuf = msgBuf.TrimEnd(new char[] {'\r', '\n'}); } else { // A message could not be located. msgBuf = null; } } else { msgBuf = null; } return msgBuf; } #endregion // Public Static Methods #region Override Object Implementation /// <summary> /// Return error information string /// </summary> /// <returns>error information string</returns> /// <remarks> /// <para> /// Return error information string /// </para> /// </remarks> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "0x{0:x8}", this.Number) + (this.Message != null ? ": " + this.Message : ""); } #endregion // Override Object Implementation #region Stubs For Native Function Calls /// <summary> /// Formats a message string. /// </summary> /// <param name="dwFlags">Formatting options, and how to interpret the <paramref name="lpSource" /> parameter.</param> /// <param name="lpSource">Location of the message definition.</param> /// <param name="dwMessageId">Message identifier for the requested message.</param> /// <param name="dwLanguageId">Language identifier for the requested message.</param> /// <param name="lpBuffer">If <paramref name="dwFlags" /> includes FORMAT_MESSAGE_ALLOCATE_BUFFER, the function allocates a buffer using the <c>LocalAlloc</c> function, and places the pointer to the buffer at the address specified in <paramref name="lpBuffer" />.</param> /// <param name="nSize">If the FORMAT_MESSAGE_ALLOCATE_BUFFER flag is not set, this parameter specifies the maximum number of TCHARs that can be stored in the output buffer. If FORMAT_MESSAGE_ALLOCATE_BUFFER is set, this parameter specifies the minimum number of TCHARs to allocate for an output buffer.</param> /// <param name="Arguments">Pointer to an array of values that are used as insert values in the formatted message.</param> /// <remarks> /// <para> /// The function requires a message definition as input. The message definition can come from a /// buffer passed into the function. It can come from a message table resource in an /// already-loaded module. Or the caller can ask the function to search the system's message /// table resource(s) for the message definition. The function finds the message definition /// in a message table resource based on a message identifier and a language identifier. /// The function copies the formatted message text to an output buffer, processing any embedded /// insert sequences if requested. /// </para> /// <para> /// To prevent the usage of unsafe code, this stub does not support inserting values in the formatted message. /// </para> /// </remarks> /// <returns> /// <para> /// If the function succeeds, the return value is the number of TCHARs stored in the output /// buffer, excluding the terminating null character. /// </para> /// <para> /// If the function fails, the return value is zero. To get extended error information, /// call <see cref="Marshal.GetLastWin32Error()" />. /// </para> /// </returns> #if NETCF [DllImport("CoreDll.dll", SetLastError=true, CharSet=CharSet.Unicode)] #else [DllImport("Kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] #endif private static extern int FormatMessage( int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr Arguments); #endregion // Stubs For Native Function Calls #region Private Instance Fields private int m_number; private string m_message; #endregion } } #endif // !CLI_1_0 #endif // !SSCLI #endif // !MONO
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Sandbox.ModAPI; using System.IO; using VRage.Game; using VRage.Game.Components; using VRage.Game.ModAPI; using VRage.ModAPI; using VRage.Utils; using VRageMath; namespace SGCam_HelmetAT { [MySessionComponentDescriptor(MyUpdateOrder.BeforeSimulation)] //defines update location (before, after, never) public class RUN : MySessionComponentBase //this is where everything starts { private int runcount; private bool initialized; private bool processing; private bool autotoggleON; public override void UpdateBeforeSimulation() //this is where things actually start each update (60 times per second) { try { if (MyAPIGateway.Session == null) //if game is not running, dont run { return; } if (!initialized) //dont run if disabled by user { Initialize(); return; } if (!autotoggleON) //dont run if disabled by user { return; } if (++runcount % (5) != 0) //runs every 5th frame { return; } LOG.Log.WriteLine("starting run"); if (processing) //dont double run { LOG.Log.WriteLine("still processing?"); return; } MyAPIGateway.Parallel.Start(() => { try { LOG.Log.WriteLine("trying parallel"); processing = true; runHauto(); processing = false; LOG.Log.WriteLine("closing parallel"); } catch (Exception ex) //thrown if parallel string fails (ie complicated part of mod) { processing = false; LOG.Log.WriteLine("exception in parallel: " + ex.ToString()); } }); } catch (Exception ex) //thrown if entire update for mod fails { LOG.Log.WriteLine("exception in main: " + ex.ToString()); } } private void Initialize() { MyAPIGateway.Utilities.MessageEntered += HandleMessageEntered; autotoggleON = true; //default on/off setting for mod initialized = true; LOG.Log.WriteLine("initialized"); return; } private void runHauto() //core function of mod { LOG.Log.WriteLine("running main function"); bool helmetEnabled = MyAPIGateway.Session.Player.Character.EnabledHelmet; float oxyLevel = MyAPIGateway.Session.Player.Character.EnvironmentOxygenLevel; //float from 0.0 to 1.0 *potentially out of range? LOG.Log.WriteLine("oxyLevel: " + oxyLevel.ToString()); if (helmetEnabled) //if the helmet is on { LOG.Log.WriteLine("helmet on"); if (oxyLevel > 0.55) //if oxygen, take helmet off { LOG.Log.WriteLine("oxygen high, removing helmet"); MyAPIGateway.Session.Player.Character.SwitchHelmet(); return; } else if (oxyLevel < 0.56 && oxyLevel > -0.01) //if no oxygen, keep helmet on { LOG.Log.WriteLine("oxygen low, keeping helmet on"); return; } else { LOG.Log.WriteLine("helmet on, oxyLevel out of range " + oxyLevel.ToString()); return; } } if (!helmetEnabled) //if the helmet is off { LOG.Log.WriteLine("helmet off"); if (oxyLevel > 0.55) //if oxygen keep helmet off { LOG.Log.WriteLine("oxygen high, keeping helmet off"); return; } else if (oxyLevel < 0.56 && oxyLevel > -0.01) //if no oxygen, put helmet on { LOG.Log.WriteLine("oxygen low, putting helmet on"); MyAPIGateway.Session.Player.Character.SwitchHelmet(); return; } else { LOG.Log.WriteLine("helmet off, oxyLevel out of range " + oxyLevel.ToString()); return; } } LOG.Log.WriteLine("helmet enable is null " + helmetEnabled.ToString()); return; } protected override void UnloadData() //closes chat reader { LOG.Log.WriteLine("unloading data"); if (LOG.debug) { LOG.Log.Close(); } MyAPIGateway.Utilities.MessageEntered -= HandleMessageEntered; } private void HandleMessageEntered(string messageText, ref bool sendToOthers) //filters chat inputs and sends to server { LOG.Log.WriteLine("handling message"); if (messageText[0] != '/') //quick check to see if command { LOG.Log.WriteLine("parse: not a command"); return; } string messageLower = messageText.ToLower(); if (!messageLower.StartsWith("/hat ")) //makes sure command pertains to the mod { LOG.Log.WriteLine("parse: not this mod"); return; } string[] splits = messageLower.Split(' '); //rejects if not a one word command LOG.Log.WriteLine("split0 = " + splits[0].ToString()); LOG.Log.WriteLine("split1 = " + splits[1].ToString()); if (splits.Length > 2) { LOG.Log.WriteLine("parse: too many words"); MyAPIGateway.Utilities.ShowMessage("HelmetAutoToggle ", "Invalid command. Try /hat help"); return; } switch (splits[1]) //parses incoming text and changes settings { case "on": if (true) { LOG.Log.WriteLine("user set autotoggle to ON"); autotoggleON = true; MyAPIGateway.Utilities.ShowMessage("HelmetAutoToggle ", "Mod Activated"); break; } case "off": if (true) { LOG.Log.WriteLine("user set autotoggle to OFF"); autotoggleON = false; MyAPIGateway.Utilities.ShowMessage("HelmetAutoToggle ", "Mod Deactivated"); break; } case "help": { LOG.Log.WriteLine("user asked for help"); string helpMessage = "This mod automatically takes your helmet on and off when leaving or entering high-oxygen environments.\r\n" + "Currently enabled? " + autotoggleON.ToString() + "\r\n" + "Use \"/hat on\" to enable\r\n" + "Use \"/hat off\" to disable"; MyAPIGateway.Utilities.ShowMessage("HelmetAutoToggle ", helpMessage); break; } default: { LOG.Log.WriteLine("invalid command"); MyAPIGateway.Utilities.ShowMessage("HelmetAutoToggle ", "Invalid command. Try /hat help"); } return; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Linq; using Xunit; namespace System.Reflection.Tests { public static partial class ModuleTests { [Fact] public static void LoadMultiModuleFromDisk_GetModule() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("Bob.netmodule"); Assert.Equal(a, m.Assembly); Assert.Equal(bobNetModulePath, m.FullyQualifiedName); Assert.Equal(Path.GetFileName(bobNetModulePath), m.Name); Assert.Equal(TestData.s_JoeScopeName, m.ScopeName); Assert.Equal(TestData.s_JoeNetModuleMvid, m.ModuleVersionId); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleCaseInsensitive() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("bOB.nEtmODule"); Assert.Equal(a, m.Assembly); Assert.Equal(bobNetModulePath, m.FullyQualifiedName); Assert.Equal(Path.GetFileName(bobNetModulePath), m.Name); Assert.Equal(TestData.s_JoeScopeName, m.ScopeName); Assert.Equal(TestData.s_JoeNetModuleMvid, m.ModuleVersionId); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleNameNotInManifest() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("NotThere.netmodule"); Assert.Null(m); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleNameNotThere() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Assert.Throws<FileNotFoundException>(() => a.GetModule("Bob.netmodule")); } } } [Fact] public static void LoadMultiModuleFromDisk_Twice() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module m1 = a.GetModule("Bob.netmodule"); Module m2 = a.GetModule("bob.netmodule"); Assert.Equal(m1, m2); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleManifest() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module m = a.GetModule("Main.dll"); Assert.Equal(a.ManifestModule, m); } } } [Fact] public static void LoadMultiModuleFromDisk_GetModuleNull() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Assert.Throws<ArgumentNullException>(() => a.GetModule(null)); } } } [Fact] public static void LoadMultiModuleFromByteArray_GetModule() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); Assert.Throws<FileNotFoundException>(() => a.GetModule("Bob.netmodule")); } } [Theory] [InlineData(new object[] { false })] [InlineData(new object[] { true })] public static void MultiModule_GetModules(bool getResourceModules) { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module[] ms = a.GetModules(getResourceModules: getResourceModules); Assert.Equal(2, ms.Length); Module bob = a.GetModule("Bob.netmodule"); Assert.NotNull(bob); Assert.Contains<Module>(a.ManifestModule, ms); Assert.Contains<Module>(bob, ms); } } } [Fact] public static void LoadModule_Null() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); Assert.Throws<ArgumentNullException>(() => a.LoadModule(null, TestData.s_JoeNetModuleImage)); Assert.Throws<ArgumentNullException>(() => a.LoadModule("Bob.netmodule", null)); } } [Fact] public static void LoadModule_CannotLoadModuleManifestModule() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); Assert.Throws<ArgumentException>(() => a.LoadModule("Main.dll", TestData.s_JoeNetModuleImage)); } } [Fact] public static void LoadModule_CannotLoadModuleNotInManifest() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); Assert.Throws<ArgumentException>(() => a.LoadModule("NotInManifest.dll", TestData.s_JoeNetModuleImage)); } } [Theory] [InlineData("Bob.netmodule")] [InlineData("bOB.NETMODULE")] public static void LoadModule(string moduleName) { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); Module m = a.LoadModule(moduleName, TestData.s_JoeNetModuleImage); Module m1 = a.GetModule(moduleName); Assert.NotNull(m); Assert.Equal(m, m1); Assert.Equal(a, m.Assembly); Assert.Equal("<unknown>", m.FullyQualifiedName); Assert.Equal("<unknown>", m.Name); Assert.Equal("Joe.netmodule", m.ScopeName); Assert.Equal(TestData.s_JoeNetModuleMvid, m.ModuleVersionId); } } [Fact] public static void LoadModuleTwiceQuirk() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); Module m1 = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); Module m2 = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); Module winner = a.GetModule("Bob.netmodule"); Assert.NotNull(winner); Assert.Equal(winner, m1); // Compat quirk: Why does the second Assembly.LoadModule() call not return the module that actually won the race // like the LoadAssemblyFrom() apis do? Assert.NotEqual(m1, m2); } } [Fact] public static void ModuleResolveEvent() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Module moduleReturnedFromEventHandler = null; Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); a.ModuleResolve += delegate (object context, ResolveEventArgs e) { Assert.Same(a, context); Assert.Null(moduleReturnedFromEventHandler); // We're not doing anything to cause this to trigger twice! Assert.Equal("Bob.netmodule", e.Name); moduleReturnedFromEventHandler = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); return moduleReturnedFromEventHandler; }; Module m = a.GetModule("Bob.netmodule"); Assert.NotNull(m); Assert.Equal(moduleReturnedFromEventHandler, m); // Make sure the event doesn't get raised twice. For a single-threaded case like this, that's a reasonable assumption. Module m1 = a.GetModule("Bob.netmodule"); } } [Fact] public static void MultiModule_AssemblyGetTypes() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Type[] types = a.GetTypes(); AssertContentsOfMultiModule(types, a); } } } [Fact] public static void MultiModule_AssemblyDefinedTypes() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Type[] types = a.DefinedTypes.ToArray(); AssertContentsOfMultiModule(types, a); } } } [Fact] public static void MultiModule_AssemblyGetTypes_ReturnsDifferentObjectEachType() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); TestUtils.AssertNewObjectReturnedEachTime(() => a.GetTypes()); } } } [Fact] public static void MultiModule_AssemblyDefinedTypes_ReturnsDifferentObjectEachType() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); TestUtils.AssertNewObjectReturnedEachTime(() => a.DefinedTypes); } } } [Fact] public static void ModuleGetTypes() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Type[] types = a.ManifestModule.GetTypes(); Assert.Equal(2, types.Length); AssertMainModuleTypesFound(types, a); Module bob = a.GetModule("Bob.netmodule"); Assert.NotNull(bob); Type[] bobTypes = bob.GetTypes(); Assert.Equal(2, bobTypes.Length); AssertBobModuleTypesFound(bobTypes, a); } } } [Fact] public static void ModuleGetTypesReturnsNewObjectEachType() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); TestUtils.AssertNewObjectReturnedEachTime(() => a.ManifestModule.GetTypes()); } } } [Fact] public static void CrossModuleTypeRefResolution() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "MultiModule.dll"); string bobNetModulePath = Path.Combine(td.Path, "Bob.netmodule"); File.WriteAllBytes(assemblyPath, TestData.s_MultiModuleDllImage); File.WriteAllBytes(bobNetModulePath, TestData.s_JoeNetModuleImage); // Note: ScopeName ("Joe") intentionally different from manifest name ("Bob") using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module bob = a.GetModule("Bob.netmodule"); Type mainType1 = a.ManifestModule.GetType("MainType1", throwOnError: true, ignoreCase: false); Type baseType = mainType1.BaseType; Assert.Equal("JoeType1", baseType.FullName); Assert.Equal(bob, baseType.Module); } } } private static void AssertContentsOfMultiModule(Type[] types, Assembly a) { Assert.Equal(4, types.Length); AssertMainModuleTypesFound(types, a); AssertBobModuleTypesFound(types, a); } private static void AssertMainModuleTypesFound(Type[] types, Assembly a) { Assert.Contains(types, (t) => t.Module == a.ManifestModule && t.FullName == "MainType1"); Assert.Contains(types, (t) => t.Module == a.ManifestModule && t.FullName == "MainType2"); } private static void AssertBobModuleTypesFound(Type[] types, Assembly a) { Module bob = a.GetModule("Bob.netmodule"); Assert.NotNull(bob); Assert.Contains(types, (t) => t.Module == bob && t.FullName == "JoeType1"); Assert.Contains(types, (t) => t.Module == bob && t.FullName == "JoeType2"); } [Fact] public static void ResourceOnlyModules() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "n.dll"); string myRes1Path = Path.Combine(td.Path, "MyRes1"); string myRes2Path = Path.Combine(td.Path, "MyRes2"); string myRes3Path = Path.Combine(td.Path, "MyRes3"); File.WriteAllBytes(assemblyPath, TestData.s_AssemblyWithResourcesInManifestFilesImage); File.WriteAllBytes(myRes1Path, TestData.s_MyRes1); File.WriteAllBytes(myRes2Path, TestData.s_MyRes2); File.WriteAllBytes(myRes3Path, TestData.s_MyRes3); using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module[] modules1 = a.GetModules(getResourceModules: false); Assert.Equal<Module>(new Module[] { a.ManifestModule }, modules1); Module[] modules2 = a.GetModules(getResourceModules: true); Assert.Equal(4, modules2.Length); Module m = a.GetModule("MyRes2"); Assert.NotNull(m); Assert.True(m.IsResource()); Assert.Throws<InvalidOperationException>(() => m.ModuleVersionId); Assert.Equal(0, m.MetadataToken); Assert.Equal("MyRes2", m.ScopeName); Assert.Equal("MyRes2", m.Name); Assert.Equal(myRes2Path, m.FullyQualifiedName); m.GetPEKind(out PortableExecutableKinds peKind, out ImageFileMachine machine); Assert.Equal(PortableExecutableKinds.NotAPortableExecutableImage, peKind); Assert.Equal(default(ImageFileMachine), machine); Assert.True(!m.GetCustomAttributesData().Any()); const BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; Assert.Null(m.GetField("ANY", bf)); Assert.Null(m.GetMethod("ANY")); Assert.True(!m.GetFields(bf).Any()); Assert.True(!m.GetMethods(bf).Any()); Assert.True(!m.GetTypes().Any()); } } } [Fact] public static void GetLoadModules1() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); { Module[] loadedModules = a.GetLoadedModules(getResourceModules: true); Assert.Equal(1, loadedModules.Length); Assert.Equal(a.ManifestModule, loadedModules[0]); } { Module[] loadedModules = a.GetLoadedModules(getResourceModules: false); Assert.Equal(1, loadedModules.Length); Assert.Equal(a.ManifestModule, loadedModules[0]); } Module m1 = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); { Module[] loadedModules = a.GetLoadedModules(getResourceModules: true); Assert.Equal(2, loadedModules.Length); Assert.Contains<Module>(a.ManifestModule, loadedModules); Assert.Contains<Module>(m1, loadedModules); } { Module[] loadedModules = a.GetLoadedModules(getResourceModules: false); Assert.Equal(2, loadedModules.Length); Assert.Contains<Module>(a.ManifestModule, loadedModules); Assert.Contains<Module>(m1, loadedModules); } } } [Fact] public static void GetLoadModules2() { using (TempDirectory td = new TempDirectory()) { string assemblyPath = Path.Combine(td.Path, "n.dll"); string myRes1Path = Path.Combine(td.Path, "MyRes1"); string myRes2Path = Path.Combine(td.Path, "MyRes2"); File.WriteAllBytes(assemblyPath, TestData.s_AssemblyWithResourcesInManifestFilesImage); File.WriteAllBytes(myRes1Path, TestData.s_MyRes1); File.WriteAllBytes(myRes2Path, TestData.s_MyRes2); using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromAssemblyPath(assemblyPath); Module res1 = a.GetModule("MyRes1"); Module res2 = a.GetModule("MyRes2"); { Module[] modules = a.GetLoadedModules(getResourceModules: true); Assert.Equal(3, modules.Length); Assert.Contains<Module>(a.ManifestModule, modules); Assert.Contains<Module>(res1, modules); Assert.Contains<Module>(res2, modules); } { Module[] modules = a.GetLoadedModules(getResourceModules: false); Assert.Equal(1, modules.Length); Assert.Equal(a.ManifestModule, modules[0]); } } } } [Fact] public static void GetLoadModulesReturnsUniqueArrays() { using (MetadataLoadContext lc = new MetadataLoadContext(new EmptyCoreMetadataAssemblyResolver())) { Assembly a = lc.LoadFromByteArray(TestData.s_MultiModuleDllImage); Module m1 = a.LoadModule("Bob.netmodule", TestData.s_JoeNetModuleImage); TestUtils.AssertNewObjectReturnedEachTime(() => a.GetLoadedModules(getResourceModules: true)); TestUtils.AssertNewObjectReturnedEachTime(() => a.GetLoadedModules(getResourceModules: false)); } } } }
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using OmniSharp.Models; using OmniSharp.Options; using OmniSharp.Roslyn.CSharp.Services.Intellisense; using OmniSharp.Tests; using Xunit; namespace OmniSharp.Roslyn.CSharp.Tests { public class SnippetFacts { [Fact] public async Task Can_template_generic_type_argument() { var source = @"public class Class1 { public Class1() { var l = new System.Collections.Generic.Lis$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("List<${1:T}>()$0", completions); } [Fact] public async Task Can_return_method_type_arguments_snippets() { var source = @"using System.Collections.Generic; public class Test { public string Get<SomeType>() { } } public class Class1 { public Class1() { var someObj = new Test(); someObj.G$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("Get<${1:SomeType}>()$0 : string", completions); } [Fact] public async Task Does_not_include_tsource_argument_type() { var source = @"using System.Collections.Generic; using System.Linq; public class Class1 { public Class1() { var l = new List<string>(); l.Firs$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("First()$0 : string", completions); ContainsSnippet("FirstOrDefault(${1:Func<string, bool> predicate})$0 : string", completions); } [Fact] public async Task Does_not_include_tresult_argument_type() { var source = @"using System.Collections.Generic; using System.Linq; public class Class1 { public Class1() { var dict = new Dictionary<string, object>(); dict.Sel$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("Select(${1:Func<KeyValuePair<string, object>, TResult> selector})$0 : IEnumerable<TResult>", completions); } [Fact] public async Task Can_template_field() { var source = @"using System.Collections.Generic; public class Class1 { public int someField; public Class1() { somef$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("someField$0 : int", completions); } [Fact] public async Task Can_return_all_constructors() { var source = @"public class MyClass { public MyClass() {} public MyClass(int param) {} public MyClass(int param, string param) {} } public class Class2 { public Class2() { var c = new My$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("MyClass()$0", completions); ContainsSnippet("MyClass(${1:int param})$0", completions); ContainsSnippet("MyClass(${1:int param}, ${2:string param})$0", completions); } [Fact] public async Task Can_template_generic_type_arguments() { var source = @"using System.Collections.Generic; public class Class1 { public Class1() { var l = new Dict$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("Dictionary<${1:TKey}, ${2:TValue}>()$0", completions); } [Fact] public async Task Can_template_parameter() { var source = @"using System.Collections.Generic; public class Class1 { public Class1() { var l = new Lis$ } }"; var completions = await FindCompletionsAsync(source); ContainsSnippet("List<${1:T}>(${2:IEnumerable<T> collection})$0", completions); } [Fact] public async Task Can_complete_namespace() { var source = @"using Sys$"; var completions = await FindCompletionsAsync(source); ContainsSnippet("System$0", completions); } [Fact] public async Task Can_complete_variable() { var source = @" public class Class1 { public Class1() { var aVariable = 1; av$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("aVariable$0 : int", completions); } [Fact] public async Task Void_methods_end_with_semicolons() { var source = @" using System; public class Class1 { public Class1() { Console.WriteLi$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("WriteLine();$0 : void", completions); } [Fact] public async Task Fuzzy_matches_are_returned_when_first_letters_match() { var source = @" using System; public class Class1 { public Class1() { Console.wrl$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("WriteLine();$0 : void", completions); } [Fact] public async Task Fuzzy_matches_are_not_returned_when_first_letters_do_not_match() { var source = @" using System; public class Class1 { public Class1() { Console.rl$ } } "; var completions = await FindCompletionsAsync(source); Assert.DoesNotContain("WriteLine();$0 : void", completions); } [Fact] public async Task Can_complete_parameter() { var source = @" public class Class1 { public Class1() { } public Class2(Class1 class1) { clas$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("class1$0 : Class1", completions); } [Fact] public async Task Can_return_keywords() { var source = @"usin$"; var completions = await FindCompletionsAsync(source); ContainsSnippet("using", completions); } [Fact] public async Task Returns_enums() { var source = @"public enum Colors { Red, Blue } public class MyClass1 { public MyClass1() { Col$ } }"; var completions = await FindCompletionsAsync(source); Assert.Equal(1, completions.Count()); ContainsSnippet("Colors$0", completions); } [Fact] public async Task Returns_event_without_event_keyword() { var source = @" public class MyClass1 { public event TickHandler TickChanged; public MyClass1() { Tick$ } }"; var completions = await FindCompletionsAsync(source); Assert.Equal(1, completions.Count()); ContainsSnippet("TickChanged$0", completions); } [Fact] public async Task Returns_method_without_optional_params() { var source = @" public class Class1 { public void OptionalParam(int i, string s = null) { } public void DoSomething() { Opt$ } } "; var completions = await FindCompletionsAsync(source); ContainsSnippet("OptionalParam(${1:int i});$0 : void", completions); ContainsSnippet("OptionalParam(${1:int i}, ${2:string s = null});$0 : void", completions); } private void ContainsSnippet(string expected, IEnumerable<string> completions) { if (!completions.Contains(expected)) { System.Console.Error.WriteLine("Did not find - " + expected); foreach (var completion in completions) { System.Console.WriteLine(completion); } } Assert.Contains(expected, completions); } private async Task<IEnumerable<string>> FindCompletionsAsync(string source) { var workspace = await TestHelpers.CreateSimpleWorkspace(source); var controller = new IntellisenseService(workspace, new FormattingOptions()); var request = CreateRequest(source); var response = await controller.Handle(request); var completions = response as IEnumerable<AutoCompleteResponse>; return completions.Select(completion => BuildCompletion(completion)); } private string BuildCompletion(AutoCompleteResponse completion) { string result = completion.Snippet; if (completion.ReturnType != null) { result += " : " + completion.ReturnType; } return result; } private AutoCompleteRequest CreateRequest(string source, string fileName = "dummy.cs") { var lineColumn = TestHelpers.GetLineAndColumnFromDollar(source); return new AutoCompleteRequest { Line = lineColumn.Line, Column = lineColumn.Column, FileName = fileName, Buffer = source.Replace("$", ""), WordToComplete = GetPartialWord(source), WantSnippet = true, WantReturnType = true }; } private static string GetPartialWord(string editorText) { MatchCollection matches = Regex.Matches(editorText, @"([a-zA-Z0-9_]*)\$"); return matches[0].Groups[1].ToString(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; using System.Reflection; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace Microsoft.Management.UI.Internal { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public partial class ManagementList : Control { #region Properties private ReadOnlyCollection<object> logicalChildren; private PropertiesTextContainsFilterRule defaultFullTextSearchRule = new PropertiesTextContainsFilterRule(); private ObservableCollection<StateDescriptor<ManagementList>> views = new ObservableCollection<StateDescriptor<ManagementList>>(); /// <summary> /// Gets the collection of saved views. /// </summary> public ObservableCollection<StateDescriptor<ManagementList>> Views { get { return this.views; } } private IStateDescriptorFactory<ManagementList> savedViewFactory; /// <summary> /// Gets or sets a factory used to create new views. /// </summary> public IStateDescriptorFactory<ManagementList> SavedViewFactory { get { if (this.savedViewFactory == null) { this.savedViewFactory = new ManagementListStateDescriptorFactory(); } return this.savedViewFactory; } set { if (value == null) { throw new ArgumentNullException("value"); } this.savedViewFactory = value; } } #endregion Properties #region Ctor /// <summary> /// Initializes a new instance of the ManagementList class. /// </summary> public ManagementList() { this.SearchBox = new SearchBox(); this.SearchBox.Parser.FullTextRule = this.defaultFullTextSearchRule; this.List = new InnerList(); this.FilterRulePanel = new FilterRulePanel(); this.AddFilterRulePicker = new AddFilterRulePicker(); this.Evaluator = new ItemsControlFilterEvaluator(); // Register the programmatically-added controls as logical children \\ this.logicalChildren = new ReadOnlyCollection<object>(new object[] { this.AddFilterRulePicker, this.List }); foreach (var logicalChild in this.logicalChildren) { this.AddLogicalChild(logicalChild); } } #endregion Ctor /// <summary> /// Moves focus to the SearchBox when Ctrl+E is pressed. /// </summary> /// <param name="e">The event data.</param> protected override void OnKeyDown(KeyEventArgs e) { if (this.IsSearchShown && e.Key == Key.E && Keyboard.Modifiers == ModifierKeys.Control) { this.SearchBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); e.Handled = true; } else { base.OnKeyDown(e); } } /// <summary> /// Gets an enumerator for logical child elements of this element. /// </summary> protected override IEnumerator LogicalChildren { get { return this.logicalChildren.GetEnumerator(); } } partial void OnEvaluatorChangedImplementation(PropertyChangedEventArgs<ItemsControlFilterEvaluator> e) { // Unregister the previous evaluator \\ if (e.OldValue != null) { e.OldValue.RemoveFilterExpressionProvider(this.SearchBox); e.OldValue.RemoveFilterExpressionProvider(this.FilterRulePanel); e.OldValue.FilterExpressionChanged -= this.Evaluator_FilterExpressionChanged; e.NewValue.PropertyChanged -= this.Evaluator_PropertyChanged; } // Register the new evaluator \\ e.NewValue.FilterTarget = this.List; e.NewValue.AddFilterExpressionProvider(this.SearchBox); e.NewValue.AddFilterExpressionProvider(this.FilterRulePanel); e.NewValue.FilterExpressionChanged += this.Evaluator_FilterExpressionChanged; e.NewValue.PropertyChanged += this.Evaluator_PropertyChanged; } private void Evaluator_PropertyChanged(object sender, PropertyChangedEventArgs e) { // Our UI components depend on whether our commands can execute, which in turn depend on evaluator properties. // To ensure these are always up-to-date, re-evaluate whether the commands can execute when evaluator properties change. if (e.PropertyName == "FilterStatus" || e.PropertyName == "HasFilterExpression") { CommandManager.InvalidateRequerySuggested(); } // If the filter has been applied or cleared, update the scroll position \\ bool filteredItemsHaveChanged = e.PropertyName == "FilterStatus" && (this.Evaluator.FilterStatus == FilterStatus.Applied || this.Evaluator.FilterStatus == FilterStatus.NotApplied); if (filteredItemsHaveChanged && this.List.Items.Count > 0) { // If no items are selected, select the first item \\ if (this.List.SelectedIndex < 0) { this.List.SelectedIndex = 0; } this.List.ScrollIntoViewFromTop(this.List.SelectedItem); } } #region Registration Helpers /// <summary> /// Adds the specified column. /// Default filter rules for the column will be added if the filter is shown. /// A default search rule will be added if the search box is shown and the column's data type is searchable. /// </summary> /// <param name="column">The column to add.</param> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> public void AddColumn(InnerListColumn column) { if (column == null) { throw new ArgumentNullException("column"); } this.AddColumn(column, this.IsFilterShown); } /// <summary> /// Adds the specified columns, and optionally default filter and search rules. /// </summary> /// <param name="column">The column to add.</param> /// <param name="addDefaultFilterRules">Whether to add default filter rules for the specified column.</param> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> public void AddColumn(InnerListColumn column, bool addDefaultFilterRules) { if (column == null) { throw new ArgumentNullException("column"); } this.List.Columns.Add(column); if (addDefaultFilterRules) { Type genericSelectorRuleType = typeof(PropertyValueSelectorFilterRule<>).MakeGenericType(column.DataDescription.DataType); ConstructorInfo selectorRuleConstructorInfo = genericSelectorRuleType.GetConstructor(new Type[] { typeof(string), typeof(string) }); SelectorFilterRule selectorRule = (SelectorFilterRule)selectorRuleConstructorInfo.Invoke(new object[] { column.DataDescription.PropertyName, column.DataDescription.DisplayName }); if (addDefaultFilterRules) { this.AddFilterRulePicker.ColumnFilterRules.Add(new AddFilterRulePickerItem(new FilterRulePanelItem(selectorRule, selectorRule.DisplayName))); } // Automatically add a search rule if the search box is shown \\ if (this.IsSearchShown) { this.SearchBox.Parser.TryAddSearchableRule<TextContainsFilterRule>(selectorRule); // Add this property to the full-text search properties \\ this.defaultFullTextSearchRule.PropertyNames.Add(column.DataDescription.PropertyName); } } } /// <summary> /// Adds the specified rule, using the rule's display name as its group name. /// </summary> /// <param name="rule">The rule to add.</param> /// <exception cref="ArgumentNullException">The specified value is a null reference.</exception> public void AddRule(FilterRule rule) { if (rule == null) { throw new ArgumentNullException("rule"); } this.AddFilterRulePicker.ShortcutFilterRules.Add(new AddFilterRulePickerItem(new FilterRulePanelItem(rule, rule.DisplayName))); } /// <summary> /// Clears all of the current columns, searchable rules and filter rules. /// </summary> public void ResetView() { this.List.Columns.Clear(); this.defaultFullTextSearchRule.PropertyNames.Clear(); this.AddFilterRulePicker.ShortcutFilterRules.Clear(); this.AddFilterRulePicker.ColumnFilterRules.Clear(); this.SearchBox.Text = string.Empty; this.SearchBox.Parser.ClearSearchableRules(); this.SearchBox.Parser.FullTextRule = this.defaultFullTextSearchRule; } #endregion #region StartFilter partial void OnStartFilterCanExecuteImplementation(CanExecuteRoutedEventArgs e) { // Allow filtering if there is a filter expression or filtering has been triggered \\ e.CanExecute = this.Evaluator.HasFilterExpression || this.Evaluator.FilterStatus != FilterStatus.NotApplied; } partial void OnStartFilterExecutedImplementation(ExecutedRoutedEventArgs e) { this.Evaluator.StartFilter(); } #endregion #region OnStopFilter partial void OnStopFilterCanExecuteImplementation(CanExecuteRoutedEventArgs e) { e.CanExecute = this.Evaluator.FilterStatus == FilterStatus.InProgress; } partial void OnStopFilterExecutedImplementation(ExecutedRoutedEventArgs e) { this.Evaluator.StopFilter(); } #endregion #region OnClearFilter partial void OnClearFilterCanExecuteImplementation(CanExecuteRoutedEventArgs e) { e.CanExecute = this.FilterRulePanel.FilterRulePanelItems.Count > 0; } partial void OnClearFilterExecutedImplementation(ExecutedRoutedEventArgs e) { for (int i = this.FilterRulePanel.FilterRulePanelItems.Count - 1; i >= 0; i--) { FilterRulePanel.RemoveRuleCommand.TryExecute(this.FilterRulePanel.FilterRulePanelItems[i], this.FilterRulePanel); } SearchBox.ClearTextCommand.TryExecute(null, this.SearchBox); this.CurrentView = null; this.Evaluator.StartFilter(); } #endregion #region View Manager Callbacks partial void OnSaveViewCanExecuteImplementation(CanExecuteRoutedEventArgs e) { string viewName = (string)e.Parameter; bool isNotEmpty = !string.IsNullOrEmpty(viewName) && (viewName.Trim().Length != 0); e.CanExecute = isNotEmpty; } partial void OnSaveViewExecutedImplementation(ExecutedRoutedEventArgs e) { string viewName = (string)e.Parameter; this.viewSaver.IsOpen = false; StateDescriptor<ManagementList> sd = null; if ((sd = this.DoesViewAlreadyExist(viewName)) == null) { sd = this.SavedViewFactory.Create(); sd.Name = viewName; this.Views.Add(sd); } sd.SaveState(this); this.RaiseEvent(new RoutedEventArgs(ViewsChangedEvent)); this.CurrentView = sd; } private StateDescriptor<ManagementList> DoesViewAlreadyExist(string viewName) { foreach (StateDescriptor<ManagementList> sd in this.Views) { if (sd.Name.Equals(viewName, StringComparison.CurrentCultureIgnoreCase)) { return sd; } } return null; } private void ViewManager_ItemSelected(object sender, DataRoutedEventArgs<object> e) { if (e.Data == null) { throw new ArgumentException("e.Data is null", "e"); } StateDescriptor<ManagementList> sd = (StateDescriptor<ManagementList>)e.Data; sd.RestoreState(this); this.CurrentView = sd; } private void ViewManager_ItemDeleted(object sender, DataRoutedEventArgs<object> e) { if (e.Data == null) { throw new ArgumentException("e.Data is null", "e"); } StateDescriptor<ManagementList> sd = (StateDescriptor<ManagementList>)e.Data; this.Views.Remove(sd); this.RaiseEvent(new RoutedEventArgs(ViewsChangedEvent)); if (object.ReferenceEquals(sd, this.CurrentView)) { this.CurrentView = null; } } #endregion View Manager Callbacks #region OnApplyTemplate partial void PreOnApplyTemplate() { if (this.viewManager != null) { this.viewManager.ItemSelected -= this.ViewManager_ItemSelected; this.viewManager.ItemDeleted -= this.ViewManager_ItemDeleted; } } partial void PostOnApplyTemplate() { this.viewManager.ItemSelected += this.ViewManager_ItemSelected; this.viewManager.ItemDeleted += this.ViewManager_ItemDeleted; } #endregion OnApplyTemplate #region Hooks For Changing Filter State Due To Events private void Evaluator_FilterExpressionChanged(object sender, EventArgs e) { // For non-live mode, stop filtering if the user has cleared the filter (rules and search text). // This allows the user to clear search results without having to click the Search button on an empty filter. // This happens automatically in live mode. if (this.Evaluator.StartFilterOnExpressionChanged == false && this.FilterRulePanel.HasFilterExpression == false && this.SearchBox.HasFilterExpression == false) { this.Evaluator.StopFilter(); } } #endregion Hooks For Changing Filter State Due To Events } }
//----------------------------------------------------------------------------- // Copyright (c) 2015 Pressure Profile Systems // // Licensed under the MIT license. This file may not be copied, modified, or // distributed except according to those terms. //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO.Ports; using System.IO; using ZedGraph; using System.Threading; using SingleTactLibrary; using System.Management; namespace SingleTact_Demo { public partial class GUI : Form { private bool backgroundIsFinished_ = false; // Flag to check background thread is finished private double measuredFrequency_ = 50; // Sensor update rate private int timerItr_ = 0; // Some things are slower that the timer frequency private bool isFirstFrame_ = true; // Is first frame after boot private const int graphXRange_ = 30; // 30 seconds private int memorySpaceUse = 0; private const int reservedAddresses = 4; // Don't use I2C addresses 0 to 3 private Object workThreadLock = new Object(); //Thread synchronization private List<USBdevice_GUI> USBdevices = new List<USBdevice_GUI>(); private List<string> comPortList = new List<string>(); private SingleTact activeSingleTact; private delegate void CloseMainFormDelegate(); //Used to close the program if hardware is not connected private double NBtoForceFactor = 0; private DateTime systemStartTime = new DateTime(); private bool hasStartTime = false; public GUI() { string exceptionMessage = null; InitializeComponent(); var finder = new ComPortFinder(); // Get available serial ports. comPortList = finder.findSingleTact(); if (comPortList.Count == 0) { MessageBox.Show( "Failed to start sensor: no serial ports found.\n\nPlease ensure Arduino drivers are installed.\nThis can be checked by looking if the Arduino is identified in Device Manager.\n\nPlease connect the device then restart this application.", "Hardware initialisation failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // There's no point showing the GUI. Force the app to auto-close. Environment.Exit(-1); } else { for (int i = 0; i < comPortList.Count; i++) { USBdevice_GUI USB = new USBdevice_GUI(); USB.Initialise(finder.prettyToComPort(comPortList[i])); USBdevices.Add(USB); } if (comPortList.Count == 1) updateUIforOneDevice(); } try { PopulateGUIFields(); foreach (USBdevice USB in USBdevices) { USB.singleTact.PushSettingsToHardware(); RefreshFlashSettings_Click(this, null); //Get the settings from flash } CreateStripChart(); AcquisitionWorker.RunWorkerAsync(); //Start the acquisition thread guiTimer_.Start(); } catch { string summary = "Failed to start sensor"; if (comPortList.Count == 0) summary += ": no serial ports detected."; else summary += " on " + comPortList[0] + "."; summary += "\n\n"; if (exceptionMessage != null) summary += exceptionMessage; else summary += "Please connect the device then restart this application."; MessageBox.Show( summary, "Hardware initialisation failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // There's no point showing the GUI. Force the app to auto-close. Environment.Exit(-1); } } private void updateUIforOneDevice() { //hide GUI elements intended for multiple USBs //hide GUI elements intended for multiple USBs tareAll.Text = "Tare"; int UIOffset = 60; if (USBdevices[0].isCalibrated == true && USBdevices[0].singleTact.Settings.FirmwareVersion > 0) { sensorRange.Visible = true; sensorRangeLabel.Visible = true; if (USBdevices[0].singleTact.Settings.ReferenceGain == 1) { sensorRange.Items.Add(' '); sensorRange.Items.Add("4.5"); sensorRange.Items.Add("45"); sensorRange.Items.Add("450"); } if (USBdevices[0].singleTact.Settings.ReferenceGain == 5) { sensorRange.Items.Add(' '); sensorRange.Items.Add("1"); sensorRange.Items.Add("10"); sensorRange.Items.Add("100"); } UIOffset = 30; } tareAll.Top -= UIOffset; buttonSave.Top -= UIOffset; Settings.Top -= UIOffset; linkLabel1.Top -= UIOffset; Settings.Height += UIOffset; SetBaselineButton.Visible = false; ActiveSensorLabel.Visible = false; ActiveSensor.Visible = false; } /// <summary> /// Fill appropriate Values into GUI Comboboxes /// </summary> private void PopulateGUIFields() { // Populate i2c addresses i2cAddressInputComboBox_.Items.Clear(); //TODO appears to be race condition to populate combo box // This causes the invalid settings warning for (int i = reservedAddresses; i < 128; i++) { i2cAddressInputComboBox_.Items .Add("0x" + i.ToString("X2")); } //Populate active sensor combobox int j = 0; foreach (string port in comPortList) { string[] portSplit = port.Split('-'); // replace COM port with index String name = portSplit[1] + " " + (comPortList.IndexOf(port) + 1).ToString(); if (USBdevices[j].singleTact.firmwareVersion > 0) { if (USBdevices[j].isCalibrated) { name = name + "(calibrated)"; } } ActiveSensor.Items.Add(name); j++; } ActiveSensor.SelectedIndex = 0; activeSingleTact = USBdevices[0].singleTact; if(activeSingleTact.Settings.Scaling < 100) { activeSingleTact.Settings.Scaling = 100; } int maxWidth = 0; System.Windows.Forms.Label dummy = new System.Windows.Forms.Label(); // find widest label to resize dropdown dynamically foreach (var obj in ActiveSensor.Items) { dummy.Text = obj.ToString(); int temp = dummy.PreferredWidth; if (temp > maxWidth) { maxWidth = temp; } } ActiveSensor.DropDownWidth = maxWidth; // Get firmware version byte fwRev = activeSingleTact.firmwareVersion; firmwareLabel.Text = fwRev.ToString(); } /// <summary> /// Using ZedGraph, create a stripchart /// More info on Zedgraph can be found at: http://zedgraph.sourceforge.net/index.html /// </summary> void CreateStripChart() { // This is to remove all plots graph_.GraphPane.CurveList.Clear(); // GraphPane object holds one or more Curve objects (or plots) GraphPane myPane = graph_.GraphPane; // Draw a box item to highlight the valid range BoxObj box = new BoxObj(0, 512, 30, 512, Color.Empty, Color.FromArgb(150, Color.LightGreen)); box.Fill = new Fill(Color.FromArgb(200, Color.LightGreen), Color.FromArgb(200, Color.LightGreen), 45.0F); // Use the BehindGrid zorder to draw the highlight beneath the grid lines box.ZOrder = ZOrder.F_BehindGrid; myPane.GraphObjList.Add(box); //Lables myPane.XAxis.Title.Text = "Time (s)"; myPane.YAxis.Title.Text = "Output (511 = Full Scale Range)"; myPane.Title.IsVisible = false; myPane.Legend.IsVisible = true; //Set scale myPane.XAxis.Scale.Max = 20; //Show 30s of data myPane.XAxis.Scale.Min = -10; //Set scale myPane.YAxis.Scale.Max = 768; //Valid range myPane.YAxis.Scale.Min = -255; // Set font sizes myPane.XAxis.Title.FontSpec.Size = 10; myPane.YAxis.Title.FontSpec.Size = 10; myPane.XAxis.Scale.FontSpec.Size = 7; myPane.YAxis.Scale.FontSpec.Size = 7; //Make grid visible myPane.YAxis.MajorGrid.IsVisible = true; myPane.YAxis.MinorGrid.IsVisible = true; // Refeshes the plot. graph_.AxisChange(); graph_.Invalidate(); graph_.Refresh(); } /// <summary> /// Add new measurements to the graph /// </summary> /// <param name="time"></param> /// <param name="measurements"></param> private void AddData(double time, double[] measurements, USBdevice_GUI USB) { if (NBtoForceFactor != 0) { for (int i = 0; i < measurements.Length; i++) measurements[i] = measurements[i] * NBtoForceFactor / 512; } memorySpaceUse = USB.dataBuffer.AddData(measurements, time); // update } private void updateGraph(USBdevice_GUI USB) { int index = USBdevices.IndexOf(USB); // get current sensor number SingleTactData data_pt = USB.dataBuffer; Color[] colours = { Color.Blue, Color.Orange, Color.DarkViolet, Color.Red, Color.DeepPink, Color.DarkSlateGray }; if (data_pt.data.Count > 0 && index < colours.Length) { // start graphing GraphPane graphPane = graph_.GraphPane; if (graphPane.CurveList.Count <= index) // initialise curves { string name = comPortList[index].ToString().Split('-')[1] + " " + (index + 1).ToString(); if (USBdevices[index].singleTact.firmwareVersion > 0) { if (USBdevices[index].isCalibrated) { name = name + "(calibrated)"; } if (USB.singleTact.Settings.SerialNumber != 0) name += " SN" + USB.singleTact.Settings.SerialNumber.ToString("D5"); } LineItem myCurve = new LineItem( name, new PointPairList(), colours[index], SymbolType.None, 3.0f); graphPane.CurveList.Add(myCurve); } else { // update curve data with new readings if (data_pt.data[0].Count > 1) { graphPane.CurveList[index].AddPoint(data_pt.data[0].Peek());//grab the latest value from the buffer. if (graphPane.CurveList[index].NPts > 100 * 60) //only keep 6000 points on the screen graphPane.CurveList[index].RemovePoint(0); } } // This is to update the max and min value if (isFirstFrame_) { graphPane.XAxis.Scale.Min = data_pt.MostRecentTime; graphPane.XAxis.Scale.Max = graphPane.XAxis.Scale.Min + graphXRange_; isFirstFrame_ = false; } if (data_pt.MostRecentTime >= graphPane.XAxis.Scale.Max) { graphPane.XAxis.Scale.Max = data_pt.MostRecentTime; graphPane.XAxis.Scale.Min = graphPane.XAxis.Scale.Max - graphXRange_; //Update green valid region box BoxObj b = (BoxObj)graphPane.GraphObjList[0]; b.Location.X = graphPane.XAxis.Scale.Max - graphXRange_; if (NBtoForceFactor != 0) { b.Location.Y = Math.Min(graphPane.YAxis.Scale.Max, NBtoForceFactor); b.Location.Height = Math.Min(graphPane.YAxis.Scale.Max - graphPane.YAxis.Scale.Min, NBtoForceFactor); } else { b.Location.Y = Math.Min(graphPane.YAxis.Scale.Max, 512); b.Location.Height = Math.Min(graphPane.YAxis.Scale.Max - graphPane.YAxis.Scale.Min, 512); } try { graph_.AxisChange(); } catch { } } graph_.Refresh(); } } /// <summary> /// Finds a character to separate exported values. /// </summary> /// <returns>A semi-colon for locales where comma is the decimal /// separator; otherwise a comma.</returns> private string safeSeparator() { double testValue = 3.14; string testText = testValue.ToString(); if (testText.IndexOf(',') < 0) return ","; return ";"; } //Save data to CSV private void buttonSave_Click(object sender, EventArgs e) { bool backgroundWasRunning = AcquisitionWorker.IsBusy; if (backgroundWasRunning) { StopAcquisitionThread(); } // Initialize the Dialog to save the file SaveFileDialog saveDataDialog = new SaveFileDialog(); saveDataDialog.Filter = "*.csv|*.csv"; saveDataDialog.RestoreDirectory = true; string fileName = "SingleTactSampleData"; if (hasStartTime) fileName += "_" + ((DateTimeOffset)systemStartTime).ToUnixTimeSeconds(); saveDataDialog.FileName = fileName; Invoke((Action)(() => { if (saveDataDialog.ShowDialog() == DialogResult.OK) { // To fix Issue 3, separate exported values by semi-colon instead // of comma if current locale's decimal separator is comma. string separator = safeSeparator(); string saveFileName = saveDataDialog.FileName; StreamWriter dataWriter = new StreamWriter(saveFileName, false, Encoding.Default); if (hasStartTime) { dataWriter.WriteLine("Start Time" + separator + systemStartTime.ToString()); dataWriter.WriteLine(""); } // write column headers string columnNames = "Time(s)" + separator; // populate columns with serial port names foreach(string portName in comPortList) { int index = comPortList.IndexOf(portName); string name = portName.ToString().Split('-')[1] + " " + (index + 1).ToString(); if (USBdevices[index].singleTact.firmwareVersion > 0) { if (USBdevices[index].isCalibrated) { name = name + "(calibrated)"; } } if (NBtoForceFactor != 0) { columnNames += portName + " (N)" + separator; } else { columnNames += portName + " (NB)" + separator; } } if (NBtoForceFactor == 0) { columnNames += "NB (0 = 0 PSI; 511 = Full Scale Range)"; } else { columnNames += "(Selected Full Scale Range: " + NBtoForceFactor + "N)"; } dataWriter.WriteLine(columnNames); // write data string row = ""; int data_length = USBdevices[0].dataBuffer.data[0].Count; for (int i = 0; i < data_length; i++) // for each sensor reading { bool first = true; foreach (USBdevice_GUI USB in USBdevices) { try { SingleTactData data = USB.dataBuffer; PointPair dataPoint = data.data[0][i]; if (first) // only save the time the first sensor's reading was taken { // round the time value to mitigate any uncertainty around sampling time row += Math.Round(dataPoint.X, 3) + separator + dataPoint.Y + separator; first = false; } else { row += dataPoint.Y + separator; } } catch // index out of range, unequal number of sensor readings { row += "null" + separator; } } dataWriter.WriteLine(row); row = ""; } dataWriter.Close(); } })); if (backgroundWasRunning) { StartAcquisitionThread(); } } private void tareAllButton_Click(object sender, EventArgs e) { StopAcquisitionThread(); foreach (USBdevice USB in USBdevices) { SingleTact singletact = USB.singleTact; if (singletact.Tare()) { RefreshFlashSettings_Click(null, null); } } StartAcquisitionThread(); } /// <summary> /// Stop acquisition thread /// </summary> private void StopAcquisitionThread() { AcquisitionWorker.CancelAsync(); while (false == backgroundIsFinished_) { System.Windows.Forms.Application.DoEvents(); //Wait for us to finish Thread.Sleep(1); } } /// <summary> /// Start the Acquisition Thread /// </summary> private void StartAcquisitionThread() { AcquisitionWorker.RunWorkerAsync(); } /// <summary> /// Do work - process sensor data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AcquisitionWorker_DoWork(object sender, DoWorkEventArgs e) { backgroundIsFinished_ = false; BackgroundWorker worker = sender as BackgroundWorker; while (!worker.CancellationPending) //Do the work { foreach (USBdevice_GUI USB in USBdevices) { SingleTact singleTact = USB.singleTact; SingleTactFrame newFrame = singleTact.ReadSensorData(); //Get sensor data if (null != newFrame) //If we have data { USB.addFrame(newFrame); // use first timestamp only to quantise readings and match csv output AddData(USBdevices[0].lastTimeStamp, newFrame.SensorData, USB); //Add to stripchart if (!hasStartTime) { systemStartTime = DateTime.Now - TimeSpan.FromSeconds(USBdevices[0].lastTimeStamp); hasStartTime = true; } } else // USB has been unplugged { new Thread(() => { guiTimer_.Stop(); backgroundIsFinished_ = true; var index = USBdevices.IndexOf(USB); var comPort = comPortList[index]; var result = MessageBox.Show( comPort.ToString() + " has been unplugged.\nWould you like to save your data before exiting?", "Error!", MessageBoxButtons.YesNo, MessageBoxIcon.Error); if (result == DialogResult.Yes) { buttonSave_Click(this, null); } Application.Exit(); }).Start(); backgroundIsFinished_ = false; StopAcquisitionThread(); break; } //Calculate rate double delta = newFrame.TimeStamp - USB.lastTimeStamp; // calculate delta relative to previous sensor's last reading if (delta != 0) measuredFrequency_ = measuredFrequency_ * 0.95 + 0.05 * (1.0 / (delta)); //Averaging //measuredFrequency_ = 1/delta; USB.setTimestamp(newFrame.TimeStamp); } } } /// <summary> /// Update plot /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void guiTimer__Tick(object sender, EventArgs e) { foreach (USBdevice_GUI USB in USBdevices) { if(!backgroundIsFinished_) updateGraph(USB); } //Update update rate timerItr_++; if (0 == timerItr_ % 5) this.Text = Application.ProductName + " - Version " + Application.ProductVersion + " [ " + measuredFrequency_.ToString("##0") + " Hz ]"; memorySpaceBar.Value = memorySpaceUse; } /// <summary> /// Done - we are closing down /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AcquisitionWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { backgroundIsFinished_ = true; } private void GUI_FormClosing(object sender, FormClosingEventArgs e) { if(AcquisitionWorker.IsBusy) StopAcquisitionThread(); } /// <summary> /// Get settings from sensor flash /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void RefreshFlashSettings_Click(object sender, EventArgs e) { bool backgroundWasRunning = AcquisitionWorker.IsBusy; if (backgroundWasRunning) StopAcquisitionThread(); if (!activeSingleTact.PullSettingsFromHardware()) { MessageBox.Show( "Failed to retrieve current settings.", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { try { byte fwRev = activeSingleTact.firmwareVersion; firmwareLabel.Text = fwRev.ToString(); textAddress.Text = "0x" + activeSingleTact.Settings.I2CAddress.ToString("X2"); textGain.Text = activeSingleTact.Settings.ReferenceGain.ToString("00") + " (" + (activeSingleTact.Settings.ReferenceGain + 1).ToString("0") + "x)"; textTare.Text = activeSingleTact.Settings.Baselines.ElementAt(0).ToString("0000"); textScale.Text = activeSingleTact.Settings.Scaling.ToString(); i2cAddressInputComboBox_.SelectedIndex = activeSingleTact.Settings.I2CAddress - reservedAddresses; } catch (Exception ex) { Console.WriteLine(ex.ToString()); MessageBox.Show("Invalid settings", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (backgroundWasRunning) { StartAcquisitionThread(); } } /// <summary> /// Set settings to sensor flash /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SetSettingsButton_Click(object sender, EventArgs e) { bool backgroundWasRunning = AcquisitionWorker.IsBusy; if (backgroundWasRunning) StopAcquisitionThread(); try { // ReferenceGain still has value from PullSettingsFromHardware // which is OK because the firmware fully controls this anyway. activeSingleTact.Settings.I2CAddress = (byte)(i2cAddressInputComboBox_.SelectedIndex + reservedAddresses); activeSingleTact.Settings.Accumulator = 5; //singleTact_.Settings.Baselines = } catch (Exception) { MessageBox.Show("Invalid settings", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } activeSingleTact.PushSettingsToHardware(); RefreshFlashSettings_Click(this, null); if (backgroundWasRunning) { StartAcquisitionThread(); } } /// <summary> /// Reset sensor to a default configuration /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ResetSensorButton_Click(object sender, EventArgs e) { } /// <summary> /// Update the sensor baseline /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SetBaselineButton_Click(object sender, EventArgs e) { StopAcquisitionThread(); if (activeSingleTact.Tare()) { RefreshFlashSettings_Click(null, null); } StartAcquisitionThread(); } /// <summary> /// Lock the sensor if needed /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void LockButton_Click(object sender, EventArgs e) { // Get the Info that whether the settings in the MainRegister is locked or not bool backgroundWasRunning = AcquisitionWorker.IsBusy; if (backgroundWasRunning) StopAcquisitionThread(); try { activeSingleTact.Settings.Calibrated = (activeSingleTact.Settings.Calibrated == 0) ? (byte)1 : (byte)0; } catch (Exception) { MessageBox.Show("Invalid settings", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } activeSingleTact.PushSettingsToHardware(); RefreshFlashSettings_Click(this, null); if (backgroundWasRunning) StartAcquisitionThread(); } private void Send_Calibration_Click(object sender, EventArgs e) { // Get the Info that whether the settings in the MainRegister is locked or not bool backgroundWasRunning = AcquisitionWorker.IsBusy; int[] calibrationTable = new int[1024]; if (backgroundWasRunning) StopAcquisitionThread(); activeSingleTact.PushCalibrationToHardware(calibrationTable); if (backgroundWasRunning) StartAcquisitionThread(); } private void LinkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { var text = linkLabel1.Text; if (linkLabel1.Text.Contains((char)0x25BC)) { linkLabel1.Text = text.Replace((char)0x25BC, (char)0x25B2); } else { linkLabel1.Text = text.Replace((char)0x25B2, (char)0x25BC); } Settings.Visible = !Settings.Visible; } private void ActiveSensor_SelectedIndexChanged(object sender, EventArgs e) { activeSingleTact = USBdevices[ActiveSensor.SelectedIndex].singleTact; if (activeSingleTact.isUSB && activeSingleTact.isCalibrated) { linkLabel1.Visible = true; if (Settings.TabPages.Count > 1) { Settings.TabPages.RemoveAt(Settings.TabPages.Count - 1); } } else if (activeSingleTact.isUSB && !activeSingleTact.isCalibrated) { linkLabel1.Visible = true; if (Settings.TabPages.Count > 1) { Settings.TabPages.RemoveAt(Settings.TabPages.Count - 1); } } else if (!activeSingleTact.isUSB && activeSingleTact.isCalibrated) { linkLabel1.Visible = true; SetSettingsButton.Enabled = true; } else { linkLabel1.Visible = true; SetSettingsButton.Enabled = true; } RefreshFlashSettings_Click(this, null); //Update display } private void sensorRange_SelectedIndexChanged(object sender, EventArgs e) { double tempFactor = 0; try { tempFactor = Convert.ToDouble(sensorRange.SelectedItem); } catch { tempFactor = 0; } if (tempFactor == NBtoForceFactor) return; NBtoForceFactor = tempFactor; double greenBoxMax = 0; if (NBtoForceFactor != 0) { graph_.GraphPane.YAxis.Title.Text = "Force (N)"; graph_.GraphPane.YAxis.Scale.Max = 1.5 * NBtoForceFactor; //Valid range graph_.GraphPane.YAxis.Scale.Min = -0.5 * NBtoForceFactor; greenBoxMax = NBtoForceFactor; } else { graph_.GraphPane.YAxis.Title.Text = "Output (511 = Full Scale Range)"; graph_.GraphPane.YAxis.Scale.Max = 768; //Valid range graph_.GraphPane.YAxis.Scale.Min = -255; greenBoxMax = 512; } BoxObj b = (BoxObj)graph_.GraphPane.GraphObjList[0]; b.Location.X = 0; b.Location.Y = Math.Min(graph_.GraphPane.YAxis.Scale.Max, greenBoxMax); b.Location.Height = Math.Min(graph_.GraphPane.YAxis.Scale.Max - graph_.GraphPane.YAxis.Scale.Min, greenBoxMax); graph_.GraphPane.XAxis.Scale.Max = 30; graph_.GraphPane.XAxis.Scale.Min = 0; USBdevices[0].setTimestamp(0); USBdevices[0].removeAllFrame(); USBdevices[0].singleTact.resetTimeStamp(); hasStartTime = false; graph_.GraphPane.CurveList[0].Clear(); graph_.AxisChange(); graph_.Invalidate(); graph_.Refresh(); } private void GUI_Load(object sender, EventArgs e) { } private void memorySpaceBar_Click(object sender, EventArgs e) { foreach (USBdevice_GUI USB in USBdevices) { USB.dataBuffer.data[0].Clear(); } hasStartTime = false; } private void memorySpaceBar_MouseHover(object sender, EventArgs e) { toolTip1.Show("Click here to clear the buffer.", memorySpaceBar); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void UnpackHighSByte() { var test = new SimpleBinaryOpTest__UnpackHighSByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse2.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse2.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse2.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__UnpackHighSByte { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<SByte> _fld1; public Vector128<SByte> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__UnpackHighSByte testClass) { var result = Sse2.UnpackHigh(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__UnpackHighSByte testClass) { fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse2.UnpackHigh( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte); private static SByte[] _data1 = new SByte[Op1ElementCount]; private static SByte[] _data2 = new SByte[Op2ElementCount]; private static Vector128<SByte> _clsVar1; private static Vector128<SByte> _clsVar2; private Vector128<SByte> _fld1; private Vector128<SByte> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__UnpackHighSByte() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); } public SimpleBinaryOpTest__UnpackHighSByte() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); } _dataTable = new DataTable(_data1, _data2, new SByte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.UnpackHigh( Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.UnpackHigh( Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.UnpackHigh( Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackHigh), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackHigh), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.UnpackHigh), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.UnpackHigh( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<SByte>* pClsVar1 = &_clsVar1) fixed (Vector128<SByte>* pClsVar2 = &_clsVar2) { var result = Sse2.UnpackHigh( Sse2.LoadVector128((SByte*)(pClsVar1)), Sse2.LoadVector128((SByte*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr); var result = Sse2.UnpackHigh(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.UnpackHigh(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)); var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr)); var result = Sse2.UnpackHigh(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__UnpackHighSByte(); var result = Sse2.UnpackHigh(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__UnpackHighSByte(); fixed (Vector128<SByte>* pFld1 = &test._fld1) fixed (Vector128<SByte>* pFld2 = &test._fld2) { var result = Sse2.UnpackHigh( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.UnpackHigh(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<SByte>* pFld1 = &_fld1) fixed (Vector128<SByte>* pFld2 = &_fld2) { var result = Sse2.UnpackHigh( Sse2.LoadVector128((SByte*)(pFld1)), Sse2.LoadVector128((SByte*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.UnpackHigh(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse2.UnpackHigh( Sse2.LoadVector128((SByte*)(&test._fld1)), Sse2.LoadVector128((SByte*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { SByte[] inArray1 = new SByte[Op1ElementCount]; SByte[] inArray2 = new SByte[Op2ElementCount]; SByte[] outArray = new SByte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[8]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i % 2 == 0) ? result[i] != left[i/2 + 8] : result[i] != right[(i - 1)/2 + 8]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.UnpackHigh)}<SByte>(Vector128<SByte>, Vector128<SByte>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using Xunit; namespace Jint.Tests.Ecma { public class Test_15_4_4_21 : EcmaTest { [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceMustExistAsAFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-0-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthMustBe1() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-0-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToTheMathObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToDateObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToRegexpObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToTheJsonObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-13.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToErrorObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-14.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToTheArgumentsObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-15.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToNull() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToBooleanPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToBooleanObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToNumberPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToNumberObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToStringPrimitive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToStringObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToFunctionObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-1-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDoesnTMutateTheArrayOnWhichItIsCalledOn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReducesTheArrayInAscendingOrderOfIndices() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceSubclassedArrayOfLength1() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceSubclassedArrayWithLengthMoreThan1() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReducesTheArrayInAscendingOrderOfIndicesInitialvaluePresent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceSubclassedArrayWhenInitialvalueProvided() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceSubclassedArrayWithLength1AndInitialvalueProvided() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDoesnTVisitExpandos() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-10-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsOwnDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToArrayLikeObjectLengthIsAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyWithoutAGetFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToArrayLikeObjectThatLengthIsInheritedAccessorPropertyWithoutAGetFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-13.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToTheArrayLikeObjectThatLengthPropertyDoesnTExist() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-14.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsPropertyOfTheGlobalObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-15.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-17.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToStringObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-18.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToFunctionObjectWhichImplementsItsOwnPropertyGetMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-19.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsOwnDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAnOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToArrayLikeObjectLengthIsAnOwnDataPropertyThatOverridesAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToArrayLikeObjectLengthIsAnInheritedDataProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToArrayLikeObjectLengthIsAnOwnAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyThatOverridesAnInheritedDataProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToArrayLikeObjectLengthIsAnOwnAccessorPropertyThatOverridesAnInheritedAccessorProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-2-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsNumberPrimitiveValueIsNan() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAStringContainingAPositiveNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAStringContainingANegativeNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAStringContainingADecimalNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-13.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAStringContainingInfinity() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-14.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAStringContainingAnExponentialNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-15.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAStringContainingAHexNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-16.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAStringContainingANumberWithLeadingZeros() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-17.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsAStringThatCanTConvertToANumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-18.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsAnObjectWhichHasAnOwnTostringMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-19.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsABooleanValueIsTrue() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsAnObjectWhichHasAnOwnValueofMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-20.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLengthIsAnObjectThatHasAnOwnValueofMethodThatReturnsAnObjectAndTostringMethodThatReturnsAString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-21.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorExceptionLengthIsAnObjectWithTostringAndValueofMethodsThatDonTReturnPrimitiveValues() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-22.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceUsesInheritedValueofMethodLengthIsAnObjectWithAnOwnTostringAndInheritedValueofMethods() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-23.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsAPositiveNonIntegerEnsureTruncationOccursInTheProperDirection() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-24.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsANegativeNonIntegerEnsureTruncationOccursInTheProperDirection() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-25.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsBoundaryValue232() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-28.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsBoundaryValue2321() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-29.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsANumberValueIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsANumberValueIs02() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsANumberValueIs03() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsANumberValueIsPositive() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsANumberValueIsNegative() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsANumberValueIsInfinity() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfLengthIsANumberValueIsInfinity2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-3-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfCallbackfnIsUndefined() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheExceptionIsNotThrownIfExceptionWasThrownByStep2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheExceptionIsNotThrownIfExceptionWasThrownByStep3() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnIsAFunction() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallingWithNoCallbackfnIsTheSameAsPassingUndefinedForCallbackfn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-15.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsReferenceerrorIfCallbackfnIsUnreferenced() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfCallbackfnIsNull() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfCallbackfnIsBoolean() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfCallbackfnIsNumber() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfCallbackfnIsString() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfCallbackfnIsObjectWithoutCallInternalMethod() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceSideEffectsProducedByStep2AreVisibleWhenAnExceptionOccurs() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceSideEffectsProducedByStep3AreVisibleWhenAnExceptionOccurs() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-4-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfLengthIs0EmptyArrayNoInitval() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceIfExceptionOccursItOccursAfterAnySideEffectsThatMightBeProducedByStep2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceIfTheExceptionOccursItOccursAfterAnySideEffectsThatMightBeProducedByStep3() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheExceptionIsNotThrownIfExceptionWasThrownByStep22() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheExceptionIsNotThrownIfExceptionWasThrownByStep32() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-13.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfLengthIs0SubclassedArrayLengthOverriddenToNullTypeConversionNoInitval() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfLengthIs0SubclassedArrayLengthOverriddenToFalseTypeConversionNoInitval() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfLengthIs0SubclassedArrayLengthOverriddenTo0TypeConversionNoInitval() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfLengthIs0SubclassedArrayLengthOverriddenTo0TypeConversionNoInitval2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfLengthIs0SubclassedArrayLengthOverriddenWithObjWithValueofNoInitval() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfLengthIs0SubclassedArrayLengthOverriddenWithObjWOValueofTostringNoInitval() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorIfLengthIs0SubclassedArrayLengthOverriddenWithNoInitval() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceInitialvalueIsReturnedIfLenIs0AndInitialvalueIsPresent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-5-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentEmptyArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceInitialvalueIsPresent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceInitialvalueIsNotPresent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentSubclassedArrayLengthOverriddenToNullTypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentSubclassedArrayLengthOverriddenToFalseTypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentSubclassedArrayLengthOverriddenTo0TypeConversion() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentSubclassedArrayLengthOverriddenTo0TypeConversion2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentSubclassedArrayLengthOverriddenWithObjWithValueof() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentSubclassedArrayLengthOverriddenWithObjWOValueofTostring() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentSubclassedArrayLengthOverriddenWith() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueIfLengthIs0AndInitialvalueIsPresentSubclassedArrayLengthOverriddenWith0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-7-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceNoObservableEffectsOccurIfLenIs0() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceModificationsToLengthDonTChangeNumberOfIterationsInStep9() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceLoopIsBrokenOnceKpresentIsTrue() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAddedPropertiesInStep2AreVisibleHere() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-ii-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletedPropertiesInStep2AreVisibleHere() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-ii-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceWhenElementToBeRetrievedIsOwnAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-13.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-14.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-15.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-16.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-17.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-18.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-19.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-20.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedAccessorPropertyWithoutAGetFunctionOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-21.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedAccessorPropertyWithoutAGetFunctionOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-22.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThisObjectIsTheGlobalObjectWhichContainsIndexProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-23.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsIsLessThanNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-25.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsEqualsNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-26.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsIsGreaterThanNumberOfParameters() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-27.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToStringObjectWhichImplementsItsOwnPropertyGetMethod2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-28.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToFunctionObjectWhichImplementsItsOwnPropertyGetMethod2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-29.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementChangedByGetterOnCurrentIterationsIsObservedInSubsequentIterationsOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-30.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementChangedByGetterOnCurrentIterationsIsObservedInSubsequentIterationsOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-31.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceExceptionInGetterTerminatesIterationOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-32.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceExceptionInGetterTerminatesIterationOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-33.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedDataPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedDataPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-b-iii-1-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorWhenArrayIsEmptyAndInitialvalueIsNotPresent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorWhenElementsAssignedValuesAreDeletedByReducingArrayLengthAndInitialvalueIsNotPresent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThrowsTypeerrorWhenElementsAssignedValuesAreDeletedAndInitialvalueIsNotPresent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDoesnTThrowErrorWhenArrayHasNoOwnPropertiesButPrototypeContainsASingleProperty() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceIfExceptionOccursItOccursAfterAnySideEffectsThatMightBeProducedByStep22() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceIfExceptionOccursItOccursAfterAnySideEffectsThatMightBeProducedByStep3() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheExceptionIsNotThrownIfExceptionWasThrownByStep23() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheExceptionIsNotThrownIfExceptionWasThrownByStep33() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDoesnTConsiderNewElementsAddedToArrayAfterItIsCalled() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCalledWithAnInitialValueDoesnTConsiderNewElementsAddedToArrayAfterItIsCalled() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceConsidersNewValueOfElementsInArrayAfterItIsCalled() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDoesnTVisitDeletedElementsInArrayAfterTheCall() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDoesnTVisitDeletedElementsWhenArrayLengthIsDecreased() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnNotCalledForArrayWithOneElement() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceVisitsDeletedElementInArrayAfterTheCallWhenSameIndexIsAlsoPresentInPrototype() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceStopsCallingCallbackfnOnceTheArrayIsDeletedDuringTheCall() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceNoObservableEffectsOccurIfLenIs02() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceModificationsToLengthDonTChangeNumberOfIterationsInStep92() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceReturnsInitialvalueWhenArrayIsEmptyAndInitialvalueIsPresent() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingPropertyOfPrototypeInStep8CausesDeletedIndexPropertyNotToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingPropertyOfPrototypeInStep8CausesDeletedIndexPropertyNotToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingOwnPropertyWithPrototypePropertyInStep8CausesPrototypeIndexPropertyToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingOwnPropertyWithPrototypePropertyInStep8CausesPrototypeIndexPropertyToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-13.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDecreasingLengthOfArrayInStep8CausesDeletedIndexPropertyNotToBeVisited() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-14.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDecreasingLengthOfArrayWithPrototypePropertyInStep8CausesPrototypeIndexPropertyToBeVisited() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-15.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDecreasingLengthOfArrayInStep8DoesNotDeleteNonConfigurableProperties() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-16.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReducePropertiesAddedIntoOwnObjectAreVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-17.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReducePropertiesAddedIntoOwnObjectAreVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-18.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReducePropertiesAddedToPrototypeAreVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-19.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAddedPropertiesInStep2AreVisibleHere2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReducePropertiesCanBeAddedToPrototypeAreVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-20.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingOwnPropertyCausesDeletedIndexPropertyNotToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-21.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingOwnPropertyCausesDeletedIndexPropertyNotToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-22.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingPropertyOfPrototypeCausesDeletedIndexPropertyNotToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-23.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingPropertyOfPrototypeCausesDeletedIndexPropertyNotToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-24.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingOwnPropertyWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-25.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingOwnPropertyWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-26.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDecreasingLengthOfArrayCausesDeletedIndexPropertyNotToBeVisited() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-27.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDecreasingLengthOfArrayWithPrototypePropertyCausesPrototypeIndexPropertyToBeVisited() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-28.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDecreasingLengthOfArrayDoesNotDeleteNonConfigurableProperties() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-29.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletedPropertiesInStep2AreVisibleHere2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReducePropertiesAddedIntoOwnObjectInStep8AreVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReducePropertiesAddedIntoOwnObjectInStep8AreVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReducePropertiesAddedToPrototypeInStep8AreVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReducePropertiesAddedToPrototypeInStep8AreVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingOwnPropertyInStep8CausesDeletedIndexPropertyNotToBeVisitedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDeletingOwnPropertyInStep8CausesDeletedIndexPropertyNotToBeVisitedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-b-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnNotCalledForIndexesNeverBeenAssignedValues() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedDataPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedDataPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-13.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyThatOverridesAnInheritedAccessorPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-14.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedAccessorPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-15.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedAccessorPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-16.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-17.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-18.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-19.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyWithoutAGetFunctionThatOverridesAnInheritedAccessorPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-20.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedAccessorPropertyWithoutAGetFunctionOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-21.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedAccessorPropertyWithoutAGetFunctionOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-22.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThisObjectIsTheGlobalObjectWhichContainsIndexProperty2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-23.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsIsLessThanNumberOfParameters2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-25.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsEqualsNumberOfParameters2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-26.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceThisObjectIsTheArgumentsObjectWhichImplementsItsOwnPropertyGetMethodNumberOfArgumentsIsGreaterThanNumberOfParameters2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-27.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToStringObjectWhichImplementsItsOwnPropertyGetMethod3() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-28.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAppliedToFunctionObjectWhichImplementsItsOwnPropertyGetMethod3() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-29.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementChangedByGetterOnPreviousIterationsIsObservedOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-30.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementChangedByGetterOnPreviousIterationsIsObservedOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-31.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceUnnhandledExceptionsHappenedInGetterTerminateIterationOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-32.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceUnnhandledExceptionsHappenedInGetterTerminateIterationOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-33.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedDataPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedAccessorPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnDataPropertyThatOverridesAnInheritedAccessorPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-6.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedDataPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsInheritedDataPropertyOnAnArray2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementToBeRetrievedIsOwnAccessorPropertyOnAnArrayLikeObject2() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-i-9.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnCalledWithCorrectParametersInitialvalueNotPassed() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-1.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnIsCalledWith1FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-10.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnIsCalledWith2FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-11.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnIsCalledWith3FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-12.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnIsCalledWith4FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-13.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnThatUsesArguments() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-14.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceNonIndexedPropertiesAreNotCalled() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-16.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceAccumulatorUsedForCurrentIterationIsTheResultOfPreviousIterationOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-17.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfAccumulatorUsedForFirstIterationIsTheValueOfInitialvalueWhenItIsPresentOnAnArrayLikeObject() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-18.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceValueOfAccumulatorUsedForFirstIterationIsTheValueOfLeastIndexPropertyWhichIsNotUndefinedWhenInitialvalueIsNotPresentOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-19.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnCalledWithCorrectParametersInitialvaluePassed() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-2.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceUndefinedCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-20.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceNullCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-21.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceBooleanPrimitiveCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-22.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceNumberPrimitiveCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-23.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceStringPrimitiveCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-24.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceFunctionObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-25.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceArrayObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-26.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceStringObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-27.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceBooleanObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-28.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceNumberObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-29.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnTakes4Arguments() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-3.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheMathObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-30.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceDateObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-31.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceRegexpObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-32.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheJsonCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-33.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceErrorObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-34.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheArgumentsObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-35.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceTheGlobalObjectCanBeUsedAsAccumulator() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-37.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceUndefinedPassedAsThisvalueToStrictCallbackfn() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-4-s.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceKValuesArePassedInAcendingNumericOrderOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-4.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceKValuesAreAccessedDuringEachIterationAndNotPriorToStartingTheLoopOnAnArray() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-5.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceUnhandledExceptionsHappenedInCallbackfnTerminateIteration() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-7.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceElementChangedByCallbackfnOnPreviousIterationsIsObserved() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-8.js", false); } [Fact] [Trait("Category", "15.4.4.21")] public void ArrayPrototypeReduceCallbackfnIsCalledWith0FormalParameter() { RunTest(@"TestCases/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-9-c-ii-9.js", false); } } }
// Copyright (C) 2004-2007 MySQL AB // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as published by // the Free Software Foundation // // There are special exceptions to the terms and conditions of the GPL // as it is applied to this software. View the full text of the // exception in file EXCEPTIONS in the directory of this software // distribution. // // 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 using System; using System.Data; using System.Data.Common; using System.Collections; using MySql.Data.Types; using System.Data.SqlTypes; using System.Collections.Generic; using System.Globalization; using MySql.Data.MySqlClient.Properties; namespace MySql.Data.MySqlClient { /// <include file='docs/MySqlDataReader.xml' path='docs/ClassSummary/*'/> public sealed class MySqlDataReader : DbDataReader, IDisposable { // The DataReader should always be open when returned to the user. private bool isOpen = true; // Keep track of the results and position // within the resultset (starts prior to first record). private MySqlField[] fields; internal IMySqlValue[] values; private CommandBehavior commandBehavior; private MySqlCommand command; private bool canRead; private bool hasRows; private long affectedRows; private bool[] uaFieldsUsed; private Driver driver; private long lastInsertId; private PreparableStatement statement; private int seqIndex; private bool hasRead; private bool nextResultDone; private Hashtable fieldHashCS; private Hashtable fieldHashCI; /* * Keep track of the connection in order to implement the * CommandBehavior.CloseConnection flag. A null reference means * normal behavior (do not automatically close). */ private MySqlConnection connection = null; /* * Because the user should not be able to directly create a * DataReader object, the constructors are * marked as internal. */ internal MySqlDataReader(MySqlCommand cmd, PreparableStatement statement, CommandBehavior behavior) { this.command = cmd; connection = (MySqlConnection)command.Connection; commandBehavior = behavior; driver = connection.driver; affectedRows = -1; this.statement = statement; nextResultDone = false; fieldHashCS = new Hashtable(); fieldHashCI = new Hashtable(StringComparer.OrdinalIgnoreCase); } #region Properties internal long InsertedId { get { return this.lastInsertId; } } internal CommandBehavior Behavior { get { return commandBehavior; } } /// <summary> /// Gets a value indicating the depth of nesting for the current row. This method is not /// supported currently and always returns 0. /// </summary> public override int Depth { get { return 0; } } /// <summary> /// Gets the number of columns in the current row. /// </summary> public override int FieldCount { // Return the count of the number of columns, which in // this case is the size of the column metadata // array. get { if (fields != null) return fields.Length; return 0; } } /// <summary> /// Gets a value indicating whether the MySqlDataReader contains one or more rows. /// </summary> public override bool HasRows { get { return hasRows; } } /// <summary> /// Gets a value indicating whether the data reader is closed. /// </summary> public override bool IsClosed { get { return !isOpen; } } /// <summary> /// Gets the number of rows changed, inserted, or deleted by execution of the SQL statement. /// </summary> public override int RecordsAffected { // RecordsAffected returns the number of rows affected in batch // statments from insert/delete/update statments. This property // is not completely accurate until .Close() has been called. get { return (int)affectedRows; } } /// <summary> /// Overloaded. Gets the value of a column in its native format. /// In C#, this property is the indexer for the MySqlDataReader class. /// </summary> public override object this[int i] { get { return GetValue(i); } } /// <summary> /// Gets the value of a column in its native format. /// [C#] In C#, this property is the indexer for the MySqlDataReader class. /// </summary> public override object this[String name] { // Look up the ordinal and return // the value at that position. get { return this[GetOrdinal(name)]; } } #endregion /// <summary> /// Closes the MySqlDataReader object. /// </summary> internal void Close() { if (!isOpen) return; bool shouldCloseConnection = (commandBehavior & CommandBehavior.CloseConnection) != 0; commandBehavior = CommandBehavior.Default; connection.Reader = null; // we set the nextResultDone var to true inside NextResult when // it returns false. This allows us to avoid calling NextResult // here unnecessarily. Calling NextResult here will work but this // is just an optimization. if (!nextResultDone) while (NextResult()) { } // we now give the command a chance to terminate. In the case of // stored procedures it needs to update out and inout parameters command.Close(); if (shouldCloseConnection) connection.Close(); command = null; connection = null; isOpen = false; } #region TypeSafe Accessors /// <summary> /// Gets the value of the specified column as a Boolean. /// </summary> /// <param name="name"></param> /// <returns></returns> public bool GetBoolean(string name) { return GetBoolean(GetOrdinal(name)); } /// <summary> /// Gets the value of the specified column as a Boolean. /// </summary> /// <param name="i"></param> /// <returns></returns> public override bool GetBoolean(int i) { return Convert.ToBoolean(GetValue(i)); } /// <summary> /// Gets the value of the specified column as a byte. /// </summary> /// <param name="name"></param> /// <returns></returns> public byte GetByte(string name) { return GetByte(GetOrdinal(name)); } /// <summary> /// Gets the value of the specified column as a byte. /// </summary> /// <param name="i"></param> /// <returns></returns> public override byte GetByte(int i) { IMySqlValue v = GetFieldValue(i, false); if (v is MySqlUByte) return ((MySqlUByte)v).Value; else return (byte)((MySqlByte)v).Value; } /// <summary> /// Gets the value of the specified column as a sbyte. /// </summary> /// <param name="name"></param> /// <returns></returns> public byte GetSByte(string name) { return GetByte(GetOrdinal(name)); } /// <summary> /// Gets the value of the specified column as a sbyte. /// </summary> /// <param name="i"></param> /// <returns></returns> public sbyte GetSByte(int i) { IMySqlValue v = GetFieldValue(i, false); if (v is MySqlByte) return ((MySqlByte)v).Value; else return (sbyte)((MySqlByte)v).Value; } /// <summary> /// Reads a stream of bytes from the specified column offset into the buffer an array starting at the given buffer offset. /// </summary> /// <param name="i">The zero-based column ordinal. </param> /// <param name="fieldOffset">The index within the field from which to begin the read operation. </param> /// <param name="buffer">The buffer into which to read the stream of bytes. </param> /// <param name="bufferoffset">The index for buffer to begin the read operation. </param> /// <param name="length">The maximum length to copy into the buffer. </param> /// <returns>The actual number of bytes read.</returns> /// <include file='docs/MySqlDataReader.xml' path='MyDocs/MyMembers[@name="GetBytes"]/*'/> public override long GetBytes(int i, long fieldOffset, byte[] buffer, int bufferoffset, int length) { if (i >= fields.Length) throw new IndexOutOfRangeException(); IMySqlValue val = GetFieldValue(i, false); if (!(val is MySqlBinary)) throw new MySqlException("GetBytes can only be called on binary columns"); MySqlBinary binary = (MySqlBinary)val; if (buffer == null) return (long)binary.Value.Length; if (bufferoffset >= buffer.Length || bufferoffset < 0) throw new IndexOutOfRangeException("Buffer index must be a valid index in buffer"); if (buffer.Length < (bufferoffset + length)) throw new ArgumentException("Buffer is not large enough to hold the requested data"); if (fieldOffset < 0 || ((ulong)fieldOffset >= (ulong)binary.Value.Length && (ulong)binary.Value.Length > 0)) throw new IndexOutOfRangeException("Data index must be a valid index in the field"); byte[] bytes = (byte[])binary.Value; // adjust the length so we don't run off the end if ((ulong)binary.Value.Length < (ulong)(fieldOffset + length)) { length = (int)((ulong)binary.Value.Length - (ulong)fieldOffset); } Buffer.BlockCopy(bytes, (int)fieldOffset, buffer, (int)bufferoffset, (int)length); return length; } /// <summary> /// Gets the value of the specified column as a single character. /// </summary> /// <param name="name"></param> /// <returns></returns> public char GetChar(string name) { return GetChar(GetOrdinal(name)); } /// <summary> /// Gets the value of the specified column as a single character. /// </summary> /// <param name="i"></param> /// <returns></returns> public override char GetChar(int i) { string s = GetString(i); return s[0]; } /// <summary> /// Reads a stream of characters from the specified column offset into the buffer as an array starting at the given buffer offset. /// </summary> /// <param name="i"></param> /// <param name="fieldoffset"></param> /// <param name="buffer"></param> /// <param name="bufferoffset"></param> /// <param name="length"></param> /// <returns></returns> public override long GetChars(int i, long fieldoffset, char[] buffer, int bufferoffset, int length) { if (i >= fields.Length) throw new IndexOutOfRangeException(); string valAsString = GetString(i); if (buffer == null) return valAsString.Length; if (bufferoffset >= buffer.Length || bufferoffset < 0) throw new IndexOutOfRangeException("Buffer index must be a valid index in buffer"); if (buffer.Length < (bufferoffset + length)) throw new ArgumentException("Buffer is not large enough to hold the requested data"); if (fieldoffset < 0 || fieldoffset >= valAsString.Length) throw new IndexOutOfRangeException("Field offset must be a valid index in the field"); if (valAsString.Length < length) length = valAsString.Length; valAsString.CopyTo((int)fieldoffset, buffer, bufferoffset, length); return length; } /// <summary> /// Gets the name of the source data type. /// </summary> /// <param name="i"></param> /// <returns></returns> public override String GetDataTypeName(int i) { if (!isOpen) throw new Exception("No current query in data reader"); if (i >= fields.Length) throw new IndexOutOfRangeException(); // return the name of the type used on the backend return values[i].MySqlTypeName; } /// <include file='docs/MySqlDataReader.xml' path='docs/GetMySqlDateTime/*'/> public MySqlDateTime GetMySqlDateTime(string column) { return GetMySqlDateTime(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetMySqlDateTime/*'/> public MySqlDateTime GetMySqlDateTime(int column) { return (MySqlDateTime)GetFieldValue(column, true); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetDateTimeS/*'/> public DateTime GetDateTime(string column) { return GetDateTime(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetDateTime/*'/> public override DateTime GetDateTime(int i) { IMySqlValue val = GetFieldValue(i, true); MySqlDateTime dt; if (val is MySqlDateTime) dt = (MySqlDateTime)val; else { // we need to do this because functions like date_add return string string s = GetString(i); dt = MySqlDateTime.Parse(s, this.connection.driver.Version); } if (connection.Settings.ConvertZeroDateTime && !dt.IsValidDateTime) return DateTime.MinValue; else return dt.GetDateTime(); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetDecimalS/*'/> public Decimal GetDecimal(string column) { return GetDecimal(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetDecimal/*'/> public override Decimal GetDecimal(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlDecimal) return ((MySqlDecimal)v).Value; return Convert.ToDecimal(v.Value); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetDoubleS/*'/> public double GetDouble(string column) { return GetDouble(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetDouble/*'/> public override double GetDouble(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlDouble) return ((MySqlDouble)v).Value; return Convert.ToDouble(v.Value); } /// <summary> /// Gets the Type that is the data type of the object. /// </summary> /// <param name="i"></param> /// <returns></returns> public override Type GetFieldType(int i) { if (!isOpen) throw new Exception("No current query in data reader"); if (i >= fields.Length) throw new IndexOutOfRangeException(); if (values[i] is MySqlDateTime) { if (!connection.Settings.AllowZeroDateTime) return typeof(DateTime); return typeof(MySqlDateTime); } return values[i].SystemType; } /// <include file='docs/MySqlDataReader.xml' path='docs/GetFloatS/*'/> public float GetFloat(string column) { return GetFloat(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetFloat/*'/> public override float GetFloat(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlSingle) return ((MySqlSingle)v).Value; return Convert.ToSingle(v.Value); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetGuidS/*'/> public Guid GetGuid(string column) { return GetGuid(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetGuid/*'/> public override Guid GetGuid(int i) { object v = GetValue(i); if (v is Guid) return (Guid)v; if (v is string) return new Guid(v as string); if (v is byte[]) { byte[] bytes = (byte[])v; if (bytes.Length == 16) return new Guid(bytes); } throw new MySqlException(Resources.ValueNotSupportedForGuid); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetInt16S/*'/> public Int16 GetInt16(string column) { return GetInt16(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetInt16/*'/> public override Int16 GetInt16(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlInt16) return ((MySqlInt16)v).Value; connection.UsageAdvisor.Converting(command.CommandText, fields[i].ColumnName, v.MySqlTypeName, "Int16"); return ((IConvertible)v.Value).ToInt16(null); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetInt32S/*'/> public Int32 GetInt32(string column) { return GetInt32(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetInt32/*'/> public override Int32 GetInt32(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlInt32) return ((MySqlInt32)v).Value; connection.UsageAdvisor.Converting(command.CommandText, fields[i].ColumnName, v.MySqlTypeName, "Int32"); return ((IConvertible)v.Value).ToInt32(null); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetInt64S/*'/> public Int64 GetInt64(string column) { return GetInt64(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetInt64/*'/> public override Int64 GetInt64(int i) { IMySqlValue v = GetFieldValue(i, true); if (v is MySqlInt64) return ((MySqlInt64)v).Value; connection.UsageAdvisor.Converting(command.CommandText, fields[i].ColumnName, v.MySqlTypeName, "Int64"); return ((IConvertible)v.Value).ToInt64(null); } /// <summary> /// Gets the name of the specified column. /// </summary> /// <param name="i"></param> /// <returns></returns> public override String GetName(int i) { return fields[i].ColumnName; } /// <summary> /// Gets the column ordinal, given the name of the column. /// </summary> /// <param name="name"></param> /// <returns></returns> public override int GetOrdinal(string name) { if (!isOpen) throw new Exception("No current query in data reader"); // first we try a quick hash lookup object ordinal = fieldHashCS[name]; if (ordinal != null) return (int)ordinal; // ok that failed so we use our CI hash ordinal = fieldHashCI[name]; if (ordinal != null) return (int)ordinal; // Throw an exception if the ordinal cannot be found. throw new IndexOutOfRangeException("Could not find specified column in results"); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetStringS/*'/> public string GetString(string column) { return GetString(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetString/*'/> public override String GetString(int i) { IMySqlValue val = GetFieldValue(i, true); if (val is MySqlBinary) { byte[] v = ((MySqlBinary)val).Value; return fields[i].Encoding.GetString(v, 0, v.Length); } return val.Value.ToString(); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetTimeSpan/*'/> public TimeSpan GetTimeSpan(string column) { return GetTimeSpan(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetTimeSpan/*'/> public TimeSpan GetTimeSpan(int column) { IMySqlValue val = GetFieldValue(column, true); MySqlTimeSpan ts = (MySqlTimeSpan)val; return ts.Value; } /// <summary> /// Gets the value of the specified column in its native format. /// </summary> /// <param name="i"></param> /// <returns></returns> public override object GetValue(int i) { if (!isOpen) throw new Exception("No current query in data reader"); if (i >= fields.Length) throw new IndexOutOfRangeException(); IMySqlValue val = GetFieldValue(i, false); if (val.IsNull) return DBNull.Value; // if the column is a date/time, then we return a MySqlDateTime // so .ToString() will print '0000-00-00' correctly if (val is MySqlDateTime) { MySqlDateTime dt = (MySqlDateTime)val; if (!dt.IsValidDateTime && connection.Settings.ConvertZeroDateTime) return DateTime.MinValue; else if (connection.Settings.AllowZeroDateTime) return val; else return dt.GetDateTime(); } return val.Value; } /// <summary> /// Gets all attribute columns in the collection for the current row. /// </summary> /// <param name="values"></param> /// <returns></returns> public override int GetValues(object[] values) { if (!hasRead) return 0; int numCols = Math.Min(values.Length, fields.Length); for (int i = 0; i < numCols; i++) values[i] = GetValue(i); return numCols; } /// <include file='docs/MySqlDataReader.xml' path='docs/GetUInt16/*'/> public UInt16 GetUInt16(string column) { return GetUInt16(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetUInt16/*'/> public UInt16 GetUInt16(int column) { IMySqlValue v = GetFieldValue(column, true); if (v is MySqlUInt16) return ((MySqlUInt16)v).Value; connection.UsageAdvisor.Converting(command.CommandText, fields[column].ColumnName, v.MySqlTypeName, "UInt16"); return Convert.ToUInt16(v.Value); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetUInt32/*'/> public UInt32 GetUInt32(string column) { return GetUInt32(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetUInt32/*'/> public UInt32 GetUInt32(int column) { IMySqlValue v = GetFieldValue(column, true); if (v is MySqlUInt32) return ((MySqlUInt32)v).Value; connection.UsageAdvisor.Converting(command.CommandText, fields[column].ColumnName, v.MySqlTypeName, "UInt32"); return Convert.ToUInt32(v.Value); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetUInt64/*'/> public UInt64 GetUInt64(string column) { return GetUInt64(GetOrdinal(column)); } /// <include file='docs/MySqlDataReader.xml' path='docs/GetUInt64/*'/> public UInt64 GetUInt64(int column) { IMySqlValue v = GetFieldValue(column, true); if (v is MySqlUInt64) return ((MySqlUInt64)v).Value; connection.UsageAdvisor.Converting(command.CommandText, fields[column].ColumnName, v.MySqlTypeName, "UInt64"); return Convert.ToUInt64(v.Value); } #endregion /// <summary> /// Gets a value indicating whether the column contains non-existent or missing values. /// </summary> /// <param name="i"></param> /// <returns></returns> public override bool IsDBNull(int i) { return DBNull.Value == GetValue(i); } /// <summary> /// GetResultSet is the core resultset processing method. It gets called by NextResult /// and will loop until it finds a select resultset at which point it will return the /// number of columns in that result. It will _not_ return for non-select resultsets instead /// just updating the internal lastInsertId and affectedRows variables. /// </summary> /// <returns>-1 if no more results exist, >= 0 for select results</returns> private long GetResultSet() { while (true) { ulong affectedRowsTemp = 0; long fieldCount = driver.ReadResult(ref affectedRowsTemp, ref lastInsertId); if (fieldCount > 0) return fieldCount; else if (fieldCount == 0) { command.lastInsertedId = lastInsertId; if (affectedRows == -1) affectedRows = (long)affectedRowsTemp; else affectedRows += (long)affectedRowsTemp; } else if (fieldCount == -1) if (!statement.ExecuteNext()) break; } return -1; } /// <summary> /// Advances the data reader to the next result, when reading the results of batch SQL statements. /// </summary> /// <returns></returns> public override bool NextResult() { if (!isOpen) throw new MySqlException(Resources.NextResultIsClosed); bool firstResult = fields == null; if (fields != null) { ClearCurrentResultset(); fields = null; } // single result means we only return a single resultset. If we have already // returned one, then we return false; if (!firstResult && (commandBehavior & CommandBehavior.SingleResult) != 0) return false; // tell our command to continue execution of the SQL batch until it its // another resultset try { long fieldCount = GetResultSet(); if (fieldCount == -1) { nextResultDone = true; hasRows = canRead = false; return false; } // issue any requested UA warnings if (connection.Settings.UseUsageAdvisor) { if ((connection.driver.ServerStatus & ServerStatusFlags.NoIndex) != 0) connection.UsageAdvisor.UsingNoIndex(command.CommandText); if ((connection.driver.ServerStatus & ServerStatusFlags.BadIndex) != 0) connection.UsageAdvisor.UsingBadIndex(command.CommandText); } fields = driver.ReadColumnMetadata((int)fieldCount); fieldHashCS.Clear(); fieldHashCI.Clear(); values = new IMySqlValue[fields.Length]; for (int i = 0; i < fields.Length; i++) { string columnName = fields[i].ColumnName; if (!fieldHashCS.ContainsKey(columnName)) fieldHashCS.Add(columnName, i); if (!fieldHashCI.ContainsKey(columnName)) fieldHashCI.Add(columnName, i); values[i] = fields[i].GetValueObject(); } hasRead = false; uaFieldsUsed = new bool[fields.Length]; hasRows = canRead = driver.FetchDataRow(statement.StatementId, 0, fields.Length); return true; } catch (MySqlException ex) { if (ex.IsFatal) connection.Abort(); nextResultDone = true; hasRows = canRead = false; if (command.TimedOut) throw new MySqlException(Resources.Timeout); if (ex.Number == 0) throw new MySqlException(Resources.FatalErrorReadingResult, ex); throw; } } /// <summary> /// Advances the MySqlDataReader to the next record. /// </summary> /// <returns></returns> public override bool Read() { if (!isOpen) throw new MySqlException("Invalid attempt to Read when reader is closed."); if (!canRead) return false; if (Behavior == CommandBehavior.SingleRow && hasRead) return false; try { bool isSequential = (Behavior & CommandBehavior.SequentialAccess) != 0; seqIndex = -1; if (hasRead) canRead = driver.FetchDataRow(statement.StatementId, 0, fields.Length); hasRead = true; if (canRead && !isSequential) for (int i = 0; i < fields.Length; i++) values[i] = driver.ReadColumnValue(i, fields[i], values[i]); return canRead; } catch (MySqlException ex) { if (ex.IsFatal) connection.Abort(); // if we get a query interrupted then our resultset is done if (ex.Number == 1317) { nextResultDone = true; canRead = false; if (command.TimedOut) throw new MySqlException(Resources.Timeout); return false; } throw new MySqlException(Resources.FatalErrorDuringRead, ex); } } private IMySqlValue GetFieldValue(int index, bool checkNull) { if (index < 0 || index >= fields.Length) throw new ArgumentException("You have specified an invalid column ordinal."); if (!hasRead) throw new MySqlException("Invalid attempt to access a field before calling Read()"); // keep count of how many columns we have left to access this.uaFieldsUsed[index] = true; if ((this.commandBehavior & CommandBehavior.SequentialAccess) != 0 && index != seqIndex) { if (index < seqIndex) throw new MySqlException("Invalid attempt to read a prior column using SequentialAccess"); while (seqIndex < (index - 1)) driver.SkipColumnValue(values[++seqIndex]); values[index] = driver.ReadColumnValue(index, fields[index], values[index]); seqIndex = index; } IMySqlValue v = values[index]; if (checkNull && v.IsNull) throw new SqlNullValueException(); return v; } private void ClearCurrentResultset() { if (!canRead) return; while (driver.SkipDataRow()) { } if (!connection.Settings.UseUsageAdvisor) return; // we were asked to run the usage advisor so report if the resultset // was not entirely read. if (canRead) connection.UsageAdvisor.ReadPartialResultSet(command.CommandText); bool readAll = true; foreach (bool b in this.uaFieldsUsed) readAll &= b; if (!readAll) connection.UsageAdvisor.ReadPartialRowSet(command.CommandText, uaFieldsUsed, fields); } #region IEnumerator /// <summary> /// Returns an <see cref="IEnumerator"/> that iterates through the <see cref="MySqlDataReader"/>. /// </summary> /// <returns></returns> public override IEnumerator GetEnumerator() { // TODO: Remove when the System.Data.Common includes DbEnumerator throw new NotImplementedException(); } #endregion } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // The contents of this file are subject to the MIT License (MIT) // you may not use this file except in compliance with the License. You may obtain a copy of the License at // http://dotspatial.codeplex.com/license // // Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF // ANY KIND, either expressed or implied. See the License for the specific language governing rights and // limitations under the License. // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/22/2009 11:21:12 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// GradientControl /// </summary> [DefaultEvent("PositionChanging")] public class HueSlider : Control { /// <summary> /// Occurs as the user is adjusting the positions on either of the sliders /// </summary> public event EventHandler PositionChanging; /// <summary> /// Occurs after the user has finished adjusting the positions of either of the sliders and has released control /// </summary> public event EventHandler PositionChanged; #region Private Variables private int _dx; private int _hueShift; private bool _inverted; private HueHandle _leftHandle; private int _max; private int _min; private HueHandle _rightHandle; #endregion #region Constructors /// <summary> /// Creates a new instance of GradientControl /// </summary> public HueSlider() { _min = 0; _max = 360; _leftHandle = new HueHandle(this); _leftHandle.Position = 72; _leftHandle.Left = true; _rightHandle = new HueHandle(this); _rightHandle.Position = 288; } #endregion #region Methods /// <summary> /// Uses the hue values from the specified start and end color to set the handle positions. /// </summary> /// <param name="startColor">The start color that represents the left hue</param> /// <param name="endColor">The start color that represents the right hue</param> public void SetRange(Color startColor, Color endColor) { int hStart = (int)startColor.GetHue(); int hEnd = (int)endColor.GetHue(); _inverted = (hStart > hEnd); LeftValue = hStart; RightValue = hEnd; } #endregion #region Properties /// <summary> /// Gets or sets a boolean indicating whether the hue pattern should be flipped. /// </summary> public bool Inverted { get { return _inverted; } set { _inverted = value; Invalidate(); } } /// <summary> /// Gets or sets an integer value indicating how much to adjust the hue to change where wrapping occurs. /// </summary> [Description("Gets or sets an integer value indicating how much to adjust the hue to change where wrapping occurs.")] public int HueShift { get { return _hueShift; } set { _hueShift = value; Invalidate(); } } /// <summary> /// Gets or sets the floating point position of the left slider. This must range /// between 0 and 1, and to the left of the right slider, (therefore with a value lower than the right slider.) /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof(ExpandableObjectConverter))] public HueHandle LeftHandle { get { return _leftHandle; } set { _leftHandle = value; } } /// <summary> /// Gets or sets the floating point position of the right slider. This must range /// between 0 and 1, and to the right of the left slider. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof(ExpandableObjectConverter))] public HueHandle RightHandle { get { return _rightHandle; } set { _rightHandle = value; } } /// <summary> /// Gets or sets the maximum allowed value for the slider. /// </summary> [Description("Gets or sets the maximum allowed value for the slider.")] public int Maximum { get { return _max; } set { _max = value; if (_max < _rightHandle.Position) _rightHandle.Position = _max; if (_max < _leftHandle.Position) _leftHandle.Position = _max; } } /// <summary> /// Gets or sets the minimum allowed value for the slider. /// </summary> [Description("Gets or sets the minimum allowed value for the slider.")] public int Minimum { get { return _min; } set { _min = value; if (_leftHandle.Position < _min) _leftHandle.Position = _min; if (_rightHandle.Position < _min) _rightHandle.Position = _min; } } /// <summary> /// The value represented by the left handle, taking into account /// whether or not the slider has been reversed. /// </summary> public float LeftValue { get { if (_inverted) { return _max - _leftHandle.Position; } return _leftHandle.Position; } set { if (_inverted) { _leftHandle.Position = _max - value; return; } _leftHandle.Position = value; } } /// <summary> /// The value represented by the right handle, taking into account /// whether or not the slider has been reversed. /// </summary> public float RightValue { get { if (_inverted) { return _max - (_rightHandle.Position); } return _rightHandle.Position; } set { if (_inverted) { _rightHandle.Position = _max - value; return; } _rightHandle.Position = value; } } #endregion #region Protected Methods /// <summary> /// Prevent flicker /// </summary> /// <param name="pevent"></param> protected override void OnPaintBackground(PaintEventArgs pevent) { //base.OnPaintBackground(pevent); } /// <summary> /// Draw the clipped portion /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = e.ClipRectangle; if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(-clip.X, -clip.Y); g.Clip = new Region(clip); g.Clear(BackColor); g.SmoothingMode = SmoothingMode.AntiAlias; OnDraw(g, clip); g.Dispose(); e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel); } /// <summary> /// Controls the actual drawing for this gradient slider control. /// </summary> /// <param name="g"></param> /// <param name="clipRectangle"></param> protected virtual void OnDraw(Graphics g, Rectangle clipRectangle) { GraphicsPath gp = new GraphicsPath(); Rectangle innerRect = new Rectangle(_leftHandle.Width, 3, Width - 1 - _rightHandle.Width - _leftHandle.Width, Height - 1 - 6); gp.AddRoundedRectangle(innerRect, 2); if (Width == 0 || Height == 0) return; // Create a rounded gradient effect as the backdrop that other colors will be drawn to LinearGradientBrush silver = new LinearGradientBrush(ClientRectangle, BackColor.Lighter(.2F), BackColor.Darker(.6F), LinearGradientMode.Vertical); g.FillPath(silver, gp); silver.Dispose(); LinearGradientBrush lgb = new LinearGradientBrush(innerRect, Color.White, Color.White, LinearGradientMode.Horizontal); Color[] colors = new Color[37]; float[] positions = new float[37]; for (int i = 0; i <= 36; i++) { int j = _inverted ? 36 - i : i; colors[j] = SymbologyGlobal.ColorFromHsl((i * 10 + _hueShift) % 360, 1, .7).ToTransparent(.7f); positions[i] = i / 36f; } ColorBlend cb = new ColorBlend(); cb.Colors = colors; cb.Positions = positions; lgb.InterpolationColors = cb; g.FillPath(lgb, gp); lgb.Dispose(); g.DrawPath(Pens.Gray, gp); gp.Dispose(); if (Enabled) { _leftHandle.Draw(g); _rightHandle.Draw(g); } } /// <summary> /// Initiates slider dragging /// </summary> /// <param name="e"></param> protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left && Enabled) { Rectangle l = _leftHandle.GetBounds(); if (l.Contains(e.Location) && _leftHandle.Visible) { _dx = _leftHandle.GetBounds().Right - e.X; _leftHandle.IsDragging = true; } Rectangle r = _rightHandle.GetBounds(); if (r.Contains(e.Location) && _rightHandle.Visible) { _dx = e.X - _rightHandle.GetBounds().Left; _rightHandle.IsDragging = true; } } base.OnMouseDown(e); } /// <summary> /// Handles slider dragging /// </summary> /// <param name="e"></param> protected override void OnMouseMove(MouseEventArgs e) { float w = Width - _leftHandle.Width; if (_rightHandle.IsDragging) { float x = e.X - _dx; int min = 0; if (_leftHandle.Visible) min = _leftHandle.Width; if (x > w) x = w; if (x < min) x = min; _rightHandle.Position = _min + (x / w) * (_max - _min); if (_leftHandle.Visible) { if (_leftHandle.Position > _rightHandle.Position) { _leftHandle.Position = _rightHandle.Position; } } OnPositionChanging(); } if (_leftHandle.IsDragging) { float x = e.X + _dx; int max = Width; if (_rightHandle.Visible) max = Width - _rightHandle.Width; if (x > max) x = max; if (x < 0) x = 0; _leftHandle.Position = _min + (x / w) * (_max - _min); if (_rightHandle.Visible) { if (_rightHandle.Position < _leftHandle.Position) { _rightHandle.Position = _leftHandle.Position; } } OnPositionChanging(); } Invalidate(); base.OnMouseMove(e); } /// <summary> /// Handles the mouse up situation /// </summary> /// <param name="e"></param> protected override void OnMouseUp(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (_rightHandle.IsDragging) _rightHandle.IsDragging = false; if (_leftHandle.IsDragging) _leftHandle.IsDragging = false; OnPositionChanged(); } base.OnMouseUp(e); } /// <summary> /// Fires the Position Changing event while either slider is being dragged /// </summary> protected virtual void OnPositionChanging() { if (PositionChanging != null) PositionChanging(this, EventArgs.Empty); } /// <summary> /// Fires the Position Changed event after sliders are released /// </summary> protected virtual void OnPositionChanged() { if (PositionChanged != null) PositionChanged(this, EventArgs.Empty); } #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.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editing; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// This is the root class for all code model objects. It contains methods that /// are common to everything. /// </summary> public partial class AbstractCodeModelObject { private static CodeGenerationOptions GetCodeGenerationOptions( EnvDTE.vsCMAccess access, ParseOptions parseOptions) { var generateDefaultAccessibility = (access & EnvDTE.vsCMAccess.vsCMAccessDefault) == 0; return new CodeGenerationOptions( generateDefaultAccessibility: generateDefaultAccessibility, parseOptions: parseOptions); } protected SyntaxNode CreateConstructorDeclaration(SyntaxNode containerNode, string typeName, EnvDTE.vsCMAccess access) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination), modifiers: new DeclarationModifiers(), typeName: typeName, parameters: default(ImmutableArray<IParameterSymbol>)); return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination, options: GetCodeGenerationOptions(access, containerNode.SyntaxTree.Options)); } protected SyntaxNode CreateDestructorDeclaration(SyntaxNode containerNode, string typeName) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateDestructorSymbol( attributes: default(ImmutableArray<AttributeData>), typeName: typeName); return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination); } protected SyntaxNode CreateDelegateTypeDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, INamedTypeSymbol returnType) { var destination = CodeModelService.GetDestination(containerNode); var newTypeSymbol = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination), modifiers: new DeclarationModifiers(), returnType: returnType, returnsByRef: false, name: name); return CodeGenerationService.CreateNamedTypeDeclaration( newTypeSymbol, destination, options: GetCodeGenerationOptions(access, containerNode.SyntaxTree.Options)); } protected SyntaxNode CreateEventDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type, bool createPropertyStyleEvent) { var destination = CodeModelService.GetDestination(containerNode); IMethodSymbol addMethod = null; IMethodSymbol removeMethod = null; if (createPropertyStyleEvent) { addMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, returnsByRef: false, explicitInterfaceSymbol: null, name: "add_" + name, typeParameters: default(ImmutableArray<ITypeParameterSymbol>), parameters: default(ImmutableArray<IParameterSymbol>)); removeMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, returnsByRef: false, explicitInterfaceSymbol: null, name: "remove_" + name, typeParameters: default(ImmutableArray<ITypeParameterSymbol>), parameters: default(ImmutableArray<IParameterSymbol>)); } var newEventSymbol = CodeGenerationSymbolFactory.CreateEventSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Event, destination), modifiers: new DeclarationModifiers(), type: type, explicitInterfaceSymbol: null, name: name, addMethod: addMethod, removeMethod: removeMethod); return CodeGenerationService.CreateEventDeclaration( newEventSymbol, destination, options: GetCodeGenerationOptions(access, containerNode.SyntaxTree.Options)); } protected SyntaxNode CreateFieldDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol type) { var destination = CodeModelService.GetDestination(containerNode); var newFieldSymbol = CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination), modifiers: new DeclarationModifiers(isWithEvents: CodeModelService.GetWithEvents(access)), type: type, name: name); return CodeGenerationService.CreateFieldDeclaration( newFieldSymbol, destination, options: GetCodeGenerationOptions(access, containerNode.SyntaxTree.Options)); } protected SyntaxNode CreateMethodDeclaration(SyntaxNode containerNode, string name, EnvDTE.vsCMAccess access, ITypeSymbol returnType) { var destination = CodeModelService.GetDestination(containerNode); var newMethodSymbol = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Method, destination), modifiers: new DeclarationModifiers(), returnType: returnType, returnsByRef: false, explicitInterfaceSymbol: null, name: name, typeParameters: default(ImmutableArray<ITypeParameterSymbol>), parameters: default(ImmutableArray<IParameterSymbol>)); return CodeGenerationService.CreateMethodDeclaration( newMethodSymbol, destination, options: GetCodeGenerationOptions(access, containerNode.SyntaxTree.Options)); } protected SyntaxNode CreatePropertyDeclaration(SyntaxNode containerNode, string name, bool generateGetter, bool generateSetter, EnvDTE.vsCMAccess access, ITypeSymbol type) { var destination = CodeModelService.GetDestination(containerNode); IMethodSymbol getMethod = null; if (generateGetter) { getMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, returnsByRef: false, explicitInterfaceSymbol: null, name: "get_" + name, typeParameters: default(ImmutableArray<ITypeParameterSymbol>), parameters: default(ImmutableArray<IParameterSymbol>), statements: ImmutableArray.Create(CodeModelService.CreateReturnDefaultValueStatement(type))); } IMethodSymbol setMethod = null; if (generateSetter) { setMethod = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: Accessibility.NotApplicable, modifiers: new DeclarationModifiers(), returnType: null, returnsByRef: false, explicitInterfaceSymbol: null, name: "set_" + name, typeParameters: default(ImmutableArray<ITypeParameterSymbol>), parameters: default(ImmutableArray<IParameterSymbol>)); } var newPropertySymbol = CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: CodeModelService.GetAccessibility(access, SymbolKind.Field, destination), modifiers: new DeclarationModifiers(), type: type, returnsByRef: false, explicitInterfaceSymbol: null, name: name, parameters: default(ImmutableArray<IParameterSymbol>), getMethod: getMethod, setMethod: setMethod); return CodeGenerationService.CreatePropertyDeclaration( newPropertySymbol, destination, options: GetCodeGenerationOptions(access, containerNode.SyntaxTree.Options)); } protected SyntaxNode CreateNamespaceDeclaration(SyntaxNode containerNode, string name) { var destination = CodeModelService.GetDestination(containerNode); var newNamespaceSymbol = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name); var newNamespace = CodeGenerationService.CreateNamespaceDeclaration( newNamespaceSymbol, destination); return newNamespace; } protected SyntaxNode CreateTypeDeclaration( SyntaxNode containerNode, TypeKind typeKind, string name, EnvDTE.vsCMAccess access, INamedTypeSymbol baseType = null, ImmutableArray<INamedTypeSymbol> implementedInterfaces = default(ImmutableArray<INamedTypeSymbol>)) { var destination = CodeModelService.GetDestination(containerNode); var newTypeSymbol = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default(ImmutableArray<AttributeData>), accessibility: CodeModelService.GetAccessibility(access, SymbolKind.NamedType, destination), modifiers: new DeclarationModifiers(), typeKind: typeKind, name: name, typeParameters: default(ImmutableArray<ITypeParameterSymbol>), baseType: baseType, interfaces: implementedInterfaces, specialType: SpecialType.None, members: default(ImmutableArray<ISymbol>)); return CodeGenerationService.CreateNamedTypeDeclaration( newTypeSymbol, destination, options: GetCodeGenerationOptions(access, containerNode.SyntaxTree.Options)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using MongoWebApi.Areas.HelpPage.Models; namespace MongoWebApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#pragma warning disable 1591 using AjaxControlToolkit.Design; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Drawing; using System.Collections.ObjectModel; namespace AjaxControlToolkit { /// <summary> /// AjaxFileUpload is an ASP.NET AJAX Control that allows you to asynchronously upload files to the server. /// </summary> [Designer(typeof(AjaxFileUploadDesigner))] [RequiredScript(typeof(CommonToolkitScripts))] [ClientCssResource(Constants.AjaxFileUploadName)] [ClientScriptResource("Sys.Extended.UI.AjaxFileUpload.Control", Constants.AjaxFileUploadName)] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.AjaxFileUploadName + Constants.IconPostfix)] public class AjaxFileUpload : ScriptControlBase { internal const string ContextKey = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}"; const string DefaultTempSubDir = "_AjaxFileUpload"; // Location of uploaded temporary file path string _uploadedFilePath = null; public AjaxFileUpload() : base(true, HtmlTextWriterTag.Div) { } bool IsDesignMode { get { return (HttpContext.Current == null); } } // Any value/Id that can be used when storing file. public string ContextKeys { get; set; } /// <summary> /// The ID of a control that is shown on the file upload. /// The throbber image is displayed for browsers that do not support the HTML5 File API or server-side polling. /// </summary> [Description("ID of Throbber")] [Category("Behavior")] [DefaultValue("")] public string ThrobberID { get { return (string)(ViewState["ThrobberID"] ?? string.Empty); } set { ViewState["ThrobberID"] = value; } } ///<summary> /// This will be true when a postback will be performed from the control. /// This can be used to avoid execution of unnecessary code during a partial postback. /// The default is false. /// </summary> [Browsable(false)] [DefaultValue(false)] public bool IsInFileUploadPostBack { get; set; } /// <summary> /// A maximum number of files in an upload queue. /// The default is 10. /// </summary> [ExtenderControlProperty] [DefaultValue(10)] [ClientPropertyName("maximumNumberOfFiles")] public int MaximumNumberOfFiles { get; set; } /// <summary> /// A comma-separated list of allowed file extensions. /// The default is an empty string. /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("allowedFileTypes")] public string AllowedFileTypes { get; set; } /// <summary> /// The size of a chunk used by HTML5 to upload large files in bytes. /// The default is 4096. /// </summary> [ExtenderControlProperty] [DefaultValue(4096)] [ClientPropertyName("chunkSize")] public int ChunkSize { get { return int.Parse((string)ViewState["ChunkSize"] ?? "4096"); } set { ViewState["ChunkSize"] = value.ToString(); } } /// <summary> /// The maximum size of a file to be uploaded in Kbytes. /// A non-positive value means the size is unlimited. /// The default is 0. /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("maxFileSize")] public int MaxFileSize { get { return int.Parse((string)ViewState["MaxFileSize"] ?? "0"); } set { ViewState["MaxFileSize"] = value.ToString(); } } /// <summary> /// Whether or not to hide file upload list container after the uploading finished /// </summary> [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("clearFileListAfterUpload")] public bool ClearFileListAfterUpload { get { return bool.Parse((string)ViewState["ClearFileListAfterUpload"] ?? "false"); } set { ViewState["ClearFileListAfterUpload"] = value.ToString(); } } /// <summary> /// Whether or not to use absolute path for AjaxFileUploadHandler /// </summary> [ExtenderControlProperty] [DefaultValue(true)] [ClientPropertyName("useAbsoluteHandlerPath")] public bool UseAbsoluteHandlerPath { get { return bool.Parse((string)ViewState["UseAbsoluteHandlerPath"] ?? "true"); } set { ViewState["UseAbsoluteHandlerPath"] = value.ToString(); } } ///<summary> /// How AjaxFileUpload displays a progress bar. /// The default is Auto. /// </summary> [ExtenderControlProperty] [DefaultValue(AjaxFileUploadMode.Auto)] [ClientPropertyName("mode")] public AjaxFileUploadMode Mode { get { return (AjaxFileUploadMode)Enum.Parse(typeof(AjaxFileUploadMode), (string)ViewState["Mode"] ?? "Auto"); } set { ViewState["Mode"] = value.ToString(); } } /// <summary> /// An event raised when the file upload starts. /// </summary> [Bindable(true)] [Category("Server Events")] public event EventHandler<AjaxFileUploadStartEventArgs> UploadStart; /// <summary> /// An event raised when the file upload is complete. /// </summary> [Bindable(true)] [Category("Server Events")] public event EventHandler<AjaxFileUploadEventArgs> UploadComplete; /// <summary> /// An event handler that will be raised when the UploadComplete event is raised /// in all files in an upload queue, or when a user presses the Cancel button to stop uploading. /// </summary> [Bindable(true)] [Category("Server Events")] public event EventHandler<AjaxFileUploadCompleteAllEventArgs> UploadCompleteAll; /// <summary> /// The name of a JavaScript function executed on the client side before any files are uploaded. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadStart")] public string OnClientUploadStart { get { return (string)(ViewState["OnClientUploadStart"] ?? string.Empty); } set { ViewState["OnClientUploadStart"] = value; } } /// <summary> /// The name of a JavaScript function executed on the client side after a file is uploaded successfully. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadComplete")] public string OnClientUploadComplete { get { return (string)(ViewState["OnClientUploadComplete"] ?? string.Empty); } set { ViewState["OnClientUploadComplete"] = value; } } /// <summary> /// The client script that executes when all of files in queue uploaded, /// or when user hits Cancel button to stop uploading /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadCompleteAll")] public string OnClientUploadCompleteAll { get { return (string)(ViewState["OnClientUploadCompleteAll"] ?? string.Empty); } set { ViewState["OnClientUploadCompleteAll"] = value; } } /// <summary> /// The name of a JavaScript function executed on the client side if the file upload failed. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadError")] public string OnClientUploadError { get { return (string)(ViewState["OnClientUploadError"] ?? string.Empty); } set { ViewState["OnClientUploadError"] = value; } } /// <summary> /// Whether or not AjaxFileUpload supports server polling. /// </summary> public bool ServerPollingSupport { get { return true; } } protected override void OnInit(EventArgs e) { base.OnInit(e); if(!IsDesignMode) { if(!string.IsNullOrEmpty(Page.Request.QueryString["contextkey"]) && Page.Request.QueryString["contextkey"] == ContextKey && Page.Request.QueryString["controlID"] == ClientID) IsInFileUploadPostBack = true; } } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Register an empty OnSubmit statement so the ASP.NET WebForm_OnSubmit method will be automatically // created and our behavior will be able to disable input file controls prior to submission ScriptManager.RegisterOnSubmitStatement(this, typeof(AjaxFileUpload), "AjaxFileUploadOnSubmit", "null;"); } XhrType ParseRequest(out string fileId) { fileId = Page.Request.QueryString["guid"]; if(Page.Request.QueryString["contextkey"] != ContextKey || Page.Request.QueryString["controlID"] != ClientID) return XhrType.None; if(!string.IsNullOrEmpty(fileId)) { if(Page.Request.QueryString["poll"] == "1") return XhrType.Poll; if(Page.Request.QueryString["cancel"] == "1") return XhrType.Cancel; if(Page.Request.QueryString["done"] == "1") return XhrType.Done; } if(Page.Request.QueryString["complete"] == "1") return XhrType.Complete; if(Page.Request.QueryString["start"] == "1") return XhrType.Start; return XhrType.None; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); string fileId; var xhrType = ParseRequest(out fileId); if(xhrType != XhrType.None) { Page.Response.ClearContent(); Page.Response.Cache.SetCacheability(HttpCacheability.NoCache); // Process xhr request switch(xhrType) { case XhrType.Poll: // Upload progress polling request XhrPoll(fileId); break; case XhrType.Cancel: // Cancel upload request XhrCancel(fileId); break; case XhrType.Done: // A file is successfully uploaded XhrDone(fileId); break; case XhrType.Complete: // All files successfully uploaded XhrComplete(); break; case XhrType.Start: XhrStart(); break; } Page.Response.End(); } } void XhrStart() { var filesInQueue = int.Parse(Page.Request.QueryString["queue"] ?? "0"); var args = new AjaxFileUploadStartEventArgs(filesInQueue); if(UploadStart != null) UploadStart(this, args); Page.Response.Write(new JavaScriptSerializer().Serialize(args)); } void XhrComplete() { var filesInQueue = int.Parse(Page.Request.QueryString["queue"] ?? "0"); var filesUploaded = int.Parse(Page.Request.QueryString["uploaded"] ?? "0"); var reason = Page.Request.QueryString["reason"]; AjaxFileUploadCompleteAllReason completeReason; switch(reason) { case "done": completeReason = AjaxFileUploadCompleteAllReason.Success; break; case "cancel": completeReason = AjaxFileUploadCompleteAllReason.Canceled; break; default: completeReason = AjaxFileUploadCompleteAllReason.Unknown; break; } var args = new AjaxFileUploadCompleteAllEventArgs(filesInQueue, filesUploaded, completeReason); if(UploadCompleteAll != null) UploadCompleteAll(this, args); Page.Response.Write(new JavaScriptSerializer().Serialize(args)); } void XhrDone(string fileId) { AjaxFileUploadEventArgs args; var tempFolder = BuildTempFolder(fileId); if(!Directory.Exists(tempFolder)) return; var files = Directory.GetFiles(tempFolder); if(files.Length == 0) return; var fileInfo = new FileInfo(files[0]); _uploadedFilePath = fileInfo.FullName; args = new AjaxFileUploadEventArgs( fileId, AjaxFileUploadState.Success, "Success", fileInfo.Name, (int)fileInfo.Length, fileInfo.Extension); if(UploadComplete != null) UploadComplete(this, args); Page.Response.Write(new JavaScriptSerializer().Serialize(args)); } void XhrCancel(string fileId) { AjaxFileUploadHelper.Abort(Context, fileId); } void XhrPoll(string fileId) { Page.Response.Write((new AjaxFileUploadStates(Context, fileId)).Percent.ToString()); } /// <summary> /// Saves the uploaded file with the specified file name /// </summary> /// <param name="fileName" type="String">Name of the file to save</param> public void SaveAs(string fileName) { var dir = Path.GetDirectoryName(_uploadedFilePath); // Override existing file if any if(File.Exists(fileName)) File.Delete(fileName); File.Copy(_uploadedFilePath, fileName); File.Delete(_uploadedFilePath); // Delete temporary data Directory.Delete(dir); } public static void CleanAllTemporaryData() { var dirInfo = new DirectoryInfo(BuildRootTempFolder()); foreach(var dir in dirInfo.GetDirectories()) { dir.Delete(true); } } public static string BuildTempFolder(string fileId) { return Path.Combine(BuildRootTempFolder(), fileId); } public static string BuildRootTempFolder() { var userPath = ToolkitConfig.TempFolder; if(!String.IsNullOrWhiteSpace(userPath)) { var physicalPath = GetPhysicalPath(userPath); if(!Directory.Exists(physicalPath)) throw new IOException(String.Format("Temp directory '{0}' does not exist.", physicalPath)); return physicalPath; } var defaultPath = Path.Combine(Path.GetTempPath(), DefaultTempSubDir); if(!Directory.Exists(defaultPath)) Directory.CreateDirectory(defaultPath); return defaultPath; } static string GetPhysicalPath(string path) { if(path.StartsWith("~")) return HttpContext.Current.Server.MapPath(path); return path; } internal void CreateChilds() { Controls.Clear(); CreateChildControls(); } protected override void CreateChildControls() { GenerateHtmlInputControls(); } // Return the client id of parent div that contains all other html controls. protected string GenerateHtmlInputControls() { HtmlGenericControl parent = new HtmlGenericControl("div"); parent.Attributes.Add("class", "ajax__fileupload"); Controls.Add(parent); var inputFileStyle = "opacity:0; -moz-opacity: 0.0; filter: alpha(opacity=0);"; HtmlInputFile inputFile = new HtmlInputFile(); if(!Enabled) inputFile.Disabled = true; inputFile.Attributes.Add("id", ClientID + "_Html5InputFile"); inputFile.Attributes.Add("multiple", "multiple"); inputFile.Attributes.Add("style", inputFileStyle); HideElement(inputFile); HtmlInputFile inputFileElement = new HtmlInputFile(); if(!Enabled) inputFileElement.Disabled = true; inputFileElement.Attributes.Add("id", ClientID + "_InputFileElement"); inputFileElement.Attributes.Add("name", "act-file-data"); inputFileElement.Attributes.Add("style", inputFileStyle); HideElement(inputFileElement); HtmlGenericControl dropZone = new HtmlGenericControl("div"); dropZone.Attributes.Add("class", "ajax__fileupload_dropzone"); dropZone.Attributes.Add("id", ClientID + "_Html5DropZone"); // IE 10 requested dropzone to be have actual size dropZone.Attributes.Add("style", "width:100%; height:60px;"); HideElement(dropZone); parent.Controls.Add(dropZone); HtmlGenericControl fileStatusContainer = new HtmlGenericControl("div"); fileStatusContainer.Attributes.Add("id", ClientID + "_FileStatusContainer"); fileStatusContainer.Style[HtmlTextWriterStyle.Position] = "absolute"; fileStatusContainer.Style["right"] = "0"; fileStatusContainer.Style["top"] = "2px"; fileStatusContainer.Style["height"] = "20px"; fileStatusContainer.Style["line-height"] = "20px"; HideElement(fileStatusContainer); var selectFileContainer = GenerateHtmlSelectFileContainer(inputFileElement, inputFile); parent.Controls.Add(selectFileContainer); parent.Controls.Add(GenerateHtmlTopFileStatus(fileStatusContainer)); var queueContainer = new HtmlGenericControl("div"); queueContainer.Attributes.Add("id", ClientID + "_QueueContainer"); queueContainer.Attributes.Add("class", "ajax__fileupload_queueContainer"); queueContainer.Style[HtmlTextWriterStyle.MarginTop] = "28px"; parent.Controls.Add(queueContainer); HideElement(queueContainer); var progressBar = new HtmlGenericControl("div"); progressBar.Attributes.Add("id", ClientID + "_ProgressBar"); progressBar.Attributes.Add("class", "ajax__fileupload_progressBar"); progressBar.Attributes.Add("style", "width: 100%; display: none; visibility: hidden; overflow:visible;white-space:nowrap; height:20px;"); var uploadButton = GenerateHtmlFooterContainer(progressBar); parent.Controls.Add(uploadButton); return parent.ClientID; } HtmlGenericControl GenerateHtmlFooterContainer(Control progressBar) { var footerContainer = new HtmlGenericControl("div"); footerContainer.Attributes.Add("class", "ajax__fileupload_footer"); footerContainer.Attributes.Add("id", ClientID + "_Footer"); footerContainer.Attributes["align"] = "right"; var uploadOrCancelButton = new HtmlGenericControl("div"); uploadOrCancelButton.Attributes.Add("id", ClientID + "_UploadOrCancelButton"); uploadOrCancelButton.Attributes.Add("class", "ajax__fileupload_uploadbutton"); var progressBarContainer = new HtmlGenericControl("div"); progressBarContainer.Attributes.Add("id", ClientID + "_ProgressBarContainer"); progressBarContainer.Attributes["align"] = "left"; progressBarContainer.Style["float"] = "left"; progressBarContainer.Style["width"] = "100%"; progressBarContainer.Controls.Add(progressBar); HideElement(progressBarContainer); var progressBarHolder = new HtmlGenericControl("div"); progressBarHolder.Attributes.Add("class", "ajax__fileupload_ProgressBarHolder"); progressBarHolder.Controls.Add(progressBarContainer); footerContainer.Controls.Add(progressBarHolder); footerContainer.Controls.Add(uploadOrCancelButton); return footerContainer; } HtmlGenericControl GenerateHtmlSelectFileContainer(Control html5InputFileElement, Control inputFileElement) { // build select file Container that stays on top var htmlSelectFileContainer = new HtmlGenericControl("span"); htmlSelectFileContainer.Attributes.Add("id", ClientID + "_SelectFileContainer"); htmlSelectFileContainer.Attributes.Add("class", "ajax__fileupload_selectFileContainer"); htmlSelectFileContainer.Style["float"] = "left"; // build select file button var htmlSelectFileButton = new HtmlGenericControl("span"); htmlSelectFileButton.Attributes.Add("id", ClientID + "_SelectFileButton"); htmlSelectFileButton.Attributes.Add("class", "ajax__fileupload_selectFileButton"); htmlSelectFileContainer.Controls.Add(htmlSelectFileButton); htmlSelectFileContainer.Controls.Add(inputFileElement); htmlSelectFileContainer.Controls.Add(html5InputFileElement); return htmlSelectFileContainer; } HtmlGenericControl GenerateHtmlTopFileStatus(Control fileStatusContainer) { var htmlTopFileStatus = new HtmlGenericControl("div"); htmlTopFileStatus.Attributes.Add("class", "ajax__fileupload_topFileStatus"); htmlTopFileStatus.Style[HtmlTextWriterStyle.Position] = "relative"; htmlTopFileStatus.Controls.Add(fileStatusContainer); return htmlTopFileStatus; } void HideElement(HtmlControl element) { element.Style["display"] = "none"; element.Style["visibility"] = "hidden"; } protected override void DescribeComponent(ScriptComponentDescriptor descriptor) { base.DescribeComponent(descriptor); if(IsDesignMode) return; descriptor.AddProperty("contextKey", ContextKey); descriptor.AddProperty("postBackUrl", Page.Request.RawUrl); descriptor.AddProperty("serverPollingSupport", ServerPollingSupport); if(ThrobberID != String.Empty) { Control control = FindControl(ThrobberID); if(control != null) descriptor.AddElementProperty("throbber", control.ClientID); } } } } #pragma warning restore 1591
using System; using BigMath; using Raksha.Crypto.Parameters; using Raksha.Math; namespace Raksha.Crypto.Engines { /** * support class for constructing intergrated encryption ciphers * for doing basic message exchanges on top of key agreement ciphers */ public class IesEngine { private readonly IBasicAgreement agree; private readonly IDerivationFunction kdf; private readonly IMac mac; private readonly BufferedBlockCipher cipher; private readonly byte[] macBuf; private bool forEncryption; private ICipherParameters privParam, pubParam; private IesParameters param; /** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message */ public IesEngine( IBasicAgreement agree, IDerivationFunction kdf, IMac mac) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.GetMacSize()]; // this.cipher = null; } /** * set up for use in conjunction with a block cipher to handle the * message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public IesEngine( IBasicAgreement agree, IDerivationFunction kdf, IMac mac, BufferedBlockCipher cipher) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.GetMacSize()]; this.cipher = cipher; } /** * Initialise the encryptor. * * @param forEncryption whether or not this is encryption/decryption. * @param privParam our private key parameters * @param pubParam the recipient's/sender's public key parameters * @param param encoding and derivation parameters. */ public void Init( bool forEncryption, ICipherParameters privParameters, ICipherParameters pubParameters, ICipherParameters iesParameters) { this.forEncryption = forEncryption; this.privParam = privParameters; this.pubParam = pubParameters; this.param = (IesParameters)iesParameters; } private byte[] DecryptBlock( byte[] in_enc, int inOff, int inLen, byte[] z) { byte[] M = null; KeyParameter macKey = null; KdfParameters kParam = new KdfParameters(z, param.GetDerivationV()); int macKeySize = param.MacKeySize; kdf.Init(kParam); inLen -= mac.GetMacSize(); if (cipher == null) // stream mode { byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8)); M = new byte[inLen]; for (int i = 0; i != inLen; i++) { M[i] = (byte)(in_enc[inOff + i] ^ Buffer[i]); } macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8)); } else { int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize; byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8)); cipher.Init(false, new KeyParameter(Buffer, 0, (cipherKeySize / 8))); M = cipher.DoFinal(in_enc, inOff, inLen); macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8)); } byte[] macIV = param.GetEncodingV(); mac.Init(macKey); mac.BlockUpdate(in_enc, inOff, inLen); mac.BlockUpdate(macIV, 0, macIV.Length); mac.DoFinal(macBuf, 0); inOff += inLen; for (int t = 0; t < macBuf.Length; t++) { if (macBuf[t] != in_enc[inOff + t]) { throw (new InvalidCipherTextException("IMac codes failed to equal.")); } } return M; } private byte[] EncryptBlock( byte[] input, int inOff, int inLen, byte[] z) { byte[] C = null; KeyParameter macKey = null; KdfParameters kParam = new KdfParameters(z, param.GetDerivationV()); int c_text_length = 0; int macKeySize = param.MacKeySize; if (cipher == null) // stream mode { byte[] Buffer = GenerateKdfBytes(kParam, inLen + (macKeySize / 8)); C = new byte[inLen + mac.GetMacSize()]; c_text_length = inLen; for (int i = 0; i != inLen; i++) { C[i] = (byte)(input[inOff + i] ^ Buffer[i]); } macKey = new KeyParameter(Buffer, inLen, (macKeySize / 8)); } else { int cipherKeySize = ((IesWithCipherParameters)param).CipherKeySize; byte[] Buffer = GenerateKdfBytes(kParam, (cipherKeySize / 8) + (macKeySize / 8)); cipher.Init(true, new KeyParameter(Buffer, 0, (cipherKeySize / 8))); c_text_length = cipher.GetOutputSize(inLen); byte[] tmp = new byte[c_text_length]; int len = cipher.ProcessBytes(input, inOff, inLen, tmp, 0); len += cipher.DoFinal(tmp, len); C = new byte[len + mac.GetMacSize()]; c_text_length = len; Array.Copy(tmp, 0, C, 0, len); macKey = new KeyParameter(Buffer, (cipherKeySize / 8), (macKeySize / 8)); } byte[] macIV = param.GetEncodingV(); mac.Init(macKey); mac.BlockUpdate(C, 0, c_text_length); mac.BlockUpdate(macIV, 0, macIV.Length); // // return the message and it's MAC // mac.DoFinal(C, c_text_length); return C; } private byte[] GenerateKdfBytes( KdfParameters kParam, int length) { byte[] buf = new byte[length]; kdf.Init(kParam); kdf.GenerateBytes(buf, 0, buf.Length); return buf; } public byte[] ProcessBlock( byte[] input, int inOff, int inLen) { agree.Init(privParam); BigInteger z = agree.CalculateAgreement(pubParam); // TODO Check that this is right (...Unsigned? Check length?) byte[] zBytes = z.ToByteArray(); return forEncryption ? EncryptBlock(input, inOff, inLen, zBytes) : DecryptBlock(input, inOff, inLen, zBytes); } } }