context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagve = Google.Ads.GoogleAds.V8.Enums; using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedCampaignExtensionSettingServiceClientTest { [Category("Autogenerated")][Test] public void GetCampaignExtensionSettingRequestObject() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting response = client.GetCampaignExtensionSetting(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignExtensionSettingRequestObjectAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting responseCallSettings = await client.GetCampaignExtensionSettingAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignExtensionSetting responseCancellationToken = await client.GetCampaignExtensionSettingAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCampaignExtensionSetting() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting response = client.GetCampaignExtensionSetting(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignExtensionSettingAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting responseCallSettings = await client.GetCampaignExtensionSettingAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignExtensionSetting responseCancellationToken = await client.GetCampaignExtensionSettingAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetCampaignExtensionSettingResourceNames() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSetting(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting response = client.GetCampaignExtensionSetting(request.ResourceNameAsCampaignExtensionSettingName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetCampaignExtensionSettingResourceNamesAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); GetCampaignExtensionSettingRequest request = new GetCampaignExtensionSettingRequest { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), }; gagvr::CampaignExtensionSetting expectedResponse = new gagvr::CampaignExtensionSetting { ResourceNameAsCampaignExtensionSettingName = gagvr::CampaignExtensionSettingName.FromCustomerCampaignExtensionType("[CUSTOMER_ID]", "[CAMPAIGN_ID]", "[EXTENSION_TYPE]"), ExtensionType = gagve::ExtensionTypeEnum.Types.ExtensionType.Promotion, Device = gagve::ExtensionSettingDeviceEnum.Types.ExtensionSettingDevice.Unknown, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), ExtensionFeedItemsAsExtensionFeedItemNames = { gagvr::ExtensionFeedItemName.FromCustomerFeedItem("[CUSTOMER_ID]", "[FEED_ITEM_ID]"), }, }; mockGrpcClient.Setup(x => x.GetCampaignExtensionSettingAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CampaignExtensionSetting>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); gagvr::CampaignExtensionSetting responseCallSettings = await client.GetCampaignExtensionSettingAsync(request.ResourceNameAsCampaignExtensionSettingName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::CampaignExtensionSetting responseCancellationToken = await client.GetCampaignExtensionSettingAsync(request.ResourceNameAsCampaignExtensionSettingName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCampaignExtensionSettingsRequestObject() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCampaignExtensionSettingsRequest request = new MutateCampaignExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignExtensionSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignExtensionSettingsResponse expectedResponse = new MutateCampaignExtensionSettingsResponse { Results = { new MutateCampaignExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignExtensionSettingsResponse response = client.MutateCampaignExtensionSettings(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCampaignExtensionSettingsRequestObjectAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCampaignExtensionSettingsRequest request = new MutateCampaignExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignExtensionSettingOperation(), }, PartialFailure = false, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, }; MutateCampaignExtensionSettingsResponse expectedResponse = new MutateCampaignExtensionSettingsResponse { Results = { new MutateCampaignExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignExtensionSettingsResponse responseCallSettings = await client.MutateCampaignExtensionSettingsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignExtensionSettingsResponse responseCancellationToken = await client.MutateCampaignExtensionSettingsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateCampaignExtensionSettings() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCampaignExtensionSettingsRequest request = new MutateCampaignExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignExtensionSettingOperation(), }, }; MutateCampaignExtensionSettingsResponse expectedResponse = new MutateCampaignExtensionSettingsResponse { Results = { new MutateCampaignExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignExtensionSettings(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignExtensionSettingsResponse response = client.MutateCampaignExtensionSettings(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateCampaignExtensionSettingsAsync() { moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient> mockGrpcClient = new moq::Mock<CampaignExtensionSettingService.CampaignExtensionSettingServiceClient>(moq::MockBehavior.Strict); MutateCampaignExtensionSettingsRequest request = new MutateCampaignExtensionSettingsRequest { CustomerId = "customer_id3b3724cb", Operations = { new CampaignExtensionSettingOperation(), }, }; MutateCampaignExtensionSettingsResponse expectedResponse = new MutateCampaignExtensionSettingsResponse { Results = { new MutateCampaignExtensionSettingResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateCampaignExtensionSettingsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCampaignExtensionSettingsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); CampaignExtensionSettingServiceClient client = new CampaignExtensionSettingServiceClientImpl(mockGrpcClient.Object, null); MutateCampaignExtensionSettingsResponse responseCallSettings = await client.MutateCampaignExtensionSettingsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateCampaignExtensionSettingsResponse responseCancellationToken = await client.MutateCampaignExtensionSettingsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Linq; using System.Text; using System.Collections.Generic; using Wintellect.PowerCollections; class Event : IComparable { public DateTime date; public String title; public String location; public Event(DateTime date, String title, String location) { this.date = date; this.title = title; this.location = location; } public int CompareTo(object obj) { Event other = obj as Event; int byDate = this.date.CompareTo(other.date); int byTitle = this.title.CompareTo(other.title); int byLocation = this.location.CompareTo(other.location); if (byDate == 0) { if (byTitle == 0) { return byLocation; } else { return byTitle; } } else { return byDate; } } public override string ToString() { StringBuilder toString = new StringBuilder(); toString.Append(date.ToString("yyyy-MM-ddTHH:mm:ss")); toString.Append(" | " + title); if (location != null && location != "") { toString.Append(" | " + location); return toString.ToString(); } } class Program { static StringBuilder output = new StringBuilder(); static class Messages { public static void EventAdded() { output.Append("Event added\n"); } public static void EventDeleted(int x) { if (x == 0) { NoEventsFound(); } else { output.AppendFormat("{0} events deleted\n", x); } } public static void NoEventsFound() { output.Append("No events found\n"); } public static void PrintEvent(Event eventToPrint) { if (eventToPrint != null) { output.Append(eventToPrint + "\n"); } } } class EventHolder { MultiDictionary<string, Event> byTitle = new MultiDictionary<string, Event>(true); OrderedBag<Event> byDate = new OrderedBag<Event>(); public void AddEvent(DateTime date, string title, string location) { Event newEvent = new Event(date, title, location); byTitle.Add(title.ToLower(), newEvent); byDate.Add(newEvent); Messages.EventAdded(); } public void DeleteEvents(string titleToDelete) { int removed = 0; string title = titleToDelete.ToLower(); foreach (var eventToRemove in byTitle[title]) { removed++; byDate.Remove(eventToRemove); } byTitle.Remove(title); Messages.EventDeleted(removed); } public void ListEvents(DateTime date, int count) { int showed = 0; OrderedBag<Event>.VieweventsToShow = byDate.RangeFrom(new Event(date, "", ""), true); foreach (var eventToShow in eventsToShow) { if (showed == count) { break; } Messages.PrintEvent(eventToShow); showed++; } if (showed == 0) { Messages.NoEventsFound(); } } } static EventHolder events = new EventHolder(); static void Main(string[] args) { while (ExecuteNextCommand()) { Console.WriteLine(output); } } private static bool ExecuteNextCommand() { string command = Console.ReadLine(); if (command[0] == 'A') { AddEvent(command); return true; } if (command[0] == 'D') { DeleteEvents(command); return true; } if (command[0] == 'L') { ListEvents(command); return true; } if (command[0] == 'E') { return false; } return false; } private static void ListEvents(string command) { int pipeIndex = command.IndexOf('|'); DateTime date = GetDate( command, "ListEvents"); string countString = command.Substring(pipeIndex + 1); int count = int.Parse(countString); events.ListEvents(date, count); } private static void DeleteEvents(string command) { string title = command.Substring ("DeleteEvents".Length + 1); events.DeleteEvents(title); } private static void AddEvent(string command) { DateTime date; string title; string location; GetParameters(command, "AddEvent", out date, out title, out location); events.AddEvent(date, title, location); } private static void GetParameters(string commandForExecution, string commandType, out DateTime dateAndTime, out string eventTitle, out string eventLocation) { dateAndTime = GetDate(commandForExecution, commandType); int firstPipeIndex = commandForExecution.IndexOf('|'); int lastPipeIndex = commandForExecution.LastIndexOf('|'); if (firstPipeIndex == lastPipeIndex) { eventTitle = commandForExecution.Substring(firstPipeIndex + 1).Trim(); eventLocation = ""; } else { eventTitle = commandForExecution.Substring(firstPipeIndex + 1, lastPipeIndex - firstPipeIndex - 1).Trim(); eventLocation = commandForExecution.Substring(lastPipeIndex + 1).Trim(); } } private static DateTime GetDate(string command, string commandType) { DateTime date = DateTime.Parse(command.Substring(commandType.Length + 1, 20)); return date; } } }
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ using System.Threading; using System.Threading.Tasks; using Amqp; using Amqp.Framing; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Transactions; namespace Test.Amqp { [TestClass] public class TransactionTests { Address address = LinkTests.address; [ClassInitialize] public static void Initialize(TestContext context) { LinkTests.Initialize(context); } // if the project is targeted 4.5.1, TransactionScope can be created with // TransactionScopeAsyncFlowOption.Enabled option, and message can be sent // using SendAsync method. [TestMethod] public void TransactedPosting() { string testName = "TransactedPosting"; int nMsgs = 5; Connection connection = new Connection(this.address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); // commit using (var ts = new TransactionScope()) { for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName }; sender.Send(message); } ts.Complete(); } // rollback using (var ts = new TransactionScope()) { for (int i = nMsgs; i < nMsgs * 2; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "rollback" + i, GroupId = testName }; sender.Send(message); } } // commit using (var ts = new TransactionScope()) { for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName }; sender.Send(message); } ts.Complete(); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); for (int i = 0; i < nMsgs * 2; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.IsTrue(message.Properties.MessageId.StartsWith("commit")); } connection.Close(); } [TestMethod] public void TransactedRetiring() { string testName = "TransactedRetiring"; int nMsgs = 10; Connection connection = new Connection(this.address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); // send one extra for validation for (int i = 0; i < nMsgs + 1; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; sender.Send(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); Message[] messages = new Message[nMsgs]; for (int i = 0; i < nMsgs; i++) { messages[i] = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", messages[i].Properties.MessageId); } // commit harf using (var ts = new TransactionScope()) { for (int i = 0; i < nMsgs / 2; i++) { receiver.Accept(messages[i]); } ts.Complete(); } // rollback using (var ts = new TransactionScope()) { for (int i = nMsgs / 2; i < nMsgs; i++) { receiver.Accept(messages[i]); } } // after rollback, messages should be still acquired { Message message = receiver.Receive(); Assert.AreEqual("msg" + nMsgs, message.Properties.MessageId); receiver.Release(message); } // commit using (var ts = new TransactionScope()) { for (int i = nMsgs / 2; i < nMsgs; i++) { receiver.Accept(messages[i]); } ts.Complete(); } // only the last message is left { Message message = receiver.Receive(); Assert.AreEqual("msg" + nMsgs, message.Properties.MessageId); receiver.Accept(message); } // at this point, the queue should have zero messages. // If there are messages, it is a bug in the broker. connection.Close(); } [TestMethod] public void TransactedRetiringAndPosting() { string testName = "TransactedRetiringAndPosting"; int nMsgs = 10; Connection connection = new Connection(this.address); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); for (int i = 0; i < nMsgs; i++) { Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName }; sender.Send(message); } ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1"); receiver.SetCredit(2, false); Message message1 = receiver.Receive(); Message message2 = receiver.Receive(); // ack message1 and send a new message in a txn using (var ts = new TransactionScope()) { receiver.Accept(message1); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + nMsgs, GroupId = testName }; sender.Send(message); ts.Complete(); } // ack message2 and send a new message in a txn but abort the txn using (var ts = new TransactionScope()) { receiver.Accept(message2); Message message = new Message("test"); message.Properties = new Properties() { MessageId = "msg" + (nMsgs + 1), GroupId = testName }; sender.Send(message1); } receiver.Release(message2); // receive all messages. should see the effect of the first txn receiver.SetCredit(nMsgs, false); for (int i = 1; i <= nMsgs; i++) { Message message = receiver.Receive(); Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId); receiver.Accept(message); Assert.AreEqual("msg" + i, message.Properties.MessageId); } connection.Close(); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <[email protected]> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email [email protected] or visit the website www.fyiReporting.com. This file is originally from MS documentation: http://msdn.microsoft.com/en-us/library/system.reflection.binder.aspx Above license only applies to changes made above and beyond that code. */ using System; using System.Reflection; using System.Globalization; namespace fyiReporting.RDL { public class LaxBinder : Binder { public LaxBinder() : base() { } private class BinderState { public object[] args; } public override FieldInfo BindToField( BindingFlags bindingAttr, FieldInfo[] match, object value, CultureInfo culture ) { if (match == null) throw new ArgumentNullException("match"); // Get a field for which the value parameter can be converted to the specified field type. for (int i = 0; i < match.Length; i++) if (ChangeType(value, match[i].FieldType, culture) != null) return match[i]; return null; } public override MethodBase BindToMethod( BindingFlags bindingAttr, MethodBase[] match, ref object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] names, out object state ) { // Store the arguments to the method in a state object. BinderState myBinderState = new BinderState(); object[] arguments = new Object[args.Length]; args.CopyTo(arguments, 0); myBinderState.args = arguments; state = myBinderState; if (match == null) throw new ArgumentNullException(); // Find a method that has the same parameters as those of the args parameter. for (int i = 0; i < match.Length; i++) { // Count the number of parameters that match. int count = 0; ParameterInfo[] parameters = match[i].GetParameters(); // Go on to the next method if the number of parameters do not match. if (args.Length != parameters.Length) continue; // Match each of the parameters that the user expects the method to have. for (int j = 0; j < args.Length; j++) { // If the names parameter is not null, then reorder args. if (names != null) { if (names.Length != args.Length) throw new ArgumentException("names and args must have the same number of elements."); for (int k = 0; k < names.Length; k++) if (String.Compare(parameters[j].Name, names[k].ToString()) == 0) args[j] = myBinderState.args[k]; } // Determine whether the types specified by the user can be converted to the parameter type. if (ChangeType(args[j], parameters[j].ParameterType, culture) != null) count += 1; else break; } // Determine whether the method has been found. if (count == args.Length) return match[i]; } return null; } public override object ChangeType( object value, Type myChangeType, CultureInfo culture ) { // Determine whether the value parameter can be converted to a value of type myType. if (CanConvertFrom(value.GetType(), myChangeType)) // Return the converted object. return Convert.ChangeType(value, myChangeType); else // Return null. return null; } public override void ReorderArgumentArray( ref object[] args, object state ) { // Return the args that had been reordered by BindToMethod. ((BinderState)state).args.CopyTo(args, 0); } public override MethodBase SelectMethod( BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers ) { if (match == null) throw new ArgumentNullException("match"); for (int i = 0; i < match.Length; i++) { // Count the number of parameters that match. int count = 0; ParameterInfo[] parameters = match[i].GetParameters(); // Go on to the next method if the number of parameters do not match. if (types.Length != parameters.Length) continue; // Match each of the parameters that the user expects the method to have. for (int j = 0; j < types.Length; j++) // Determine whether the types specified by the user can be converted to parameter type. if (CanConvertFrom(types[j], parameters[j].ParameterType)) count += 1; else break; // Determine whether the method has been found. if (count == types.Length) return match[i]; } return null; } public override PropertyInfo SelectProperty( BindingFlags bindingAttr, PropertyInfo[] match, Type returnType, Type[] indexes, ParameterModifier[] modifiers ) { if (match == null) throw new ArgumentNullException("match"); for (int i = 0; i < match.Length; i++) { // Count the number of indexes that match. int count = 0; ParameterInfo[] parameters = match[i].GetIndexParameters(); // Go on to the next property if the number of indexes do not match. if (indexes.Length != parameters.Length) continue; // Match each of the indexes that the user expects the property to have. for (int j = 0; j < indexes.Length; j++) // Determine whether the types specified by the user can be converted to index type. if (CanConvertFrom(indexes[j], parameters[j].ParameterType)) count += 1; else break; // Determine whether the property has been found. if (count == indexes.Length) // Determine whether the return type can be converted to the properties type. if (CanConvertFrom(returnType, match[i].PropertyType)) return match[i]; else continue; } return null; } // Determines whether type1 can be converted to type2. Check only for primitive types. private bool CanConvertFrom(Type type1, Type type2) { if (type1.IsPrimitive && type2.IsPrimitive) { TypeCode typeCode1 = Type.GetTypeCode(type1); TypeCode typeCode2 = Type.GetTypeCode(type2); // If both type1 and type2 have the same type, return true. if (typeCode1 == typeCode2) return true; // Possible conversions from Char follow. if (typeCode1 == TypeCode.Char) switch (typeCode2) { case TypeCode.UInt16: return true; case TypeCode.UInt32: return true; case TypeCode.Int32: return true; case TypeCode.UInt64: return true; case TypeCode.Int64: return true; case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from Byte follow. if (typeCode1 == TypeCode.Byte) switch (typeCode2) { case TypeCode.Char: return true; case TypeCode.UInt16: return true; case TypeCode.Int16: return true; case TypeCode.UInt32: return true; case TypeCode.Int32: return true; case TypeCode.UInt64: return true; case TypeCode.Int64: return true; case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from SByte follow. if (typeCode1 == TypeCode.SByte) switch (typeCode2) { case TypeCode.Int16: return true; case TypeCode.Int32: return true; case TypeCode.Int64: return true; case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from UInt16 follow. if (typeCode1 == TypeCode.UInt16) switch (typeCode2) { case TypeCode.UInt32: return true; case TypeCode.Int32: return true; case TypeCode.UInt64: return true; case TypeCode.Int64: return true; case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from Int16 follow. if (typeCode1 == TypeCode.Int16) switch (typeCode2) { case TypeCode.Int32: return true; case TypeCode.Int64: return true; case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from UInt32 follow. if (typeCode1 == TypeCode.UInt32) switch (typeCode2) { case TypeCode.UInt64: return true; case TypeCode.Int64: return true; case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from Int32 follow. if (typeCode1 == TypeCode.Int32) switch (typeCode2) { case TypeCode.Int64: return true; case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from UInt64 follow. if (typeCode1 == TypeCode.UInt64) switch (typeCode2) { case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from Int64 follow. if (typeCode1 == TypeCode.Int64) switch (typeCode2) { case TypeCode.Single: return true; case TypeCode.Double: return true; default: return false; } // Possible conversions from Single follow. if (typeCode1 == TypeCode.Single) switch (typeCode2) { case TypeCode.Double: return true; default: return false; } } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using Xunit; namespace System.ComponentModel.Tests { public class MyTypeDescriptorContext : ITypeDescriptorContext { public IContainer Container => null; public object Instance { get { return null; } } public PropertyDescriptor PropertyDescriptor { get { return null; } } public bool OnComponentChanging() { return true; } public void OnComponentChanged() { } public object GetService(Type serviceType) { return null; } } public struct SomeValueType { public int a; } public enum SomeEnum { Add, Sub, Mul } [Flags] public enum SomeFlagsEnum { Option1 = 1, Option2 = 2, Option3 = 4 } public class FormattableClass : IFormattable { public string ToString(string format, IFormatProvider formatProvider) { return FormattableClass.Token; } public const string Token = "Formatted class."; } public class Collection1 : ICollection { public void CopyTo(Array array, int index) { throw new NotImplementedException(); } public int Count { get { throw new NotImplementedException(); } } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } public IEnumerator GetEnumerator() { throw new NotImplementedException(); } } public class MyTypeListConverter : TypeListConverter { public MyTypeListConverter(Type[] types) : base(types) { } } #if FUNCTIONAL_TESTS [TypeConverter("System.ComponentModel.Tests.BaseClassConverter, System.ComponentModel.TypeConverter.Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")] #elif PERFORMANCE_TESTS [TypeConverter("System.ComponentModel.Tests.BaseClassConverter, System.ComponentModel.TypeConverter.Performance.Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")] #else #error Define FUNCTIONAL_TESTS or PERFORMANCE_TESTS #endif public class BaseClass { public BaseClass() { BaseProperty = 1; } public override bool Equals(object other) { BaseClass otherBaseClass = other as BaseClass; if (otherBaseClass == null) { return false; } if (otherBaseClass.BaseProperty == BaseProperty) { return true; } return base.Equals(other); } public override int GetHashCode() { return base.GetHashCode(); } public int BaseProperty; } public class BaseClassConverter : TypeConverter { public BaseClassConverter(string someString) { throw new InvalidOperationException("This constructor should not be invoked by TypeDescriptor.GetConverter."); } public BaseClassConverter() { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(int)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(int)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is int) { BaseClass baseClass = new BaseClass(); baseClass.BaseProperty = (int)value; return baseClass; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(int)) { BaseClass baseClass = value as BaseClass; if (baseClass != null) { return baseClass.BaseProperty; } } return base.ConvertTo(context, culture, value, destinationType); } } [TypeConverter("System.ComponentModel.Tests.DerivedClassConverter")] internal class DerivedClass : BaseClass { public DerivedClass() : base() { DerivedProperty = 2; } public DerivedClass(int i) : base() { DerivedProperty = i; } public override bool Equals(object other) { DerivedClass otherDerivedClass = other as DerivedClass; if (otherDerivedClass == null) { return false; } if (otherDerivedClass.DerivedProperty != DerivedProperty) { return false; } return base.Equals(other); } public override int GetHashCode() { return base.GetHashCode(); } public int DerivedProperty; } internal class DerivedClassConverter : TypeConverter { public DerivedClassConverter() { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(int)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(int)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value is int) { DerivedClass derived = new DerivedClass(); derived.BaseProperty = (int)value; derived.DerivedProperty = (int)value; return derived; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(int)) { DerivedClass derived = value as DerivedClass; if (derived != null) { return derived.BaseProperty + derived.DerivedProperty; } } return base.ConvertTo(context, culture, value, destinationType); } } [TypeConverter(typeof(IBaseConverter))] public interface IBase { int InterfaceProperty { get; set; } } public interface IDerived : IBase { int DerivedInterfaceProperty { get; set; } } public class ClassIBase : IBase { public ClassIBase() { InterfaceProperty = 10; } public int InterfaceProperty { get; set; } } public class ClassIDerived : IDerived { public ClassIDerived() { InterfaceProperty = 20; DerivedInterfaceProperty = InterfaceProperty / 2; } public int InterfaceProperty { get; set; } public int DerivedInterfaceProperty { get; set; } } public class IBaseConverter : TypeConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string) || destinationType == typeof(int)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string)) { IBase baseInterface = (IBase)value; return "InterfaceProperty = " + baseInterface.InterfaceProperty.ToString(); } if (destinationType == typeof(int)) { IBase baseInterface = (IBase)value; return baseInterface.InterfaceProperty; } return base.ConvertTo(context, culture, value, destinationType); } } [TypeConverter("System.ComponentModel.Tests.InvalidConverter")] internal class ClassWithInvalidConverter : BaseClass { } public class InvalidConverter : TypeConverter { public InvalidConverter(string someString) { throw new InvalidOperationException("This constructor should not be invoked by TypeDescriptor.GetConverter."); } // Default constructor is missing, we expect the following exception when getting a converter: // System.MissingMethodException: No parameterless constructor defined for this object. } // TypeDescriptor should default to the TypeConverter in this case. public class ClassWithNoConverter { } }
// *********************************************************************** // Copyright (c) 2011 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. // *********************************************************************** using System; using System.Collections; using System.Collections.Specialized; using System.IO; using System.Diagnostics; using System.Globalization; using System.Threading; #if !NUNITLITE using System.Security.Principal; #endif using NUnit.Framework.Api; #if !NETCF && !PORTABLE using System.Runtime.Remoting.Messaging; #endif namespace NUnit.Framework.Internal { /// <summary> /// Helper class used to save and restore certain static or /// singleton settings in the environment that affect tests /// or which might be changed by the user tests. /// /// An internal class is used to hold settings and a stack /// of these objects is pushed and popped as Save and Restore /// are called. /// /// Static methods for each setting forward to the internal /// object on the top of the stack. /// </summary> public class TestExecutionContext #if !SILVERLIGHT && !NETCF && !PORTABLE : ILogicalThreadAffinative #endif { #region Instance Fields /// <summary> /// Link to a prior saved context /// </summary> public TestExecutionContext prior; /// <summary> /// The currently executing test /// </summary> private Test currentTest; /// <summary> /// The time the test began execution /// </summary> private DateTime startTime; /// <summary> /// The active TestResult for the current test /// </summary> private TestResult currentResult; /// <summary> /// The work directory to receive test output /// </summary> private string workDirectory; /// <summary> /// The object on which tests are currently being executed - i.e. the user fixture object /// </summary> private object testObject; /// <summary> /// The event listener currently receiving notifications /// </summary> private ITestListener listener = TestListener.NULL; /// <summary> /// The number of assertions for the current test /// </summary> private int assertCount; /// <summary> /// Indicates whether execution should terminate after the first error /// </summary> private bool stopOnError; /// <summary> /// Default timeout for test cases /// </summary> private int testCaseTimeout; private RandomGenerator randomGenerator; #if !NETCF /// <summary> /// The current culture /// </summary> private CultureInfo currentCulture; /// <summary> /// The current UI culture /// </summary> private CultureInfo currentUICulture; #endif #if !NETCF && !SILVERLIGHT /// <summary> /// Destination for standard output /// </summary> private TextWriter outWriter; /// <summary> /// Destination for standard error /// </summary> private TextWriter errorWriter; /// <summary> /// Indicates whether trace is enabled /// </summary> private bool tracing; /// <summary> /// Destination for Trace output /// </summary> private TextWriter traceWriter; #endif #if !NUNITLITE /// <summary> /// Indicates whether logging is enabled /// </summary> private bool logging; /// <summary> /// The current working directory /// </summary> private string currentDirectory; private Log4NetCapture logCapture; /// <summary> /// The current Principal. /// </summary> private IPrincipal currentPrincipal; #endif #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> public TestExecutionContext() { this.prior = null; this.testCaseTimeout = 0; #if !NETCF this.currentCulture = CultureInfo.CurrentCulture; this.currentUICulture = CultureInfo.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT && !PORTABLE this.outWriter = Console.Out; this.errorWriter = Console.Error; this.traceWriter = null; this.tracing = false; #endif #if !NUNITLITE this.logging = false; this.currentDirectory = Environment.CurrentDirectory; this.logCapture = new Log4NetCapture(); this.currentPrincipal = Thread.CurrentPrincipal; #endif } /// <summary> /// Initializes a new instance of the <see cref="TestExecutionContext"/> class. /// </summary> /// <param name="other">An existing instance of TestExecutionContext.</param> public TestExecutionContext( TestExecutionContext other ) { this.prior = other; this.currentTest = other.currentTest; this.currentResult = other.currentResult; this.testObject = other.testObject; this.workDirectory = other.workDirectory; this.listener = other.listener; this.stopOnError = other.stopOnError; this.testCaseTimeout = other.testCaseTimeout; #if !NETCF this.currentCulture = CultureInfo.CurrentCulture; this.currentUICulture = CultureInfo.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT this.outWriter = other.outWriter; this.errorWriter = other.errorWriter; this.traceWriter = other.traceWriter; this.tracing = other.tracing; #endif #if !NUNITLITE this.logging = other.logging; this.currentDirectory = Environment.CurrentDirectory; this.logCapture = other.logCapture; this.currentPrincipal = Thread.CurrentPrincipal; #endif } #endregion #region Static Singleton Instance /// <summary> /// The current context, head of the list of saved contexts. /// </summary> #if SILVERLIGHT || NETCF || PORTABLE #if (CLR_2_0 || CLR_4_0) && !NETCF && !PORTABLE [ThreadStatic] #endif private static TestExecutionContext current; #endif /// <summary> /// Gets the current context. /// </summary> /// <value>The current context.</value> public static TestExecutionContext CurrentContext { get { #if SILVERLIGHT || NETCF || PORTABLE if (current == null) current = new TestExecutionContext(); return current; #else return CallContext.GetData("NUnit.Framework.TestContext") as TestExecutionContext; #endif } } #endregion #region Static Methods internal static void SetCurrentContext(TestExecutionContext ec) { #if SILVERLIGHT || NETCF || PORTABLE current = ec; #else CallContext.SetData("NUnit.Framework.TestContext", ec); #endif } #endregion #region Properties /// <summary> /// Gets or sets the current test /// </summary> public Test CurrentTest { get { return currentTest; } set { currentTest = value; } } /// <summary> /// The time the current test started execution /// </summary> public DateTime StartTime { get { return startTime; } set { startTime = value; } } /// <summary> /// Gets or sets the current test result /// </summary> public TestResult CurrentResult { get { return currentResult; } set { currentResult = value; } } /// <summary> /// The current test object - that is the user fixture /// object on which tests are being executed. /// </summary> public object TestObject { get { return testObject; } set { testObject = value; } } /// <summary> /// Get or set the working directory /// </summary> public string WorkDirectory { get { return workDirectory; } set { workDirectory = value; } } /// <summary> /// Get or set indicator that run should stop on the first error /// </summary> public bool StopOnError { get { return stopOnError; } set { stopOnError = value; } } /// <summary> /// The current test event listener /// </summary> internal ITestListener Listener { get { return listener; } set { listener = value; } } /// <summary> /// Gets the RandomGenerator specific to this Test /// </summary> public RandomGenerator RandomGenerator { get { if (randomGenerator == null) { randomGenerator = new RandomGenerator(currentTest.Seed); } return randomGenerator; } } /// <summary> /// Gets the assert count. /// </summary> /// <value>The assert count.</value> internal int AssertCount { get { return assertCount; } set { assertCount = value; } } /// <summary> /// Gets or sets the test case timeout vaue /// </summary> public int TestCaseTimeout { get { return testCaseTimeout; } set { testCaseTimeout = value; } } #if !NETCF /// <summary> /// Saves or restores the CurrentCulture /// </summary> public CultureInfo CurrentCulture { get { return currentCulture; } set { currentCulture = value; Thread.CurrentThread.CurrentCulture = currentCulture; } } /// <summary> /// Saves or restores the CurrentUICulture /// </summary> public CultureInfo CurrentUICulture { get { return currentUICulture; } set { currentUICulture = value; Thread.CurrentThread.CurrentUICulture = currentUICulture; } } #endif #if !NETCF && !SILVERLIGHT && !PORTABLE /// <summary> /// Controls where Console.Out is directed /// </summary> internal TextWriter Out { get { return outWriter; } set { if ( outWriter != value ) { outWriter = value; Console.Out.Flush(); Console.SetOut( outWriter ); } } } /// <summary> /// Controls where Console.Error is directed /// </summary> internal TextWriter Error { get { return errorWriter; } set { if ( errorWriter != value ) { errorWriter = value; Console.Error.Flush(); Console.SetError( errorWriter ); } } } /// <summary> /// Controls whether trace and debug output are written /// to the standard output. /// </summary> internal bool Tracing { get { return tracing; } set { if (tracing != value) { if (traceWriter != null && tracing) StopTracing(); tracing = value; if (traceWriter != null && tracing) StartTracing(); } } } /// <summary> /// Controls where Trace output is directed /// </summary> internal TextWriter TraceWriter { get { return traceWriter; } set { if ( traceWriter != value ) { if ( traceWriter != null && tracing ) StopTracing(); traceWriter = value; if ( traceWriter != null && tracing ) StartTracing(); } } } private void StopTracing() { traceWriter.Close(); System.Diagnostics.Trace.Listeners.Remove( "NUnit" ); } private void StartTracing() { System.Diagnostics.Trace.Listeners.Add( new TextWriterTraceListener( traceWriter, "NUnit" ) ); } #endif #if !NUNITLITE /// <summary> /// Controls whether log output is captured /// </summary> public bool Logging { get { return logCapture.Enabled; } set { logCapture.Enabled = value; } } /// <summary> /// Gets or sets the Log writer, which is actually held by a log4net /// TextWriterAppender. When first set, the appender will be created /// and will thereafter send any log events to the writer. /// /// In normal operation, LogWriter is set to an EventListenerTextWriter /// connected to the EventQueue in the test domain. The events are /// subsequently captured in the Gui an the output displayed in /// the Log tab. The application under test does not need to define /// any additional appenders. /// </summary> public TextWriter LogWriter { get { return logCapture.Writer; } set { logCapture.Writer = value; } } /// <summary> /// Saves and restores the CurrentDirectory /// </summary> public string CurrentDirectory { get { return currentDirectory; } set { currentDirectory = value; Environment.CurrentDirectory = currentDirectory; } } /// <summary> /// Gets or sets the current <see cref="IPrincipal"/> for the Thread. /// </summary> public IPrincipal CurrentPrincipal { get { return this.currentPrincipal; } set { this.currentPrincipal = value; Thread.CurrentPrincipal = this.currentPrincipal; } } #endif #endregion #region Instance Methods /// <summary> /// Saves the old context and returns a fresh one /// with the same settings. /// </summary> public TestExecutionContext Save() { return new TestExecutionContext(this); } /// <summary> /// Restores the last saved context and puts /// any saved settings back into effect. /// </summary> public TestExecutionContext Restore() { if (prior == null) throw new InvalidOperationException("TestContext: too many Restores"); this.TestCaseTimeout = prior.TestCaseTimeout; #if !NETCF this.CurrentCulture = prior.CurrentCulture; this.CurrentUICulture = prior.CurrentUICulture; #endif #if !NETCF && !SILVERLIGHT && !PORTABLE this.Out = prior.Out; this.Error = prior.Error; this.Tracing = prior.Tracing; #endif #if !NUNITLITE this.CurrentDirectory = prior.CurrentDirectory; this.CurrentPrincipal = prior.CurrentPrincipal; #endif return prior; } /// <summary> /// Record any changes in the environment made by /// the test code in the execution context so it /// will be passed on to lower level tests. /// </summary> public void UpdateContext() { #if !NETCF this.currentCulture = CultureInfo.CurrentCulture; this.currentUICulture = CultureInfo.CurrentUICulture; #endif #if !NUNITLITE this.currentDirectory = Environment.CurrentDirectory; this.currentPrincipal = System.Threading.Thread.CurrentPrincipal; #endif } /// <summary> /// Increments the assert count. /// </summary> public void IncrementAssertCount() { System.Threading.Interlocked.Increment(ref assertCount); } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Reflection; using System.Text.RegularExpressions; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Console; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using FriendInfo = OpenSim.Services.Interfaces.FriendInfo; using OpenSim.Services.Connectors.Hypergrid; namespace OpenSim.Services.LLLoginService { public class LLLoginService : ILoginService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static bool Initialized = false; protected IUserAccountService m_UserAccountService; protected IGridUserService m_GridUserService; protected IAuthenticationService m_AuthenticationService; protected IInventoryService m_InventoryService; protected IGridService m_GridService; protected IPresenceService m_PresenceService; protected ISimulationService m_LocalSimulationService; protected ISimulationService m_RemoteSimulationService; protected ILibraryService m_LibraryService; protected IFriendsService m_FriendsService; protected IAvatarService m_AvatarService; protected IUserAgentService m_UserAgentService; protected GatekeeperServiceConnector m_GatekeeperConnector; protected string m_DefaultRegionName; protected string m_WelcomeMessage; protected bool m_RequireInventory; protected int m_MinLoginLevel; protected string m_GatekeeperURL; protected bool m_AllowRemoteSetLoginLevel; protected string m_MapTileURL; protected string m_SearchURL; IConfig m_LoginServerConfig; public LLLoginService(IConfigSource config, ISimulationService simService, ILibraryService libraryService) { m_LoginServerConfig = config.Configs["LoginService"]; if (m_LoginServerConfig == null) throw new Exception(String.Format("No section LoginService in config file")); string accountService = m_LoginServerConfig.GetString("UserAccountService", String.Empty); string gridUserService = m_LoginServerConfig.GetString("GridUserService", String.Empty); string agentService = m_LoginServerConfig.GetString("UserAgentService", String.Empty); string authService = m_LoginServerConfig.GetString("AuthenticationService", String.Empty); string invService = m_LoginServerConfig.GetString("InventoryService", String.Empty); string gridService = m_LoginServerConfig.GetString("GridService", String.Empty); string presenceService = m_LoginServerConfig.GetString("PresenceService", String.Empty); string libService = m_LoginServerConfig.GetString("LibraryService", String.Empty); string friendsService = m_LoginServerConfig.GetString("FriendsService", String.Empty); string avatarService = m_LoginServerConfig.GetString("AvatarService", String.Empty); string simulationService = m_LoginServerConfig.GetString("SimulationService", String.Empty); m_DefaultRegionName = m_LoginServerConfig.GetString("DefaultRegion", String.Empty); m_WelcomeMessage = m_LoginServerConfig.GetString("WelcomeMessage", "Welcome to OpenSim!"); m_RequireInventory = m_LoginServerConfig.GetBoolean("RequireInventory", true); m_AllowRemoteSetLoginLevel = m_LoginServerConfig.GetBoolean("AllowRemoteSetLoginLevel", false); m_MinLoginLevel = m_LoginServerConfig.GetInt("MinLoginLevel", 0); m_GatekeeperURL = m_LoginServerConfig.GetString("GatekeeperURI", string.Empty); m_MapTileURL = m_LoginServerConfig.GetString("MapTileURL", string.Empty); m_SearchURL = m_LoginServerConfig.GetString("SearchURL", string.Empty); // These are required; the others aren't if (accountService == string.Empty || authService == string.Empty) throw new Exception("LoginService is missing service specifications"); Object[] args = new Object[] { config }; m_UserAccountService = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args); m_GridUserService = ServerUtils.LoadPlugin<IGridUserService>(gridUserService, args); m_AuthenticationService = ServerUtils.LoadPlugin<IAuthenticationService>(authService, args); m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(invService, args); if (gridService != string.Empty) m_GridService = ServerUtils.LoadPlugin<IGridService>(gridService, args); if (presenceService != string.Empty) m_PresenceService = ServerUtils.LoadPlugin<IPresenceService>(presenceService, args); if (avatarService != string.Empty) m_AvatarService = ServerUtils.LoadPlugin<IAvatarService>(avatarService, args); if (friendsService != string.Empty) m_FriendsService = ServerUtils.LoadPlugin<IFriendsService>(friendsService, args); if (simulationService != string.Empty) m_RemoteSimulationService = ServerUtils.LoadPlugin<ISimulationService>(simulationService, args); if (agentService != string.Empty) m_UserAgentService = ServerUtils.LoadPlugin<IUserAgentService>(agentService, args); // // deal with the services given as argument // m_LocalSimulationService = simService; if (libraryService != null) { m_log.DebugFormat("[LLOGIN SERVICE]: Using LibraryService given as argument"); m_LibraryService = libraryService; } else if (libService != string.Empty) { m_log.DebugFormat("[LLOGIN SERVICE]: Using instantiated LibraryService"); m_LibraryService = ServerUtils.LoadPlugin<ILibraryService>(libService, args); } m_GatekeeperConnector = new GatekeeperServiceConnector(); if (!Initialized) { Initialized = true; RegisterCommands(); } m_log.DebugFormat("[LLOGIN SERVICE]: Starting..."); } public LLLoginService(IConfigSource config) : this(config, null, null) { } public Hashtable SetLevel(string firstName, string lastName, string passwd, int level, IPEndPoint clientIP) { Hashtable response = new Hashtable(); response["success"] = "false"; if (!m_AllowRemoteSetLoginLevel) return response; try { UserAccount account = m_UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) { m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, user {0} {1} not found", firstName, lastName); return response; } if (account.UserLevel < 200) { m_log.InfoFormat("[LLOGIN SERVICE]: Set Level failed, reason: user level too low"); return response; } // // Authenticate this user // // We don't support clear passwords here // string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30); UUID secureSession = UUID.Zero; if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession))) { m_log.InfoFormat("[LLOGIN SERVICE]: SetLevel failed, reason: authentication failed"); return response; } } catch (Exception e) { m_log.Error("[LLOGIN SERVICE]: SetLevel failed, exception " + e.ToString()); return response; } m_MinLoginLevel = level; m_log.InfoFormat("[LLOGIN SERVICE]: Login level set to {0} by {1} {2}", level, firstName, lastName); response["success"] = true; return response; } public LoginResponse Login(string firstName, string lastName, string passwd, string startLocation, UUID scopeID, string clientVersion, string channel, string mac, string id0, IPEndPoint clientIP) { bool success = false; UUID session = UUID.Random(); m_log.InfoFormat("[LLOGIN SERVICE]: Login request for {0} {1} from {2} with user agent {3} starting in {4}", firstName, lastName, clientIP.Address.ToString(), clientVersion, startLocation); try { // // Get the account and check that it exists // UserAccount account = m_UserAccountService.GetUserAccount(scopeID, firstName, lastName); if (account == null) { m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: user not found"); return LLFailedLoginResponse.UserProblem; } if (account.UserLevel < m_MinLoginLevel) { m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: login is blocked for user level {0}", account.UserLevel); return LLFailedLoginResponse.LoginBlockedProblem; } // If a scope id is requested, check that the account is in // that scope, or unscoped. // if (scopeID != UUID.Zero) { if (account.ScopeID != scopeID && account.ScopeID != UUID.Zero) { m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: user not found"); return LLFailedLoginResponse.UserProblem; } } else { scopeID = account.ScopeID; } // // Authenticate this user // if (!passwd.StartsWith("$1$")) passwd = "$1$" + Util.Md5Hash(passwd); passwd = passwd.Remove(0, 3); //remove $1$ string token = m_AuthenticationService.Authenticate(account.PrincipalID, passwd, 30); UUID secureSession = UUID.Zero; if ((token == string.Empty) || (token != string.Empty && !UUID.TryParse(token, out secureSession))) { m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: authentication failed"); return LLFailedLoginResponse.UserProblem; } // // Get the user's inventory // if (m_RequireInventory && m_InventoryService == null) { m_log.WarnFormat("[LLOGIN SERVICE]: Login failed, reason: inventory service not set up"); return LLFailedLoginResponse.InventoryProblem; } List<InventoryFolderBase> inventorySkel = m_InventoryService.GetInventorySkeleton(account.PrincipalID); if (m_RequireInventory && ((inventorySkel == null) || (inventorySkel != null && inventorySkel.Count == 0))) { m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: unable to retrieve user inventory"); return LLFailedLoginResponse.InventoryProblem; } // Get active gestures List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(account.PrincipalID); m_log.DebugFormat("[LLOGIN SERVICE]: {0} active gestures", gestures.Count); // // Login the presence // if (m_PresenceService != null) { success = m_PresenceService.LoginAgent(account.PrincipalID.ToString(), session, secureSession); if (!success) { m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: could not login presence"); return LLFailedLoginResponse.GridProblem; } } // // Change Online status and get the home region // GridRegion home = null; GridUserInfo guinfo = m_GridUserService.LoggedIn(account.PrincipalID.ToString()); if (guinfo != null && (guinfo.HomeRegionID != UUID.Zero) && m_GridService != null) { home = m_GridService.GetRegionByUUID(scopeID, guinfo.HomeRegionID); } if (guinfo == null) { // something went wrong, make something up, so that we don't have to test this anywhere else guinfo = new GridUserInfo(); guinfo.LastPosition = guinfo.HomePosition = new Vector3(128, 128, 30); } // // Find the destination region/grid // string where = string.Empty; Vector3 position = Vector3.Zero; Vector3 lookAt = Vector3.Zero; GridRegion gatekeeper = null; GridRegion destination = FindDestination(account, scopeID, guinfo, session, startLocation, home, out gatekeeper, out where, out position, out lookAt); if (destination == null) { m_PresenceService.LogoutAgent(session); m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: destination not found"); return LLFailedLoginResponse.GridProblem; } // // Get the avatar // AvatarAppearance avatar = null; if (m_AvatarService != null) { avatar = m_AvatarService.GetAppearance(account.PrincipalID); } // // Instantiate/get the simulation interface and launch an agent at the destination // string reason = string.Empty; GridRegion dest; AgentCircuitData aCircuit = LaunchAgentAtGrid(gatekeeper, destination, account, avatar, session, secureSession, position, where, clientVersion, channel, mac, id0, clientIP, out where, out reason, out dest); destination = dest; if (aCircuit == null) { m_PresenceService.LogoutAgent(session); m_log.InfoFormat("[LLOGIN SERVICE]: Login failed, reason: {0}", reason); return new LLFailedLoginResponse("key", reason, "false"); } // Get Friends list FriendInfo[] friendsList = new FriendInfo[0]; if (m_FriendsService != null) { friendsList = m_FriendsService.GetFriends(account.PrincipalID); m_log.DebugFormat("[LLOGIN SERVICE]: Retrieved {0} friends", friendsList.Length); } // // Finally, fill out the response and return it // LLLoginResponse response = new LLLoginResponse(account, aCircuit, guinfo, destination, inventorySkel, friendsList, m_LibraryService, where, startLocation, position, lookAt, gestures, m_WelcomeMessage, home, clientIP, m_MapTileURL, m_SearchURL); m_log.DebugFormat("[LLOGIN SERVICE]: All clear. Sending login response to client."); return response; } catch (Exception e) { m_log.WarnFormat("[LLOGIN SERVICE]: Exception processing login for {0} {1}: {2} {3}", firstName, lastName, e.ToString(), e.StackTrace); if (m_PresenceService != null) m_PresenceService.LogoutAgent(session); return LLFailedLoginResponse.InternalError; } } protected GridRegion FindDestination(UserAccount account, UUID scopeID, GridUserInfo pinfo, UUID sessionID, string startLocation, GridRegion home, out GridRegion gatekeeper, out string where, out Vector3 position, out Vector3 lookAt) { m_log.DebugFormat("[LLOGIN SERVICE]: FindDestination for start location {0}", startLocation); gatekeeper = null; where = "home"; position = new Vector3(128, 128, 0); lookAt = new Vector3(0, 1, 0); if (m_GridService == null) return null; if (startLocation.Equals("home")) { // logging into home region if (pinfo == null) return null; GridRegion region = null; bool tryDefaults = false; if (home == null) { m_log.WarnFormat( "[LLOGIN SERVICE]: User {0} {1} tried to login to a 'home' start location but they have none set", account.FirstName, account.LastName); tryDefaults = true; } else { region = home; position = pinfo.HomePosition; lookAt = pinfo.HomeLookAt; } if (tryDefaults) { List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } else { m_log.WarnFormat("[LLOGIN SERVICE]: User {0} {1} does not have a valid home and this grid does not have default locations. Attempting to find random region", account.FirstName, account.LastName); defaults = m_GridService.GetRegionsByName(scopeID, "", 1); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } } } return region; } else if (startLocation.Equals("last")) { // logging into last visited region where = "last"; if (pinfo == null) return null; GridRegion region = null; if (pinfo.LastRegionID.Equals(UUID.Zero) || (region = m_GridService.GetRegionByUUID(scopeID, pinfo.LastRegionID)) == null) { List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } else { m_log.Info("[LLOGIN SERVICE]: Last Region Not Found Attempting to find random region"); defaults = m_GridService.GetRegionsByName(scopeID, "", 1); if (defaults != null && defaults.Count > 0) { region = defaults[0]; where = "safe"; } } } else { position = pinfo.LastPosition; lookAt = pinfo.LastLookAt; } return region; } else { // free uri form // e.g. New Moon&135&46 New [email protected]:8002&153&34 where = "url"; Regex reURI = new Regex(@"^uri:(?<region>[^&]+)&(?<x>\d+)&(?<y>\d+)&(?<z>\d+)$"); Match uriMatch = reURI.Match(startLocation); if (uriMatch == null) { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, but can't process it", startLocation); return null; } else { position = new Vector3(float.Parse(uriMatch.Groups["x"].Value, Culture.NumberFormatInfo), float.Parse(uriMatch.Groups["y"].Value, Culture.NumberFormatInfo), float.Parse(uriMatch.Groups["z"].Value, Culture.NumberFormatInfo)); string regionName = uriMatch.Groups["region"].ToString(); if (regionName != null) { if (!regionName.Contains("@")) { List<GridRegion> regions = m_GridService.GetRegionsByName(scopeID, regionName, 1); if ((regions == null) || (regions != null && regions.Count == 0)) { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}. Trying defaults.", startLocation, regionName); regions = m_GridService.GetDefaultRegions(scopeID); if (regions != null && regions.Count > 0) { where = "safe"; return regions[0]; } else { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, Grid does not provide default regions.", startLocation); return null; } } return regions[0]; } else { if (m_UserAgentService == null) { m_log.WarnFormat("[LLLOGIN SERVICE]: This llogin service is not running a user agent service, as such it can't lauch agents at foreign grids"); return null; } string[] parts = regionName.Split(new char[] { '@' }); if (parts.Length < 2) { m_log.InfoFormat("[LLLOGIN SERVICE]: Got Custom Login URI {0}, can't locate region {1}", startLocation, regionName); return null; } // Valid specification of a remote grid regionName = parts[0]; string domainLocator = parts[1]; parts = domainLocator.Split(new char[] {':'}); string domainName = parts[0]; uint port = 0; if (parts.Length > 1) UInt32.TryParse(parts[1], out port); GridRegion region = FindForeignRegion(domainName, port, regionName, out gatekeeper); return region; } } else { List<GridRegion> defaults = m_GridService.GetDefaultRegions(scopeID); if (defaults != null && defaults.Count > 0) { where = "safe"; return defaults[0]; } else return null; } } //response.LookAt = "[r0,r1,r0]"; //// can be: last, home, safe, url //response.StartLocation = "url"; } } private GridRegion FindForeignRegion(string domainName, uint port, string regionName, out GridRegion gatekeeper) { gatekeeper = new GridRegion(); gatekeeper.ExternalHostName = domainName; gatekeeper.HttpPort = port; gatekeeper.RegionName = regionName; gatekeeper.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 0); UUID regionID; ulong handle; string imageURL = string.Empty, reason = string.Empty; if (m_GatekeeperConnector.LinkRegion(gatekeeper, out regionID, out handle, out domainName, out imageURL, out reason)) { GridRegion destination = m_GatekeeperConnector.GetHyperlinkRegion(gatekeeper, regionID); return destination; } return null; } private string hostName = string.Empty; private int port = 0; private void SetHostAndPort(string url) { try { Uri uri = new Uri(url); hostName = uri.Host; port = uri.Port; } catch { m_log.WarnFormat("[LLLogin SERVICE]: Unable to parse GatekeeperURL {0}", url); } } protected AgentCircuitData LaunchAgentAtGrid(GridRegion gatekeeper, GridRegion destination, UserAccount account, AvatarAppearance avatar, UUID session, UUID secureSession, Vector3 position, string currentWhere, string viewer, string channel, string mac, string id0, IPEndPoint clientIP, out string where, out string reason, out GridRegion dest) { where = currentWhere; ISimulationService simConnector = null; reason = string.Empty; uint circuitCode = 0; AgentCircuitData aCircuit = null; if (m_UserAgentService == null) { // HG standalones have both a localSimulatonDll and a remoteSimulationDll // non-HG standalones have just a localSimulationDll // independent login servers have just a remoteSimulationDll if (m_LocalSimulationService != null) simConnector = m_LocalSimulationService; else if (m_RemoteSimulationService != null) simConnector = m_RemoteSimulationService; } else // User Agent Service is on { if (gatekeeper == null) // login to local grid { if (hostName == string.Empty) SetHostAndPort(m_GatekeeperURL); gatekeeper = new GridRegion(destination); gatekeeper.ExternalHostName = hostName; gatekeeper.HttpPort = (uint)port; } else // login to foreign grid { } } bool success = false; if (m_UserAgentService == null && simConnector != null) { circuitCode = (uint)Util.RandomClass.Next(); ; aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0); success = LaunchAgentDirectly(simConnector, destination, aCircuit, out reason); if (!success && m_GridService != null) { // Try the fallback regions List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY); if (fallbacks != null) { foreach (GridRegion r in fallbacks) { success = LaunchAgentDirectly(simConnector, r, aCircuit, out reason); if (success) { where = "safe"; destination = r; break; } } } } } if (m_UserAgentService != null) { circuitCode = (uint)Util.RandomClass.Next(); ; aCircuit = MakeAgent(destination, account, avatar, session, secureSession, circuitCode, position, clientIP.Address.ToString(), viewer, channel, mac, id0); success = LaunchAgentIndirectly(gatekeeper, destination, aCircuit, clientIP, out reason); if (!success && m_GridService != null) { // Try the fallback regions List<GridRegion> fallbacks = m_GridService.GetFallbackRegions(account.ScopeID, destination.RegionLocX, destination.RegionLocY); if (fallbacks != null) { foreach (GridRegion r in fallbacks) { success = LaunchAgentIndirectly(gatekeeper, r, aCircuit, clientIP, out reason); if (success) { where = "safe"; destination = r; break; } } } } } dest = destination; if (success) return aCircuit; else return null; } private AgentCircuitData MakeAgent(GridRegion region, UserAccount account, AvatarAppearance avatar, UUID session, UUID secureSession, uint circuit, Vector3 position, string ipaddress, string viewer, string channel, string mac, string id0) { AgentCircuitData aCircuit = new AgentCircuitData(); aCircuit.AgentID = account.PrincipalID; if (avatar != null) aCircuit.Appearance = new AvatarAppearance(avatar); else aCircuit.Appearance = new AvatarAppearance(account.PrincipalID); //aCircuit.BaseFolder = irrelevant aCircuit.CapsPath = CapsUtil.GetRandomCapsObjectPath(); aCircuit.child = false; // the first login agent is root aCircuit.ChildrenCapSeeds = new Dictionary<ulong, string>(); aCircuit.circuitcode = circuit; aCircuit.firstname = account.FirstName; //aCircuit.InventoryFolder = irrelevant aCircuit.lastname = account.LastName; aCircuit.SecureSessionID = secureSession; aCircuit.SessionID = session; aCircuit.startpos = position; aCircuit.IPAddress = ipaddress; aCircuit.Viewer = viewer; aCircuit.Channel = channel; aCircuit.Mac = mac; aCircuit.Id0 = id0; SetServiceURLs(aCircuit, account); return aCircuit; //m_UserAgentService.LoginAgentToGrid(aCircuit, GatekeeperServiceConnector, region, out reason); //if (simConnector.CreateAgent(region, aCircuit, 0, out reason)) // return aCircuit; //return null; } private void SetServiceURLs(AgentCircuitData aCircuit, UserAccount account) { aCircuit.ServiceURLs = new Dictionary<string, object>(); if (account.ServiceURLs == null) return; foreach (KeyValuePair<string, object> kvp in account.ServiceURLs) { if (kvp.Value == null || (kvp.Value != null && kvp.Value.ToString() == string.Empty)) { aCircuit.ServiceURLs[kvp.Key] = m_LoginServerConfig.GetString(kvp.Key, string.Empty); } else { aCircuit.ServiceURLs[kvp.Key] = kvp.Value; } } } private bool LaunchAgentDirectly(ISimulationService simConnector, GridRegion region, AgentCircuitData aCircuit, out string reason) { return simConnector.CreateAgent(region, aCircuit, (int)Constants.TeleportFlags.ViaLogin, out reason); } private bool LaunchAgentIndirectly(GridRegion gatekeeper, GridRegion destination, AgentCircuitData aCircuit, IPEndPoint clientIP, out string reason) { m_log.Debug("[LLOGIN SERVICE] Launching agent at " + destination.RegionName); if (m_UserAgentService.LoginAgentToGrid(aCircuit, gatekeeper, destination, clientIP, out reason)) return true; return false; } #region Console Commands private void RegisterCommands() { //MainConsole.Instance.Commands.AddCommand MainConsole.Instance.Commands.AddCommand("loginservice", false, "login level", "login level <level>", "Set the minimum user level to log in", HandleLoginCommand); MainConsole.Instance.Commands.AddCommand("loginservice", false, "login reset", "login reset", "Reset the login level to allow all users", HandleLoginCommand); MainConsole.Instance.Commands.AddCommand("loginservice", false, "login text", "login text <text>", "Set the text users will see on login", HandleLoginCommand); } private void HandleLoginCommand(string module, string[] cmd) { string subcommand = cmd[1]; switch (subcommand) { case "level": // Set the minimum level to allow login // Useful to allow grid update without worrying about users. // or fixing critical issues // if (cmd.Length > 2) Int32.TryParse(cmd[2], out m_MinLoginLevel); break; case "reset": m_MinLoginLevel = 0; break; case "text": if (cmd.Length > 2) m_WelcomeMessage = cmd[2]; break; } } } #endregion }
// Copyright (C) 2014 dot42 // // Original filename: Org.Apache.Http.Conn.Params.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma warning disable 1717 namespace Org.Apache.Http.Conn.Params { /// <summary> /// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnConnectionPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the maximum number of ignorable lines before we expect a HTTP response's status line. </para><para>With HTTP/1.1 persistent connections, the problem arises that broken scripts could return a wrong Content-Length (there are more bytes sent than specified). Unfortunately, in some cases, this cannot be detected after the bad response, but only before the next one. So HttpClient must be able to skip those surplus lines this way. </para><para>This parameter expects a value of type Integer. 0 disallows all garbage/empty lines before the status line. Use java.lang.Integer#MAX_VALUE for unlimited (default in lenient mode). </para> /// </summary> /// <java-name> /// MAX_STATUS_LINE_GARBAGE /// </java-name> [Dot42.DexImport("MAX_STATUS_LINE_GARBAGE", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_STATUS_LINE_GARBAGE = "http.connection.max-status-line-garbage"; } /// <summary> /// <para>Parameter names for connections in HttpConn.</para><para><para></para><title>Revision:</title><para>576068 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionPNames", AccessFlags = 1537)] public partial interface IConnConnectionPNames /* scope: __dot42__ */ { } /// <summary> /// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRoutePNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnRoutePNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Parameter for the default proxy. The default value will be used by some HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type org.apache.http.HttpHost. </para> /// </summary> /// <java-name> /// DEFAULT_PROXY /// </java-name> [Dot42.DexImport("DEFAULT_PROXY", "Ljava/lang/String;", AccessFlags = 25)] public const string DEFAULT_PROXY = "http.route.default-proxy"; /// <summary> /// <para>Parameter for the local address. On machines with multiple network interfaces, this parameter can be used to select the network interface from which the connection originates. It will be interpreted by the standard HttpRoutePlanner implementations, in particular the default implementation. </para><para>This parameter expects a value of type java.net.InetAddress. </para> /// </summary> /// <java-name> /// LOCAL_ADDRESS /// </java-name> [Dot42.DexImport("LOCAL_ADDRESS", "Ljava/lang/String;", AccessFlags = 25)] public const string LOCAL_ADDRESS = "http.route.local-address"; /// <summary> /// <para>Parameter for an forced route. The forced route will be interpreted by the standard HttpRoutePlanner implementations. Instead of computing a route, the given forced route will be returned, even if it points to the wrong target host. </para><para>This parameter expects a value of type HttpRoute. </para> /// </summary> /// <java-name> /// FORCED_ROUTE /// </java-name> [Dot42.DexImport("FORCED_ROUTE", "Ljava/lang/String;", AccessFlags = 25)] public const string FORCED_ROUTE = "http.route.forced-route"; } /// <summary> /// <para>Parameter names for routing in HttpConn.</para><para><para></para><title>Revision:</title><para>613656 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRoutePNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRoutePNames", AccessFlags = 1537)] public partial interface IConnRoutePNames /* scope: __dot42__ */ { } /// <summary> /// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537, IgnoreFromJava = true, Priority = 1)] public static partial class IConnManagerPNamesConstants /* scope: __dot42__ */ { /// <summary> /// <para>Defines the timeout in milliseconds used when retrieving an instance of org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager. </para><para>This parameter expects a value of type Long. </para> /// </summary> /// <java-name> /// TIMEOUT /// </java-name> [Dot42.DexImport("TIMEOUT", "Ljava/lang/String;", AccessFlags = 25)] public const string TIMEOUT = "http.conn-manager.timeout"; /// <summary> /// <para>Defines the maximum number of connections per route. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type ConnPerRoute. </para> /// </summary> /// <java-name> /// MAX_CONNECTIONS_PER_ROUTE /// </java-name> [Dot42.DexImport("MAX_CONNECTIONS_PER_ROUTE", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_CONNECTIONS_PER_ROUTE = "http.conn-manager.max-per-route"; /// <summary> /// <para>Defines the maximum number of connections in total. This limit is interpreted by client connection managers and applies to individual manager instances. </para><para>This parameter expects a value of type Integer. </para> /// </summary> /// <java-name> /// MAX_TOTAL_CONNECTIONS /// </java-name> [Dot42.DexImport("MAX_TOTAL_CONNECTIONS", "Ljava/lang/String;", AccessFlags = 25)] public const string MAX_TOTAL_CONNECTIONS = "http.conn-manager.max-total"; } /// <summary> /// <para>Parameter names for connection managers in HttpConn.</para><para><para></para><title>Revision:</title><para>658781 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerPNames /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerPNames", AccessFlags = 1537)] public partial interface IConnManagerPNames /* scope: __dot42__ */ { } /// <summary> /// <para>This interface is intended for looking up maximum number of connections allowed for for a given route. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>651813 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnPerRoute /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnPerRoute", AccessFlags = 1537)] public partial interface IConnPerRoute /* scope: __dot42__ */ { /// <java-name> /// getMaxForRoute /// </java-name> [Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1025)] int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ ; } /// <summary> /// <para>Allows for setting parameters relating to connection routes on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRouteParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRouteParamBean", AccessFlags = 33)] public partial class ConnRouteParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnRouteParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::DEFAULT_PROXY </para></para> /// </summary> /// <java-name> /// setDefaultProxy /// </java-name> [Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/HttpHost;)V", AccessFlags = 1)] public virtual void SetDefaultProxy(global::Org.Apache.Http.HttpHost defaultProxy) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::LOCAL_ADDRESS </para></para> /// </summary> /// <java-name> /// setLocalAddress /// </java-name> [Dot42.DexImport("setLocalAddress", "(Ljava/net/InetAddress;)V", AccessFlags = 1)] public virtual void SetLocalAddress(global::Java.Net.InetAddress address) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnRoutePNames::FORCED_ROUTE </para></para> /// </summary> /// <java-name> /// setForcedRoute /// </java-name> [Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 1)] public virtual void SetForcedRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnRouteParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>An adaptor for accessing route related parameters in HttpParams. See ConnRoutePNames for parameter name definitions.</para><para><para> </para><simplesectsep></simplesectsep><para></para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnRouteParams /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnRouteParams", AccessFlags = 33)] public partial class ConnRouteParams : global::Org.Apache.Http.Conn.Params.IConnRoutePNames /* scope: __dot42__ */ { /// <summary> /// <para>A special value indicating "no host". This relies on a nonsense scheme name to avoid conflicts with actual hosts. Note that this is a <b>valid</b> host. </para> /// </summary> /// <java-name> /// NO_HOST /// </java-name> [Dot42.DexImport("NO_HOST", "Lorg/apache/http/HttpHost;", AccessFlags = 25)] public static readonly global::Org.Apache.Http.HttpHost NO_HOST; /// <summary> /// <para>A special value indicating "no route". This is a route with NO_HOST as the target. </para> /// </summary> /// <java-name> /// NO_ROUTE /// </java-name> [Dot42.DexImport("NO_ROUTE", "Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 25)] public static readonly global::Org.Apache.Http.Conn.Routing.HttpRoute NO_ROUTE; /// <summary> /// <para>Disabled default constructor. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 0)] internal ConnRouteParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the DEFAULT_PROXY parameter value. NO_HOST will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the default proxy set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getDefaultProxy /// </java-name> [Dot42.DexImport("getDefaultProxy", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/HttpHost;", AccessFlags = 9)] public static global::Org.Apache.Http.HttpHost GetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.HttpHost); } /// <summary> /// <para>Sets the DEFAULT_PROXY parameter value.</para><para></para> /// </summary> /// <java-name> /// setDefaultProxy /// </java-name> [Dot42.DexImport("setDefaultProxy", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/HttpHost;)V", AccessFlags = 9)] public static void SetDefaultProxy(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.HttpHost proxy) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the FORCED_ROUTE parameter value. NO_ROUTE will be mapped to <code>null</code>, to allow unsetting in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the forced route set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getForcedRoute /// </java-name> [Dot42.DexImport("getForcedRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/routing/HttpRoute;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Routing.HttpRoute GetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Routing.HttpRoute); } /// <summary> /// <para>Sets the FORCED_ROUTE parameter value.</para><para></para> /// </summary> /// <java-name> /// setForcedRoute /// </java-name> [Dot42.DexImport("setForcedRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/routing/HttpRoute;)V", AccessFlags = 9)] public static void SetForcedRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { } /// <summary> /// <para>Obtains the LOCAL_ADDRESS parameter value. There is no special value that would automatically be mapped to <code>null</code>. You can use the wildcard address (0.0.0.0 for IPv4, :: for IPv6) to override a specific local address in a hierarchy.</para><para></para> /// </summary> /// <returns> /// <para>the local address set in the argument parameters, or <code>null</code> if not set </para> /// </returns> /// <java-name> /// getLocalAddress /// </java-name> [Dot42.DexImport("getLocalAddress", "(Lorg/apache/http/params/HttpParams;)Ljava/net/InetAddress;", AccessFlags = 9)] public static global::Java.Net.InetAddress GetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Java.Net.InetAddress); } /// <summary> /// <para>Sets the LOCAL_ADDRESS parameter value.</para><para></para> /// </summary> /// <java-name> /// setLocalAddress /// </java-name> [Dot42.DexImport("setLocalAddress", "(Lorg/apache/http/params/HttpParams;Ljava/net/InetAddress;)V", AccessFlags = 9)] public static void SetLocalAddress(global::Org.Apache.Http.Params.IHttpParams @params, global::Java.Net.InetAddress local) /* MethodBuilder.Create */ { } } /// <summary> /// <para>Allows for setting parameters relating to connections on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnConnectionParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnConnectionParamBean", AccessFlags = 33)] public partial class ConnConnectionParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnConnectionParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnConnectionPNames::MAX_STATUS_LINE_GARBAGE </para></para> /// </summary> /// <java-name> /// setMaxStatusLineGarbage /// </java-name> [Dot42.DexImport("setMaxStatusLineGarbage", "(I)V", AccessFlags = 1)] public virtual void SetMaxStatusLineGarbage(int maxStatusLineGarbage) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnConnectionParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } /// <summary> /// <para>This class maintains a map of HTTP routes to maximum number of connections allowed for those routes. This class can be used by pooling connection managers for a fine-grained control of connections on a per route basis.</para><para><para></para><para></para><title>Revision:</title><para>652947 </para></para><para><para>4.0 </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnPerRouteBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnPerRouteBean", AccessFlags = 49)] public sealed partial class ConnPerRouteBean : global::Org.Apache.Http.Conn.Params.IConnPerRoute /* scope: __dot42__ */ { /// <summary> /// <para>The default maximum number of connections allowed per host </para> /// </summary> /// <java-name> /// DEFAULT_MAX_CONNECTIONS_PER_ROUTE /// </java-name> [Dot42.DexImport("DEFAULT_MAX_CONNECTIONS_PER_ROUTE", "I", AccessFlags = 25)] public const int DEFAULT_MAX_CONNECTIONS_PER_ROUTE = 2; [Dot42.DexImport("<init>", "(I)V", AccessFlags = 1)] public ConnPerRouteBean(int defaultMax) /* MethodBuilder.Create */ { } [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ConnPerRouteBean() /* MethodBuilder.Create */ { } /// <java-name> /// getDefaultMax /// </java-name> [Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)] public int GetDefaultMax() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setDefaultMaxPerRoute /// </java-name> [Dot42.DexImport("setDefaultMaxPerRoute", "(I)V", AccessFlags = 1)] public void SetDefaultMaxPerRoute(int max) /* MethodBuilder.Create */ { } /// <java-name> /// setMaxForRoute /// </java-name> [Dot42.DexImport("setMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;I)V", AccessFlags = 1)] public void SetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route, int max) /* MethodBuilder.Create */ { } /// <java-name> /// getMaxForRoute /// </java-name> [Dot42.DexImport("getMaxForRoute", "(Lorg/apache/http/conn/routing/HttpRoute;)I", AccessFlags = 1)] public int GetMaxForRoute(global::Org.Apache.Http.Conn.Routing.HttpRoute route) /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// setMaxForRoutes /// </java-name> [Dot42.DexImport("setMaxForRoutes", "(Ljava/util/Map;)V", AccessFlags = 1, Signature = "(Ljava/util/Map<Lorg/apache/http/conn/routing/HttpRoute;Ljava/lang/Integer;>;)V")] public void SetMaxForRoutes(global::Java.Util.IMap<global::Org.Apache.Http.Conn.Routing.HttpRoute, int?> map) /* MethodBuilder.Create */ { } /// <java-name> /// getDefaultMax /// </java-name> public int DefaultMax { [Dot42.DexImport("getDefaultMax", "()I", AccessFlags = 1)] get{ return GetDefaultMax(); } } } /// <summary> /// <para>This class represents a collection of HTTP protocol parameters applicable to client-side connection managers.</para><para><para> </para><simplesectsep></simplesectsep><para>Michael Becke</para><para></para><title>Revision:</title><para>658785 </para></para><para><para>4.0</para><para>ConnManagerPNames </para></para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerParams /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerParams", AccessFlags = 49)] public sealed partial class ConnManagerParams : global::Org.Apache.Http.Conn.Params.IConnManagerPNames /* scope: __dot42__ */ { /// <summary> /// <para>The default maximum number of connections allowed overall </para> /// </summary> /// <java-name> /// DEFAULT_MAX_TOTAL_CONNECTIONS /// </java-name> [Dot42.DexImport("DEFAULT_MAX_TOTAL_CONNECTIONS", "I", AccessFlags = 25)] public const int DEFAULT_MAX_TOTAL_CONNECTIONS = 20; [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public ConnManagerParams() /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para> /// </summary> /// <returns> /// <para>timeout in milliseconds. </para> /// </returns> /// <java-name> /// getTimeout /// </java-name> [Dot42.DexImport("getTimeout", "(Lorg/apache/http/params/HttpParams;)J", AccessFlags = 9)] public static long GetTimeout(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(long); } /// <summary> /// <para>Sets the timeout in milliseconds used when retrieving a org.apache.http.conn.ManagedClientConnection from the org.apache.http.conn.ClientConnectionManager.</para><para></para> /// </summary> /// <java-name> /// setTimeout /// </java-name> [Dot42.DexImport("setTimeout", "(Lorg/apache/http/params/HttpParams;J)V", AccessFlags = 9)] public static void SetTimeout(global::Org.Apache.Http.Params.IHttpParams @params, long timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para>Sets lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <java-name> /// setMaxConnectionsPerRoute /// </java-name> [Dot42.DexImport("setMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;Lorg/apache/http/conn/params/ConnPerRoute;)V", AccessFlags = 9)] public static void SetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params, global::Org.Apache.Http.Conn.Params.IConnPerRoute connPerRoute) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns lookup interface for maximum number of connections allowed per route.</para><para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <returns> /// <para>lookup interface for maximum number of connections allowed per route.</para> /// </returns> /// <java-name> /// getMaxConnectionsPerRoute /// </java-name> [Dot42.DexImport("getMaxConnectionsPerRoute", "(Lorg/apache/http/params/HttpParams;)Lorg/apache/http/conn/params/ConnPerRoute;", AccessFlags = 9)] public static global::Org.Apache.Http.Conn.Params.IConnPerRoute GetMaxConnectionsPerRoute(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(global::Org.Apache.Http.Conn.Params.IConnPerRoute); } /// <summary> /// <para>Sets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <java-name> /// setMaxTotalConnections /// </java-name> [Dot42.DexImport("setMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;I)V", AccessFlags = 9)] public static void SetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params, int maxTotalConnections) /* MethodBuilder.Create */ { } /// <summary> /// <para>Gets the maximum number of connections allowed.</para><para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <returns> /// <para>The maximum number of connections allowed.</para> /// </returns> /// <java-name> /// getMaxTotalConnections /// </java-name> [Dot42.DexImport("getMaxTotalConnections", "(Lorg/apache/http/params/HttpParams;)I", AccessFlags = 9)] public static int GetMaxTotalConnections(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { return default(int); } } /// <summary> /// <para>Allows for setting parameters relating to connection managers on HttpParams. This class ensures that the values set on the params are type-safe. </para> /// </summary> /// <java-name> /// org/apache/http/conn/params/ConnManagerParamBean /// </java-name> [Dot42.DexImport("org/apache/http/conn/params/ConnManagerParamBean", AccessFlags = 33)] public partial class ConnManagerParamBean : global::Org.Apache.Http.Params.HttpAbstractParamBean /* scope: __dot42__ */ { [Dot42.DexImport("<init>", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1)] public ConnManagerParamBean(global::Org.Apache.Http.Params.IHttpParams @params) /* MethodBuilder.Create */ { } /// <java-name> /// setTimeout /// </java-name> [Dot42.DexImport("setTimeout", "(J)V", AccessFlags = 1)] public virtual void SetTimeout(long timeout) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnManagerPNames::MAX_TOTAL_CONNECTIONS </para></para> /// </summary> /// <java-name> /// setMaxTotalConnections /// </java-name> [Dot42.DexImport("setMaxTotalConnections", "(I)V", AccessFlags = 1)] public virtual void SetMaxTotalConnections(int maxConnections) /* MethodBuilder.Create */ { } /// <summary> /// <para><para>ConnManagerPNames::MAX_CONNECTIONS_PER_ROUTE </para></para> /// </summary> /// <java-name> /// setConnectionsPerRoute /// </java-name> [Dot42.DexImport("setConnectionsPerRoute", "(Lorg/apache/http/conn/params/ConnPerRouteBean;)V", AccessFlags = 1)] public virtual void SetConnectionsPerRoute(global::Org.Apache.Http.Conn.Params.ConnPerRouteBean connPerRoute) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal ConnManagerParamBean() /* TypeBuilder.AddDefaultConstructor */ { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Diagnostics; using ZendeskApi_v2; using FastMember; static class Main { public const string API_ENDPOINT = "https://yourcompany.zendesk.com/api/v2"; public const string API_USERNAME = "[email protected]"; public const string API_TOKEN = "abcd1234"; public const long YOURCOMPANY_ORGANIZATION_ID = 29958914; public const string TIME_ZONE_NAME = "Eastern Standard Time"; public const string SQL_CONNECTION_STRING = ""; public const long TIME_SPENT_CUSTOM_FIELD_ID = 22682894; public const long CATEGORY_CUSTOM_FIELD_ID = 30240257; public const long ACTION_CUSTOM_FIELD_ID = 22397090; public const long CLOSE_CODE_CUSTOM_FIELD_ID = 30242258; public static int Main(string[] args) { ZendeskTicketCache ZendeskTicketCache = new ZendeskTicketCache(SQL_CONNECTION_STRING); ZendeskTicketCache.UpdateTickets((args != null) && args.Count == 1 ? args(0) : string.Empty); if (args == null || args.Count == 0) ZendeskTicketCache.RemoveDeletedTickets(); Console.WriteLine("Done"); return 0; //success } private class ZendeskTicketCache { private ZendeskApi API = new ZendeskApi(Main.API_ENDPOINT, Main.API_USERNAME, string.Empty, Main.API_TOKEN); private string CONN_STRING; private Dictionary<long, DateTime> TICKET_CACHE = new Dictionary<long, DateTime>(); private List<long> TICKET_CACHE_NEW_OPEN = new List<long>(); public ZendeskTicketCache(string aConnString) { this.CONN_STRING = aConnString; } public class TicketWithMoreInfo { public Ticket Ticket = new Ticket(); public List<Timelog> Timelog = new List<Timelog>(); public List<AssigneeChange> AssigneeChange = new List<AssigneeChange>(); public List<Comment> Comment = new List<Comment>(); public List<GroupChange> GroupChange = new List<GroupChange>(); public List<StatusChange> StatusChange = new List<StatusChange>(); } private string GetSearchQuery(System.DateTime ModifiedDate) { return "updated>=" + ModifiedDate.AddDays(0).ToString("yyyy-MM-dd"); } private System.DateTime GetLastModifedDate() { DateTime myDate = default(DateTime); using (SqlClient.SqlConnection myConnection = new SqlClient.SqlConnection(this.CONN_STRING)) { myConnection.Open(); using (SqlClient.SqlCommand myCommand = new SqlClient.SqlCommand("SELECT MAX(Modified_Date) as LastDate FROM tblZendeskTicket WITH(NOLOCK)", myConnection)) { object myResult = myCommand.ExecuteScalar; myDate = myResult == null || object.ReferenceEquals(myResult, DBNull.Value) ? System.DateTime.Today.AddDays(-45) : (DateTime)myCommand.ExecuteScalar; } myConnection.Close(); } return myDate; } public void RemoveDeletedTickets() { List<long> myH2O = new List<long>(); using (SqlClient.SqlConnection myConnection = new SqlClient.SqlConnection(this.CONN_STRING)) { myConnection.Open(); using (SqlClient.SqlCommand myCommand = new SqlClient.SqlCommand("SELECT Ticket_ID FROM tblZendeskTicket WITH(NOLOCK) WHERE Status IN ('NEW','OPEN')", myConnection)) { SqlClient.SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read) { myH2O.Add(myReader.GetInt64(0)); } } myConnection.Close(); } List<long> myZD = new List<long>(); Models.Search.SearchResults mySearchResults = API.Search.SearchFor("type:ticket status<pending"); while (mySearchResults != null && mySearchResults.Results != null && mySearchResults.Results.Count > 0) { foreach (Models.Search.Result myItem in mySearchResults.Results) { if (!myZD.Contains(myItem.Id)) myZD.Add(myItem.Id); } mySearchResults = mySearchResults.Count > mySearchResults.Results.Count ? API.Search.GetByPageUrl<Models.Search.SearchResults>(mySearchResults.NextPage) : null; } List<long> myListToDelete = new List<long>(); foreach (long myID in myH2O) { if (!myZD.Contains(myID)) { if (!DoesTicketExist(myID)) myListToDelete.Add(myID); } } if (myListToDelete.Count > 0) { using (SqlClient.SqlConnection myConnection = new SqlClient.SqlConnection(this.CONN_STRING)) { myConnection.Open(); using (SqlClient.SqlCommand myCommand = new SqlClient.SqlCommand(string.Format("DELETE FROM tblZendeskTicket WHERE Ticket_ID IN ({0})", string.Join(",", myListToDelete)), myConnection)) { myCommand.ExecuteNonQuery(); } myConnection.Close(); } } Console.WriteLine("Done checking for deleted tickets."); } private void LoadCacheWithLastUpdated() { this.TICKET_CACHE_NEW_OPEN = new List<long>(); using (SqlClient.SqlConnection myConnection = new SqlClient.SqlConnection(this.CONN_STRING)) { myConnection.Open(); using (SqlClient.SqlCommand myCommand = new SqlClient.SqlCommand("SELECT Ticket_ID, Modified_Date FROM tblZendeskTicket WITH(NOLOCK)", myConnection)) { SqlClient.SqlDataReader myReader = myCommand.ExecuteReader(); while (myReader.Read) { this.TICKET_CACHE.Add(myReader.GetInt64(0), myReader.GetDateTime(1)); } } myConnection.Close(); } } private DateTime ConvertDateTime(DateTimeOffset aDateTime) { return TimeZoneInfo.ConvertTimeFromUtc(aDateTime.ToUniversalTime.DateTime, TimeZoneInfo.FindSystemTimeZoneById(TIME_ZONE_NAME)); } private bool DoesTicketExist(long TicketId) { string mySearchQuery = "type:ticket " + TicketId.ToString; Console.WriteLine("Checking for existence of ticket: " + TicketId.ToString + ""); Models.Search.SearchResults mySearchResults = API.Search.SearchFor(mySearchQuery); foreach (Models.Search.Result myResult in mySearchResults.Results) { if (myResult.Id == TicketId) return true; } Console.WriteLine("Ticket " + TicketId.ToString + " not found."); return false; } public List<Ticket> UpdateTickets(string aQuery = "") { Console.WriteLine("Loading cache..."); this.LoadCacheWithLastUpdated(); Console.WriteLine("Finished loading cache."); Dictionary<long, Ticket> myTickets = new Dictionary<long, Ticket>(); List<Timelog> myTimelogs = new List<Timelog>(); List<Comment> myComments = new List<Comment>(); List<GroupChange> myGroupChanges = new List<GroupChange>(); List<StatusChange> myStatusChanges = new List<StatusChange>(); List<AssigneeChange> myAssigneeChanges = new List<AssigneeChange>(); string[] mySearchQueries = null; if ((aQuery != null) && !string.IsNullOrEmpty(aQuery)) { mySearchQueries = new string[1]; mySearchQueries(0) = aQuery; } else { mySearchQueries = { GetSearchQuery(GetLastModifedDate()), "status<closed" }; } foreach (void mySearchQuery_loopVariable in mySearchQueries) { mySearchQuery = mySearchQuery_loopVariable; mySearchQuery = "type:ticket " + mySearchQuery; Console.WriteLine("Starting query: " + mySearchQuery + ""); Models.Search.SearchResults mySearchResults = API.Search.SearchFor(mySearchQuery); long myCounter = 0; while (mySearchResults != null && mySearchResults.Results != null && mySearchResults.Results.Count > 0) { Console.WriteLine("Search Results: " + mySearchResults.Count.ToString + " (" + myCounter.ToString + " so far)"); foreach (Models.Search.Result myItem in mySearchResults.Results) { myCounter += 1; if (!myTickets.ContainsKey(myItem.Id)) { System.DateTime.Today.ToUniversalTime(); if (TICKET_CACHE.ContainsKey(myItem.Id) && TICKET_CACHE(myItem.Id) == ConvertDateTime(myItem.UpdatedAt.Value)) { Console.WriteLine("No update needed for " + myItem.Id.ToString); } else { TicketWithMoreInfo myLookup = LookupTicket(myItem); myTickets.Add(myLookup.Ticket.Ticket_ID, myLookup.Ticket); myTimelogs.AddRange(myLookup.Timelog); myComments.AddRange(myLookup.Comment); myGroupChanges.AddRange(myLookup.GroupChange); myStatusChanges.AddRange(myLookup.StatusChange); myAssigneeChanges.AddRange(myLookup.AssigneeChange); } } } if (myTickets.Any && myTickets.Count >= 250) { Console.WriteLine("Flushing to database..."); WriteContentToDb(myTickets.Values.ToList(), myTimelogs, myComments, myGroupChanges, myAssigneeChanges, myStatusChanges); myTickets.Clear(); myAssigneeChanges.Clear(); myTimelogs.Clear(); myComments.Clear(); myGroupChanges.Clear(); myStatusChanges.Clear(); Console.WriteLine("Finished flushing to database."); } mySearchResults = mySearchResults.Count > mySearchResults.Results.Count ? API.Search.GetByPageUrl<Models.Search.SearchResults>(mySearchResults.NextPage) : null; } } if (myTickets.Any) { WriteContentToDb(myTickets.Values.ToList(), myTimelogs, myComments, myGroupChanges, myAssigneeChanges, myStatusChanges); } else { Console.WriteLine("No updates to database needed."); } return myTickets.Values.ToList(); } private void WriteContentToDb(List<Ticket> myTickets, List<Timelog> myTimelogs, List<Comment> myComments, List<GroupChange> myGroupChanges, List<AssigneeChange> myAssigneeChanges, List<StatusChange> myStatusChanges) { using (SqlClient.SqlConnection myConnection = new SqlClient.SqlConnection(CONN_STRING)) { myConnection.Open(); using (SqlClient.SqlCommand myCommand = new SqlClient.SqlCommand("create table #temp (Ticket_ID INT)", myConnection)) { myCommand.ExecuteNonQuery(); } BulkInsertlongs(myConnection, "#temp", myTickets.Select<long>(t => t.Ticket_ID).ToArray.ToList, "Ticket_ID"); using (SqlClient.SqlCommand myCommand = new SqlClient.SqlCommand("DELETE FROM tblZendeskticket WHERE Ticket_ID IN (SELECT Ticket_ID FROM #temp)", myConnection)) { myCommand.ExecuteNonQuery(); } BulkInsert<Ticket>(myConnection, "tblZendeskTicket", myTickets); BulkInsert<Timelog>(myConnection, "tblZendeskTimelog", myTimelogs); BulkInsert<AssigneeChange>(myConnection, "tblZendeskAssigneeChange", myAssigneeChanges); BulkInsert<Comment>(myConnection, "tblZendeskComment", myComments); BulkInsert<StatusChange>(myConnection, "tblZendeskStatusChange", myStatusChanges); BulkInsert<GroupChange>(myConnection, "tblZendeskGroupChange", myGroupChanges); myConnection.Close(); } } private void BulkInsertlongs(SqlClient.SqlConnection aConnection, string TableName, List<long> ListOfStuff, string FieldName) { DataTable myDT = new DataTable(); myDT.Columns.Add(new DataColumn(FieldName, typeof(long))); foreach (long a in ListOfStuff) { myDT.Rows.Add({ a }); } using (SqlClient.SqlBulkCopy myBulk = new SqlClient.SqlBulkCopy(aConnection)) { foreach (DataColumn myColumn in myDT.Columns) { myBulk.ColumnMappings.Add(new SqlClient.SqlBulkCopyColumnMapping(myColumn.ColumnName, myColumn.ColumnName)); } myBulk.DestinationTableName = TableName; myBulk.WriteToServer(myDT); } } private void BulkInsert<T>(SqlClient.SqlConnection aConnection, string TableName, List<T> ListOfStuff) { DataTable myDT = new DataTable(); using (ObjectReader myReader = ObjectReader.Create<T>(ListOfStuff)) { myDT.Load(myReader); } using (SqlClient.SqlBulkCopy myBulk = new SqlClient.SqlBulkCopy(aConnection)) { foreach (DataColumn myColumn in myDT.Columns) { myBulk.ColumnMappings.Add(new SqlClient.SqlBulkCopyColumnMapping(myColumn.ColumnName, myColumn.ColumnName)); } myBulk.DestinationTableName = TableName; myBulk.WriteToServer(myDT); } } private List<Models.Shared.Audit> GetAudits(long TicketID) { List<Models.Shared.Audit> myAudits = new List<Models.Shared.Audit>(); ZendeskApi_v2.Models.Shared.GroupAuditResponse myAuditGroup = API.Tickets.GetAudits(TicketID); do { if ((myAuditGroup.Audits != null)) { myAudits.AddRange(myAuditGroup.Audits); myAuditGroup = myAuditGroup.NextPage == null ? null : API.Search.GetByPageUrl<Models.Shared.GroupAuditResponse>(myAuditGroup.NextPage); } } while (myAuditGroup != null); return myAudits; } public TicketWithMoreInfo LookupTicket(Models.Search.Result aResult) { Console.WriteLine("Getting " + aResult.Id.ToString); TicketWithMoreInfo myReturn = new TicketWithMoreInfo(); var _with1 = myReturn.Ticket; _with1.Subject = aResult.Subject; _with1.Assignee = LookupUser(aResult.AssigneeId.GetValueOrDefault).Name; _with1.Organization = LookupOrganization(aResult.OrganizationId.GetValueOrDefault).Name; _with1.Ticket_ID = aResult.Id; _with1.Priority = aResult.Priority; _with1.Created_Date = ConvertDateTime(aResult.CreatedAt.Value); _with1.Tags = aResult.Tags != null ? string.Join(" ", aResult.Tags) : string.Empty; _with1.Group = LookupGroup(aResult.GroupId.GetValueOrDefault).Name; _with1.Modified_Date = ConvertDateTime(aResult.UpdatedAt.Value); _with1.Status = aResult.Status; _with1.Category = aResult.CustomFields.FirstOrDefault(a => a.Id == Main.CATEGORY_CUSTOM_FIELD_ID).Value ?? ""; _with1.Action = aResult.CustomFields.FirstOrDefault(a => a.Id == Main.ACTION_CUSTOM_FIELD_ID).Value ?? ""; _with1.Close_Code = aResult.CustomFields.FirstOrDefault(a => a.Id == Main.CLOSE_CODE_CUSTOM_FIELD_ID).Value ?? ""; List<Models.Shared.Audit> myAudits = GetAudits(aResult.Id); foreach (Models.Shared.Audit myAudit in myAudits) { Models.Shared.Event mySatisfactionScore = myAudit.Events.Where(a => a.FieldName != null && a.FieldName.ToUpper == "SATISFACTION_SCORE").FirstOrDefault; Models.Shared.Event mySatisfactionComment = myAudit.Events.Where(a => a.FieldName != null && a.FieldName.ToUpper == "SATISFACTION_COMMENT").FirstOrDefault; if ((mySatisfactionScore != null)) { switch (mySatisfactionScore.Value.ToString.ToUpper) { case "OFFERED": case "UNOFFERED": case "": myReturn.Ticket.Satisfaction_Comments = string.Empty; myReturn.Ticket.Satisfaction_Date = null; myReturn.Ticket.Satisfaction_Rating = string.Empty; break; default: myReturn.Ticket.Satisfaction_Comments = mySatisfactionComment == null ? string.Empty : mySatisfactionComment.Value.ToString; if (myReturn.Ticket.Satisfaction_Comments.Length > 500) myReturn.Ticket.Satisfaction_Comments.Substring(0, 500); myReturn.Ticket.Satisfaction_Rating = mySatisfactionScore.Value.ToString; myReturn.Ticket.Satisfaction_Date = ConvertDateTime(myAudit.CreatedAt.Value); break; } } Models.Shared.Event myTimeEvent = myAudit.Events.Where(a => a.FieldName == Main.TIME_SPENT_CUSTOM_FIELD_ID.ToString).FirstOrDefault; if ((myTimeEvent != null)) { myReturn.Timelog.Add(new Timelog { Duration = long.Parse(myTimeEvent.Value.ToString), Created_Date = ConvertDateTime(myAudit.CreatedAt.Value), Zendesk_Identifier = myAudit.Id.ToString, Ticket_ID = aResult.Id, User = LookupUser(myAudit.AuthorId).Name }); } Models.Shared.Event myComment = myAudit.Events.Where(a => a.Type.ToUpper == "COMMENT").FirstOrDefault; if ((myComment != null)) { Models.Users.User myUser = LookupUser(myComment.AuthorId.GetValueOrDefault); myReturn.Comment.Add(new Comment { Created_Date = ConvertDateTime(myAudit.CreatedAt.Value), Zendesk_Identifier = myAudit.Id.ToString, Ticket_ID = aResult.Id, Type = myComment.Public ? myUser.OrganizationId.GetValueOrDefault == Main.YOURCOMPANY_ORGANIZATION_ID ? Enum_Comment_Type.PUBLIC : Enum_Comment_Type.CUSTOMER : Enum_Comment_Type.INTERNAL.ToString, User = myUser.Name }); } Models.Shared.Event myGroupChange = myAudit.Events.Where(a => a.Type.ToUpper == "CHANGE" & (a.FieldName != null && a.FieldName.ToUpper == "GROUP_ID")).FirstOrDefault; if ((myGroupChange != null)) { Models.Users.User myUser = LookupUser(myAudit.AuthorId); if (myGroupChange.PreviousValue == null) myGroupChange.PreviousValue = "0"; if (myGroupChange.Value == null) myGroupChange.Value = "0"; Models.Groups.Group myFromGroup = LookupGroup(long.Parse(myGroupChange.PreviousValue.ToString)); Models.Groups.Group myToGroup = LookupGroup(long.Parse(myGroupChange.Value.ToString)); myReturn.GroupChange.Add(new GroupChange { Created_Date = ConvertDateTime(myAudit.CreatedAt.Value), Zendesk_Identifier = myAudit.Id.ToString, Ticket_ID = aResult.Id, Old_Group = myFromGroup == null ? "" : myFromGroup.Name, New_Group = myToGroup == null ? "" : myToGroup.Name, By_Customer = !(myUser.OrganizationId.GetValueOrDefault == 0 | myUser.OrganizationId.GetValueOrDefault == Main.YOURCOMPANY_ORGANIZATION_ID), User = myUser.Name }); } Models.Shared.Event myAssigneeChange = myAudit.Events.Where(a => a.Type.ToUpper == "CHANGE" & (a.FieldName != null && a.FieldName.ToUpper == "ASSIGNEE_ID")).FirstOrDefault; if ((myAssigneeChange != null)) { Models.Users.User myUser = LookupUser(myAudit.AuthorId); if (myAssigneeChange.PreviousValue == null) myAssigneeChange.PreviousValue = "0"; if (myAssigneeChange.Value == null) myAssigneeChange.Value = "0"; Models.Users.User myFromAssignee = LookupUser(long.Parse(myAssigneeChange.PreviousValue.ToString)); Models.Users.User myToAssignee = LookupUser(long.Parse(myAssigneeChange.Value.ToString)); myReturn.AssigneeChange.Add(new AssigneeChange { Created_Date = ConvertDateTime(myAudit.CreatedAt.Value), Zendesk_Identifier = myAudit.Id.ToString, Ticket_ID = aResult.Id, Old_Assignee = myFromAssignee == null ? "" : myFromAssignee.Name, New_Assignee = myToAssignee == null ? "" : myToAssignee.Name, User = myUser.Name }); } Models.Shared.Event myStatusChange = myAudit.Events.Where(a => a.Type.ToUpper == "CHANGE" & (a.FieldName != null && a.FieldName.ToUpper == "STATUS")).FirstOrDefault; if ((myStatusChange != null)) { if (myStatusChange.PreviousValue == null) myStatusChange.PreviousValue = ""; if (myStatusChange.Value == null) myStatusChange.Value = ""; Models.Users.User myUser = LookupUser(myAudit.AuthorId); myReturn.StatusChange.Add(new StatusChange { Created_Date = ConvertDateTime(myAudit.CreatedAt.Value), Zendesk_Identifier = myAudit.Id.ToString, Ticket_ID = aResult.Id, Old_Status = myStatusChange.PreviousValue.ToString, New_Status = myStatusChange.Value.ToString, By_Customer = !(myUser.OrganizationId.GetValueOrDefault == 0 | myUser.OrganizationId.GetValueOrDefault == Main.YOURCOMPANY_ORGANIZATION_ID), User = myUser.Name }); } } return myReturn; } private Dictionary<long, Models.Groups.Group> CacheGroup = new Dictionary<long, Models.Groups.Group>(); private Dictionary<long, Models.Users.User> CacheUser = new Dictionary<long, Models.Users.User>(); private Dictionary<long, Models.Organizations.Organization> CacheOrganization = new Dictionary<long, Models.Organizations.Organization>(); private Models.Users.User LookupUser(long UserId) { if (UserId <= 0) return new Models.Users.User { Id = UserId, Name = "" }; if (!CacheUser.ContainsKey(UserId)) { Models.Users.User myUser = null; try { myUser = API.Users.GetUser(UserId).User; } catch (Exception ex) { myUser = new Models.Users.User { Id = UserId, Name = "Unknown" }; } CacheUser.Add(UserId, myUser); } return CacheUser(UserId); } private Models.Groups.Group LookupGroup(long GroupId) { if (GroupId <= 0) return new Models.Groups.Group { Id = GroupId, Name = "" }; if (!CacheGroup.ContainsKey(GroupId)) { Models.Groups.Group myGroup = null; try { myGroup = API.Groups.GetGroupById(GroupId).Group; } catch (Exception ex) { myGroup = new Models.Groups.Group { Id = GroupId, Name = "Unknown" }; } CacheGroup.Add(GroupId, myGroup); } return CacheGroup(GroupId); } private Models.Organizations.Organization LookupOrganization(long OrganizationId) { if (OrganizationId <= 0) return new Models.Organizations.Organization { Id = OrganizationId, Name = "" }; if (!CacheOrganization.ContainsKey(OrganizationId)) { Models.Organizations.Organization myOrganization = null; try { myOrganization = API.Organizations.GetOrganization(OrganizationId).Organization; } catch (Exception ex) { myOrganization = new Models.Organizations.Organization { Id = OrganizationId, Name = "Unknown" }; } CacheOrganization.Add(OrganizationId, myOrganization); } return CacheOrganization(OrganizationId); } public class Ticket { public long Ticket_ID { get; set; } public string Organization { get; set; } public string Subject { get; set; } public DateTime Created_Date { get; set; } public string Tags { get; set; } public string Category { get; set; } public string Priority { get; set; } public string Assignee { get; set; } public string Group { get; set; } public string Status { get; set; } public string Satisfaction_Rating { get; set; } public string Satisfaction_Comments { get; set; } public System.DateTime? Satisfaction_Date { get; set; } public DateTime Modified_Date { get; set; } public DateTime Inserted_Date { get; set; } public string Action { get; set; } public string Close_Code { get; set; } } public class AssigneeChange { public long Ticket_ID { get; set; } public string Zendesk_Identifier { get; set; } public string User { get; set; } public string Old_Assignee { get; set; } public string New_Assignee { get; set; } public DateTime Created_Date { get; set; } } public class GroupChange { public long Ticket_ID { get; set; } public string Zendesk_Identifier { get; set; } public string User { get; set; } public string Old_Group { get; set; } public string New_Group { get; set; } public DateTime Created_Date { get; set; } public bool By_Customer { get; set; } } public class StatusChange { public long Ticket_ID { get; set; } public string Zendesk_Identifier { get; set; } public string User { get; set; } public string Old_Status { get; set; } public string New_Status { get; set; } public DateTime Created_Date { get; set; } public bool By_Customer { get; set; } } public class Timelog { public long Ticket_ID { get; set; } public string Zendesk_Identifier { get; set; } public string User { get; set; } public long Duration { get; set; } public DateTime Created_Date { get; set; } } public class Comment { public long Ticket_ID { get; set; } public string Zendesk_Identifier { get; set; } public string User { get; set; } public string Type { get; set; } public DateTime Created_Date { get; set; } } public enum Enum_Comment_Type { CUSTOMER, INTERNAL, PUBLIC } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: POGOProtos/Data/Battle/BattleResults.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace POGOProtos.Data.Battle { /// <summary>Holder for reflection information generated from POGOProtos/Data/Battle/BattleResults.proto</summary> public static partial class BattleResultsReflection { #region Descriptor /// <summary>File descriptor for POGOProtos/Data/Battle/BattleResults.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static BattleResultsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CipQT0dPUHJvdG9zL0RhdGEvQmF0dGxlL0JhdHRsZVJlc3VsdHMucHJvdG8S", "FlBPR09Qcm90b3MuRGF0YS5CYXR0bGUaIlBPR09Qcm90b3MvRGF0YS9HeW0v", "R3ltU3RhdGUucHJvdG8aLlBPR09Qcm90b3MvRGF0YS9CYXR0bGUvQmF0dGxl", "UGFydGljaXBhbnQucHJvdG8i3gEKDUJhdHRsZVJlc3VsdHMSMAoJZ3ltX3N0", "YXRlGAEgASgLMh0uUE9HT1Byb3Rvcy5EYXRhLkd5bS5HeW1TdGF0ZRI8Cglh", "dHRhY2tlcnMYAiADKAsyKS5QT0dPUHJvdG9zLkRhdGEuQmF0dGxlLkJhdHRs", "ZVBhcnRpY2lwYW50EiEKGXBsYXllcl9leHBlcmllbmNlX2F3YXJkZWQYAyAD", "KAUSIAoYbmV4dF9kZWZlbmRlcl9wb2tlbW9uX2lkGAQgASgDEhgKEGd5bV9w", "b2ludHNfZGVsdGEYBSABKAViBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::POGOProtos.Data.Gym.GymStateReflection.Descriptor, global::POGOProtos.Data.Battle.BattleParticipantReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::POGOProtos.Data.Battle.BattleResults), global::POGOProtos.Data.Battle.BattleResults.Parser, new[]{ "GymState", "Attackers", "PlayerExperienceAwarded", "NextDefenderPokemonId", "GymPointsDelta" }, null, null, null) })); } #endregion } #region Messages public sealed partial class BattleResults : pb::IMessage<BattleResults> { private static readonly pb::MessageParser<BattleResults> _parser = new pb::MessageParser<BattleResults>(() => new BattleResults()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<BattleResults> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::POGOProtos.Data.Battle.BattleResultsReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BattleResults() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BattleResults(BattleResults other) : this() { GymState = other.gymState_ != null ? other.GymState.Clone() : null; attackers_ = other.attackers_.Clone(); playerExperienceAwarded_ = other.playerExperienceAwarded_.Clone(); nextDefenderPokemonId_ = other.nextDefenderPokemonId_; gymPointsDelta_ = other.gymPointsDelta_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public BattleResults Clone() { return new BattleResults(this); } /// <summary>Field number for the "gym_state" field.</summary> public const int GymStateFieldNumber = 1; private global::POGOProtos.Data.Gym.GymState gymState_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::POGOProtos.Data.Gym.GymState GymState { get { return gymState_; } set { gymState_ = value; } } /// <summary>Field number for the "attackers" field.</summary> public const int AttackersFieldNumber = 2; private static readonly pb::FieldCodec<global::POGOProtos.Data.Battle.BattleParticipant> _repeated_attackers_codec = pb::FieldCodec.ForMessage(18, global::POGOProtos.Data.Battle.BattleParticipant.Parser); private readonly pbc::RepeatedField<global::POGOProtos.Data.Battle.BattleParticipant> attackers_ = new pbc::RepeatedField<global::POGOProtos.Data.Battle.BattleParticipant>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::POGOProtos.Data.Battle.BattleParticipant> Attackers { get { return attackers_; } } /// <summary>Field number for the "player_experience_awarded" field.</summary> public const int PlayerExperienceAwardedFieldNumber = 3; private static readonly pb::FieldCodec<int> _repeated_playerExperienceAwarded_codec = pb::FieldCodec.ForInt32(26); private readonly pbc::RepeatedField<int> playerExperienceAwarded_ = new pbc::RepeatedField<int>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<int> PlayerExperienceAwarded { get { return playerExperienceAwarded_; } } /// <summary>Field number for the "next_defender_pokemon_id" field.</summary> public const int NextDefenderPokemonIdFieldNumber = 4; private long nextDefenderPokemonId_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long NextDefenderPokemonId { get { return nextDefenderPokemonId_; } set { nextDefenderPokemonId_ = value; } } /// <summary>Field number for the "gym_points_delta" field.</summary> public const int GymPointsDeltaFieldNumber = 5; private int gymPointsDelta_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int GymPointsDelta { get { return gymPointsDelta_; } set { gymPointsDelta_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as BattleResults); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(BattleResults other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(GymState, other.GymState)) return false; if(!attackers_.Equals(other.attackers_)) return false; if(!playerExperienceAwarded_.Equals(other.playerExperienceAwarded_)) return false; if (NextDefenderPokemonId != other.NextDefenderPokemonId) return false; if (GymPointsDelta != other.GymPointsDelta) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (gymState_ != null) hash ^= GymState.GetHashCode(); hash ^= attackers_.GetHashCode(); hash ^= playerExperienceAwarded_.GetHashCode(); if (NextDefenderPokemonId != 0L) hash ^= NextDefenderPokemonId.GetHashCode(); if (GymPointsDelta != 0) hash ^= GymPointsDelta.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (gymState_ != null) { output.WriteRawTag(10); output.WriteMessage(GymState); } attackers_.WriteTo(output, _repeated_attackers_codec); playerExperienceAwarded_.WriteTo(output, _repeated_playerExperienceAwarded_codec); if (NextDefenderPokemonId != 0L) { output.WriteRawTag(32); output.WriteInt64(NextDefenderPokemonId); } if (GymPointsDelta != 0) { output.WriteRawTag(40); output.WriteInt32(GymPointsDelta); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (gymState_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(GymState); } size += attackers_.CalculateSize(_repeated_attackers_codec); size += playerExperienceAwarded_.CalculateSize(_repeated_playerExperienceAwarded_codec); if (NextDefenderPokemonId != 0L) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(NextDefenderPokemonId); } if (GymPointsDelta != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(GymPointsDelta); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(BattleResults other) { if (other == null) { return; } if (other.gymState_ != null) { if (gymState_ == null) { gymState_ = new global::POGOProtos.Data.Gym.GymState(); } GymState.MergeFrom(other.GymState); } attackers_.Add(other.attackers_); playerExperienceAwarded_.Add(other.playerExperienceAwarded_); if (other.NextDefenderPokemonId != 0L) { NextDefenderPokemonId = other.NextDefenderPokemonId; } if (other.GymPointsDelta != 0) { GymPointsDelta = other.GymPointsDelta; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (gymState_ == null) { gymState_ = new global::POGOProtos.Data.Gym.GymState(); } input.ReadMessage(gymState_); break; } case 18: { attackers_.AddEntriesFrom(input, _repeated_attackers_codec); break; } case 26: case 24: { playerExperienceAwarded_.AddEntriesFrom(input, _repeated_playerExperienceAwarded_codec); break; } case 32: { NextDefenderPokemonId = input.ReadInt64(); break; } case 40: { GymPointsDelta = input.ReadInt32(); break; } } } } } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Reflection; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal partial class ExpressionBinder { // ---------------------------------------------------------------------------- // BindImplicitConversion // ---------------------------------------------------------------------------- private class ImplicitConversion { public ImplicitConversion(ExpressionBinder binder, EXPR exprSrc, CType typeSrc, EXPRTYPEORNAMESPACE typeDest, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest.TypeOrNamespace.AsType(); _exprTypeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public EXPR ExprDest { get { return _exprDest; } } private EXPR _exprDest; private ExpressionBinder _binder; private EXPR _exprSrc; private CType _typeSrc; private CType _typeDest; private EXPRTYPEORNAMESPACE _exprTypeDest; private bool _needsExprDest; private CONVERTTYPE _flags; /* * BindImplicitConversion * * This is a complex routine with complex parameters. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with implicit conversions. * * exprSrc - the expression being converted. Can be null if only type conversion * info is being supplied. * typeSrc - type of the source * typeDest - type of the destination * exprDest - returns an expression of the src converted to the dest. If null, we * only care about whether the conversion can be attempted, not the * expression tree. * flags - flags possibly customizing the conversions allowed. E.g., can suppress * user-defined conversions. * * returns true if the conversion can be made, false if not. */ public bool Bind() { // 13.1 Implicit conversions // // The following conversions are classified as implicit conversions: // // * Identity conversions // * Implicit numeric conversions // * Implicit enumeration conversions // * Implicit reference conversions // * Boxing conversions // * Implicit type parameter conversions // * Implicit constant expression conversions // * User-defined implicit conversions // * Implicit conversions from an anonymous method expression to a compatible delegate type // * Implicit conversion from a method group to a compatible delegate type // * Conversions from the null type (11.2.7) to any nullable type // * Implicit nullable conversions // * Lifted user-defined implicit conversions // // Implicit conversions can occur in a variety of situations, including function member invocations // (14.4.3), cast expressions (14.6.6), and assignments (14.14). // Can't convert to or from the error type. if (_typeSrc == null || _typeDest == null || _typeDest.IsNeverSameType()) { return false; } Debug.Assert(_typeSrc != null && _typeDest != null); // types must be supplied. Debug.Assert(_exprSrc == null || _typeSrc == _exprSrc.type); // type of source should be correct if source supplied Debug.Assert(!_needsExprDest || _exprSrc != null); // need source expr to create dest expr switch (_typeDest.GetTypeKind()) { case TypeKind.TK_ErrorType: Debug.Assert(_typeDest.AsErrorType().HasTypeParent() || _typeDest.AsErrorType().HasNSParent()); if (_typeSrc != _typeDest) { return false; } if (_needsExprDest) { _exprDest = _exprSrc; } return true; case TypeKind.TK_NullType: // Can only convert to the null type if src is null. if (!_typeSrc.IsNullType()) { return false; } if (_needsExprDest) { _exprDest = _exprSrc; } return true; case TypeKind.TK_MethodGroupType: VSFAIL("Something is wrong with Type.IsNeverSameType()"); return false; case TypeKind.TK_NaturalIntegerType: case TypeKind.TK_ArgumentListType: return _typeSrc == _typeDest; case TypeKind.TK_VoidType: return false; default: break; } if (_typeSrc.IsErrorType()) { Debug.Assert(!_typeDest.IsErrorType()); return false; } // 13.1.1 Identity conversion // // An identity conversion converts from any type to the same type. This conversion exists only // such that an entity that already has a required type can be said to be convertible to that type. if (_typeSrc == _typeDest && ((_flags & CONVERTTYPE.ISEXPLICIT) == 0 || (!_typeSrc.isPredefType(PredefinedType.PT_FLOAT) && !_typeSrc.isPredefType(PredefinedType.PT_DOUBLE)))) { if (_needsExprDest) { _exprDest = _exprSrc; } return true; } if (_typeDest.IsNullableType()) { return BindNubConversion(_typeDest.AsNullableType()); } if (_typeSrc.IsNullableType()) { return bindImplicitConversionFromNullable(_typeSrc.AsNullableType()); } if ((_flags & CONVERTTYPE.ISEXPLICIT) != 0) { _flags |= CONVERTTYPE.NOUDC; } // Get the fundamental types of destination. FUNDTYPE ftDest = _typeDest.fundType(); Debug.Assert(ftDest != FUNDTYPE.FT_NONE || _typeDest.IsParameterModifierType()); switch (_typeSrc.GetTypeKind()) { default: VSFAIL("Bad type symbol kind"); break; case TypeKind.TK_MethodGroupType: if (_exprSrc.isMEMGRP()) { EXPRCALL outExpr; bool retVal = _binder.BindGrpConversion(_exprSrc.asMEMGRP(), _typeDest, _needsExprDest, out outExpr, false); _exprDest = outExpr; return retVal; } return false; case TypeKind.TK_VoidType: case TypeKind.TK_ErrorType: case TypeKind.TK_ParameterModifierType: case TypeKind.TK_ArgumentListType: return false; case TypeKind.TK_NullType: if (bindImplicitConversionFromNull()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_ArrayType: if (bindImplicitConversionFromArray()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_PointerType: if (bindImplicitConversionFromPointer()) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_TypeParameterType: if (bindImplicitConversionFromTypeVar(_typeSrc.AsTypeParameterType())) { return true; } // If not, try user defined implicit conversions. break; case TypeKind.TK_AggregateType: // TypeReference and ArgIterator can't be boxed (or converted to anything else) if (_typeSrc.isSpecialByRefType()) { return false; } if (bindImplicitConversionFromAgg(_typeSrc.AsAggregateType())) { return true; } // If not, try user defined implicit conversions. break; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // Every incoming dynamic operand should be implicitly convertible // to any type that it is an instance of. if (_exprSrc != null && _exprSrc.RuntimeObject != null && _typeDest.AssociatedSystemType.IsInstanceOfType(_exprSrc.RuntimeObject) && _binder.GetSemanticChecker().CheckTypeAccess(_typeDest, _binder.Context.ContextForMemberLookup())) { if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, _exprSrc.flags & EXPRFLAG.EXF_CANTBENULL); } return true; } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // END RUNTIME BINDER ONLY CHANGE // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // 13.1.8 User-defined implicit conversions // // A user-defined implicit conversion consists of an optional standard implicit conversion, // followed by execution of a user-defined implicit conversion operator, followed by another // optional standard implicit conversion. The exact rules for evaluating user-defined // conversions are described in 13.4.3. if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, true); } // No conversion was found. return false; } /*************************************************************************************************** Called by BindImplicitConversion when the destination type is Nullable<T>. The following conversions are handled by this method: * For S in { object, ValueType, interfaces implemented by underlying type} there is an explicit unboxing conversion S => T? * System.Enum => T? there is an unboxing conversion if T is an enum type * null => T? implemented as default(T?) * Implicit T?* => T?+ implemented by either wrapping or calling GetValueOrDefault the appropriate number of times. * If imp/exp S => T then imp/exp S => T?+ implemented by converting to T then wrapping the appropriate number of times. * If imp/exp S => T then imp/exp S?+ => T?+ implemented by calling GetValueOrDefault (m-1) times then calling HasValue, producing a null if it returns false, otherwise calling Value, converting to T then wrapping the appropriate number of times. The 3 rules above can be summarized with the following recursive rules: * If imp/exp S => T? then imp/exp S? => T? implemented as qs.HasValue ? (T?)(qs.Value) : default(T?) * If imp/exp S => T then imp/exp S => T? implemented as new T?((T)s) This method also handles calling bindUserDefinedConverion. This method does NOT handle the following conversions: * Implicit boxing conversion from S? to { object, ValueType, Enum, ifaces implemented by S }. (Handled by BindImplicitConversion.) * If imp/exp S => T then explicit S?+ => T implemented by calling Value the appropriate number of times. (Handled by BindExplicitConversion.) The recursive equivalent is: * If imp/exp S => T and T is not nullable then explicit S? => T implemented as qs.Value Some nullable conversion are NOT standard conversions. In particular, if S => T is implicit then S? => T is not standard. Similarly if S => T is not implicit then S => T? is not standard. ***************************************************************************************************/ private bool BindNubConversion(NullableType nubDst) { // This code assumes that STANDARD and ISEXPLICIT are never both set. // bindUserDefinedConversion should ensure this! Debug.Assert(0 != (~_flags & (CONVERTTYPE.STANDARD | CONVERTTYPE.ISEXPLICIT))); Debug.Assert(_exprSrc == null || _exprSrc.type == _typeSrc); Debug.Assert(!_needsExprDest || _exprSrc != null); Debug.Assert(_typeSrc != nubDst); // BindImplicitConversion should have taken care of this already. AggregateType atsDst = nubDst.GetAts(GetErrorContext()); if (atsDst == null) return false; // Check for the unboxing conversion. This takes precedence over the wrapping conversions. if (GetSymbolLoader().HasBaseConversion(nubDst.GetUnderlyingType(), _typeSrc) && !CConversions.FWrappingConv(_typeSrc, nubDst)) { // These should be different! Fix the caller if typeSrc is an AggregateType of Nullable. Debug.Assert(atsDst != _typeSrc); // typeSrc is a base type of the destination nullable type so there is an explicit // unboxing conversion. if (0 == (_flags & CONVERTTYPE.ISEXPLICIT)) { return false; } if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); } return true; } int cnubDst; int cnubSrc; CType typeDstBase = nubDst.StripNubs(out cnubDst); EXPRCLASS exprTypeDstBase = GetExprFactory().MakeClass(typeDstBase); CType typeSrcBase = _typeSrc.StripNubs(out cnubSrc); ConversionFunc pfn = (_flags & CONVERTTYPE.ISEXPLICIT) != 0 ? (ConversionFunc)_binder.BindExplicitConversion : (ConversionFunc)_binder.BindImplicitConversion; if (cnubSrc == 0) { Debug.Assert(_typeSrc == typeSrcBase); // The null type can be implicitly converted to T? as the default value. if (_typeSrc.IsNullType()) { // If we have the constant null, generate it as a default value of T?. If we have // some crazy expression which has been determined to be always null, like (null??null) // keep it in its expression form and transform it in the nullable rewrite pass. if (_needsExprDest) { if (_exprSrc.isCONSTANT_OK()) { _exprDest = GetExprFactory().CreateZeroInit(nubDst); } else { _exprDest = GetExprFactory().CreateCast(0x00, _typeDest, _exprSrc); } } return true; } EXPR exprTmp = _exprSrc; // If there is an implicit/explicit S => T then there is an implicit/explicit S => T? if (_typeSrc == typeDstBase || pfn(_exprSrc, _typeSrc, exprTypeDstBase, nubDst, _needsExprDest, out exprTmp, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { EXPRUSERDEFINEDCONVERSION exprUDC = exprTmp.kind == ExpressionKind.EK_USERDEFINEDCONVERSION ? exprTmp.asUSERDEFINEDCONVERSION() : null; if (exprUDC != null) { exprTmp = exprUDC.UserDefinedCall; } // This logic is left over from the days when T?? was legal. However there are error/LAF cases that necessitates the loop. // typeSrc is not nullable so just wrap the required number of times. For legal code (cnubDst <= 0). for (int i = 0; i < cnubDst; i++) { exprTmp = _binder.BindNubNew(exprTmp); exprTmp.asCALL().nubLiftKind = NullableCallLiftKind.NullableConversionConstructor; } if (exprUDC != null) { exprUDC.UserDefinedCall = exprTmp; exprUDC.setType((CType)exprTmp.type); exprTmp = exprUDC; } Debug.Assert(exprTmp.type == nubDst); _exprDest = exprTmp; } return true; } // No builtin conversion. Maybe there is a user defined conversion.... return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, nubDst, _needsExprDest, out _exprDest, 0 == (_flags & CONVERTTYPE.ISEXPLICIT)); } // Both are Nullable so there is only a conversion if there is a conversion between the base types. // That is, if there is an implicit/explicit S => T then there is an implicit/explicit S?+ => T?+. if (typeSrcBase != typeDstBase && !pfn(null, typeSrcBase, exprTypeDstBase, nubDst, false, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { // No builtin conversion. Maybe there is a user defined conversion.... return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, nubDst, _needsExprDest, out _exprDest, 0 == (_flags & CONVERTTYPE.ISEXPLICIT)); } if (_needsExprDest) { MethWithInst mwi = new MethWithInst(null, null); EXPRMEMGRP pMemGroup = GetExprFactory().CreateMemGroup(null, mwi); EXPRCALL exprDst = GetExprFactory().CreateCall(0, nubDst, _exprSrc, pMemGroup, null); // Here we want to first check whether or not the conversions work on the base types. EXPR arg1 = _binder.mustCast(_exprSrc, typeSrcBase); EXPRCLASS arg2 = GetExprFactory().MakeClass(typeDstBase); bool convertible; if (0 != (_flags & CONVERTTYPE.ISEXPLICIT)) { convertible = _binder.BindExplicitConversion(arg1, arg1.type, arg2, typeDstBase, out arg1, _flags | CONVERTTYPE.NOUDC); } else { convertible = _binder.BindImplicitConversion(arg1, arg1.type, arg2, typeDstBase, out arg1, _flags | CONVERTTYPE.NOUDC); } if (!convertible) { VSFAIL("bind(Im|Ex)plicitConversion failed unexpectedly"); return false; } exprDst.castOfNonLiftedResultToLiftedType = _binder.mustCast(arg1, nubDst, 0); exprDst.nubLiftKind = NullableCallLiftKind.NullableConversion; exprDst.pConversions = exprDst.castOfNonLiftedResultToLiftedType; _exprDest = exprDst; } return true; } private bool bindImplicitConversionFromNull() { // null type can be implicitly converted to any reference type or pointer type or type // variable with reference-type constraint. FUNDTYPE ftDest = _typeDest.fundType(); if (ftDest != FUNDTYPE.FT_REF && ftDest != FUNDTYPE.FT_PTR && (ftDest != FUNDTYPE.FT_VAR || !_typeDest.AsTypeParameterType().IsReferenceType()) && // null is convertible to System.Nullable<T>. !_typeDest.isPredefType(PredefinedType.PT_G_OPTIONAL)) { return false; } if (_needsExprDest) { // If the conversion argument is a constant null then return a ZEROINIT. // Otherwise, bind this as a cast to the destination type. In a later // rewrite pass we will rewrite the cast as SEQ(side effects, ZEROINIT). if (_exprSrc.isCONSTANT_OK()) { _exprDest = GetExprFactory().CreateZeroInit(_typeDest); } else { _exprDest = GetExprFactory().CreateCast(0x00, _typeDest, _exprSrc); } } return true; } private bool bindImplicitConversionFromNullable(NullableType nubSrc) { // We can convert T? using a boxing conversion, we can convert it to ValueType, and // we can convert it to any interface implemented by T. // // 13.1.5 Boxing Conversions // // A nullable-type has a boxing conversion to the same set of types to which the nullable-type's // underlying type has boxing conversions. A boxing conversion applied to a value of a nullable-type // proceeds as follows: // // * If the HasValue property of the nullable value evaluates to false, then the result of the // boxing conversion is the null reference of the appropriate type. // // Otherwise, the result is obtained by boxing the result of evaluating the Value property on // the nullable value. AggregateType atsNub = nubSrc.GetAts(GetErrorContext()); if (atsNub == null) { return false; } if (atsNub == _typeDest) { if (_needsExprDest) { _exprDest = _exprSrc; } return true; } if (GetSymbolLoader().HasBaseConversion(nubSrc.GetUnderlyingType(), _typeDest) && !CConversions.FUnwrappingConv(nubSrc, _typeDest)) { if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_BOX); if (!_typeDest.isPredefType(PredefinedType.PT_OBJECT)) { // The base type of a nullable is always a non-nullable value type, // therefore so is typeDest unless typeDest is PT_OBJECT. In this case the conversion // needs to be unboxed. We only need this if we actually will use the result. _binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); } } return true; } return 0 == (_flags & CONVERTTYPE.NOUDC) && _binder.bindUserDefinedConversion(_exprSrc, nubSrc, _typeDest, _needsExprDest, out _exprDest, true); } private bool bindImplicitConversionFromArray() { // 13.1.4 // // The implicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element // type TE, provided all of the following are true: // * S and T differ only in element type. In other words, S and T have the same number of dimensions. // * An implicit reference conversion exists from SE to TE. // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<S>, // System.Collections.Generic.IReadOnlyList<S> and their base interfaces // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> // and their base interfaces, provided there is an implicit reference conversion from S to T. // * From any array-type to System.Array. // * From any array-type to any interface implemented by System.Array. if (!GetSymbolLoader().HasBaseConversion(_typeSrc, _typeDest)) { return false; } EXPRFLAG grfex = 0; // The above if checks for dest==Array, object or an interface the array implements, // including IList<T>, ICollection<T>, IEnumerable<T>, IReadOnlyList<T>, IReadOnlyCollection<T> // and the non-generic versions. if ((_typeDest.IsArrayType() || (_typeDest.isInterfaceType() && _typeDest.AsAggregateType().GetTypeArgsAll().Size == 1 && ((_typeDest.AsAggregateType().GetTypeArgsAll().Item(0) != _typeSrc.AsArrayType().GetElementType()) || 0 != (_flags & CONVERTTYPE.FORCECAST)))) && (0 != (_flags & CONVERTTYPE.FORCECAST) || TypeManager.TypeContainsTyVars(_typeSrc, null) || TypeManager.TypeContainsTyVars(_typeDest, null))) { grfex = EXPRFLAG.EXF_REFCHECK; } if (_needsExprDest) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, grfex); } return true; } private bool bindImplicitConversionFromPointer() { // 27.4 Pointer conversions // // In an unsafe context, the set of available implicit conversions (13.1) is extended to include // the following implicit pointer conversions: // // * From any pointer-type to the type void*. if (_typeDest.IsPointerType() && _typeDest.AsPointerType().GetReferentType() == _binder.getVoidType()) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } return false; } private bool bindImplicitConversionFromAgg(AggregateType aggTypeSrc) { // GENERICS: The case for constructed types is very similar to types with // no parameters. The parameters are irrelevant for most of the conversions // below. They could be relevant if we had user-defined conversions on // generic types. AggregateSymbol aggSrc = aggTypeSrc.getAggregate(); if (aggSrc.IsEnum()) { return bindImplicitConversionFromEnum(aggTypeSrc); } if (_typeDest.isEnumType()) { if (bindImplicitConversionToEnum(aggTypeSrc)) { return true; } // Even though enum is sealed, a class can derive from enum in LAF scenarios -- // continue testing for derived to base conversions below. } else if (aggSrc.getThisType().isSimpleType() && _typeDest.isSimpleType()) { if (bindImplicitConversionBetweenSimpleTypes(aggTypeSrc)) { return true; } // No simple conversion -- continue testing for derived to base conversions below. } return bindImplicitConversionToBase(aggTypeSrc); } private bool bindImplicitConversionToBase(AggregateType pSource) { // 13.1.4 Implicit reference conversions // // * From any reference-type to object. // * From any class-type S to any class-type T, provided S is derived from T. // * From any class-type S to any interface-type T, provided S implements T. // * From any interface-type S to any interface-type T, provided S is derived from T. // * From any delegate-type to System.Delegate. // * From any delegate-type to System.ICloneable. if (!_typeDest.IsAggregateType() || !GetSymbolLoader().HasBaseConversion(pSource, _typeDest)) { return false; } EXPRFLAG flags = 0x00; if (pSource.getAggregate().IsStruct() && _typeDest.fundType() == FUNDTYPE.FT_REF) { flags = EXPRFLAG.EXF_BOX | EXPRFLAG.EXF_CANTBENULL; } else if (_exprSrc != null) { flags = _exprSrc.flags & EXPRFLAG.EXF_CANTBENULL; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, flags); return true; } private bool bindImplicitConversionFromEnum(AggregateType aggTypeSrc) { // 13.1.5 Boxing conversions // // A boxing conversion permits any non-nullable-value-type to be implicitly converted to the type // object or System.ValueType or to any interface-type implemented by the value-type, and any enum // type to be implicitly converted to System.Enum as well. Boxing a value of a // non-nullable-value-type consists of allocating an object instance and copying the value-type // value into that instance. An enum can be boxed to the type System.Enum, since that is the direct // base class for all enums (21.4). A struct or enum can be boxed to the type System.ValueType, // since that is the direct base class for all structs (18.3.2) and a base class for all enums. if (_typeDest.IsAggregateType() && GetSymbolLoader().HasBaseConversion(aggTypeSrc, _typeDest.AsAggregateType())) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_BOX | EXPRFLAG.EXF_CANTBENULL); return true; } return false; } private bool bindImplicitConversionToEnum(AggregateType aggTypeSrc) { // The spec states: // ***************** // 13.1.3 Implicit enumeration conversions // // An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any // enum-type. // ***************** // However, we actually allow any constant zero, not just the integer literal zero, to be converted // to enum. The reason for this is for backwards compatibility with a premature optimization // that used to be in the binding layer. We would optimize away expressions such as 0 | blah to be // just 0, but not erase the "is literal" bit. This meant that expression such as 0 | 0 | E.X // would succeed rather than correctly producing an error pointing out that 0 | 0 is not a literal // zero and therefore does not convert to any enum. // // We have removed the premature optimization but want old code to continue to compile. Rather than // try to emulate the somewhat complex behaviour of the previous optimizer, it is easier to simply // say that any compile time constant zero is convertible to any enum. This means unfortunately // expressions such as (7-7) * 12 are convertible to enum, but frankly, that's better than having // some terribly complex rule about what constitutes a legal zero and what doesn't. // Note: Don't use GetConst here since the conversion only applies to bona-fide compile time constants. if ( aggTypeSrc.getAggregate().GetPredefType() != PredefinedType.PT_BOOL && _exprSrc != null && _exprSrc.isZero() && _exprSrc.type.isNumericType() && /*(exprSrc.flags & EXF_LITERALCONST) &&*/ 0 == (_flags & CONVERTTYPE.STANDARD)) { // NOTE: This allows conversions from uint, long, ulong, float, double, and hexadecimal int // NOTE: This is for backwards compatibility with Everett // This is another place where we lose EXPR fidelity. We shouldn't fold this // into a constant here - we should move this to a later pass. if (_needsExprDest) { _exprDest = GetExprFactory().CreateConstant(_typeDest, ConstValFactory.GetDefaultValue(_typeDest.constValKind())); } return true; } return false; } private bool bindImplicitConversionBetweenSimpleTypes(AggregateType aggTypeSrc) { AggregateSymbol aggSrc = aggTypeSrc.getAggregate(); Debug.Assert(aggSrc.getThisType().isSimpleType()); Debug.Assert(_typeDest.isSimpleType()); Debug.Assert(aggSrc.IsPredefined() && _typeDest.isPredefined()); PredefinedType ptSrc = aggSrc.GetPredefType(); PredefinedType ptDest = _typeDest.getPredefType(); ConvKind convertKind; bool fConstShrinkCast = false; Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); // 13.1.7 Implicit constant expression conversions // // An implicit constant expression conversion permits the following conversions: // * A constant-expression (14.16) of type int can be converted to type sbyte, byte, short, // ushort, uint, or ulong, provided the value of the constant-expression is within the range // of the destination type. // * A constant-expression of type long can be converted to type ulong, provided the value of // the constant-expression is not negative. // Note: Don't use GetConst here since the conversion only applies to bona-fide compile time constants. if (_exprSrc != null && _exprSrc.isCONSTANT_OK() && ((ptSrc == PredefinedType.PT_INT && ptDest != PredefinedType.PT_BOOL && ptDest != PredefinedType.PT_CHAR) || (ptSrc == PredefinedType.PT_LONG && ptDest == PredefinedType.PT_ULONG)) && isConstantInRange(_exprSrc.asCONSTANT(), _typeDest)) { // Special case (CLR 6.1.6): if integral constant is in range, the conversion is a legal implicit conversion. convertKind = ConvKind.Implicit; fConstShrinkCast = _needsExprDest && (GetConvKind(ptSrc, ptDest) != ConvKind.Implicit); } else if (ptSrc == ptDest) { // Special case: precision limiting casts to float or double Debug.Assert(ptSrc == PredefinedType.PT_FLOAT || ptSrc == PredefinedType.PT_DOUBLE); Debug.Assert(0 != (_flags & CONVERTTYPE.ISEXPLICIT)); convertKind = ConvKind.Implicit; } else { convertKind = GetConvKind(ptSrc, ptDest); Debug.Assert(convertKind != ConvKind.Identity); // identity conversion should have been handled at first. } if (convertKind != ConvKind.Implicit) { return false; } // An implicit conversion exists. Do the conversion. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, false); if (result == ConstCastResult.Success) { return true; // else, don't fold and use a regular cast, below. } } if (isUserDefinedConversion(ptSrc, ptDest)) { if (!_needsExprDest) { return true; } // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the NOUDC flag here. return _binder.bindUserDefinedConversion(_exprSrc, aggTypeSrc, _typeDest, _needsExprDest, out _exprDest, true); } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } private bool bindImplicitConversionFromTypeVar(TypeParameterType tyVarSrc) { // 13.1.4 // // For a type-parameter T that is known to be a reference type (25.7), the following implicit // reference conversions exist: // // * From T to its effective base class C, from T to any base class of C, and from T to any // interface implemented by C. // * From T to an interface-type I in T's effective interface set and from T to any base // interface of I. // * From T to a type parameter U provided that T depends on U (25.7). [Note: Since T is known // to be a reference type, within the scope of T, the run-time type of U will always be a // reference type, even if U is not known to be a reference type at compile-time.] // * From the null type (11.2.7) to T. // // 13.1.5 // // For a type-parameter T that is not known to be a reference type (25.7), the following conversions // involving T are considered to be boxing conversions at compile-time. At run-time, if T is a value // type, the conversion is executed as a boxing conversion. At run-time, if T is a reference type, // the conversion is executed as an implicit reference conversion or identity conversion. // // * From T to its effective base class C, from T to any base class of C, and from T to any // interface implemented by C. [Note: C will be one of the types System.Object, System.ValueType, // or System.Enum (otherwise T would be known to be a reference type and 13.1.4 would apply // instead of this clause).] // * From T to an interface-type I in T's effective interface set and from T to any base // interface of I. // // 13.1.6 Implicit type parameter conversions // // This clause details implicit conversions involving type parameters that are not classified as // implicit reference conversions or implicit boxing conversions. // // For a type-parameter T that is not known to be a reference type, there is an implicit conversion // from T to a type parameter U provided T depends on U. At run-time, if T is a value type and U is // a reference type, the conversion is executed as a boxing conversion. At run-time, if both T and U // are value types, then T and U are necessarily the same type and no conversion is performed. At // run-time, if T is a reference type, then U is necessarily also a reference type and the conversion // is executed as an implicit reference conversion or identity conversion (25.7). CType typeTmp = tyVarSrc.GetEffectiveBaseClass(); TypeArray bnds = tyVarSrc.GetBounds(); int itype = -1; for (; ;) { if (_binder.canConvert(typeTmp, _typeDest, _flags | CONVERTTYPE.NOUDC)) { if (!_needsExprDest) { return true; } if (_typeDest.IsTypeParameterType()) { // For a type var destination we need to cast to object then to the other type var. EXPR exprT; EXPRCLASS exprObj = GetExprFactory().MakeClass(_binder.GetReqPDT(PredefinedType.PT_OBJECT)); _binder.bindSimpleCast(_exprSrc, exprObj, out exprT, EXPRFLAG.EXF_FORCE_BOX); _binder.bindSimpleCast(exprT, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_UNBOX); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_FORCE_BOX); } return true; } do { if (++itype >= bnds.Size) { return false; } typeTmp = bnds.Item(itype); } while (!typeTmp.isInterfaceType() && !typeTmp.IsTypeParameterType()); } } private SymbolLoader GetSymbolLoader() { return _binder.GetSymbolLoader(); } private ExprFactory GetExprFactory() { return _binder.GetExprFactory(); } private ErrorHandling GetErrorContext() { return _binder.GetErrorContext(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.WebEncoders.Testing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.Razor.TagHelpers { public class UrlResolutionTagHelperTest { public static TheoryData ResolvableUrlData { get { // url, expectedHref return new TheoryData<string, string> { { "~/home/index.html", "/approot/home/index.html" }, { " ~/home/index.html", "/approot/home/index.html" }, { "~/home/index.html ~/secondValue/index.html", "/approot/home/index.html ~/secondValue/index.html" }, }; } } [Fact] public void Process_DoesNothingIfTagNameIsNull() { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: null, attributes: new TagHelperAttributeList { { "href", "~/home/index.html" } }, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null)); var tagHelper = new UrlResolutionTagHelper(Mock.Of<IUrlHelperFactory>(), new HtmlTestEncoder()); var context = new TagHelperContext( allAttributes: new TagHelperAttributeList( Enumerable.Empty<TagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act tagHelper.Process(context, tagHelperOutput); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal("href", attribute.Name, StringComparer.Ordinal); var attributeValue = Assert.IsType<string>(attribute.Value); Assert.Equal("~/home/index.html", attributeValue, StringComparer.Ordinal); } [Theory] [MemberData(nameof(ResolvableUrlData))] public void Process_ResolvesTildeSlashValues(string url, string expectedHref) { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "a", attributes: new TagHelperAttributeList { { "href", url } }, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null)); var urlHelperMock = new Mock<IUrlHelper>(); urlHelperMock .Setup(urlHelper => urlHelper.Content(It.IsAny<string>())) .Returns(new Func<string, string>(value => "/approot" + value.Substring(1))); var urlHelperFactory = new Mock<IUrlHelperFactory>(); urlHelperFactory .Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())) .Returns(urlHelperMock.Object); var tagHelper = new UrlResolutionTagHelper(urlHelperFactory.Object, new HtmlTestEncoder()); var context = new TagHelperContext( tagName: "a", allAttributes: new TagHelperAttributeList( Enumerable.Empty<TagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act tagHelper.Process(context, tagHelperOutput); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal("href", attribute.Name, StringComparer.Ordinal); var attributeValue = Assert.IsType<string>(attribute.Value); Assert.Equal(expectedHref, attributeValue, StringComparer.Ordinal); Assert.Equal(HtmlAttributeValueStyle.DoubleQuotes, attribute.ValueStyle); } public static TheoryData ResolvableUrlHtmlStringData { get { // url, expectedHref return new TheoryData<string, string> { { "~/home/index.html", "HtmlEncode[[/approot/]]home/index.html" }, { " ~/home/index.html", "HtmlEncode[[/approot/]]home/index.html" }, { "~/home/index.html ~/secondValue/index.html", "HtmlEncode[[/approot/]]home/index.html ~/secondValue/index.html" }, }; } } [Theory] [MemberData(nameof(ResolvableUrlHtmlStringData))] public void Process_ResolvesTildeSlashValues_InHtmlString(string url, string expectedHref) { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "a", attributes: new TagHelperAttributeList { { "href", new HtmlString(url) } }, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null)); var urlHelperMock = new Mock<IUrlHelper>(); urlHelperMock .Setup(urlHelper => urlHelper.Content(It.IsAny<string>())) .Returns(new Func<string, string>(value => "/approot" + value.Substring(1))); var urlHelperFactory = new Mock<IUrlHelperFactory>(); urlHelperFactory .Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())) .Returns(urlHelperMock.Object); var tagHelper = new UrlResolutionTagHelper(urlHelperFactory.Object, new HtmlTestEncoder()); var context = new TagHelperContext( tagName: "a", allAttributes: new TagHelperAttributeList( Enumerable.Empty<TagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act tagHelper.Process(context, tagHelperOutput); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal("href", attribute.Name, StringComparer.Ordinal); var htmlContent = Assert.IsAssignableFrom<IHtmlContent>(attribute.Value); Assert.Equal(expectedHref, HtmlContentUtilities.HtmlContentToString(htmlContent), StringComparer.Ordinal); Assert.Equal(HtmlAttributeValueStyle.DoubleQuotes, attribute.ValueStyle); } public static TheoryData UnresolvableUrlData { get { // url return new TheoryData<string> { { "/home/index.html" }, { "~ /home/index.html" }, { "/home/index.html ~/second/wontresolve.html" }, { " ~\\home\\index.html" }, { "~\\/home/index.html" }, }; } } [Theory] [MemberData(nameof(UnresolvableUrlData))] public void Process_DoesNotResolveNonTildeSlashValues(string url) { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "a", attributes: new TagHelperAttributeList { { "href", url } }, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null)); var urlHelperMock = new Mock<IUrlHelper>(); urlHelperMock .Setup(urlHelper => urlHelper.Content(It.IsAny<string>())) .Returns("approot/home/index.html"); var urlHelperFactory = new Mock<IUrlHelperFactory>(); urlHelperFactory .Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())) .Returns(urlHelperMock.Object); var tagHelper = new UrlResolutionTagHelper(urlHelperFactory.Object, new HtmlTestEncoder()); var context = new TagHelperContext( tagName: "a", allAttributes: new TagHelperAttributeList( Enumerable.Empty<TagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act tagHelper.Process(context, tagHelperOutput); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal("href", attribute.Name, StringComparer.Ordinal); var attributeValue = Assert.IsType<string>(attribute.Value); Assert.Equal(url, attributeValue, StringComparer.Ordinal); Assert.Equal(HtmlAttributeValueStyle.DoubleQuotes, attribute.ValueStyle); } public static TheoryData UnresolvableUrlHtmlStringData { get { // url return new TheoryData<string> { { "/home/index.html" }, { "~ /home/index.html" }, { "/home/index.html ~/second/wontresolve.html" }, { "~\\home\\index.html" }, { "~\\/home/index.html" }, }; } } [Theory] [MemberData(nameof(UnresolvableUrlHtmlStringData))] public void Process_DoesNotResolveNonTildeSlashValues_InHtmlString(string url) { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "a", attributes: new TagHelperAttributeList { { "href", new HtmlString(url) } }, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null)); var urlHelperMock = new Mock<IUrlHelper>(); urlHelperMock .Setup(urlHelper => urlHelper.Content(It.IsAny<string>())) .Returns("approot/home/index.html"); var urlHelperFactory = new Mock<IUrlHelperFactory>(); urlHelperFactory .Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())) .Returns(urlHelperMock.Object); var tagHelper = new UrlResolutionTagHelper(urlHelperFactory.Object, new HtmlTestEncoder()); var context = new TagHelperContext( tagName: "a", allAttributes: new TagHelperAttributeList( Enumerable.Empty<TagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act tagHelper.Process(context, tagHelperOutput); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal("href", attribute.Name, StringComparer.Ordinal); var attributeValue = Assert.IsType<HtmlString>(attribute.Value); Assert.Equal(url.ToString(), attributeValue.ToString(), StringComparer.Ordinal); Assert.Equal(HtmlAttributeValueStyle.DoubleQuotes, attribute.ValueStyle); } [Fact] public void Process_IgnoresNonHtmlStringOrStringValues() { // Arrange var tagHelperOutput = new TagHelperOutput( tagName: "a", attributes: new TagHelperAttributeList { { "href", true } }, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null)); var tagHelper = new UrlResolutionTagHelper(urlHelperFactory: null, htmlEncoder: null); var context = new TagHelperContext( tagName: "a", allAttributes: new TagHelperAttributeList( Enumerable.Empty<TagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act tagHelper.Process(context, tagHelperOutput); // Assert var attribute = Assert.Single(tagHelperOutput.Attributes); Assert.Equal("href", attribute.Name, StringComparer.Ordinal); Assert.True(Assert.IsType<bool>(attribute.Value)); Assert.Equal(HtmlAttributeValueStyle.DoubleQuotes, attribute.ValueStyle); } [Fact] public void Process_ThrowsWhenEncodingNeededAndIUrlHelperActsUnexpectedly() { // Arrange var relativeUrl = "~/home/index.html"; var expectedExceptionMessage = Resources.FormatCouldNotResolveApplicationRelativeUrl_TagHelper( relativeUrl, nameof(IUrlHelper), nameof(IUrlHelper.Content), "removeTagHelper", typeof(UrlResolutionTagHelper).FullName, typeof(UrlResolutionTagHelper).Assembly.GetName().Name); var tagHelperOutput = new TagHelperOutput( tagName: "a", attributes: new TagHelperAttributeList { { "href", new HtmlString(relativeUrl) } }, getChildContentAsync: (useCachedResult, encoder) => Task.FromResult<TagHelperContent>(null)); var urlHelperMock = new Mock<IUrlHelper>(); urlHelperMock .Setup(urlHelper => urlHelper.Content(It.IsAny<string>())) .Returns("UnexpectedResult"); var urlHelperFactory = new Mock<IUrlHelperFactory>(); urlHelperFactory .Setup(f => f.GetUrlHelper(It.IsAny<ActionContext>())) .Returns(urlHelperMock.Object); var tagHelper = new UrlResolutionTagHelper(urlHelperFactory.Object, new HtmlTestEncoder()); var context = new TagHelperContext( tagName: "a", allAttributes: new TagHelperAttributeList( Enumerable.Empty<TagHelperAttribute>()), items: new Dictionary<object, object>(), uniqueId: "test"); // Act & Assert var exception = Assert.Throws<InvalidOperationException>( () => tagHelper.Process(context, tagHelperOutput)); Assert.Equal(expectedExceptionMessage, exception.Message, StringComparer.Ordinal); } } }
// Copyright (c) 2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Diagnostics; using System.Linq; using System.Collections.Generic; using System.IO; using IBusDotNet; using SIL.Keyboarding; namespace SIL.Windows.Forms.Keyboarding.Linux { /// <summary> /// Class for handling ibus keyboards on Linux. Currently just a wrapper for KeyboardSwitcher. /// </summary> public class IbusKeyboardRetrievingAdaptor : IKeyboardRetrievingAdaptor { private readonly IIbusCommunicator _ibusComm; /// <summary> /// Initializes a new instance of the /// <see cref="SIL.Windows.Forms.Keyboarding.Linux.IbusKeyboardRetrievingAdaptor"/> class. /// </summary> public IbusKeyboardRetrievingAdaptor(): this(new IbusCommunicator()) { } /// <summary> /// Used in unit tests /// </summary> public IbusKeyboardRetrievingAdaptor(IIbusCommunicator ibusCommunicator) { _ibusComm = ibusCommunicator; } protected virtual void InitKeyboards() { Dictionary<string, IbusKeyboardDescription> curKeyboards = KeyboardController.Instance.Keyboards.OfType<IbusKeyboardDescription>().ToDictionary(kd => kd.Id); foreach (IBusEngineDesc ibusKeyboard in GetIBusKeyboards()) { string id = string.Format("{0}_{1}", ibusKeyboard.Language, ibusKeyboard.LongName); IbusKeyboardDescription existingKeyboard; if (curKeyboards.TryGetValue(id, out existingKeyboard)) { if (!existingKeyboard.IsAvailable) { existingKeyboard.SetIsAvailable(true); existingKeyboard.IBusKeyboardEngine = ibusKeyboard; } curKeyboards.Remove(id); } else { var keyboard = new IbusKeyboardDescription(id, ibusKeyboard, SwitchingAdaptor); KeyboardController.Instance.Keyboards.Add(keyboard); } } foreach (IbusKeyboardDescription existingKeyboard in curKeyboards.Values) existingKeyboard.SetIsAvailable(false); } protected virtual IBusEngineDesc[] GetIBusKeyboards() { if (!_ibusComm.Connected) return new IBusEngineDesc[0]; var ibusWrapper = new InputBus(_ibusComm.Connection); return ibusWrapper.ListActiveEngines(); } internal IBusEngineDesc[] GetAllIBusKeyboards() { if (!_ibusComm.Connected) return new IBusEngineDesc[0]; var ibusWrapper = new InputBus(_ibusComm.Connection); return ibusWrapper.ListEngines(); } protected IIbusCommunicator IbusCommunicator { get { return _ibusComm; } } #region IKeyboardRetrievingAdaptor implementation /// <summary> /// The type of keyboards this adaptor handles: system or other (like Keyman, ibus...) /// </summary> public virtual KeyboardAdaptorType Type { get { return KeyboardAdaptorType.OtherIm; } } /// <summary> /// Checks whether this keyboard retriever can get keyboards. Different desktop /// environments use differing APIs to get the available keyboards. If this class is /// able to find the available keyboards this property will return <c>true</c>, /// otherwise <c>false</c>. /// </summary> public virtual bool IsApplicable { get { return _ibusComm.Connected && GetIBusKeyboards().Length > 0; } } /// <summary> /// Gets the keyboard adaptor that deals with keyboards that this class retrieves. /// </summary> public IKeyboardSwitchingAdaptor SwitchingAdaptor { get; protected set; } /// <summary> /// Initialize the installed keyboards /// </summary> public virtual void Initialize() { SwitchingAdaptor = new IbusKeyboardSwitchingAdaptor(_ibusComm); InitKeyboards(); } public void UpdateAvailableKeyboards() { InitKeyboards(); } /// <summary> /// Only the primary (Type=System) adapter is required to implement this method. This one makes keyboards /// during Initialize, but is not used to make an unavailable keyboard to match an LDML file. /// </summary> public virtual KeyboardDescription CreateKeyboardDefinition(string id) { throw new NotImplementedException(); } public bool CanHandleFormat(KeyboardFormat format) { return false; } public Action GetKeyboardSetupAction() { string args; var setupApp = GetKeyboardSetupApplication(out args); if (setupApp == null) { return null; } return () => { using (Process.Start(setupApp, args)) { } }; } protected virtual string GetKeyboardSetupApplication(out string arguments) { arguments = null; return File.Exists("/usr/bin/ibus-setup") ? "/usr/bin/ibus-setup" : null; } public bool IsSecondaryKeyboardSetupApplication { get { return false; } } #endregion #region IDisposable & Co. implementation // Region last reviewed: never /// <summary> /// Check to see if the object has been disposed. /// All public Properties and Methods should call this /// before doing anything else. /// </summary> public void CheckDisposed() { if (IsDisposed) throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } /// <summary> /// See if the object has been disposed. /// </summary> public bool IsDisposed { get; private set; } /// <summary> /// Finalizer, in case client doesn't dispose it. /// Force Dispose(false) if not already called (i.e. m_isDisposed is true) /// </summary> /// <remarks> /// In case some clients forget to dispose it directly. /// </remarks> ~IbusKeyboardRetrievingAdaptor() { Dispose(false); // The base class finalizer is called automatically. } /// <summary> /// /// </summary> /// <remarks>Must not be virtual.</remarks> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected virtual void Dispose(bool disposing) { Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. if (IsDisposed) return; if (disposing) { // Dispose managed resources here. _ibusComm.Dispose(); } // Dispose unmanaged resources here, whether disposing is true or false. IsDisposed = true; } #endregion IDisposable & Co. implementation } }
using System.Collections.Immutable; using System.Reflection; using System.Text; using NQuery.Symbols; namespace NQuery.Hosting { public class ReflectionProvider : IPropertyProvider, IMethodProvider { public ReflectionProvider() : this(BindingFlags.Instance | BindingFlags.Public) { } public ReflectionProvider(BindingFlags bindingFlags) { BindingFlags = bindingFlags; } public BindingFlags BindingFlags { get; } private static bool ExistingMemberIsMoreSpecific(Type type, MemberInfo existingMember, MemberInfo newMember) { var existingMemberDeclaringType = existingMember.DeclaringType; var newMemberDeclaringType = newMember.DeclaringType; var existingMemberDistance = 0; var newMemberDistance = 0; while (existingMemberDeclaringType is not null && existingMemberDeclaringType != type) { existingMemberDistance++; existingMemberDeclaringType = existingMemberDeclaringType.BaseType; } while (newMemberDeclaringType is not null && newMemberDeclaringType != type) { newMemberDistance++; newMemberDeclaringType = newMemberDeclaringType.BaseType; } return existingMemberDistance > newMemberDistance; } private sealed class PropertyTable { private readonly Dictionary<string, Entry> _table = new(); public class Entry { public Entry(PropertySymbol propertySymbol, MemberInfo memberInfo) { PropertySymbol = propertySymbol; MemberInfo = memberInfo; } public PropertySymbol PropertySymbol { get; } public MemberInfo MemberInfo { get; } } public void Add(PropertySymbol propertySymbol, MemberInfo memberInfo) { var entry = new Entry(propertySymbol, memberInfo); _table.Add(propertySymbol.Name, entry); } public void Remove(Entry entry) { _table.Remove(entry.PropertySymbol.Name); } public Entry this[string propertyName] { get { _table.TryGetValue(propertyName, out var result); return result; } } } private sealed class MethodTable { private readonly Dictionary<string, Entry> _table = new(); public class Entry { public Entry(string key, MethodSymbol methodSymbol, MethodInfo methodInfo) { MethodSymbol = methodSymbol; MethodInfo = methodInfo; Key = key; } public string Key { get; } public MethodSymbol MethodSymbol { get; } public MethodInfo MethodInfo { get; } } private static string GenerateKey(string methodName, IEnumerable<Type> parameterTypes) { var sb = new StringBuilder(); sb.Append(methodName); sb.Append(@"("); var isFirst = true; foreach (var t in parameterTypes) { if (isFirst) isFirst = false; else sb.Append(','); sb.Append(t.Name); } sb.Append(@")"); return sb.ToString(); } public void Add(MethodSymbol methodSymbol, MethodInfo methodInfo) { var key = GenerateKey(methodSymbol.Name, methodSymbol.GetParameterTypes()); var entry = new Entry(key, methodSymbol, methodInfo); _table.Add(entry.Key, entry); } public void Remove(Entry entry) { _table.Remove(entry.Key); } public Entry this[string methodName, IEnumerable<Type> parameterTypes] { get { var key = GenerateKey(methodName, parameterTypes); _table.TryGetValue(key, out var result); return result; } } } private static void AddProperty(PropertyTable propertyTable, ICollection<PropertySymbol> memberList, Type declaringType, PropertySymbol memberBinding, MemberInfo memberInfo) { // Check if we already have a member with the same name declared. var existingMemberEntry = propertyTable[memberBinding.Name]; if (existingMemberEntry is not null) { // OK we have one. Check if the existing member is not more specific. if (ExistingMemberIsMoreSpecific(declaringType, existingMemberEntry.MemberInfo, memberInfo)) { // The existing member is more specific. So we don't add the new one. return; } // The new member is more specific. Remove the old one. propertyTable.Remove(existingMemberEntry); memberList.Remove(existingMemberEntry.PropertySymbol); } // Either the new member is more specific or we didn't have // a member with same name. propertyTable.Add(memberBinding, memberInfo); memberList.Add(memberBinding); } private static void AddMethod(MethodTable methodTable, ICollection<MethodSymbol> methodList, Type declaringType, MethodSymbol methodSymbol, MethodInfo methodInfo) { // Check if we already have a method with the same name and parameters declared. var existingMethodEntry = methodTable[methodSymbol.Name, methodSymbol.GetParameterTypes()]; if (existingMethodEntry is not null) { // OK we have one. Check if the existing member is not more specific. if (ExistingMemberIsMoreSpecific(declaringType, existingMethodEntry.MethodInfo, methodInfo)) { // The existing member is more specific. So we don't add the new one. return; } // The new member is more specific. Remove the old one. methodTable.Remove(existingMethodEntry); methodList.Remove(existingMethodEntry.MethodSymbol); } // Either the new member is more specific or we didn't have // a member with same name. methodTable.Add(methodSymbol, methodInfo); methodList.Add(methodSymbol); } public IEnumerable<PropertySymbol> GetProperties(Type type) { ArgumentNullException.ThrowIfNull(type); var propertyTable = new PropertyTable(); var propertyList = new List<PropertySymbol>(); // Convert CLR Properties var propertyInfos = type.GetProperties(BindingFlags); foreach (var currentPropertyInfo in propertyInfos) { // Ignore indexer var indexParameters = currentPropertyInfo.GetIndexParameters(); if (indexParameters.Length > 0) continue; var property = CreateProperty(currentPropertyInfo); if (property is not null) AddProperty(propertyTable, propertyList, type, property, currentPropertyInfo); } // Convert CLR Fields var fieldInfos = type.GetFields(BindingFlags); foreach (var currentFieldInfo in fieldInfos) { var property = CreateProperty(currentFieldInfo); if (property is not null) AddProperty(propertyTable, propertyList, type, property, currentFieldInfo); } return propertyList.ToImmutableArray(); } /// <summary> /// Checks whether the given <see cref="MethodInfo"/> is invocable by the query engine, i.e. it can be used /// as <see cref="InvocableSymbol"/>. /// </summary> /// <remarks> /// A method cannot be invoked if any of the following is true: /// <ul> /// <li><paramref name="methodInfo"/> has a special name (e.g. it is getter, setter, indexer or operator method)</li> /// <li><paramref name="methodInfo"/> has abstract modifier</li> /// <li><paramref name="methodInfo"/> has return type <see cref="Void"/></li> /// <li><paramref name="methodInfo"/> has unsafe parameter types</li> /// <li><paramref name="methodInfo"/> has dynamical argument lists (e.g. params modifier)</li> /// <li><paramref name="methodInfo"/> has out or ref parameters</li> /// </ul> /// </remarks> /// <param name="methodInfo">The method info to check.</param> public static bool IsInvocable(MethodInfo methodInfo) { ArgumentNullException.ThrowIfNull(methodInfo); if (methodInfo.IsSpecialName || methodInfo.IsAbstract || methodInfo.ReturnType == typeof(void) || methodInfo.ReturnType.IsPointer || (methodInfo.CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) return false; var hasInvalidParameterTypes = (from parameterInfo in methodInfo.GetParameters() let hasParamsModifier = parameterInfo.GetCustomAttributes(typeof(ParamArrayAttribute), false).Any() where hasParamsModifier || parameterInfo.IsOut || parameterInfo.ParameterType.IsByRef || parameterInfo.ParameterType.IsPointer select parameterInfo).Any(); return !hasInvalidParameterTypes; } public IEnumerable<MethodSymbol> GetMethods(Type type) { ArgumentNullException.ThrowIfNull(type); var methodTable = new MethodTable(); var methodList = new List<MethodSymbol>(); var methodInfos = type.GetMethods(BindingFlags); Array.Sort(methodInfos, (x, y) => string.Compare(x.ToString(), y.ToString(), StringComparison.Ordinal)); foreach (var currentMethodInfo in methodInfos) { if (!IsInvocable(currentMethodInfo)) continue; var methodSymbol = CreateMethod(currentMethodInfo); if (methodSymbol is not null) AddMethod(methodTable, methodList, type, methodSymbol, currentMethodInfo); } return methodList.ToImmutableArray(); } /// <summary> /// Creates a method binding for the given <see cref="MethodInfo"/>. /// </summary> /// <param name="methodInfo">The .NET method info.</param> /// <returns>If the method should not be visible this method returns <see langword="null"/>.</returns> protected virtual MethodSymbol CreateMethod(MethodInfo methodInfo) { ArgumentNullException.ThrowIfNull(methodInfo); return new ReflectionMethodSymbol(methodInfo, methodInfo.Name); } /// <summary> /// Creates a property binding for the given <see cref="PropertyInfo"/>. /// </summary> /// <param name="propertyInfo">The .NET property info.</param> /// <returns>If the property should not be visible this method returns <see langword="null"/>.</returns> protected virtual PropertySymbol CreateProperty(PropertyInfo propertyInfo) { ArgumentNullException.ThrowIfNull(propertyInfo); return new ReflectionPropertySymbol(propertyInfo, propertyInfo.Name); } /// <summary> /// Creates a property binding for the given <see cref="FieldInfo"/>. /// </summary> /// <param name="fieldInfo">The .NET field info.</param> /// <returns>If the field should not be visible this method returns <see langword="null"/>.</returns> protected virtual PropertySymbol CreateProperty(FieldInfo fieldInfo) { ArgumentNullException.ThrowIfNull(fieldInfo); return new ReflectionFieldSymbol(fieldInfo, fieldInfo.Name); } } }
/* ==================================================================== 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System.Collections.Generic; namespace NPOI.HPSF { using System; using System.IO; using System.Text; using NPOI.Util; using NPOI.HPSF.Wellknown; /// <summary> /// Represents a property Set in the Horrible Property Set Format /// (HPSF). These are usually metadata of a Microsoft Office /// document. /// An application that wants To access these metadata should Create /// an instance of this class or one of its subclasses by calling the /// factory method {@link PropertySetFactory#Create} and then retrieve /// the information its needs by calling appropriate methods. /// {@link PropertySetFactory#Create} does its work by calling one /// of the constructors {@link PropertySet#PropertySet(InputStream)} or /// {@link PropertySet#PropertySet(byte[])}. If the constructor's /// argument is not in the Horrible Property Set Format, i.e. not a /// property Set stream, or if any other error occurs, an appropriate /// exception is thrown. /// A {@link PropertySet} has a list of {@link Section}s, and each /// {@link Section} has a {@link Property} array. Use {@link /// #GetSections} To retrieve the {@link Section}s, then call {@link /// Section#GetProperties} for each {@link Section} To Get hold of the /// {@link Property} arrays. Since the vast majority of {@link /// PropertySet}s Contains only a single {@link Section}, the /// convenience method {@link #GetProperties} returns the properties of /// a {@link PropertySet}'s {@link Section} (throwing a {@link /// NoSingleSectionException} if the {@link PropertySet} Contains more /// (or less) than exactly one {@link Section}). /// @author Rainer Klute /// <a href="mailto:[email protected]">&lt;[email protected]&gt;</a> /// @author Drew Varner (Drew.Varner hanginIn sc.edu) /// @since 2002-02-09 /// </summary> [Serializable] public class PropertySet { /** * The "byteOrder" field must equal this value. */ protected static byte[] BYTE_ORDER_ASSERTION = new byte[] { (byte)0xFE, (byte)0xFF }; /** * Specifies this {@link PropertySet}'s byte order. See the * HPFS documentation for details! */ protected int byteOrder; /// <summary> /// Gets or sets the property Set stream's low-level "byte order" /// field. It is always <c>0xFFFE</c> /// </summary> /// <value>The property Set stream's low-level "byte order" field..</value> public virtual int ByteOrder { get { return byteOrder; } set { byteOrder = value; } } /** * The "format" field must equal this value. */ protected static byte[] FORMAT_ASSERTION = new byte[] { (byte)0x00, (byte)0x00 }; /** * Specifies this {@link PropertySet}'s format. See the HPFS * documentation for details! */ protected int format; /// <summary> /// Gets or sets the property Set stream's low-level "format" /// field. It is always <c>0x0000</c> /// </summary> /// <value>The property Set stream's low-level "format" field.</value> public virtual int Format { get { return format; } set { format = value; } } /** * Specifies the version of the operating system that Created * this {@link PropertySet}. See the HPFS documentation for * details! */ protected int osVersion; /** * If the OS version field holds this value the property Set stream Was * Created on a 16-bit Windows system. */ public const int OS_WIN16 = 0x0000; /** * If the OS version field holds this value the property Set stream Was * Created on a Macintosh system. */ public const int OS_MACINTOSH = 0x0001; /** * If the OS version field holds this value the property Set stream Was * Created on a 32-bit Windows system. */ public const int OS_WIN32 = 0x0002; /// <summary> /// Returns the property Set stream's low-level "OS version" /// field. /// </summary> /// <value>The property Set stream's low-level "OS version" field.</value> public virtual int OSVersion { get { return osVersion; } set { osVersion = value; } } /** * Specifies this {@link PropertySet}'s "classID" field. See * the HPFS documentation for details! */ [NonSerialized] protected ClassID classID; /// <summary> /// Gets or sets the property Set stream's low-level "class ID" /// </summary> /// <value>The property Set stream's low-level "class ID" field.</value> public virtual ClassID ClassID { get { return classID; } set { classID = value; } } /// <summary> /// Returns the number of {@link Section}s in the property /// Set. /// </summary> /// <value>The number of {@link Section}s in the property Set.</value> public virtual int SectionCount { get { return sections.Count; } } /** * The sections in this {@link PropertySet}. */ protected List<Section> sections; /// <summary> /// Returns the {@link Section}s in the property Set. /// </summary> /// <value>{@link Section}s in the property Set.</value> public virtual List<Section> Sections { get { return sections; } } /// <summary> /// Creates an empty (uninitialized) {@link PropertySet} /// Please note: For the time being this /// constructor is protected since it is used for internal purposes /// only, but expect it To become public once the property Set's /// writing functionality is implemented. /// </summary> protected PropertySet() { } /// <summary> /// Creates a {@link PropertySet} instance from an {@link /// InputStream} in the Horrible Property Set Format. /// The constructor Reads the first few bytes from the stream /// and determines whether it is really a property Set stream. If /// it Is, it parses the rest of the stream. If it is not, it /// Resets the stream To its beginning in order To let other /// components mess around with the data and throws an /// exception. /// </summary> /// <param name="stream">Holds the data making out the property Set /// stream.</param> public PropertySet(Stream stream) { if (IsPropertySetStream(stream)) { int avail = (stream as ByteArrayInputStream).Available(); ; byte[] buffer = new byte[avail]; stream.Read(buffer, 0, buffer.Length); init(buffer, 0, buffer.Length); } else throw new NoPropertySetStreamException("this stream may not be a valid property set stream"); } /// <summary> /// Creates a {@link PropertySet} instance from a byte array /// that represents a stream in the Horrible Property Set /// Format. /// </summary> /// <param name="stream">The byte array holding the stream data.</param> /// <param name="offset">The offset in stream where the stream data begin. /// If the stream data begin with the first byte in the /// array, the offset is 0.</param> /// <param name="Length"> The Length of the stream data.</param> public PropertySet(byte[] stream, int offset, int Length) { if (IsPropertySetStream(stream, offset, Length)) init(stream, offset, Length); else throw new NoPropertySetStreamException(); } /// <summary> /// Creates a {@link PropertySet} instance from a byte array /// that represents a stream in the Horrible Property Set /// Format. /// </summary> /// <param name="stream">The byte array holding the stream data. The /// complete byte array contents is the stream data.</param> public PropertySet(byte[] stream):this(stream, 0, stream.Length) { } /// <summary> /// Checks whether an {@link InputStream} is in the Horrible /// Property Set Format. /// </summary> /// <param name="stream">The {@link InputStream} To check. In order To /// perform the check, the method Reads the first bytes from the /// stream. After Reading, the stream is Reset To the position it /// had before Reading. The {@link InputStream} must support the /// {@link InputStream#mark} method.</param> /// <returns> /// <c>true</c> if the stream is a property Set /// stream; otherwise, <c>false</c>. /// </returns> public static bool IsPropertySetStream(Stream stream) { ByteArrayInputStream dis = stream as ByteArrayInputStream; /* * Read at most this many bytes. */ int BUFFER_SIZE = 50; /* * Mark the current position in the stream so that we can * Reset To this position if the stream does not contain a * property Set. */ if (dis == null || !dis.MarkSupported()) throw new MarkUnsupportedException(stream.GetType().Name); dis.Mark(BUFFER_SIZE); /* * Read a couple of bytes from the stream. */ byte[] buffer = new byte[BUFFER_SIZE]; int bytes = stream.Read(buffer, 0, (int)Math.Min(buffer.Length, dis.Available())); bool isPropertySetStream = IsPropertySetStream(buffer, 0, bytes); //stream.Seek(0, SeekOrigin.Begin); dis.Reset(); return isPropertySetStream; } /// <summary> /// Checks whether a byte array is in the Horrible Property Set /// Format. /// </summary> /// <param name="src">The byte array To check.</param> /// <param name="offset">The offset in the byte array.</param> /// <param name="Length">The significant number of bytes in the byte /// array. Only this number of bytes will be checked.</param> /// <returns> /// <c>true</c> if the byte array is a property Set /// stream; otherwise, <c>false</c>. /// </returns> public static bool IsPropertySetStream(byte[] src, int offset, int Length) { /* FIXME (3): Ensure that at most "Length" bytes are Read. */ /* * Read the header fields of the stream. They must always be * there. */ int o = offset; int byteOrder = LittleEndian.GetUShort(src, o); o += LittleEndianConsts.SHORT_SIZE; byte[] temp = new byte[LittleEndianConsts.SHORT_SIZE]; LittleEndian.PutShort(temp, 0, (short)byteOrder); if (!Arrays.Equals(temp, BYTE_ORDER_ASSERTION)) return false; int format = LittleEndian.GetUShort(src, o); o += LittleEndianConsts.SHORT_SIZE; temp = new byte[LittleEndianConsts.SHORT_SIZE]; LittleEndian.PutShort(temp,0, (short)format); if (!Arrays.Equals(temp, FORMAT_ASSERTION)) return false; long osVersion = LittleEndian.GetUInt(src, offset); o += LittleEndianConsts.INT_SIZE; ClassID classID = new ClassID(src, offset); o += ClassID.LENGTH; long sectionCount = LittleEndian.GetUInt(src, o); o += LittleEndianConsts.INT_SIZE; if (sectionCount < 0) return false; return true; } /// <summary> /// Initializes this {@link PropertySet} instance from a byte /// array. The method assumes that it has been checked alReady that /// the byte array indeed represents a property Set stream. It does /// no more checks on its own. /// </summary> /// <param name="src">Byte array containing the property Set stream</param> /// <param name="offset">The property Set stream starts at this offset</param> /// <param name="Length">Length of the property Set stream.</param> private void init(byte[] src, int offset, int Length) { /* FIXME (3): Ensure that at most "Length" bytes are Read. */ /* * Read the stream's header fields. */ int o = offset; byteOrder = LittleEndian.GetUShort(src, o); o += LittleEndianConsts.SHORT_SIZE; format = LittleEndian.GetUShort(src, o); o += LittleEndianConsts.SHORT_SIZE; osVersion = (int)LittleEndian.GetUInt(src, o); o += LittleEndianConsts.INT_SIZE; classID = new ClassID(src, o); o += ClassID.LENGTH; int sectionCount = LittleEndian.GetInt(src, o); o += LittleEndianConsts.INT_SIZE; if (sectionCount < 0) throw new HPSFRuntimeException("Section count " + sectionCount + " is negative."); /* * Read the sections, which are following the header. They * start with an array of section descriptions. Each one * consists of a format ID telling what the section Contains * and an offset telling how many bytes from the start of the * stream the section begins. */ /* * Most property Sets have only one section. The Document * Summary Information stream has 2. Everything else is a rare * exception and is no longer fostered by Microsoft. */ sections = new List<Section>(sectionCount); /* * Loop over the section descriptor array. Each descriptor * consists of a ClassID and a DWord, and we have To increment * "offset" accordingly. */ for (int i = 0; i < sectionCount; i++) { Section s = new Section(src, o); o += ClassID.Length + LittleEndianConsts.INT_SIZE; sections.Add(s); } } /// <summary> /// Checks whether this {@link PropertySet} represents a Summary /// Information. /// </summary> /// <value> /// <c>true</c> Checks whether this {@link PropertySet} represents a Summary /// Information; otherwise, <c>false</c>. /// </value> public virtual bool IsSummaryInformation { get { if (sections.Count <= 0) return false; return Arrays.Equals(sections[0].FormatID.Bytes, SectionIDMap.SUMMARY_INFORMATION_ID); } } /// <summary> /// Gets a value indicating whether this instance is document summary information. /// </summary> /// <value> /// <c>true</c> if this instance is document summary information; otherwise, <c>false</c>. /// </value> /// Checks whether this {@link PropertySet} is a Document /// Summary Information. /// @return /// <c>true</c> /// if this {@link PropertySet} /// represents a Document Summary Information, else /// <c>false</c> public virtual bool IsDocumentSummaryInformation { get { if (sections.Count <= 0) return false; return Arrays.Equals(sections[0].FormatID.Bytes, SectionIDMap.DOCUMENT_SUMMARY_INFORMATION_ID1); } } /// <summary> /// Convenience method returning the {@link Property} array /// contained in this property Set. It is a shortcut for Getting /// the {@link PropertySet}'s {@link Section}s list and then /// Getting the {@link Property} array from the first {@link /// Section}. /// </summary> /// <value>The properties of the only {@link Section} of this /// {@link PropertySet}.</value> public virtual Property[] Properties { get { return FirstSection.Properties; } } /// <summary> /// Convenience method returning the value of the property with /// the specified ID. If the property is not available, /// <c>null</c> is returned and a subsequent call To {@link /// #WasNull} will return <c>true</c> . /// </summary> /// <param name="id">The property ID</param> /// <returns>The property value</returns> public virtual Object GetProperty(int id) { return FirstSection.GetProperty(id); } /// <summary> /// Convenience method returning the value of a bool property /// with the specified ID. If the property is not available, /// <c>false</c> is returned. A subsequent call To {@link /// #WasNull} will return <c>true</c> To let the caller /// distinguish that case from a real property value of /// <c>false</c>. /// </summary> /// <param name="id">The property ID</param> /// <returns>The property value</returns> public virtual bool GetPropertyBooleanValue(int id) { return FirstSection.GetPropertyBooleanValue(id); } /// <summary> /// Convenience method returning the value of the numeric /// property with the specified ID. If the property is not /// available, 0 is returned. A subsequent call To {@link #WasNull} /// will return <c>true</c> To let the caller distinguish /// that case from a real property value of 0. /// </summary> /// <param name="id">The property ID</param> /// <returns>The propertyIntValue value</returns> public virtual int GetPropertyIntValue(int id) { return FirstSection.GetPropertyIntValue(id); } /// <summary> /// Checks whether the property which the last call To {@link /// #GetPropertyIntValue} or {@link #GetProperty} tried To access /// Was available or not. This information might be important for /// callers of {@link #GetPropertyIntValue} since the latter /// returns 0 if the property does not exist. Using {@link /// #WasNull}, the caller can distiguish this case from a /// property's real value of 0. /// </summary> /// <value><c>true</c> if the last call To {@link /// #GetPropertyIntValue} or {@link #GetProperty} tried To access a /// property that Was not available; otherwise, <c>false</c>.</value> public virtual bool WasNull { get { return FirstSection.WasNull; } } /// <summary> /// Gets the first section. /// </summary> /// <value>The first section.</value> public virtual Section FirstSection { get { if (SectionCount< 1) throw new MissingSectionException("Property Set does not contain any sections."); return sections[0]; } } /// <summary> /// If the {@link PropertySet} has only a single section this /// method returns it. /// </summary> /// <value>The singleSection value</value> public Section SingleSection { get { int sectionCount = SectionCount; if (sectionCount != 1) throw new NoSingleSectionException ("Property Set Contains " + sectionCount + " sections."); return sections[0]; } } /// <summary> /// Returns <c>true</c> if the <c>PropertySet</c> is equal /// To the specified parameter, else <c>false</c>. /// </summary> /// <param name="o">the object To Compare this /// <c>PropertySet</c> /// with</param> /// <returns><c>true</c> /// if the objects are equal, /// <c>false</c> /// if not</returns> public override bool Equals(Object o) { if (o == null || !(o is PropertySet)) return false; PropertySet ps = (PropertySet)o; int byteOrder1 = ps.ByteOrder; int byteOrder2 = ByteOrder; ClassID classID1 = ps.ClassID; ClassID classID2 = ClassID; int format1 = ps.Format; int format2 = Format; int osVersion1 = ps.OSVersion; int osVersion2 = OSVersion; int sectionCount1 = ps.SectionCount; int sectionCount2 = SectionCount; if (byteOrder1 != byteOrder2 || !classID1.Equals(classID2) || format1 != format2 || osVersion1 != osVersion2 || sectionCount1 != sectionCount2) return false; /* Compare the sections: */ return Util.AreEqual(Sections, ps.Sections); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { throw new InvalidOperationException("FIXME: Not yet implemented."); } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override String ToString() { StringBuilder b = new StringBuilder(); int sectionCount = SectionCount; b.Append(GetType().Name); b.Append('['); b.Append("byteOrder: "); b.Append(ByteOrder); b.Append(", classID: "); b.Append(ClassID); b.Append(", format: "); b.Append(Format); b.Append(", OSVersion: "); b.Append(OSVersion); b.Append(", sectionCount: "); b.Append(sectionCount); b.Append(", sections: [\n"); foreach (Section section in Sections) { b.Append(section.ToString()); } b.Append(']'); b.Append(']'); return b.ToString(); } } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole, Rob Prouse // // 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; using System.Collections.Generic; using System.Linq; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.Framework { /// <summary> /// Supplies a set of random values to a single parameter of a parameterized test. /// </summary> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class RandomAttribute : NUnitAttribute, IParameterDataSource { private RandomDataSource _source; private readonly int _count; /// <summary> /// If true, no value will be repeated. /// </summary> public bool Distinct { get; set; } #region Constructors /// <summary> /// Construct a random set of values appropriate for the Type of the /// parameter on which the attribute appears, specifying only the count. /// </summary> /// <param name="count"></param> public RandomAttribute(int count) { _count = count; } /// <summary> /// Construct a set of ints within a specified range /// </summary> public RandomAttribute(int min, int max, int count) { _source = new IntDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned ints within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(uint min, uint max, int count) { _source = new UIntDataSource(min, max, count); } /// <summary> /// Construct a set of longs within a specified range /// </summary> public RandomAttribute(long min, long max, int count) { _source = new LongDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned longs within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(ulong min, ulong max, int count) { _source = new ULongDataSource(min, max, count); } /// <summary> /// Construct a set of shorts within a specified range /// </summary> public RandomAttribute(short min, short max, int count) { _source = new ShortDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned shorts within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(ushort min, ushort max, int count) { _source = new UShortDataSource(min, max, count); } /// <summary> /// Construct a set of doubles within a specified range /// </summary> public RandomAttribute(double min, double max, int count) { _source = new DoubleDataSource(min, max, count); } /// <summary> /// Construct a set of floats within a specified range /// </summary> public RandomAttribute(float min, float max, int count) { _source = new FloatDataSource(min, max, count); } /// <summary> /// Construct a set of bytes within a specified range /// </summary> public RandomAttribute(byte min, byte max, int count) { _source = new ByteDataSource(min, max, count); } /// <summary> /// Construct a set of sbytes within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(sbyte min, sbyte max, int count) { _source = new SByteDataSource(min, max, count); } #endregion #region IParameterDataSource Interface /// <summary> /// Retrieves a list of arguments which can be passed to the specified parameter. /// </summary> /// <param name="parameter">The parameter of a parameterized test.</param> public IEnumerable GetData(IParameterInfo parameter) { // Since a separate Randomizer is used for each parameter, // we can't fill in the data in the constructor of the // attribute. Only now, when GetData is called, do we have // sufficient information to create the values in a // repeatable manner. Type parmType = parameter.ParameterType; if (_source == null) { if (parmType == typeof(int)) _source = new IntDataSource(_count); else if (parmType == typeof(uint)) _source = new UIntDataSource(_count); else if (parmType == typeof(long)) _source = new LongDataSource(_count); else if (parmType == typeof(ulong)) _source = new ULongDataSource(_count); else if (parmType == typeof(short)) _source = new ShortDataSource(_count); else if (parmType == typeof(ushort)) _source = new UShortDataSource(_count); else if (parmType == typeof(double)) _source = new DoubleDataSource(_count); else if (parmType == typeof(float)) _source = new FloatDataSource(_count); else if (parmType == typeof(byte)) _source = new ByteDataSource(_count); else if (parmType == typeof(sbyte)) _source = new SByteDataSource(_count); else if (parmType == typeof(decimal)) _source = new DecimalDataSource(_count); else if (parmType.GetTypeInfo().IsEnum) _source = new EnumDataSource(_count); else // Default _source = new IntDataSource(_count); } else if (_source.DataType != parmType && WeConvert(_source.DataType, parmType)) { _source.Distinct = Distinct; _source = new RandomDataConverter(_source); } _source.Distinct = Distinct; return _source.GetData(parameter); } private bool WeConvert(Type sourceType, Type targetType) { if (targetType == typeof(short) || targetType == typeof(ushort) || targetType == typeof(byte) || targetType == typeof(sbyte)) return sourceType == typeof(int); if (targetType == typeof(decimal)) return sourceType == typeof(int) || sourceType == typeof(double); return false; } #endregion #region Nested DataSource Classes #region RandomDataSource abstract class RandomDataSource : IParameterDataSource { public Type DataType { get; protected set; } public bool Distinct { get; set; } public abstract IEnumerable GetData(IParameterInfo parameter); } abstract class RandomDataSource<T> : RandomDataSource { private readonly T _min; private readonly T _max; private readonly int _count; private readonly bool _inRange; private readonly List<T> previousValues = new List<T>(); protected Randomizer Randomizer; protected RandomDataSource(int count) { _count = count; _inRange = false; DataType = typeof(T); } protected RandomDataSource(T min, T max, int count) { _min = min; _max = max; _count = count; _inRange = true; DataType = typeof(T); } public override IEnumerable GetData(IParameterInfo parameter) { //Guard.ArgumentValid(parameter.ParameterType == typeof(T), "Parameter type must be " + typeof(T).Name, "parameter"); Randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo); Guard.OperationValid(!(Distinct && _inRange && !CanBeDistinct(_min, _max, _count)), $"The range of values is [{_min}, {_max}[ and the random value count is {_count} so the values cannot be distinct."); for (int i = 0; i < _count; i++) { if (Distinct) { T next; do { next = _inRange ? GetNext(_min, _max) : GetNext(); } while (previousValues.Contains(next)); previousValues.Add(next); yield return next; } else yield return _inRange ? GetNext(_min, _max) : GetNext(); } } protected abstract T GetNext(); protected abstract T GetNext(T min, T max); protected abstract bool CanBeDistinct(T min, T max, int count); } #endregion #region RandomDataConverter class RandomDataConverter : RandomDataSource { readonly IParameterDataSource _source; public RandomDataConverter(IParameterDataSource source) { _source = source; } public override IEnumerable GetData(IParameterInfo parameter) { Type parmType = parameter.ParameterType; foreach (object obj in _source.GetData(parameter)) { if (obj is int) { int ival = (int)obj; // unbox first if (parmType == typeof(short)) yield return (short)ival; else if (parmType == typeof(ushort)) yield return (ushort)ival; else if (parmType == typeof(byte)) yield return (byte)ival; else if (parmType == typeof(sbyte)) yield return (sbyte)ival; else if (parmType == typeof(decimal)) yield return (decimal)ival; } else if (obj is double) { double d = (double)obj; // unbox first if (parmType == typeof(decimal)) yield return (decimal)d; } } } } #endregion #region IntDataSource class IntDataSource : RandomDataSource<int> { public IntDataSource(int count) : base(count) { } public IntDataSource(int min, int max, int count) : base(min, max, count) { } protected override int GetNext() { return Randomizer.Next(); } protected override int GetNext(int min, int max) { return Randomizer.Next(min, max); } protected override bool CanBeDistinct(int min, int max, int count) { return count <= max - min; } } #endregion #region UIntDataSource class UIntDataSource : RandomDataSource<uint> { public UIntDataSource(int count) : base(count) { } public UIntDataSource(uint min, uint max, int count) : base(min, max, count) { } protected override uint GetNext() { return Randomizer.NextUInt(); } protected override uint GetNext(uint min, uint max) { return Randomizer.NextUInt(min, max); } protected override bool CanBeDistinct(uint min, uint max, int count) { return count <= max - min; } } #endregion #region LongDataSource class LongDataSource : RandomDataSource<long> { public LongDataSource(int count) : base(count) { } public LongDataSource(long min, long max, int count) : base(min, max, count) { } protected override long GetNext() { return Randomizer.NextLong(); } protected override long GetNext(long min, long max) { return Randomizer.NextLong(min, max); } protected override bool CanBeDistinct(long min, long max, int count) { return count <= max - min; } } #endregion #region ULongDataSource class ULongDataSource : RandomDataSource<ulong> { public ULongDataSource(int count) : base(count) { } public ULongDataSource(ulong min, ulong max, int count) : base(min, max, count) { } protected override ulong GetNext() { return Randomizer.NextULong(); } protected override ulong GetNext(ulong min, ulong max) { return Randomizer.NextULong(min, max); } protected override bool CanBeDistinct(ulong min, ulong max, int count) { return (uint)count <= max - min; } } #endregion #region ShortDataSource class ShortDataSource : RandomDataSource<short> { public ShortDataSource(int count) : base(count) { } public ShortDataSource(short min, short max, int count) : base(min, max, count) { } protected override short GetNext() { return Randomizer.NextShort(); } protected override short GetNext(short min, short max) { return Randomizer.NextShort(min, max); } protected override bool CanBeDistinct(short min, short max, int count) { return count <= max - min; } } #endregion #region UShortDataSource class UShortDataSource : RandomDataSource<ushort> { public UShortDataSource(int count) : base(count) { } public UShortDataSource(ushort min, ushort max, int count) : base(min, max, count) { } protected override ushort GetNext() { return Randomizer.NextUShort(); } protected override ushort GetNext(ushort min, ushort max) { return Randomizer.NextUShort(min, max); } protected override bool CanBeDistinct(ushort min, ushort max, int count) { return count <= max - min; } } #endregion #region DoubleDataSource class DoubleDataSource : RandomDataSource<double> { public DoubleDataSource(int count) : base(count) { } public DoubleDataSource(double min, double max, int count) : base(min, max, count) { } protected override double GetNext() { return Randomizer.NextDouble(); } protected override double GetNext(double min, double max) { return Randomizer.NextDouble(min, max); } protected override bool CanBeDistinct(double min, double max, int count) { return true; } } #endregion #region FloatDataSource class FloatDataSource : RandomDataSource<float> { public FloatDataSource(int count) : base(count) { } public FloatDataSource(float min, float max, int count) : base(min, max, count) { } protected override float GetNext() { return Randomizer.NextFloat(); } protected override float GetNext(float min, float max) { return Randomizer.NextFloat(min, max); } protected override bool CanBeDistinct(float min, float max, int count) { return true; } } #endregion #region ByteDataSource class ByteDataSource : RandomDataSource<byte> { public ByteDataSource(int count) : base(count) { } public ByteDataSource(byte min, byte max, int count) : base(min, max, count) { } protected override byte GetNext() { return Randomizer.NextByte(); } protected override byte GetNext(byte min, byte max) { return Randomizer.NextByte(min, max); } protected override bool CanBeDistinct(byte min, byte max, int count) { return count <= max - min; } } #endregion #region SByteDataSource class SByteDataSource : RandomDataSource<sbyte> { public SByteDataSource(int count) : base(count) { } public SByteDataSource(sbyte min, sbyte max, int count) : base(min, max, count) { } protected override sbyte GetNext() { return Randomizer.NextSByte(); } protected override sbyte GetNext(sbyte min, sbyte max) { return Randomizer.NextSByte(min, max); } protected override bool CanBeDistinct(sbyte min, sbyte max, int count) { return count <= max - min; } } #endregion #region EnumDataSource class EnumDataSource : RandomDataSource { private readonly int _count; private readonly List<object> previousValues = new List<object>(); public EnumDataSource(int count) { _count = count; DataType = typeof(Enum); } public override IEnumerable GetData(IParameterInfo parameter) { Guard.ArgumentValid(parameter.ParameterType.GetTypeInfo().IsEnum, "EnumDataSource requires an enum parameter", nameof(parameter)); Randomizer randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo); DataType = parameter.ParameterType; int valueCount = Enum.GetValues(DataType).Cast<int>().Distinct().Count(); Guard.OperationValid(!(Distinct && _count > valueCount), $"The enum \"{DataType.Name}\" has {valueCount} values and the random value count is {_count} so the values cannot be distinct."); for (int i = 0; i < _count; i++) { if (Distinct) { object next; do { next = randomizer.NextEnum(parameter.ParameterType); } while (previousValues.Contains(next)); previousValues.Add(next); yield return next; } else yield return randomizer.NextEnum(parameter.ParameterType); } } } #endregion #region DecimalDataSource // Currently, Randomizer doesn't implement methods for decimal // so we use random Ulongs and convert them. This doesn't cover // the full range of decimal, so it's temporary. class DecimalDataSource : RandomDataSource<decimal> { public DecimalDataSource(int count) : base(count) { } public DecimalDataSource(decimal min, decimal max, int count) : base(min, max, count) { } protected override decimal GetNext() { return Randomizer.NextDecimal(); } protected override decimal GetNext(decimal min, decimal max) { return Randomizer.NextDecimal(min, max); } protected override bool CanBeDistinct(decimal min, decimal max, int count) { return true; } } #endregion #endregion } }
// Copyright 2007 Andrew D. Weiss // Licensed under CPOL // http://www.codeproject.com/Articles/20581/Multiselect-Treeview-Implementation using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace NBTExplorer.Vendor.MultiSelectTreeView { public class MultiSelectTreeView : TreeView { #region Selected Node(s) Properties private List<TreeNode> m_SelectedNodes = null; public List<TreeNode> SelectedNodes { get { return m_SelectedNodes; } set { BeginUpdate(); ClearSelectedNodes(); if( value != null ) { foreach( TreeNode node in value ) { ToggleNode( node, true ); } } EndUpdate(); } } // Note we use the new keyword to Hide the native treeview's SelectedNode property. private TreeNode m_SelectedNode; public new TreeNode SelectedNode { get { return m_SelectedNode; } set { ClearSelectedNodes(); if( value != null ) { SelectNode( value ); } } } #endregion public MultiSelectTreeView() { DoubleBuffered = true; SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true); m_SelectedNodes = new List<TreeNode>(); base.SelectedNode = null; } private void UpdateExtendedStyles () { if (Interop.WinInteropAvailable) { int style = 0; if (DoubleBuffered) style |= NativeInterop.TVS_EX_DOUBLEBUFFER; if (style != 0) Interop.SendMessage(Handle, NativeInterop.TVM_SETEXTENDEDSTYLE, (IntPtr)NativeInterop.TVS_EX_DOUBLEBUFFER, (IntPtr)style); } } #region Overridden Events protected override void OnHandleCreated (EventArgs e) { base.OnHandleCreated(e); if (Interop.WinInteropAvailable) { UpdateExtendedStyles(); if (!Interop.IsWinXP) Interop.SendMessage(Handle, NativeInterop.TVM_SETBKCOLOR, IntPtr.Zero, (IntPtr)ColorTranslator.ToWin32(BackColor)); } } protected override void OnGotFocus( EventArgs e ) { // Make sure at least one node has a selection // this way we can tab to the ctrl and use the // keyboard to select nodes try { if( m_SelectedNode == null && this.TopNode != null ) { ToggleNode( this.TopNode, true ); } base.OnGotFocus( e ); } catch( Exception ex ) { HandleException( ex ); } } protected override void OnMouseDown( MouseEventArgs e ) { // If the user clicks on a node that was not // previously selected, select it now. try { base.SelectedNode = null; TreeNode node = this.GetNodeAt( e.Location ); if( node != null ) { int leftBound = node.Bounds.X; // - 20; // Allow user to click on image if (node.TreeView.ImageList != null) leftBound -= 20; int rightBound = node.Bounds.Right + 10; // Give a little extra room if( e.Location.X > leftBound && e.Location.X < rightBound ) { if( ModifierKeys == Keys.None && ( m_SelectedNodes.Contains( node ) ) ) { // Potential Drag Operation // Let Mouse Up do select } else { SelectNode( node ); } } } base.OnMouseDown( e ); } catch( Exception ex ) { HandleException( ex ); } } protected override void OnMouseUp( MouseEventArgs e ) { // If the clicked on a node that WAS previously // selected then, reselect it now. This will clear // any other selected nodes. e.g. A B C D are selected // the user clicks on B, now A C & D are no longer selected. try { // Check to see if a node was clicked on TreeNode node = this.GetNodeAt( e.Location ); if( node != null ) { if( ModifierKeys == Keys.None && m_SelectedNodes.Contains( node ) ) { int leftBound = node.Bounds.X; // -20; // Allow user to click on image int rightBound = node.Bounds.Right + 10; // Give a little extra room if( e.Location.X > leftBound && e.Location.X < rightBound ) { SelectNode( node ); } } } base.OnMouseUp( e ); } catch( Exception ex ) { HandleException( ex ); } } protected override void OnItemDrag( ItemDragEventArgs e ) { // If the user drags a node and the node being dragged is NOT // selected, then clear the active selection, select the // node being dragged and drag it. Otherwise if the node being // dragged is selected, drag the entire selection. try { TreeNode node = e.Item as TreeNode; if( node != null ) { if( !m_SelectedNodes.Contains( node ) ) { SelectSingleNode( node ); ToggleNode( node, true ); } } base.OnItemDrag( e ); } catch( Exception ex ) { HandleException( ex ); } } protected override void OnBeforeSelect( TreeViewCancelEventArgs e ) { // Never allow base.SelectedNode to be set! try { base.SelectedNode = null; e.Cancel = true; base.OnBeforeSelect( e ); } catch( Exception ex ) { HandleException( ex ); } } protected override void OnAfterSelect( TreeViewEventArgs e ) { // Never allow base.SelectedNode to be set! try { base.OnAfterSelect( e ); base.SelectedNode = null; } catch( Exception ex ) { HandleException( ex ); } } protected override void OnKeyDown( KeyEventArgs e ) { // Handle all possible key strokes for the control. // including navigation, selection, etc. base.OnKeyDown( e ); if( e.KeyCode == Keys.ShiftKey ) return; //this.BeginUpdate(); bool bShift = ( ModifierKeys == Keys.Shift ); try { // Nothing is selected in the tree, this isn't a good state // select the top node if( m_SelectedNode == null && this.TopNode != null ) { ToggleNode( this.TopNode, true ); } // Nothing is still selected in the tree, this isn't a good state, leave. if( m_SelectedNode == null ) return; if( e.KeyCode == Keys.Left ) { if( m_SelectedNode.IsExpanded && m_SelectedNode.Nodes.Count > 0 ) { // Collapse an expanded node that has children m_SelectedNode.Collapse(); } else if( m_SelectedNode.Parent != null ) { // Node is already collapsed, try to select its parent. SelectSingleNode( m_SelectedNode.Parent ); } } else if( e.KeyCode == Keys.Right ) { if( !m_SelectedNode.IsExpanded ) { // Expand a collpased node's children m_SelectedNode.Expand(); } else { // Node was already expanded, select the first child SelectSingleNode( m_SelectedNode.FirstNode ); } } else if( e.KeyCode == Keys.Up ) { // Select the previous node if( m_SelectedNode.PrevVisibleNode != null ) { SelectNode( m_SelectedNode.PrevVisibleNode ); } } else if( e.KeyCode == Keys.Down ) { // Select the next node if( m_SelectedNode.NextVisibleNode != null ) { SelectNode( m_SelectedNode.NextVisibleNode ); } } else if( e.KeyCode == Keys.Home ) { if( bShift ) { if( m_SelectedNode.Parent == null ) { // Select all of the root nodes up to this point if( this.Nodes.Count > 0 ) { SelectNode( this.Nodes[0] ); } } else { // Select all of the nodes up to this point under this nodes parent SelectNode( m_SelectedNode.Parent.FirstNode ); } } else { // Select this first node in the tree if( this.Nodes.Count > 0 ) { SelectSingleNode( this.Nodes[0] ); } } } else if( e.KeyCode == Keys.End ) { if( bShift ) { if( m_SelectedNode.Parent == null ) { // Select the last ROOT node in the tree if( this.Nodes.Count > 0 ) { SelectNode( this.Nodes[this.Nodes.Count - 1] ); } } else { // Select the last node in this branch SelectNode( m_SelectedNode.Parent.LastNode ); } } else { if( this.Nodes.Count > 0 ) { // Select the last node visible node in the tree. // Don't expand branches incase the tree is virtual TreeNode ndLast = this.Nodes[0].LastNode; while( ndLast.IsExpanded && ( ndLast.LastNode != null ) ) { ndLast = ndLast.LastNode; } SelectSingleNode( ndLast ); } } } else if( e.KeyCode == Keys.PageUp ) { // Select the highest node in the display int nCount = this.VisibleCount; TreeNode ndCurrent = m_SelectedNode; while( ( nCount ) > 0 && ( ndCurrent.PrevVisibleNode != null ) ) { ndCurrent = ndCurrent.PrevVisibleNode; nCount--; } SelectSingleNode( ndCurrent ); } else if( e.KeyCode == Keys.PageDown ) { // Select the lowest node in the display int nCount = this.VisibleCount; TreeNode ndCurrent = m_SelectedNode; while( ( nCount ) > 0 && ( ndCurrent.NextVisibleNode != null ) ) { ndCurrent = ndCurrent.NextVisibleNode; nCount--; } SelectSingleNode( ndCurrent ); } else { // Assume this is a search character a-z, A-Z, 0-9, etc. // Select the first node after the current node that // starts with this character string sSearch = ( (char) e.KeyValue ).ToString(); TreeNode ndCurrent = m_SelectedNode; while( ( ndCurrent.NextVisibleNode != null ) ) { ndCurrent = ndCurrent.NextVisibleNode; if( ndCurrent.Text.StartsWith( sSearch ) ) { SelectSingleNode( ndCurrent ); break; } } } } catch( Exception ex ) { HandleException( ex ); } finally { this.EndUpdate(); } } #endregion #region Helper Methods private void SelectNode( TreeNode node ) { try { this.BeginUpdate(); if( m_SelectedNode == null || ModifierKeys == Keys.Control ) { // Ctrl+Click selects an unselected node, or unselects a selected node. bool bIsSelected = m_SelectedNodes.Contains( node ); ToggleNode( node, !bIsSelected ); } else if( ModifierKeys == Keys.Shift ) { // Shift+Click selects nodes between the selected node and here. TreeNode ndStart = m_SelectedNode; TreeNode ndEnd = node; if( ndStart.Parent == ndEnd.Parent ) { // Selected node and clicked node have same parent, easy case. if( ndStart.Index < ndEnd.Index ) { // If the selected node is beneath the clicked node walk down // selecting each Visible node until we reach the end. while( ndStart != ndEnd ) { ndStart = ndStart.NextVisibleNode; if( ndStart == null ) break; ToggleNode( ndStart, true ); } } else if( ndStart.Index == ndEnd.Index ) { // Clicked same node, do nothing } else { // If the selected node is above the clicked node walk up // selecting each Visible node until we reach the end. while( ndStart != ndEnd ) { ndStart = ndStart.PrevVisibleNode; if( ndStart == null ) break; ToggleNode( ndStart, true ); } } } else { // Selected node and clicked node have same parent, hard case. // We need to find a common parent to determine if we need // to walk down selecting, or walk up selecting. TreeNode ndStartP = ndStart; TreeNode ndEndP = ndEnd; int startDepth = Math.Min( ndStartP.Level, ndEndP.Level ); // Bring lower node up to common depth while( ndStartP.Level > startDepth ) { ndStartP = ndStartP.Parent; } // Bring lower node up to common depth while( ndEndP.Level > startDepth ) { ndEndP = ndEndP.Parent; } // Walk up the tree until we find the common parent while( ndStartP.Parent != ndEndP.Parent ) { ndStartP = ndStartP.Parent; ndEndP = ndEndP.Parent; } // Select the node if( ndStartP.Index < ndEndP.Index ) { // If the selected node is beneath the clicked node walk down // selecting each Visible node until we reach the end. while( ndStart != ndEnd ) { ndStart = ndStart.NextVisibleNode; if( ndStart == null ) break; ToggleNode( ndStart, true ); } } else if( ndStartP.Index == ndEndP.Index ) { if( ndStart.Level < ndEnd.Level ) { while( ndStart != ndEnd ) { ndStart = ndStart.NextVisibleNode; if( ndStart == null ) break; ToggleNode( ndStart, true ); } } else { while( ndStart != ndEnd ) { ndStart = ndStart.PrevVisibleNode; if( ndStart == null ) break; ToggleNode( ndStart, true ); } } } else { // If the selected node is above the clicked node walk up // selecting each Visible node until we reach the end. while( ndStart != ndEnd ) { ndStart = ndStart.PrevVisibleNode; if( ndStart == null ) break; ToggleNode( ndStart, true ); } } } } else { // Just clicked a node, select it SelectSingleNode( node ); } OnAfterSelect( new TreeViewEventArgs( m_SelectedNode ) ); } finally { this.EndUpdate(); } } private void ClearSelectedNodes() { try { foreach( TreeNode node in m_SelectedNodes ) { node.BackColor = this.BackColor; node.ForeColor = this.ForeColor; } } finally { m_SelectedNodes.Clear(); m_SelectedNode = null; } } private void SelectSingleNode( TreeNode node ) { if( node == null ) { return; } ClearSelectedNodes(); ToggleNode( node, true ); node.EnsureVisible(); } private void ToggleNode( TreeNode node, bool bSelectNode ) { if( bSelectNode ) { m_SelectedNode = node; if( !m_SelectedNodes.Contains( node ) ) { m_SelectedNodes.Add( node ); } node.BackColor = SystemColors.Highlight; node.ForeColor = SystemColors.HighlightText; } else { m_SelectedNodes.Remove( node ); node.BackColor = this.BackColor; node.ForeColor = this.ForeColor; } } private void HandleException( Exception ex ) { // Perform some error handling here. // We don't want to bubble errors to the CLR. MessageBox.Show( ex.Message ); } #endregion private const int WM_ERASEBKGND = 0x14; protected override void WndProc (ref Message m) { if (m.Msg == WM_ERASEBKGND) //if message is is erase background { return; } base.WndProc(ref m); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using AdefHelpDeskBase.Models; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.AspNetCore.Http; using ADefHelpDeskApp.Classes; using AdefHelpDeskBase.Models.DataContext; using Microsoft.EntityFrameworkCore; namespace ADefHelpDeskApp.Pages { public class LogInModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IWebHostEnvironment _hostEnvironment; private IConfiguration _config { get; set; } private readonly IHttpContextAccessor _httpContextAccessor; public LogInModel(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager, IWebHostEnvironment hostEnvironment, IConfiguration config, IHttpContextAccessor httpContextAccessor) { _userManager = userManager; _signInManager = signInManager; _hostEnvironment = hostEnvironment; _config = config; _httpContextAccessor = httpContextAccessor; } [BindProperty] public InputModel Input { get; set; } public IList<AuthenticationScheme> ExternalLogins { get; set; } public string ReturnUrl { get; set; } [TempData] public string ErrorMessage { get; set; } public class InputModel { [Required] public string Email { get; set; } [Required] [DataType(DataType.Password)] public string Password { get; set; } [Display(Name = "Remember me?")] public string RememberMe { get; set; } } public void OnGet() { } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl ??= Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); DTOAuthentication objDTOAuthentication = new DTOAuthentication(); objDTOAuthentication.userName = Input.Email; objDTOAuthentication.password = Input.Password; objDTOAuthentication.rememberMe = (Input.RememberMe != null) ? (Input.RememberMe == "on") : false; LoginStatus objLoginStatus = GetLoginStatus(objDTOAuthentication); if (objLoginStatus.isLoggedIn) { return LocalRedirect(returnUrl); } else { return LocalRedirect("/loginfailedcontrol"); } } // Utility #region public LoginStatus GetLoginStatus(DTOAuthentication Authentication) public LoginStatus GetLoginStatus(DTOAuthentication Authentication) { // LoginStatus to return LoginStatus objLoginStatus = new LoginStatus(); objLoginStatus.isLoggedIn = false; // Get values passed var paramUserName = Authentication.userName; var paramPassword = Authentication.password; var paramRememberMe = Authentication.rememberMe; if ((paramUserName != null) && (paramPassword != null)) { if (this.User != null) { // First log the user out if (_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated) { // Log user out _signInManager.SignOutAsync().Wait(); } } var optionsBuilder = new DbContextOptionsBuilder<ADefHelpDeskContext>(); optionsBuilder.UseSqlServer(GetConnectionString()); try { // Only check the legacy User password if user is not in the main table if (_userManager.Users.Where(x => x.UserName == paramUserName).FirstOrDefault() == null) { using (var context = new ADefHelpDeskContext(optionsBuilder.Options)) { // First check the legacy User table var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers where AdefHelpDeskUsers.Username == paramUserName where AdefHelpDeskUsers.Password != "" select AdefHelpDeskUsers).FirstOrDefault(); if (objAdefHelpDeskUser != null) { // User is in the Legacy table and the password is not null // Check their password to see if this account can be migrated if (objAdefHelpDeskUser.Password == ComputeHash.GetSwcMD5(paramUserName.Trim().ToLower() + paramPassword.Trim())) { // Return that this account can be migrated objLoginStatus.status = "Migrate"; return objLoginStatus; } } } } } catch { // There may have been an error because this is an upgrade from a version // of Adefhelpdesk before the AspNetUsers tables existed using (var context = new ADefHelpDeskContext(optionsBuilder.Options)) { // Check the legacy User table var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers where AdefHelpDeskUsers.Username == paramUserName where AdefHelpDeskUsers.Password != "" select AdefHelpDeskUsers).FirstOrDefault(); if (objAdefHelpDeskUser != null) { // User is in the Legacy table and the password is not null // Check their password if (objAdefHelpDeskUser.Password != ComputeHash.GetSwcMD5(paramUserName.Trim().ToLower() + paramPassword.Trim())) { objLoginStatus.status = "Error: Account needs to be migrated, but account cannot be migrated because the password is incorrect"; return objLoginStatus; } } } } // Check to see if the user needs to Verify their account using (var context = new ADefHelpDeskContext(optionsBuilder.Options)) { var objAdefHelpDeskUser = (from AdefHelpDeskUsers in context.AdefHelpDeskUsers where AdefHelpDeskUsers.Username == paramUserName select AdefHelpDeskUsers).FirstOrDefault(); if (objAdefHelpDeskUser != null) { if (objAdefHelpDeskUser.VerificationCode != null) { objLoginStatus.status = "Verify"; return objLoginStatus; } } } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = _signInManager.PasswordSignInAsync( paramUserName, paramPassword, paramRememberMe, lockoutOnFailure: false).Result; if (result.Succeeded) { objLoginStatus.status = "Success"; objLoginStatus.isLoggedIn = true; return objLoginStatus; } if (result.RequiresTwoFactor) { objLoginStatus.status = "RequiresVerification"; return objLoginStatus; } if (result.IsLockedOut) { objLoginStatus.status = "IsLockedOut"; return objLoginStatus; } } objLoginStatus.status = "Authentication Failure"; return objLoginStatus; } #endregion #region private string GetConnectionString() private string GetConnectionString() { // Use this method to make sure we get the latest one string strConnectionString = "ERRROR:UNSET-CONECTION-STRING"; try { strConnectionString = _config.GetConnectionString("DefaultConnection"); } catch { // Do nothing } return strConnectionString; } #endregion } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Workflows.V1.Snippets { using Google.Api.Gax; using Google.Api.Gax.ResourceNames; using Google.Cloud.Workflows.Common.V1; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class AllGeneratedWorkflowsClientSnippets { /// <summary>Snippet for ListWorkflows</summary> public void ListWorkflowsRequestObject() { // Snippet: ListWorkflows(ListWorkflowsRequest, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) ListWorkflowsRequest request = new ListWorkflowsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", OrderBy = "", }; // Make the request PagedEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflows(request); // Iterate over all response items, lazily performing RPCs as required foreach (Workflow item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListWorkflowsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Workflow item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Workflow> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Workflow item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWorkflowsAsync</summary> public async Task ListWorkflowsRequestObjectAsync() { // Snippet: ListWorkflowsAsync(ListWorkflowsRequest, CallSettings) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) ListWorkflowsRequest request = new ListWorkflowsRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Filter = "", OrderBy = "", }; // Make the request PagedAsyncEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflowsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Workflow item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListWorkflowsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Workflow item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Workflow> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Workflow item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWorkflows</summary> public void ListWorkflows() { // Snippet: ListWorkflows(string, string, int?, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflows(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Workflow item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListWorkflowsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Workflow item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Workflow> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Workflow item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWorkflowsAsync</summary> public async Task ListWorkflowsAsync() { // Snippet: ListWorkflowsAsync(string, string, int?, CallSettings) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; // Make the request PagedAsyncEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflowsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Workflow item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListWorkflowsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Workflow item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Workflow> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Workflow item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWorkflows</summary> public void ListWorkflowsResourceNames() { // Snippet: ListWorkflows(LocationName, string, int?, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflows(parent); // Iterate over all response items, lazily performing RPCs as required foreach (Workflow item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListWorkflowsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Workflow item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Workflow> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Workflow item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListWorkflowsAsync</summary> public async Task ListWorkflowsResourceNamesAsync() { // Snippet: ListWorkflowsAsync(LocationName, string, int?, CallSettings) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); // Make the request PagedAsyncEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflowsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((Workflow item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListWorkflowsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (Workflow item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<Workflow> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (Workflow item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for GetWorkflow</summary> public void GetWorkflowRequestObject() { // Snippet: GetWorkflow(GetWorkflowRequest, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) GetWorkflowRequest request = new GetWorkflowRequest { WorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; // Make the request Workflow response = workflowsClient.GetWorkflow(request); // End snippet } /// <summary>Snippet for GetWorkflowAsync</summary> public async Task GetWorkflowRequestObjectAsync() { // Snippet: GetWorkflowAsync(GetWorkflowRequest, CallSettings) // Additional: GetWorkflowAsync(GetWorkflowRequest, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) GetWorkflowRequest request = new GetWorkflowRequest { WorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; // Make the request Workflow response = await workflowsClient.GetWorkflowAsync(request); // End snippet } /// <summary>Snippet for GetWorkflow</summary> public void GetWorkflow() { // Snippet: GetWorkflow(string, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]"; // Make the request Workflow response = workflowsClient.GetWorkflow(name); // End snippet } /// <summary>Snippet for GetWorkflowAsync</summary> public async Task GetWorkflowAsync() { // Snippet: GetWorkflowAsync(string, CallSettings) // Additional: GetWorkflowAsync(string, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]"; // Make the request Workflow response = await workflowsClient.GetWorkflowAsync(name); // End snippet } /// <summary>Snippet for GetWorkflow</summary> public void GetWorkflowResourceNames() { // Snippet: GetWorkflow(WorkflowName, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) WorkflowName name = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"); // Make the request Workflow response = workflowsClient.GetWorkflow(name); // End snippet } /// <summary>Snippet for GetWorkflowAsync</summary> public async Task GetWorkflowResourceNamesAsync() { // Snippet: GetWorkflowAsync(WorkflowName, CallSettings) // Additional: GetWorkflowAsync(WorkflowName, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) WorkflowName name = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"); // Make the request Workflow response = await workflowsClient.GetWorkflowAsync(name); // End snippet } /// <summary>Snippet for CreateWorkflow</summary> public void CreateWorkflowRequestObject() { // Snippet: CreateWorkflow(CreateWorkflowRequest, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) CreateWorkflowRequest request = new CreateWorkflowRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Workflow = new Workflow(), WorkflowId = "", }; // Make the request Operation<Workflow, OperationMetadata> response = workflowsClient.CreateWorkflow(request); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceCreateWorkflow(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateWorkflowAsync</summary> public async Task CreateWorkflowRequestObjectAsync() { // Snippet: CreateWorkflowAsync(CreateWorkflowRequest, CallSettings) // Additional: CreateWorkflowAsync(CreateWorkflowRequest, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) CreateWorkflowRequest request = new CreateWorkflowRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Workflow = new Workflow(), WorkflowId = "", }; // Make the request Operation<Workflow, OperationMetadata> response = await workflowsClient.CreateWorkflowAsync(request); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceCreateWorkflowAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateWorkflow</summary> public void CreateWorkflow() { // Snippet: CreateWorkflow(string, Workflow, string, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Workflow workflow = new Workflow(); string workflowId = ""; // Make the request Operation<Workflow, OperationMetadata> response = workflowsClient.CreateWorkflow(parent, workflow, workflowId); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceCreateWorkflow(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateWorkflowAsync</summary> public async Task CreateWorkflowAsync() { // Snippet: CreateWorkflowAsync(string, Workflow, string, CallSettings) // Additional: CreateWorkflowAsync(string, Workflow, string, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) string parent = "projects/[PROJECT]/locations/[LOCATION]"; Workflow workflow = new Workflow(); string workflowId = ""; // Make the request Operation<Workflow, OperationMetadata> response = await workflowsClient.CreateWorkflowAsync(parent, workflow, workflowId); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceCreateWorkflowAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateWorkflow</summary> public void CreateWorkflowResourceNames() { // Snippet: CreateWorkflow(LocationName, Workflow, string, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Workflow workflow = new Workflow(); string workflowId = ""; // Make the request Operation<Workflow, OperationMetadata> response = workflowsClient.CreateWorkflow(parent, workflow, workflowId); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceCreateWorkflow(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateWorkflowAsync</summary> public async Task CreateWorkflowResourceNamesAsync() { // Snippet: CreateWorkflowAsync(LocationName, Workflow, string, CallSettings) // Additional: CreateWorkflowAsync(LocationName, Workflow, string, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"); Workflow workflow = new Workflow(); string workflowId = ""; // Make the request Operation<Workflow, OperationMetadata> response = await workflowsClient.CreateWorkflowAsync(parent, workflow, workflowId); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceCreateWorkflowAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteWorkflow</summary> public void DeleteWorkflowRequestObject() { // Snippet: DeleteWorkflow(DeleteWorkflowRequest, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) DeleteWorkflowRequest request = new DeleteWorkflowRequest { WorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; // Make the request Operation<Empty, OperationMetadata> response = workflowsClient.DeleteWorkflow(request); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = workflowsClient.PollOnceDeleteWorkflow(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteWorkflowAsync</summary> public async Task DeleteWorkflowRequestObjectAsync() { // Snippet: DeleteWorkflowAsync(DeleteWorkflowRequest, CallSettings) // Additional: DeleteWorkflowAsync(DeleteWorkflowRequest, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) DeleteWorkflowRequest request = new DeleteWorkflowRequest { WorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"), }; // Make the request Operation<Empty, OperationMetadata> response = await workflowsClient.DeleteWorkflowAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceDeleteWorkflowAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteWorkflow</summary> public void DeleteWorkflow() { // Snippet: DeleteWorkflow(string, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]"; // Make the request Operation<Empty, OperationMetadata> response = workflowsClient.DeleteWorkflow(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = workflowsClient.PollOnceDeleteWorkflow(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteWorkflowAsync</summary> public async Task DeleteWorkflowAsync() { // Snippet: DeleteWorkflowAsync(string, CallSettings) // Additional: DeleteWorkflowAsync(string, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]"; // Make the request Operation<Empty, OperationMetadata> response = await workflowsClient.DeleteWorkflowAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceDeleteWorkflowAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteWorkflow</summary> public void DeleteWorkflowResourceNames() { // Snippet: DeleteWorkflow(WorkflowName, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) WorkflowName name = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"); // Make the request Operation<Empty, OperationMetadata> response = workflowsClient.DeleteWorkflow(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = workflowsClient.PollOnceDeleteWorkflow(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteWorkflowAsync</summary> public async Task DeleteWorkflowResourceNamesAsync() { // Snippet: DeleteWorkflowAsync(WorkflowName, CallSettings) // Additional: DeleteWorkflowAsync(WorkflowName, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) WorkflowName name = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"); // Make the request Operation<Empty, OperationMetadata> response = await workflowsClient.DeleteWorkflowAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceDeleteWorkflowAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateWorkflow</summary> public void UpdateWorkflowRequestObject() { // Snippet: UpdateWorkflow(UpdateWorkflowRequest, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) UpdateWorkflowRequest request = new UpdateWorkflowRequest { Workflow = new Workflow(), UpdateMask = new FieldMask(), }; // Make the request Operation<Workflow, OperationMetadata> response = workflowsClient.UpdateWorkflow(request); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceUpdateWorkflow(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateWorkflowAsync</summary> public async Task UpdateWorkflowRequestObjectAsync() { // Snippet: UpdateWorkflowAsync(UpdateWorkflowRequest, CallSettings) // Additional: UpdateWorkflowAsync(UpdateWorkflowRequest, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) UpdateWorkflowRequest request = new UpdateWorkflowRequest { Workflow = new Workflow(), UpdateMask = new FieldMask(), }; // Make the request Operation<Workflow, OperationMetadata> response = await workflowsClient.UpdateWorkflowAsync(request); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceUpdateWorkflowAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateWorkflow</summary> public void UpdateWorkflow() { // Snippet: UpdateWorkflow(Workflow, FieldMask, CallSettings) // Create client WorkflowsClient workflowsClient = WorkflowsClient.Create(); // Initialize request argument(s) Workflow workflow = new Workflow(); FieldMask updateMask = new FieldMask(); // Make the request Operation<Workflow, OperationMetadata> response = workflowsClient.UpdateWorkflow(workflow, updateMask); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceUpdateWorkflow(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for UpdateWorkflowAsync</summary> public async Task UpdateWorkflowAsync() { // Snippet: UpdateWorkflowAsync(Workflow, FieldMask, CallSettings) // Additional: UpdateWorkflowAsync(Workflow, FieldMask, CancellationToken) // Create client WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync(); // Initialize request argument(s) Workflow workflow = new Workflow(); FieldMask updateMask = new FieldMask(); // Make the request Operation<Workflow, OperationMetadata> response = await workflowsClient.UpdateWorkflowAsync(workflow, updateMask); // Poll until the returned long-running operation is complete Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Workflow result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceUpdateWorkflowAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Workflow retrievedResult = retrievedResponse.Result; } // End snippet } } }
// <copyright file="ArrayExtensions.ForEachRefActions.cs" company="Adrian Mos"> // Copyright (c) Adrian Mos with all rights reserved. Part of the IX Framework. // </copyright> using System; using System.Diagnostics.CodeAnalysis; using IX.StandardExtensions.Contracts; using IX.StandardExtensions.Efficiency; namespace IX.StandardExtensions.Extensions; /// <summary> /// Extensions for array types. /// </summary> public static partial class ArrayExtensions { /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="TItem">The array type.</typeparam> /// <typeparam name="TParam1">The type of parameter to be passed to the invoked method at index 0.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <param name="param1">A parameter of type <typeparamref name="TParam1" /> to pass to the invoked method at index 0. This parameter is passed by reference.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null"/> (<see langword="Nothing"/> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "A for loop on an array is going to be faster.")] [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "ReSharper is used for this project.")] public static void ForEach<TItem, TParam1>( this TItem[] source, RefIteratorAction<TItem, TParam1> action, ref TParam1 param1) { Requires.NotNull(source); Requires.NotNull(action); for (var i = 0; i < source.Length; i++) { action(source[i], ref param1); } } /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="TItem">The array type.</typeparam> /// <typeparam name="TParam1">The type of parameter to be passed to the invoked method at index 0.</typeparam> /// <typeparam name="TParam2">The type of parameter to be passed to the invoked method at index 1.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <param name="param1">A parameter of type <typeparamref name="TParam1" /> to pass to the invoked method at index 0. This parameter is passed by reference.</param> /// <param name="param2">A parameter of type <typeparamref name="TParam2" /> to pass to the invoked method at index 1. This parameter is passed by reference.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null"/> (<see langword="Nothing"/> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "A for loop on an array is going to be faster.")] [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "ReSharper is used for this project.")] public static void ForEach<TItem, TParam1, TParam2>( this TItem[] source, RefIteratorAction<TItem, TParam1, TParam2> action, ref TParam1 param1, ref TParam2 param2) { Requires.NotNull(source); Requires.NotNull(action); for (var i = 0; i < source.Length; i++) { action(source[i], ref param1, ref param2); } } /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="TItem">The array type.</typeparam> /// <typeparam name="TParam1">The type of parameter to be passed to the invoked method at index 0.</typeparam> /// <typeparam name="TParam2">The type of parameter to be passed to the invoked method at index 1.</typeparam> /// <typeparam name="TParam3">The type of parameter to be passed to the invoked method at index 2.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <param name="param1">A parameter of type <typeparamref name="TParam1" /> to pass to the invoked method at index 0. This parameter is passed by reference.</param> /// <param name="param2">A parameter of type <typeparamref name="TParam2" /> to pass to the invoked method at index 1. This parameter is passed by reference.</param> /// <param name="param3">A parameter of type <typeparamref name="TParam3" /> to pass to the invoked method at index 2. This parameter is passed by reference.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null"/> (<see langword="Nothing"/> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "A for loop on an array is going to be faster.")] [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "ReSharper is used for this project.")] public static void ForEach<TItem, TParam1, TParam2, TParam3>( this TItem[] source, RefIteratorAction<TItem, TParam1, TParam2, TParam3> action, ref TParam1 param1, ref TParam2 param2, ref TParam3 param3) { Requires.NotNull(source); Requires.NotNull(action); for (var i = 0; i < source.Length; i++) { action(source[i], ref param1, ref param2, ref param3); } } /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="TItem">The array type.</typeparam> /// <typeparam name="TParam1">The type of parameter to be passed to the invoked method at index 0.</typeparam> /// <typeparam name="TParam2">The type of parameter to be passed to the invoked method at index 1.</typeparam> /// <typeparam name="TParam3">The type of parameter to be passed to the invoked method at index 2.</typeparam> /// <typeparam name="TParam4">The type of parameter to be passed to the invoked method at index 3.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <param name="param1">A parameter of type <typeparamref name="TParam1" /> to pass to the invoked method at index 0. This parameter is passed by reference.</param> /// <param name="param2">A parameter of type <typeparamref name="TParam2" /> to pass to the invoked method at index 1. This parameter is passed by reference.</param> /// <param name="param3">A parameter of type <typeparamref name="TParam3" /> to pass to the invoked method at index 2. This parameter is passed by reference.</param> /// <param name="param4">A parameter of type <typeparamref name="TParam4" /> to pass to the invoked method at index 3. This parameter is passed by reference.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null"/> (<see langword="Nothing"/> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "A for loop on an array is going to be faster.")] [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "ReSharper is used for this project.")] public static void ForEach<TItem, TParam1, TParam2, TParam3, TParam4>( this TItem[] source, RefIteratorAction<TItem, TParam1, TParam2, TParam3, TParam4> action, ref TParam1 param1, ref TParam2 param2, ref TParam3 param3, ref TParam4 param4) { Requires.NotNull(source); Requires.NotNull(action); for (var i = 0; i < source.Length; i++) { action(source[i], ref param1, ref param2, ref param3, ref param4); } } /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="TItem">The array type.</typeparam> /// <typeparam name="TParam1">The type of parameter to be passed to the invoked method at index 0.</typeparam> /// <typeparam name="TParam2">The type of parameter to be passed to the invoked method at index 1.</typeparam> /// <typeparam name="TParam3">The type of parameter to be passed to the invoked method at index 2.</typeparam> /// <typeparam name="TParam4">The type of parameter to be passed to the invoked method at index 3.</typeparam> /// <typeparam name="TParam5">The type of parameter to be passed to the invoked method at index 4.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <param name="param1">A parameter of type <typeparamref name="TParam1" /> to pass to the invoked method at index 0. This parameter is passed by reference.</param> /// <param name="param2">A parameter of type <typeparamref name="TParam2" /> to pass to the invoked method at index 1. This parameter is passed by reference.</param> /// <param name="param3">A parameter of type <typeparamref name="TParam3" /> to pass to the invoked method at index 2. This parameter is passed by reference.</param> /// <param name="param4">A parameter of type <typeparamref name="TParam4" /> to pass to the invoked method at index 3. This parameter is passed by reference.</param> /// <param name="param5">A parameter of type <typeparamref name="TParam5" /> to pass to the invoked method at index 4. This parameter is passed by reference.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null"/> (<see langword="Nothing"/> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "A for loop on an array is going to be faster.")] [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "ReSharper is used for this project.")] public static void ForEach<TItem, TParam1, TParam2, TParam3, TParam4, TParam5>( this TItem[] source, RefIteratorAction<TItem, TParam1, TParam2, TParam3, TParam4, TParam5> action, ref TParam1 param1, ref TParam2 param2, ref TParam3 param3, ref TParam4 param4, ref TParam5 param5) { Requires.NotNull(source); Requires.NotNull(action); for (var i = 0; i < source.Length; i++) { action(source[i], ref param1, ref param2, ref param3, ref param4, ref param5); } } /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="TItem">The array type.</typeparam> /// <typeparam name="TParam1">The type of parameter to be passed to the invoked method at index 0.</typeparam> /// <typeparam name="TParam2">The type of parameter to be passed to the invoked method at index 1.</typeparam> /// <typeparam name="TParam3">The type of parameter to be passed to the invoked method at index 2.</typeparam> /// <typeparam name="TParam4">The type of parameter to be passed to the invoked method at index 3.</typeparam> /// <typeparam name="TParam5">The type of parameter to be passed to the invoked method at index 4.</typeparam> /// <typeparam name="TParam6">The type of parameter to be passed to the invoked method at index 5.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <param name="param1">A parameter of type <typeparamref name="TParam1" /> to pass to the invoked method at index 0. This parameter is passed by reference.</param> /// <param name="param2">A parameter of type <typeparamref name="TParam2" /> to pass to the invoked method at index 1. This parameter is passed by reference.</param> /// <param name="param3">A parameter of type <typeparamref name="TParam3" /> to pass to the invoked method at index 2. This parameter is passed by reference.</param> /// <param name="param4">A parameter of type <typeparamref name="TParam4" /> to pass to the invoked method at index 3. This parameter is passed by reference.</param> /// <param name="param5">A parameter of type <typeparamref name="TParam5" /> to pass to the invoked method at index 4. This parameter is passed by reference.</param> /// <param name="param6">A parameter of type <typeparamref name="TParam6" /> to pass to the invoked method at index 5. This parameter is passed by reference.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null"/> (<see langword="Nothing"/> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "A for loop on an array is going to be faster.")] [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "ReSharper is used for this project.")] public static void ForEach<TItem, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6>( this TItem[] source, RefIteratorAction<TItem, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6> action, ref TParam1 param1, ref TParam2 param2, ref TParam3 param3, ref TParam4 param4, ref TParam5 param5, ref TParam6 param6) { Requires.NotNull(source); Requires.NotNull(action); for (var i = 0; i < source.Length; i++) { action(source[i], ref param1, ref param2, ref param3, ref param4, ref param5, ref param6); } } /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="TItem">The array type.</typeparam> /// <typeparam name="TParam1">The type of parameter to be passed to the invoked method at index 0.</typeparam> /// <typeparam name="TParam2">The type of parameter to be passed to the invoked method at index 1.</typeparam> /// <typeparam name="TParam3">The type of parameter to be passed to the invoked method at index 2.</typeparam> /// <typeparam name="TParam4">The type of parameter to be passed to the invoked method at index 3.</typeparam> /// <typeparam name="TParam5">The type of parameter to be passed to the invoked method at index 4.</typeparam> /// <typeparam name="TParam6">The type of parameter to be passed to the invoked method at index 5.</typeparam> /// <typeparam name="TParam7">The type of parameter to be passed to the invoked method at index 6.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <param name="param1">A parameter of type <typeparamref name="TParam1" /> to pass to the invoked method at index 0. This parameter is passed by reference.</param> /// <param name="param2">A parameter of type <typeparamref name="TParam2" /> to pass to the invoked method at index 1. This parameter is passed by reference.</param> /// <param name="param3">A parameter of type <typeparamref name="TParam3" /> to pass to the invoked method at index 2. This parameter is passed by reference.</param> /// <param name="param4">A parameter of type <typeparamref name="TParam4" /> to pass to the invoked method at index 3. This parameter is passed by reference.</param> /// <param name="param5">A parameter of type <typeparamref name="TParam5" /> to pass to the invoked method at index 4. This parameter is passed by reference.</param> /// <param name="param6">A parameter of type <typeparamref name="TParam6" /> to pass to the invoked method at index 5. This parameter is passed by reference.</param> /// <param name="param7">A parameter of type <typeparamref name="TParam7" /> to pass to the invoked method at index 6. This parameter is passed by reference.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null"/> (<see langword="Nothing"/> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "A for loop on an array is going to be faster.")] [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "ReSharper is used for this project.")] public static void ForEach<TItem, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7>( this TItem[] source, RefIteratorAction<TItem, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7> action, ref TParam1 param1, ref TParam2 param2, ref TParam3 param3, ref TParam4 param4, ref TParam5 param5, ref TParam6 param6, ref TParam7 param7) { Requires.NotNull(source); Requires.NotNull(action); for (var i = 0; i < source.Length; i++) { action(source[i], ref param1, ref param2, ref param3, ref param4, ref param5, ref param6, ref param7); } } /// <summary> /// Executes an action for each one of the elements of an array. /// </summary> /// <typeparam name="TItem">The array type.</typeparam> /// <typeparam name="TParam1">The type of parameter to be passed to the invoked method at index 0.</typeparam> /// <typeparam name="TParam2">The type of parameter to be passed to the invoked method at index 1.</typeparam> /// <typeparam name="TParam3">The type of parameter to be passed to the invoked method at index 2.</typeparam> /// <typeparam name="TParam4">The type of parameter to be passed to the invoked method at index 3.</typeparam> /// <typeparam name="TParam5">The type of parameter to be passed to the invoked method at index 4.</typeparam> /// <typeparam name="TParam6">The type of parameter to be passed to the invoked method at index 5.</typeparam> /// <typeparam name="TParam7">The type of parameter to be passed to the invoked method at index 6.</typeparam> /// <typeparam name="TParam8">The type of parameter to be passed to the invoked method at index 7.</typeparam> /// <param name="source">The enumerable source.</param> /// <param name="action">The action to execute.</param> /// <param name="param1">A parameter of type <typeparamref name="TParam1" /> to pass to the invoked method at index 0. This parameter is passed by reference.</param> /// <param name="param2">A parameter of type <typeparamref name="TParam2" /> to pass to the invoked method at index 1. This parameter is passed by reference.</param> /// <param name="param3">A parameter of type <typeparamref name="TParam3" /> to pass to the invoked method at index 2. This parameter is passed by reference.</param> /// <param name="param4">A parameter of type <typeparamref name="TParam4" /> to pass to the invoked method at index 3. This parameter is passed by reference.</param> /// <param name="param5">A parameter of type <typeparamref name="TParam5" /> to pass to the invoked method at index 4. This parameter is passed by reference.</param> /// <param name="param6">A parameter of type <typeparamref name="TParam6" /> to pass to the invoked method at index 5. This parameter is passed by reference.</param> /// <param name="param7">A parameter of type <typeparamref name="TParam7" /> to pass to the invoked method at index 6. This parameter is passed by reference.</param> /// <param name="param8">A parameter of type <typeparamref name="TParam8" /> to pass to the invoked method at index 7. This parameter is passed by reference.</param> /// <exception cref="ArgumentNullException"> /// Thrown when <paramref name="source" /> or <paramref name="action" /> is /// <see langword="null"/> (<see langword="Nothing"/> in Visual Basic). /// </exception> [SuppressMessage( "ReSharper", "ForCanBeConvertedToForeach", Justification = "A for loop on an array is going to be faster.")] [SuppressMessage( "CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "ReSharper is used for this project.")] public static void ForEach<TItem, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8>( this TItem[] source, RefIteratorAction<TItem, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8> action, ref TParam1 param1, ref TParam2 param2, ref TParam3 param3, ref TParam4 param4, ref TParam5 param5, ref TParam6 param6, ref TParam7 param7, ref TParam8 param8) { Requires.NotNull(source); Requires.NotNull(action); for (var i = 0; i < source.Length; i++) { action(source[i], ref param1, ref param2, ref param3, ref param4, ref param5, ref param6, ref param7, ref param8); } } }
namespace java.security.cert { [global::MonoJavaBridge.JavaClass(typeof(global::java.security.cert.X509Certificate_))] public abstract partial class X509Certificate : java.security.cert.Certificate, X509Extension { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected X509Certificate(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public abstract bool hasUnsupportedCriticalExtension(); private static global::MonoJavaBridge.MethodId _m1; public abstract global::java.util.Set getCriticalExtensionOIDs(); private static global::MonoJavaBridge.MethodId _m2; public abstract global::java.util.Set getNonCriticalExtensionOIDs(); private static global::MonoJavaBridge.MethodId _m3; public abstract byte[] getExtensionValue(java.lang.String arg0); private static global::MonoJavaBridge.MethodId _m4; public abstract byte[] getSignature(); private static global::MonoJavaBridge.MethodId _m5; public abstract int getBasicConstraints(); private static global::MonoJavaBridge.MethodId _m6; public abstract int getVersion(); private static global::MonoJavaBridge.MethodId _m7; public abstract global::java.math.BigInteger getSerialNumber(); private static global::MonoJavaBridge.MethodId _m8; public abstract global::java.security.Principal getIssuerDN(); private static global::MonoJavaBridge.MethodId _m9; public abstract byte[] getTBSCertificate(); private static global::MonoJavaBridge.MethodId _m10; public abstract void checkValidity(); private static global::MonoJavaBridge.MethodId _m11; public abstract void checkValidity(java.util.Date arg0); private static global::MonoJavaBridge.MethodId _m12; public virtual global::javax.security.auth.x500.X500Principal getIssuerX500Principal() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<javax.security.auth.x500.X500Principal>(this, global::java.security.cert.X509Certificate.staticClass, "getIssuerX500Principal", "()Ljavax/security/auth/x500/X500Principal;", ref global::java.security.cert.X509Certificate._m12) as javax.security.auth.x500.X500Principal; } private static global::MonoJavaBridge.MethodId _m13; public abstract global::java.security.Principal getSubjectDN(); private static global::MonoJavaBridge.MethodId _m14; public virtual global::javax.security.auth.x500.X500Principal getSubjectX500Principal() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<javax.security.auth.x500.X500Principal>(this, global::java.security.cert.X509Certificate.staticClass, "getSubjectX500Principal", "()Ljavax/security/auth/x500/X500Principal;", ref global::java.security.cert.X509Certificate._m14) as javax.security.auth.x500.X500Principal; } private static global::MonoJavaBridge.MethodId _m15; public abstract global::java.util.Date getNotBefore(); private static global::MonoJavaBridge.MethodId _m16; public abstract global::java.util.Date getNotAfter(); private static global::MonoJavaBridge.MethodId _m17; public abstract global::java.lang.String getSigAlgName(); private static global::MonoJavaBridge.MethodId _m18; public abstract global::java.lang.String getSigAlgOID(); private static global::MonoJavaBridge.MethodId _m19; public abstract byte[] getSigAlgParams(); private static global::MonoJavaBridge.MethodId _m20; public abstract bool[] getIssuerUniqueID(); private static global::MonoJavaBridge.MethodId _m21; public abstract bool[] getSubjectUniqueID(); private static global::MonoJavaBridge.MethodId _m22; public abstract bool[] getKeyUsage(); private static global::MonoJavaBridge.MethodId _m23; public virtual global::java.util.List getExtendedKeyUsage() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.List>(this, global::java.security.cert.X509Certificate.staticClass, "getExtendedKeyUsage", "()Ljava/util/List;", ref global::java.security.cert.X509Certificate._m23) as java.util.List; } private static global::MonoJavaBridge.MethodId _m24; public virtual global::java.util.Collection getSubjectAlternativeNames() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Collection>(this, global::java.security.cert.X509Certificate.staticClass, "getSubjectAlternativeNames", "()Ljava/util/Collection;", ref global::java.security.cert.X509Certificate._m24) as java.util.Collection; } private static global::MonoJavaBridge.MethodId _m25; public virtual global::java.util.Collection getIssuerAlternativeNames() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Collection>(this, global::java.security.cert.X509Certificate.staticClass, "getIssuerAlternativeNames", "()Ljava/util/Collection;", ref global::java.security.cert.X509Certificate._m25) as java.util.Collection; } private static global::MonoJavaBridge.MethodId _m26; protected X509Certificate() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.security.cert.X509Certificate._m26.native == global::System.IntPtr.Zero) global::java.security.cert.X509Certificate._m26 = @__env.GetMethodIDNoThrow(global::java.security.cert.X509Certificate.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.security.cert.X509Certificate.staticClass, global::java.security.cert.X509Certificate._m26); Init(@__env, handle); } static X509Certificate() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.security.cert.X509Certificate.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/cert/X509Certificate")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.security.cert.X509Certificate))] internal sealed partial class X509Certificate_ : java.security.cert.X509Certificate { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal X509Certificate_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override bool hasUnsupportedCriticalExtension() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.security.cert.X509Certificate_.staticClass, "hasUnsupportedCriticalExtension", "()Z", ref global::java.security.cert.X509Certificate_._m0); } private static global::MonoJavaBridge.MethodId _m1; public override global::java.util.Set getCriticalExtensionOIDs() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Set>(this, global::java.security.cert.X509Certificate_.staticClass, "getCriticalExtensionOIDs", "()Ljava/util/Set;", ref global::java.security.cert.X509Certificate_._m1) as java.util.Set; } private static global::MonoJavaBridge.MethodId _m2; public override global::java.util.Set getNonCriticalExtensionOIDs() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Set>(this, global::java.security.cert.X509Certificate_.staticClass, "getNonCriticalExtensionOIDs", "()Ljava/util/Set;", ref global::java.security.cert.X509Certificate_._m2) as java.util.Set; } private static global::MonoJavaBridge.MethodId _m3; public override byte[] getExtensionValue(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::java.security.cert.X509Certificate_.staticClass, "getExtensionValue", "(Ljava/lang/String;)[B", ref global::java.security.cert.X509Certificate_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as byte[]; } private static global::MonoJavaBridge.MethodId _m4; public override byte[] getSignature() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::java.security.cert.X509Certificate_.staticClass, "getSignature", "()[B", ref global::java.security.cert.X509Certificate_._m4) as byte[]; } private static global::MonoJavaBridge.MethodId _m5; public override int getBasicConstraints() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.security.cert.X509Certificate_.staticClass, "getBasicConstraints", "()I", ref global::java.security.cert.X509Certificate_._m5); } private static global::MonoJavaBridge.MethodId _m6; public override int getVersion() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.security.cert.X509Certificate_.staticClass, "getVersion", "()I", ref global::java.security.cert.X509Certificate_._m6); } private static global::MonoJavaBridge.MethodId _m7; public override global::java.math.BigInteger getSerialNumber() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.cert.X509Certificate_.staticClass, "getSerialNumber", "()Ljava/math/BigInteger;", ref global::java.security.cert.X509Certificate_._m7) as java.math.BigInteger; } private static global::MonoJavaBridge.MethodId _m8; public override global::java.security.Principal getIssuerDN() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.security.Principal>(this, global::java.security.cert.X509Certificate_.staticClass, "getIssuerDN", "()Ljava/security/Principal;", ref global::java.security.cert.X509Certificate_._m8) as java.security.Principal; } private static global::MonoJavaBridge.MethodId _m9; public override byte[] getTBSCertificate() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::java.security.cert.X509Certificate_.staticClass, "getTBSCertificate", "()[B", ref global::java.security.cert.X509Certificate_._m9) as byte[]; } private static global::MonoJavaBridge.MethodId _m10; public override void checkValidity() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.cert.X509Certificate_.staticClass, "checkValidity", "()V", ref global::java.security.cert.X509Certificate_._m10); } private static global::MonoJavaBridge.MethodId _m11; public override void checkValidity(java.util.Date arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.cert.X509Certificate_.staticClass, "checkValidity", "(Ljava/util/Date;)V", ref global::java.security.cert.X509Certificate_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m12; public override global::java.security.Principal getSubjectDN() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.security.Principal>(this, global::java.security.cert.X509Certificate_.staticClass, "getSubjectDN", "()Ljava/security/Principal;", ref global::java.security.cert.X509Certificate_._m12) as java.security.Principal; } private static global::MonoJavaBridge.MethodId _m13; public override global::java.util.Date getNotBefore() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.cert.X509Certificate_.staticClass, "getNotBefore", "()Ljava/util/Date;", ref global::java.security.cert.X509Certificate_._m13) as java.util.Date; } private static global::MonoJavaBridge.MethodId _m14; public override global::java.util.Date getNotAfter() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.security.cert.X509Certificate_.staticClass, "getNotAfter", "()Ljava/util/Date;", ref global::java.security.cert.X509Certificate_._m14) as java.util.Date; } private static global::MonoJavaBridge.MethodId _m15; public override global::java.lang.String getSigAlgName() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.security.cert.X509Certificate_.staticClass, "getSigAlgName", "()Ljava/lang/String;", ref global::java.security.cert.X509Certificate_._m15) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m16; public override global::java.lang.String getSigAlgOID() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.security.cert.X509Certificate_.staticClass, "getSigAlgOID", "()Ljava/lang/String;", ref global::java.security.cert.X509Certificate_._m16) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m17; public override byte[] getSigAlgParams() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::java.security.cert.X509Certificate_.staticClass, "getSigAlgParams", "()[B", ref global::java.security.cert.X509Certificate_._m17) as byte[]; } private static global::MonoJavaBridge.MethodId _m18; public override bool[] getIssuerUniqueID() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<bool>(this, global::java.security.cert.X509Certificate_.staticClass, "getIssuerUniqueID", "()[Z", ref global::java.security.cert.X509Certificate_._m18) as bool[]; } private static global::MonoJavaBridge.MethodId _m19; public override bool[] getSubjectUniqueID() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<bool>(this, global::java.security.cert.X509Certificate_.staticClass, "getSubjectUniqueID", "()[Z", ref global::java.security.cert.X509Certificate_._m19) as bool[]; } private static global::MonoJavaBridge.MethodId _m20; public override bool[] getKeyUsage() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<bool>(this, global::java.security.cert.X509Certificate_.staticClass, "getKeyUsage", "()[Z", ref global::java.security.cert.X509Certificate_._m20) as bool[]; } private static global::MonoJavaBridge.MethodId _m21; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.security.cert.X509Certificate_.staticClass, "toString", "()Ljava/lang/String;", ref global::java.security.cert.X509Certificate_._m21) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m22; public override byte[] getEncoded() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::java.security.cert.X509Certificate_.staticClass, "getEncoded", "()[B", ref global::java.security.cert.X509Certificate_._m22) as byte[]; } private static global::MonoJavaBridge.MethodId _m23; public override void verify(java.security.PublicKey arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.cert.X509Certificate_.staticClass, "verify", "(Ljava/security/PublicKey;)V", ref global::java.security.cert.X509Certificate_._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m24; public override void verify(java.security.PublicKey arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.security.cert.X509Certificate_.staticClass, "verify", "(Ljava/security/PublicKey;Ljava/lang/String;)V", ref global::java.security.cert.X509Certificate_._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m25; public override global::java.security.PublicKey getPublicKey() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.security.PublicKey>(this, global::java.security.cert.X509Certificate_.staticClass, "getPublicKey", "()Ljava/security/PublicKey;", ref global::java.security.cert.X509Certificate_._m25) as java.security.PublicKey; } static X509Certificate_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.security.cert.X509Certificate_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/security/cert/X509Certificate")); } } }
// WARNING: DO NOT LEAVE COMMENTED CODE IN THIS FILE. IT GETS SCANNED BY GEN PROJECT SO IT CAN EXCLUDE ANY MANUALLY DEFINED MAPS using System.Reflection; using AutoMapper; using k8s.Models; namespace k8s.Versioning { /// <summary> /// Provides mappers that converts Kubernetes models between different versions /// </summary> public static partial class VersionConverter { static VersionConverter() { UpdateMappingConfiguration(expression => { }); } public static IMapper Mapper { get; private set; } internal static MapperConfiguration MapperConfiguration { get; private set; } /// <summary> /// Two level lookup of model types by Kind and then Version /// </summary> internal static Dictionary<string, Dictionary<string, Type>> KindVersionsMap { get; private set; } public static Type GetTypeForVersion<T>(string version) { return GetTypeForVersion(typeof(T), version); } public static Type GetTypeForVersion(Type type, string version) { return KindVersionsMap[type.GetKubernetesTypeMetadata().Kind][version]; } public static void UpdateMappingConfiguration(Action<IMapperConfigurationExpression> configuration) { MapperConfiguration = new MapperConfiguration(cfg => { GetConfigurations(cfg); configuration(cfg); }); Mapper = MapperConfiguration.CreateMapper(); KindVersionsMap = MapperConfiguration .GetAllTypeMaps() .SelectMany(x => new[] { x.Types.SourceType, x.Types.DestinationType }) .Where(x => x.GetCustomAttribute<KubernetesEntityAttribute>() != null) .Select(x => { var attr = GetKubernetesEntityAttribute(x); return new { attr.Kind, attr.ApiVersion, Type = x }; }) .GroupBy(x => x.Kind) .ToDictionary(x => x.Key, kindGroup => kindGroup .GroupBy(x => x.ApiVersion) .ToDictionary( x => x.Key, versionGroup => versionGroup.Select(x => x.Type).Distinct().Single())); // should only be one type for each Kind/Version combination } public static object ConvertToVersion(object source, string apiVersion) { if (source == null) { throw new ArgumentNullException(nameof(source)); } var type = source.GetType(); var attr = GetKubernetesEntityAttribute(type); if (attr.ApiVersion == apiVersion) { return source; } if (!KindVersionsMap.TryGetValue(attr.Kind, out var kindVersions)) { throw new InvalidOperationException($"Version converter does not have any registered types for Kind `{attr.Kind}`"); } if (!kindVersions.TryGetValue(apiVersion, out var targetType) || !kindVersions.TryGetValue(attr.ApiVersion, out var sourceType) || MapperConfiguration.FindTypeMapFor(sourceType, targetType) == null) { throw new InvalidOperationException($"There is no conversion mapping registered for Kind `{attr.Kind}` from ApiVersion {attr.ApiVersion} to {apiVersion}"); } return Mapper.Map(source, sourceType, targetType); } private static KubernetesEntityAttribute GetKubernetesEntityAttribute(Type type) { if (type == null) { throw new ArgumentNullException(nameof(type)); } var attr = type.GetCustomAttribute<KubernetesEntityAttribute>(); if (attr == null) { throw new InvalidOperationException($"Type {type} does not have {nameof(KubernetesEntityAttribute)}"); } return attr; } internal static void GetConfigurations(IMapperConfigurationExpression cfg) { AutoConfigurations(cfg); ManualConfigurations(cfg); } private static void ManualConfigurations(IMapperConfigurationExpression cfg) { cfg.AllowNullCollections = true; cfg.DisableConstructorMapping(); cfg.ForAllMaps((typeMap, opt) => { if (!typeof(IKubernetesObject).IsAssignableFrom(typeMap.Types.DestinationType)) { return; } var metadata = typeMap.Types.DestinationType.GetKubernetesTypeMetadata(); opt.ForMember(nameof(IKubernetesObject.ApiVersion), x => x.Ignore()); opt.ForMember(nameof(IKubernetesObject.Kind), x => x.Ignore()); opt.AfterMap((from, to) => { var obj = (IKubernetesObject)to; obj.ApiVersion = !string.IsNullOrEmpty(metadata.Group) ? $"{metadata.Group}/{metadata.ApiVersion}" : metadata.ApiVersion; obj.Kind = metadata.Kind; }); }); cfg.CreateMap<V1Subject, V1beta1Subject>() .ForMember(dest => dest.Group, opt => opt.Ignore()) .ForMember(dest => dest.ServiceAccount, opt => opt.Ignore()) .ForMember(dest => dest.User, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V1Subject, V1beta2Subject>() .ForMember(dest => dest.Group, opt => opt.Ignore()) .ForMember(dest => dest.ServiceAccount, opt => opt.Ignore()) .ForMember(dest => dest.User, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V1alpha1RuntimeClass, V1RuntimeClass>() .ForMember(dest => dest.Handler, opt => opt.MapFrom(src => src.Spec.RuntimeHandler)) .ForMember(dest => dest.Overhead, opt => opt.MapFrom(src => src.Spec.Overhead)) .ForMember(dest => dest.Scheduling, opt => opt.MapFrom(src => src.Spec.Scheduling)) .ReverseMap(); cfg.CreateMap<V1beta1RuntimeClass, V1RuntimeClass>() .ForMember(dest => dest.Handler, opt => opt.MapFrom(src => src.Handler)) .ForMember(dest => dest.Overhead, opt => opt.MapFrom(src => src.Overhead)) .ForMember(dest => dest.Scheduling, opt => opt.MapFrom(src => src.Scheduling)) .ReverseMap(); cfg.CreateMap<V1alpha1RuntimeClass, V1beta1RuntimeClass>() .ForMember(dest => dest.Handler, opt => opt.MapFrom(src => src.Spec.RuntimeHandler)) .ForMember(dest => dest.Overhead, opt => opt.MapFrom(src => src.Spec.Overhead)) .ForMember(dest => dest.Scheduling, opt => opt.MapFrom(src => src.Spec.Scheduling)) .ReverseMap(); cfg.CreateMap<V2beta1ResourceMetricStatus, V2beta2MetricValueStatus>() .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.CurrentAverageValue)) .ForMember(dest => dest.AverageUtilization, opt => opt.MapFrom(src => src.CurrentAverageUtilization)) .ForMember(dest => dest.Value, opt => opt.Ignore()); cfg.CreateMap<V2beta1ResourceMetricStatus, V2MetricValueStatus>() .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.CurrentAverageValue)) .ForMember(dest => dest.AverageUtilization, opt => opt.MapFrom(src => src.CurrentAverageUtilization)) .ForMember(dest => dest.Value, opt => opt.Ignore()); cfg.CreateMap<V2beta1ResourceMetricStatus, V2beta2ResourceMetricStatus>() .ForMember(dest => dest.Current, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2beta2ResourceMetricStatus, V2beta1ResourceMetricStatus>() .ForMember(dest => dest.CurrentAverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(dest => dest.CurrentAverageUtilization, opt => opt.MapFrom(src => src.Current.AverageUtilization)); cfg.CreateMap<V2beta1ResourceMetricStatus, V2ResourceMetricStatus>() .ForMember(dest => dest.Current, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2ResourceMetricStatus, V2beta1ResourceMetricStatus>() .ForMember(dest => dest.CurrentAverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(dest => dest.CurrentAverageUtilization, opt => opt.MapFrom(src => src.Current.AverageUtilization)); cfg.CreateMap<V2beta1ResourceMetricSource, V2beta2MetricTarget>() .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.TargetAverageValue)) .ForMember(dest => dest.Value, opt => opt.Ignore()) .ForMember(dest => dest.Type, opt => opt.MapFrom((src, dest) => src.TargetAverageValue != null ? "AverageValue" : "Utilization")) .ForMember(dest => dest.AverageUtilization, opt => opt.MapFrom(src => src.TargetAverageUtilization)); cfg.CreateMap<V2beta1ResourceMetricSource, V2MetricTarget>() .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.TargetAverageValue)) .ForMember(dest => dest.Value, opt => opt.Ignore()) .ForMember(dest => dest.Type, opt => opt.MapFrom((src, dest) => src.TargetAverageValue != null ? "AverageValue" : "Utilization")) .ForMember(dest => dest.AverageUtilization, opt => opt.MapFrom(src => src.TargetAverageUtilization)); cfg.CreateMap<V2beta1ResourceMetricSource, V2beta2ResourceMetricSource>() .ForMember(dest => dest.Target, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2beta2ResourceMetricSource, V2beta1ResourceMetricSource>() .ForMember(dest => dest.TargetAverageUtilization, opt => opt.MapFrom(src => src.Target.AverageUtilization)) .ForMember(dest => dest.TargetAverageValue, opt => opt.MapFrom(src => src.Target.Value)); cfg.CreateMap<V2beta1ResourceMetricSource, V2ResourceMetricSource>() .ForMember(dest => dest.Target, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2ResourceMetricSource, V2beta1ResourceMetricSource>() .ForMember(dest => dest.TargetAverageUtilization, opt => opt.MapFrom(src => src.Target.AverageUtilization)) .ForMember(dest => dest.TargetAverageValue, opt => opt.MapFrom(src => src.Target.Value)); cfg.CreateMap<V2beta1PodsMetricStatus, V2beta2MetricValueStatus>() .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.CurrentAverageValue)) .ForMember(dest => dest.Value, opt => opt.Ignore()) .ForMember(dest => dest.AverageUtilization, opt => opt.Ignore()); cfg.CreateMap<V2beta1PodsMetricStatus, V2MetricValueStatus>() .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.CurrentAverageValue)) .ForMember(dest => dest.Value, opt => opt.Ignore()) .ForMember(dest => dest.AverageUtilization, opt => opt.Ignore()); cfg.CreateMap<V2beta1PodsMetricStatus, V2beta2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Selector)); cfg.CreateMap<V2beta1PodsMetricStatus, V2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Selector)); cfg.CreateMap<V2beta1PodsMetricStatus, V2beta2PodsMetricStatus>() .ForMember(dest => dest.Current, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.Metric, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2beta2PodsMetricStatus, V2beta1PodsMetricStatus>() .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Metric.Selector)) .ForMember(dest => dest.CurrentAverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(dest => dest.MetricName, opt => opt.MapFrom(src => src.Metric.Name)); cfg.CreateMap<V2beta1PodsMetricStatus, V2PodsMetricStatus>() .ForMember(dest => dest.Current, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.Metric, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2PodsMetricStatus, V2beta1PodsMetricStatus>() .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Metric.Selector)) .ForMember(dest => dest.CurrentAverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(dest => dest.MetricName, opt => opt.MapFrom(src => src.Metric.Name)); cfg.CreateMap<V2beta1PodsMetricSource, V2beta2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Selector)) .ReverseMap(); cfg.CreateMap<V2beta1PodsMetricSource, V2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Selector)) .ReverseMap(); cfg.CreateMap<V2beta1PodsMetricSource, V2beta2MetricTarget>() .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.TargetAverageValue)) .ForMember(dest => dest.Type, opt => opt.MapFrom((src, dest) => "AverageValue")) .ForMember(dest => dest.Value, opt => opt.Ignore()) .ForMember(dest => dest.AverageUtilization, opt => opt.Ignore()); cfg.CreateMap<V2beta1PodsMetricSource, V2MetricTarget>() .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.TargetAverageValue)) .ForMember(dest => dest.Type, opt => opt.MapFrom((src, dest) => "AverageValue")) .ForMember(dest => dest.Value, opt => opt.Ignore()) .ForMember(dest => dest.AverageUtilization, opt => opt.Ignore()); cfg.CreateMap<V2beta1PodsMetricSource, V2beta2PodsMetricSource>() .ForMember(dest => dest.Metric, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.Target, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2beta2PodsMetricSource, V2beta1PodsMetricSource>() .ForMember(x => x.Selector, opt => opt.MapFrom(src => src.Metric.Selector)) .ForMember(x => x.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(x => x.TargetAverageValue, opt => opt.MapFrom(src => src.Target.AverageValue)); cfg.CreateMap<V2beta1PodsMetricSource, V2PodsMetricSource>() .ForMember(dest => dest.Metric, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.Target, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2PodsMetricSource, V2beta1PodsMetricSource>() .ForMember(x => x.Selector, opt => opt.MapFrom(src => src.Metric.Selector)) .ForMember(x => x.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(x => x.TargetAverageValue, opt => opt.MapFrom(src => src.Target.AverageValue)); cfg.CreateMap<V2beta1ObjectMetricStatus, V2beta2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Selector)) .ReverseMap(); cfg.CreateMap<V2beta1ObjectMetricStatus, V2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Selector)) .ReverseMap(); cfg.CreateMap<V2beta1ObjectMetricStatus, V2beta2MetricValueStatus>() .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.CurrentValue)) .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.AverageValue)) .ForMember(dest => dest.AverageUtilization, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V2beta1ObjectMetricStatus, V2MetricValueStatus>() .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.CurrentValue)) .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.AverageValue)) .ForMember(dest => dest.AverageUtilization, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V2beta1ObjectMetricStatus, V2beta2ObjectMetricStatus>() .ForMember(x => x.Current, opt => opt.MapFrom(src => src)) .ForMember(x => x.Metric, opt => opt.MapFrom(src => src)) .ForMember(x => x.DescribedObject, opt => opt.MapFrom(src => src.Target)); cfg.CreateMap<V2beta2ObjectMetricStatus, V2beta1ObjectMetricStatus>() .ForMember(x => x.CurrentValue, opt => opt.MapFrom(src => src.Current.Value)) .ForMember(x => x.AverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(x => x.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(x => x.Target, opt => opt.MapFrom(src => src.DescribedObject)) .ForMember(x => x.Selector, opt => opt.MapFrom(src => src.Metric.Selector)); cfg.CreateMap<V2beta1ObjectMetricStatus, V2ObjectMetricStatus>() .ForMember(x => x.Current, opt => opt.MapFrom(src => src)) .ForMember(x => x.Metric, opt => opt.MapFrom(src => src)) .ForMember(x => x.DescribedObject, opt => opt.MapFrom(src => src.Target)); cfg.CreateMap<V2ObjectMetricStatus, V2beta1ObjectMetricStatus>() .ForMember(x => x.CurrentValue, opt => opt.MapFrom(src => src.Current.Value)) .ForMember(x => x.AverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(x => x.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(x => x.Target, opt => opt.MapFrom(src => src.DescribedObject)) .ForMember(x => x.Selector, opt => opt.MapFrom(src => src.Metric.Selector)); cfg.CreateMap<V2beta1ExternalMetricSource, V2beta2MetricTarget>() .ForMember(x => x.Value, opt => opt.MapFrom(src => src.TargetValue)) .ForMember(x => x.AverageValue, opt => opt.MapFrom(src => src.TargetAverageValue)) .ForMember(x => x.AverageUtilization, opt => opt.Ignore()) .ForMember(x => x.Type, opt => opt.MapFrom((src, dest) => src.TargetValue != null ? "Value" : "AverageValue")); cfg.CreateMap<V2beta1ExternalMetricSource, V2MetricTarget>() .ForMember(x => x.Value, opt => opt.MapFrom(src => src.TargetValue)) .ForMember(x => x.AverageValue, opt => opt.MapFrom(src => src.TargetAverageValue)) .ForMember(x => x.AverageUtilization, opt => opt.Ignore()) .ForMember(x => x.Type, opt => opt.MapFrom((src, dest) => src.TargetValue != null ? "Value" : "AverageValue")); cfg.CreateMap<V2beta1ExternalMetricSource, V2beta2ExternalMetricSource>() .ForMember(x => x.Metric, opt => opt.MapFrom(src => src)) .ForMember(x => x.Target, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2beta2ExternalMetricSource, V2beta1ExternalMetricSource>() .ForMember(x => x.TargetValue, opt => opt.MapFrom(src => src.Target.Value)) .ForMember(x => x.TargetAverageValue, opt => opt.MapFrom(src => src.Target.AverageValue)) .ForMember(x => x.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(x => x.MetricSelector, opt => opt.MapFrom(src => src.Metric.Selector)); cfg.CreateMap<V2beta1ExternalMetricSource, V2ExternalMetricSource>() .ForMember(x => x.Metric, opt => opt.MapFrom(src => src)) .ForMember(x => x.Target, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2ExternalMetricSource, V2beta1ExternalMetricSource>() .ForMember(x => x.TargetValue, opt => opt.MapFrom(src => src.Target.Value)) .ForMember(x => x.TargetAverageValue, opt => opt.MapFrom(src => src.Target.AverageValue)) .ForMember(x => x.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(x => x.MetricSelector, opt => opt.MapFrom(src => src.Metric.Selector)); cfg.CreateMap<V2beta1ExternalMetricStatus, V2beta2ExternalMetricStatus>() .ForMember(x => x.Current, opt => opt.MapFrom(src => src)) .ForMember(x => x.Metric, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2beta2ExternalMetricStatus, V2beta1ExternalMetricStatus>() .ForMember(x => x.CurrentValue, opt => opt.MapFrom(src => src.Current.Value)) .ForMember(x => x.CurrentAverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(x => x.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(x => x.MetricSelector, opt => opt.MapFrom(src => src.Metric.Selector)); cfg.CreateMap<V2beta1ExternalMetricStatus, V2ExternalMetricStatus>() .ForMember(x => x.Current, opt => opt.MapFrom(src => src)) .ForMember(x => x.Metric, opt => opt.MapFrom(src => src)); cfg.CreateMap<V2ExternalMetricStatus, V2beta1ExternalMetricStatus>() .ForMember(x => x.CurrentValue, opt => opt.MapFrom(src => src.Current.Value)) .ForMember(x => x.CurrentAverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(x => x.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(x => x.MetricSelector, opt => opt.MapFrom(src => src.Metric.Selector)); cfg.CreateMap<V2beta1ExternalMetricStatus, V2beta2MetricIdentifier>() .ForMember(x => x.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(x => x.Selector, opt => opt.MapFrom(src => src.MetricSelector)) .ReverseMap(); cfg.CreateMap<V2beta1ExternalMetricStatus, V2MetricIdentifier>() .ForMember(x => x.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(x => x.Selector, opt => opt.MapFrom(src => src.MetricSelector)) .ReverseMap(); cfg.CreateMap<V2beta1ExternalMetricStatus, V2beta2MetricValueStatus>() .ForMember(x => x.Value, opt => opt.MapFrom(src => src.CurrentValue)) .ForMember(x => x.AverageValue, opt => opt.MapFrom(src => src.CurrentAverageValue)) .ForMember(x => x.AverageUtilization, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V2beta1ExternalMetricStatus, V2MetricValueStatus>() .ForMember(x => x.Value, opt => opt.MapFrom(src => src.CurrentValue)) .ForMember(x => x.AverageValue, opt => opt.MapFrom(src => src.CurrentAverageValue)) .ForMember(x => x.AverageUtilization, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V2beta1ObjectMetricSource, V2beta2MetricTarget>() .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.TargetValue)) .ForMember(dest => dest.AverageUtilization, opt => opt.Ignore()) .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.AverageValue)) .ForMember(dest => dest.Type, opt => opt.MapFrom((src, dest) => src.TargetValue != null ? "Value" : "AverageValue")); cfg.CreateMap<V2beta1ObjectMetricSource, V2MetricTarget>() .ForMember(dest => dest.Value, opt => opt.MapFrom(src => src.TargetValue)) .ForMember(dest => dest.AverageUtilization, opt => opt.Ignore()) .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.AverageValue)) .ForMember(dest => dest.Type, opt => opt.MapFrom((src, dest) => src.TargetValue != null ? "Value" : "AverageValue")); cfg.CreateMap<V2beta1ObjectMetricSource, V2beta2ObjectMetricSource>() .ForMember(dest => dest.Metric, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.Target, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.DescribedObject, opt => opt.MapFrom(src => src.Target)); cfg.CreateMap<V2beta2ObjectMetricSource, V2beta1ObjectMetricSource>() .ForMember(dest => dest.Target, opt => opt.MapFrom(src => src.DescribedObject)) .ForMember(dest => dest.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(dest => dest.TargetValue, opt => opt.MapFrom(src => src.Target.Value)) .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.Target.AverageValue)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Metric.Selector)); cfg.CreateMap<V2beta1ObjectMetricSource, V2ObjectMetricSource>() .ForMember(dest => dest.Metric, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.Target, opt => opt.MapFrom(src => src)) .ForMember(dest => dest.DescribedObject, opt => opt.MapFrom(src => src.Target)); cfg.CreateMap<V2ObjectMetricSource, V2beta1ObjectMetricSource>() .ForMember(dest => dest.Target, opt => opt.MapFrom(src => src.DescribedObject)) .ForMember(dest => dest.MetricName, opt => opt.MapFrom(src => src.Metric.Name)) .ForMember(dest => dest.TargetValue, opt => opt.MapFrom(src => src.Target.Value)) .ForMember(dest => dest.AverageValue, opt => opt.MapFrom(src => src.Target.AverageValue)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Metric.Selector)); cfg.CreateMap<V2beta1ObjectMetricSource, V2beta2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Selector)) .ReverseMap(); cfg.CreateMap<V2beta1ObjectMetricSource, V2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.Selector)) .ReverseMap(); cfg.CreateMap<V2beta1ExternalMetricSource, V2beta2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.MetricSelector)); cfg.CreateMap<V2beta1ExternalMetricSource, V2MetricIdentifier>() .ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.MetricName)) .ForMember(dest => dest.Selector, opt => opt.MapFrom(src => src.MetricSelector)); cfg.CreateMap<V2beta2MetricTarget, V2beta1ExternalMetricSource>() // todo: not needed .ForMember(dest => dest.MetricName, opt => opt.Ignore()) .ForMember(dest => dest.MetricSelector, opt => opt.Ignore()) .ForMember(dest => dest.TargetValue, opt => opt.MapFrom(src => src.Value)) .ForMember(dest => dest.TargetValue, opt => opt.MapFrom(src => src.Value)) .ForMember(dest => dest.TargetAverageValue, opt => opt.MapFrom(src => src.AverageValue)); cfg.CreateMap<V1HorizontalPodAutoscalerSpec, V2beta2HorizontalPodAutoscalerSpec>() .ForMember(dest => dest.Metrics, opt => opt.Ignore()) .ForMember(dest => dest.Behavior, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V1HorizontalPodAutoscalerSpec, V2HorizontalPodAutoscalerSpec>() .ForMember(dest => dest.Metrics, opt => opt.Ignore()) .ForMember(dest => dest.Behavior, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V1HorizontalPodAutoscalerSpec, V2beta1HorizontalPodAutoscalerSpec>() .ForMember(dest => dest.Metrics, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V2beta1HorizontalPodAutoscalerSpec, V2beta2HorizontalPodAutoscalerSpec>() .ForMember(dest => dest.Behavior, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V2beta1HorizontalPodAutoscalerSpec, V2HorizontalPodAutoscalerSpec>() .ForMember(dest => dest.Behavior, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V1HorizontalPodAutoscalerStatus, V2beta1HorizontalPodAutoscalerStatus>() .ForMember(dest => dest.Conditions, opt => opt.Ignore()) .ForMember(dest => dest.CurrentMetrics, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V1HorizontalPodAutoscalerStatus, V2beta2HorizontalPodAutoscalerStatus>() .ForMember(dest => dest.Conditions, opt => opt.Ignore()) .ForMember(dest => dest.CurrentMetrics, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V1HorizontalPodAutoscalerStatus, V2HorizontalPodAutoscalerStatus>() .ForMember(dest => dest.Conditions, opt => opt.Ignore()) .ForMember(dest => dest.CurrentMetrics, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<Corev1EventSeries, V1beta1EventSeries>() .ForMember(dest => dest.LastObservedTime, opt => opt.MapFrom(src => src.LastObservedTime)) .ReverseMap(); cfg.CreateMap<Corev1Event, V1beta1Event>() .ForMember(dest => dest.DeprecatedCount, opt => opt.Ignore()) .ForMember(dest => dest.DeprecatedFirstTimestamp, opt => opt.MapFrom(src => src.FirstTimestamp)) .ForMember(dest => dest.DeprecatedLastTimestamp, opt => opt.MapFrom(src => src.LastTimestamp)) .ForMember(dest => dest.DeprecatedSource, opt => opt.MapFrom(src => src.Source)) .ForMember(dest => dest.Note, opt => opt.MapFrom(src => src.Message)) .ForMember(dest => dest.Regarding, opt => opt.MapFrom(src => src.InvolvedObject)) .ForMember(dest => dest.ReportingController, opt => opt.MapFrom(src => src.ReportingComponent)) .ReverseMap(); cfg.CreateMap<V2beta2ContainerResourceMetricSource, V2beta1ContainerResourceMetricSource>() .ForMember(dest => dest.TargetAverageValue, opt => opt.MapFrom(src => src.Target.AverageValue)) .ForMember(dest => dest.TargetAverageUtilization, opt => opt.MapFrom(src => src.Target.AverageUtilization)) .ReverseMap(); cfg.CreateMap<V2ContainerResourceMetricSource, V2beta1ContainerResourceMetricSource>() .ForMember(dest => dest.TargetAverageValue, opt => opt.MapFrom(src => src.Target.AverageValue)) .ForMember(dest => dest.TargetAverageUtilization, opt => opt.MapFrom(src => src.Target.AverageUtilization)) .ReverseMap(); cfg.CreateMap<V2beta2ContainerResourceMetricStatus, V2beta1ContainerResourceMetricStatus>() .ForMember(dest => dest.CurrentAverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(dest => dest.CurrentAverageUtilization, opt => opt.MapFrom(src => src.Current.AverageUtilization)) .ReverseMap(); cfg.CreateMap<V2ContainerResourceMetricStatus, V2beta1ContainerResourceMetricStatus>() .ForMember(dest => dest.CurrentAverageValue, opt => opt.MapFrom(src => src.Current.AverageValue)) .ForMember(dest => dest.CurrentAverageUtilization, opt => opt.MapFrom(src => src.Current.AverageUtilization)) .ReverseMap(); cfg.CreateMap<V1beta1Endpoint, V1Endpoint>() .ForMember(dest => dest.DeprecatedTopology, opt => opt.Ignore()) .ForMember(dest => dest.Zone, opt => opt.Ignore()) .ReverseMap(); cfg.CreateMap<V1beta1EndpointPort, Discoveryv1EndpointPort>() .ReverseMap(); } } }
//--------------------------------------------------------------------- // <copyright file="Database.cs" company="Microsoft Corporation"> // Copyright (c) 1999, Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Part of the Deployment Tools Foundation project. // </summary> //--------------------------------------------------------------------- namespace Microsoft.PackageManagement.Msi.Internal.Deployment.WindowsInstaller { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; /// <summary> /// Accesses a Windows Installer database. /// </summary> /// <remarks><p> /// The <see cref="Commit"/> method must be called before the Database is closed to write out all /// persistent changes. If the Commit method is not called, the installer performs an implicit /// rollback upon object destruction. /// </p><p> /// The client can use the following procedure for data access:<list type="number"> /// <item><description>Obtain a Database object using one of the Database constructors.</description></item> /// <item><description>Initiate a query using a SQL string by calling the <see cref="OpenView"/> /// method of the Database.</description></item> /// <item><description>Set query parameters in a <see cref="Record"/> and execute the database /// query by calling the <see cref="View.Execute(Record)"/> method of the <see cref="View"/>. This /// produces a result that can be fetched or updated.</description></item> /// <item><description>Call the <see cref="View.Fetch"/> method of the View repeatedly to return /// Records.</description></item> /// <item><description>Update database rows of a Record object obtained by the Fetch method using /// one of the <see cref="View.Modify"/> methods of the View.</description></item> /// <item><description>Release the query and any unfetched records by calling the <see cref="InstallerHandle.Close"/> /// method of the View.</description></item> /// <item><description>Persist any database updates by calling the Commit method of the Database. /// </description></item> /// </list> /// </p></remarks> internal partial class Database : InstallerHandle { private string filePath; private DatabaseOpenMode openMode; private SummaryInfo summaryInfo; private TableCollection tables; private IList<string> deleteOnClose; /// <summary> /// Opens an existing database in read-only mode. /// </summary> /// <param name="filePath">Path to the database file.</param> /// <exception cref="InstallerException">the database could not be created/opened</exception> /// <remarks><p> /// Because this constructor initiates database access, it cannot be used with a /// running installation. /// </p><p> /// The Database object should be <see cref="InstallerHandle.Close"/>d after use. /// It is best that the handle be closed manually as soon as it is no longer /// needed, as leaving lots of unused handles open can degrade performance. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiopendatabase.asp">MsiOpenDatabase</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public Database(string filePath) : this(filePath, DatabaseOpenMode.ReadOnly) { } /// <summary> /// Opens an existing database with another database as output. /// </summary> /// <param name="filePath">Path to the database to be read.</param> /// <param name="outputPath">Open mode for the database</param> /// <returns>Database object representing the created or opened database</returns> /// <exception cref="InstallerException">the database could not be created/opened</exception> /// <remarks><p> /// When a database is opened as the output of another database, the summary information stream /// of the output database is actually a read-only mirror of the original database and thus cannot /// be changed. Additionally, it is not persisted with the database. To create or modify the /// summary information for the output database it must be closed and re-opened. /// </p><p> /// The Database object should be <see cref="InstallerHandle.Close"/>d after use. /// It is best that the handle be closed manually as soon as it is no longer /// needed, as leaving lots of unused handles open can degrade performance. /// </p><p> /// The database is opened in <see cref="DatabaseOpenMode.CreateDirect" /> mode, and will be /// automatically commited when it is closed. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiopendatabase.asp">MsiOpenDatabase</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public Database(string filePath, string outputPath) : this((IntPtr) Database.Open(filePath, outputPath), true, outputPath, DatabaseOpenMode.CreateDirect) { } /// <summary> /// Opens an existing database or creates a new one. /// </summary> /// <param name="filePath">Path to the database file. If an empty string /// is supplied, a temporary database is created that is not persisted.</param> /// <param name="mode">Open mode for the database</param> /// <exception cref="InstallerException">the database could not be created/opened</exception> /// <remarks><p> /// Because this constructor initiates database access, it cannot be used with a /// running installation. /// </p><p> /// The database object should be <see cref="InstallerHandle.Close"/>d after use. /// The finalizer will close the handle if it is still open, however due to the nondeterministic /// nature of finalization it is best that the handle be closed manually as soon as it is no /// longer needed, as leaving lots of unused handles open can degrade performance. /// </p><p> /// A database opened in <see cref="DatabaseOpenMode.CreateDirect" /> or /// <see cref="DatabaseOpenMode.Direct" /> mode will be automatically commited when it is /// closed. However a database opened in <see cref="DatabaseOpenMode.Create" /> or /// <see cref="DatabaseOpenMode.Transact" /> mode must have the <see cref="Commit" /> method /// called before it is closed, otherwise no changes will be persisted. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msiopendatabase.asp">MsiOpenDatabase</a> /// </p></remarks> public Database(string filePath, DatabaseOpenMode mode) : this((IntPtr) Database.Open(filePath, mode), true, filePath, mode) { } /// <summary> /// Creates a new database from an MSI handle. /// </summary> /// <param name="handle">Native MSI database handle.</param> /// <param name="ownsHandle">True if the handle should be closed /// when the database object is disposed</param> /// <param name="filePath">Path of the database file, if known</param> /// <param name="openMode">Mode the handle was originally opened in</param> protected internal Database( IntPtr handle, bool ownsHandle, string filePath, DatabaseOpenMode openMode) : base(handle, ownsHandle) { this.filePath = filePath; this.openMode = openMode; } /// <summary> /// Gets the file path the Database was originally opened from, or null if not known. /// </summary> public String FilePath { get { return this.filePath; } } /// <summary> /// Gets the open mode for the database. /// </summary> public DatabaseOpenMode OpenMode { get { return this.openMode; } } /// <summary> /// Gets a boolean value indicating whether this database was opened in read-only mode. /// </summary> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetdatabasestate.asp">MsiGetDatabaseState</a> /// </p></remarks> public bool IsReadOnly { get { if (RemotableNativeMethods.RemotingEnabled) { return true; } int state = NativeMethods.MsiGetDatabaseState((int) this.Handle); return state != 1; } } /// <summary> /// Gets the collection of tables in the Database. /// </summary> public TableCollection Tables { get { if (this.tables == null) { this.tables = new TableCollection(this); } return this.tables; } } /// <summary> /// Gets or sets the code page of the Database. /// </summary> /// <exception cref="IOException">error exporting/importing the codepage data</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// Getting or setting the code page is a slow operation because it involves an export or import /// of the codepage data to/from a temporary file. /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public int CodePage { get { string tempFile = Path.GetTempFileName(); StreamReader reader = null; try { this.Export("_ForceCodepage", tempFile); reader = File.OpenText(tempFile); reader.ReadLine(); // Skip column name record. reader.ReadLine(); // Skip column defn record. string codePageLine = reader.ReadLine(); return Int32.Parse(codePageLine.Split('\t')[0], CultureInfo.InvariantCulture.NumberFormat); } finally { if (reader != null) reader.Close(); File.Delete(tempFile); } } set { string tempFile = Path.GetTempFileName(); StreamWriter writer = null; try { writer = File.AppendText(tempFile); writer.WriteLine(""); writer.WriteLine(""); writer.WriteLine("{0}\t_ForceCodepage", value); writer.Close(); writer = null; this.Import(tempFile); } finally { if (writer != null) writer.Close(); File.Delete(tempFile); } } } /// <summary> /// Gets the SummaryInfo object for this database that can be used to examine and modify properties /// to the summary information stream. /// </summary> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// The object returned from this property does not need to be explicitly persisted or closed. /// Any modifications will be automatically saved when the database is committed. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msigetsummaryinformation.asp">MsiGetSummaryInformation</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public SummaryInfo SummaryInfo { get { if (this.summaryInfo == null || this.summaryInfo.IsClosed) { lock (this.Sync) { if (this.summaryInfo == null || this.summaryInfo.IsClosed) { int summaryInfoHandle; int maxProperties = this.IsReadOnly ? 0 : SummaryInfo.MAX_PROPERTIES; uint ret = RemotableNativeMethods.MsiGetSummaryInformation((int) this.Handle, null, (uint) maxProperties, out summaryInfoHandle); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } this.summaryInfo = new SummaryInfo((IntPtr) summaryInfoHandle, true); } } } return this.summaryInfo; } } /// <summary> /// Creates a new Database object from an integer database handle. /// </summary> /// <remarks><p> /// This method is only provided for interop purposes. A Database object /// should normally be obtained from <see cref="Session.Database"/> or /// a public Database constructor. /// </p></remarks> /// <param name="handle">Integer database handle</param> /// <param name="ownsHandle">true to close the handle when this object is disposed</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public static Database FromHandle(IntPtr handle, bool ownsHandle) { return new Database( handle, ownsHandle, null, NativeMethods.MsiGetDatabaseState((int) handle) == 1 ? DatabaseOpenMode.Direct : DatabaseOpenMode.ReadOnly); } /// <summary> /// Schedules a file or directory for deletion after the database handle is closed. /// </summary> /// <param name="path">File or directory path to be deleted. All files and subdirectories /// under a directory are deleted.</param> /// <remarks><p> /// Once an item is scheduled, it cannot be unscheduled. /// </p><p> /// The items cannot be deleted if the Database object is auto-disposed by the /// garbage collector; the handle must be explicitly closed. /// </p><p> /// Files which are read-only or otherwise locked cannot be deleted, /// but they will not cause an exception to be thrown. /// </p></remarks> public void DeleteOnClose(string path) { if (this.deleteOnClose == null) { this.deleteOnClose = new List<string>(); } this.deleteOnClose.Add(path); } /// <summary> /// Merges another database with this database. /// </summary> /// <param name="otherDatabase">The database to be merged into this database</param> /// <param name="errorTable">Optional name of table to contain the names of the tables containing /// merge conflicts, the number of conflicting rows within the table, and a reference to the table /// with the merge conflict.</param> /// <exception cref="MergeException">merge failed due to a schema difference or data conflict</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// Merge does not copy over embedded cabinet files or embedded transforms from the /// reference database into the target database. Embedded data streams that are listed in the /// Binary table or Icon table are copied from the reference database to the target database. /// Storage embedded in the reference database are not copied to the target database. /// </p><p> /// The Merge method merges the data of two databases. These databases must have the same /// codepage. The merge fails if any tables or rows in the databases conflict. A conflict exists /// if the data in any row in the first database differs from the data in the corresponding row /// of the second database. Corresponding rows are in the same table of both databases and have /// the same primary key in both databases. The tables of non-conflicting databases must have /// the same number of primary keys, same number of columns, same column types, same column names, /// and the same data in rows with identical primary keys. Temporary columns however don't matter /// in the column count and corresponding tables can have a different number of temporary columns /// without creating conflict as long as the persistent columns match. /// </p><p> /// If the number, type, or name of columns in corresponding tables are different, the /// schema of the two databases are incompatible and the installer will stop processing tables /// and the merge fails. The installer checks that the two databases have the same schema before /// checking for row merge conflicts. If the schemas are incompatible, the databases have be /// modified. /// </p><p> /// If the data in particular rows differ, this is a row merge conflict, the merge fails /// and creates a new table with the specified name. The first column of this table is the name /// of the table having the conflict. The second column gives the number of rows in the table /// having the conflict. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidatabasemerge.asp">MsiDatabaseMerge</a> /// </p></remarks> [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void Merge(Database otherDatabase, string errorTable) { if (otherDatabase == null) { throw new ArgumentNullException("otherDatabase"); } uint ret = NativeMethods.MsiDatabaseMerge((int) this.Handle, (int) otherDatabase.Handle, errorTable); if (ret != 0) { if (ret == (uint) NativeMethods.Error.FUNCTION_FAILED) { throw new MergeException(this, errorTable); } else if (ret == (uint) NativeMethods.Error.DATATYPE_MISMATCH) { throw new MergeException("Schema difference between the two databases."); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } } /// <summary> /// Merges another database with this database. /// </summary> /// <param name="otherDatabase">The database to be merged into this database</param> /// <exception cref="MergeException">merge failed due to a schema difference or data conflict</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// MsiDatabaseMerge does not copy over embedded cabinet files or embedded transforms from /// the reference database into the target database. Embedded data streams that are listed in /// the Binary table or Icon table are copied from the reference database to the target database. /// Storage embedded in the reference database are not copied to the target database. /// </p><p> /// The Merge method merges the data of two databases. These databases must have the same /// codepage. The merge fails if any tables or rows in the databases conflict. A conflict exists /// if the data in any row in the first database differs from the data in the corresponding row /// of the second database. Corresponding rows are in the same table of both databases and have /// the same primary key in both databases. The tables of non-conflicting databases must have /// the same number of primary keys, same number of columns, same column types, same column names, /// and the same data in rows with identical primary keys. Temporary columns however don't matter /// in the column count and corresponding tables can have a different number of temporary columns /// without creating conflict as long as the persistent columns match. /// </p><p> /// If the number, type, or name of columns in corresponding tables are different, the /// schema of the two databases are incompatible and the installer will stop processing tables /// and the merge fails. The installer checks that the two databases have the same schema before /// checking for row merge conflicts. If the schemas are incompatible, the databases have be /// modified. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidatabasemerge.asp">MsiDatabaseMerge</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void Merge(Database otherDatabase) { this.Merge(otherDatabase, null); } /// <summary> /// Checks whether a table exists and is persistent in the database. /// </summary> /// <param name="table">The table to the checked</param> /// <returns>true if the table exists and is persistent in the database; false otherwise</returns> /// <exception cref="ArgumentException">the table is unknown</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// To check whether a table exists regardless of persistence, /// use <see cref="TableCollection.Contains"/>. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidatabaseistablepersistent.asp">MsiDatabaseIsTablePersistent</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public bool IsTablePersistent(string table) { if (string.IsNullOrWhiteSpace(table)) { throw new ArgumentNullException("table"); } uint ret = RemotableNativeMethods.MsiDatabaseIsTablePersistent((int) this.Handle, table); if (ret == 3) // MSICONDITION_ERROR { throw new InstallerException(); } return ret == 1; } /// <summary> /// Checks whether a table contains a persistent column with a given name. /// </summary> /// <param name="table">The table to the checked</param> /// <param name="column">The name of the column to be checked</param> /// <returns>true if the column exists in the table; false if the column is temporary or does not exist.</returns> /// <exception cref="InstallerException">the View could not be executed</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// To check whether a column exists regardless of persistence, /// use <see cref="ColumnCollection.Contains"/>. /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public bool IsColumnPersistent(string table, string column) { if (string.IsNullOrWhiteSpace(table)) { throw new ArgumentNullException("table"); } if (string.IsNullOrWhiteSpace(column)) { throw new ArgumentNullException("column"); } using (View view = this.OpenView( "SELECT `Number` FROM `_Columns` WHERE `Table` = '{0}' AND `Name` = '{1}'", table, column)) { view.Execute(); using (Record rec = view.Fetch()) { return (rec != null); } } } /// <summary> /// Gets the count of all rows in the table. /// </summary> /// <param name="table">Name of the table whose rows are to be counted</param> /// <returns>The count of all rows in the table</returns> /// <exception cref="InstallerException">the View could not be executed</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> public int CountRows(string table) { return this.CountRows(table, null); } /// <summary> /// Gets the count of all rows in the table that satisfy a given condition. /// </summary> /// <param name="table">Name of the table whose rows are to be counted</param> /// <param name="where">Conditional expression, such as could be placed on the end of a SQL WHERE clause</param> /// <returns>The count of all rows in the table satisfying the condition</returns> /// <exception cref="BadQuerySyntaxException">the SQL WHERE syntax is invalid</exception> /// <exception cref="InstallerException">the View could not be executed</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> public int CountRows(string table, string where) { if (string.IsNullOrWhiteSpace(table)) { throw new ArgumentNullException("table"); } int count; using (View view = this.OpenView( "SELECT `{0}` FROM `{1}`{2}", this.Tables[table].PrimaryKeys[0], table, (where != null && where.Length != 0 ? " WHERE " + where : ""))) { view.Execute(); for (count = 0; ; count++) { // Avoid creating unnecessary Record objects by not calling View.Fetch(). int recordHandle; uint ret = RemotableNativeMethods.MsiViewFetch((int) view.Handle, out recordHandle); if (ret == (uint) NativeMethods.Error.NO_MORE_ITEMS) { break; } if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } RemotableNativeMethods.MsiCloseHandle(recordHandle); } } return count; } /// <summary> /// Finalizes the persistent form of the database. All persistent data is written /// to the writeable database, and no temporary columns or rows are written. /// </summary> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// For a database open in <see cref="DatabaseOpenMode.ReadOnly"/> mode, this method has no effect. /// </p><p> /// For a database open in <see cref="DatabaseOpenMode.CreateDirect" /> or <see cref="DatabaseOpenMode.Direct" /> /// mode, it is not necessary to call this method because the database will be automatically committed /// when it is closed. However this method may be called at any time to persist the current state of tables /// loaded into memory. /// </p><p> /// For a database open in <see cref="DatabaseOpenMode.Create" /> or <see cref="DatabaseOpenMode.Transact" /> /// mode, no changes will be persisted until this method is called. If the database object is closed without /// calling this method, the database file remains unmodified. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidatabasecommit.asp">MsiDatabaseCommit</a> /// </p></remarks> public void Commit() { if (this.summaryInfo != null && !this.summaryInfo.IsClosed) { this.summaryInfo.Persist(); this.summaryInfo.Close(); this.summaryInfo = null; } uint ret = NativeMethods.MsiDatabaseCommit((int) this.Handle); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } } /// <summary> /// Copies the structure and data from a specified table to a text archive file. /// </summary> /// <param name="table">Name of the table to be exported</param> /// <param name="exportFilePath">Path to the file to be created</param> /// <exception cref="FileNotFoundException">the file path is invalid</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidatabaseexport.asp">MsiDatabaseExport</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void Export(string table, string exportFilePath) { if (table == null) { throw new ArgumentNullException("table"); } FileInfo file = new FileInfo(exportFilePath); uint ret = NativeMethods.MsiDatabaseExport((int) this.Handle, table, file.DirectoryName, file.Name); if (ret != 0) { if (ret == (uint) NativeMethods.Error.BAD_PATHNAME) { throw new FileNotFoundException(null, exportFilePath); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } } /// <summary> /// Imports a database table from a text archive file, dropping any existing table. /// </summary> /// <param name="importFilePath">Path to the file to be imported. /// The table name is specified within the file.</param> /// <exception cref="FileNotFoundException">the file path is invalid</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidatabaseimport.asp">MsiDatabaseImport</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void Import(string importFilePath) { if (string.IsNullOrWhiteSpace(importFilePath)) { throw new ArgumentNullException("importFilePath"); } FileInfo file = new FileInfo(importFilePath); uint ret = NativeMethods.MsiDatabaseImport((int) this.Handle, file.DirectoryName, file.Name); if (ret != 0) { if (ret == (uint) NativeMethods.Error.BAD_PATHNAME) { throw new FileNotFoundException(null, importFilePath); } else { throw InstallerException.ExceptionFromReturnCode(ret); } } } /// <summary> /// Exports all database tables, streams, and summary information to archive files. /// </summary> /// <param name="directoryPath">Path to the directory where archive files will be created</param> /// <exception cref="FileNotFoundException">the directory path is invalid</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// The directory will be created if it does not already exist. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidatabaseexport.asp">MsiDatabaseExport</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void ExportAll(string directoryPath) { if (string.IsNullOrWhiteSpace(directoryPath)) { throw new ArgumentNullException("directoryPath"); } if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } this.Export("_SummaryInformation", Path.Combine(directoryPath, "_SummaryInformation.idt")); using (View view = this.OpenView("SELECT `Name` FROM `_Tables`")) { view.Execute(); foreach (Record rec in view) using (rec) { string table = (string) rec[1]; this.Export(table, Path.Combine(directoryPath, table + ".idt")); } } if (!Directory.Exists(Path.Combine(directoryPath, "_Streams"))) { Directory.CreateDirectory(Path.Combine(directoryPath, "_Streams")); } using (View view = this.OpenView("SELECT `Name`, `Data` FROM `_Streams`")) { view.Execute(); foreach (Record rec in view) using (rec) { string stream = (string) rec[1]; if (stream.EndsWith("SummaryInformation", StringComparison.Ordinal)) continue; int i = stream.IndexOf('.'); if (i >= 0) { if (File.Exists(Path.Combine( directoryPath, Path.Combine(stream.Substring(0, i), stream.Substring(i + 1) + ".ibd")))) { continue; } } rec.GetStream(2, Path.Combine(directoryPath, Path.Combine("_Streams", stream))); } } } /// <summary> /// Imports all database tables, streams, and summary information from archive files. /// </summary> /// <param name="directoryPath">Path to the directory from which archive files will be imported</param> /// <exception cref="FileNotFoundException">the directory path is invalid</exception> /// <exception cref="InvalidHandleException">the Database handle is invalid</exception> /// <remarks><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msidatabaseimport.asp">MsiDatabaseImport</a> /// </p></remarks> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public void ImportAll(string directoryPath) { if (string.IsNullOrWhiteSpace(directoryPath)) { throw new ArgumentNullException("directoryPath"); } if (File.Exists(Path.Combine(directoryPath, "_SummaryInformation.idt"))) { this.Import(Path.Combine(directoryPath, "_SummaryInformation.idt")); } string[] idtFiles = Directory.GetFiles(directoryPath, "*.idt"); foreach (string file in idtFiles) { if (Path.GetFileName(file) != "_SummaryInformation.idt") { this.Import(file); } } if (Directory.Exists(Path.Combine(directoryPath, "_Streams"))) { View view = this.OpenView("SELECT `Name`, `Data` FROM `_Streams`"); Record rec = null; try { view.Execute(); string[] streamFiles = Directory.GetFiles(Path.Combine(directoryPath, "_Streams")); foreach (string file in streamFiles) { rec = this.CreateRecord(2); rec[1] = Path.GetFileName(file); rec.SetStream(2, file); view.Insert(rec); rec.Close(); rec = null; } } finally { if (rec != null) rec.Close(); view.Close(); } } } /// <summary> /// Creates a new record object with the requested number of fields. /// </summary> /// <param name="fieldCount">Required number of fields, which may be 0. /// The maximum number of fields in a record is limited to 65535.</param> /// <returns>A new record object that can be used with the database.</returns> /// <remarks><p> /// This method is equivalent to directly calling the <see cref="Record" /> /// constructor in all cases outside of a custom action context. When in a /// custom action session, this method allows creation of a record that can /// work with a database other than the session database. /// </p><p> /// The Record object should be <see cref="InstallerHandle.Close"/>d after use. /// It is best that the handle be closed manually as soon as it is no longer /// needed, as leaving lots of unused handles open can degrade performance. /// </p><p> /// Win32 MSI API: /// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/msicreaterecord.asp">MsiCreateRecord</a> /// </p></remarks> public Record CreateRecord(int fieldCount) { int hRecord = RemotableNativeMethods.MsiCreateRecord((uint) fieldCount, (int) this.Handle); return new Record((IntPtr) hRecord, true, (View) null); } /// <summary> /// Returns the file path of this database, or the handle value if a file path was not specified. /// </summary> public override string ToString() { if (this.FilePath != null) { return this.FilePath; } else { return "#" + ((int) this.Handle).ToString(CultureInfo.InvariantCulture); } } /// <summary> /// Closes the database handle. After closing a handle, further method calls may throw <see cref="InvalidHandleException"/>. /// </summary> /// <param name="disposing">If true, the method has been called directly or /// indirectly by a user's code, so managed and unmanaged resources will be /// disposed. If false, only unmanaged resources will be disposed.</param> protected override void Dispose(bool disposing) { if (!this.IsClosed && (this.OpenMode == DatabaseOpenMode.CreateDirect || this.OpenMode == DatabaseOpenMode.Direct)) { // Always commit a direct-opened database before closing. // This avoids unexpected corruption of the database. this.Commit(); } base.Dispose(disposing); if (disposing) { if (this.summaryInfo != null) { this.summaryInfo.Close(); this.summaryInfo = null; } if (this.deleteOnClose != null) { foreach (string path in this.deleteOnClose) { try { if (Directory.Exists(path)) { Directory.Delete(path, true); } else { if (File.Exists(path)) File.Delete(path); } } catch (IOException) { } catch (UnauthorizedAccessException) { } } this.deleteOnClose = null; } } } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] private static int Open(string filePath, string outputPath) { if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentNullException("filePath"); } if (string.IsNullOrWhiteSpace(outputPath)) { throw new ArgumentNullException("outputPath"); } int hDb; uint ret = NativeMethods.MsiOpenDatabase(filePath, outputPath, out hDb); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode(ret); } return hDb; } private static int Open(string filePath, DatabaseOpenMode mode) { if (string.IsNullOrWhiteSpace(filePath)) { throw new ArgumentNullException("filePath"); } if (Path.GetExtension(filePath).Equals(".msp", StringComparison.Ordinal)) { const int DATABASEOPENMODE_PATCH = 32; int patchMode = (int) mode | DATABASEOPENMODE_PATCH; mode = (DatabaseOpenMode) patchMode; } int hDb; uint ret = NativeMethods.MsiOpenDatabase(filePath, (IntPtr) mode, out hDb); if (ret != 0) { throw InstallerException.ExceptionFromReturnCode( ret, String.Format(CultureInfo.InvariantCulture, "Database=\"{0}\"", filePath)); } return hDb; } /// <summary> /// Returns the value of the specified property. /// </summary> /// <param name="property">Name of the property to retrieve.</param> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string ExecutePropertyQuery(string property) { IList<string> values = this.ExecuteStringQuery("SELECT `Value` FROM `Property` WHERE `Property` = '{0}'", property); return (values.Count > 0 ? values[0] : null); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class LastOrDefaultTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > Int32.MinValue select x; Assert.Equal(q.LastOrDefault(), q.LastOrDefault()); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty } where !String.IsNullOrEmpty(x) select x; Assert.Equal(q.LastOrDefault(), q.LastOrDefault()); } private static void TestEmptyIList<T>() { T[] source = { }; T expected = default(T); Assert.IsAssignableFrom<IList<T>>(source); Assert.Equal(expected, source.RunOnce().LastOrDefault()); } [Fact] public void EmptyIListT() { TestEmptyIList<int>(); TestEmptyIList<string>(); TestEmptyIList<DateTime>(); TestEmptyIList<LastOrDefaultTests>(); } [Fact] public void IListTOneElement() { int[] source = { 5 }; int expected = 5; Assert.IsAssignableFrom<IList<int>>(source); Assert.Equal(expected, source.LastOrDefault()); } [Fact] public void IListTManyElementsLastIsDefault() { int?[] source = { -10, 2, 4, 3, 0, 2, null }; int? expected = null; Assert.IsAssignableFrom<IList<int?>>(source); Assert.Equal(expected, source.LastOrDefault()); } [Fact] public void IListTManyElementsLastIsNotDefault() { int?[] source = { -10, 2, 4, 3, 0, 2, null, 19 }; int? expected = 19; Assert.IsAssignableFrom<IList<int?>>(source); Assert.Equal(expected, source.LastOrDefault()); } private static IEnumerable<T> EmptySource<T>() { yield break; } private static void TestEmptyNotIList<T>() { var source = EmptySource<T>(); T expected = default(T); Assert.Null(source as IList<T>); Assert.Equal(expected, source.RunOnce().LastOrDefault()); } [Fact] public void EmptyNotIListT() { TestEmptyNotIList<int>(); TestEmptyNotIList<string>(); TestEmptyNotIList<DateTime>(); TestEmptyNotIList<LastOrDefaultTests>(); } [Fact] public void OneElementNotIListT() { IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-5, 1); int expected = -5; Assert.Null(source as IList<int>); Assert.Equal(expected, source.LastOrDefault()); } [Fact] public void ManyElementsNotIListT() { IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(3, 10); int expected = 12; Assert.Null(source as IList<int>); Assert.Equal(expected, source.LastOrDefault()); } [Fact] public void EmptyIListSource() { int?[] source = { }; Assert.Null(source.LastOrDefault(x => true)); Assert.Null(source.LastOrDefault(x => false)); } [Fact] public void OneElementIListTruePredicate() { int[] source = { 4 }; Func<int, bool> predicate = IsEven; int expected = 4; Assert.Equal(expected, source.LastOrDefault(predicate)); } [Fact] public void ManyElementsIListPredicateFalseForAll() { int[] source = { 9, 5, 1, 3, 17, 21 }; Func<int, bool> predicate = IsEven; int expected = default(int); Assert.Equal(expected, source.LastOrDefault(predicate)); } [Fact] public void IListPredicateTrueOnlyForLast() { int[] source = { 9, 5, 1, 3, 17, 21, 50 }; Func<int, bool> predicate = IsEven; int expected = 50; Assert.Equal(expected, source.LastOrDefault(predicate)); } [Fact] public void IListPredicateTrueForSome() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 }; Func<int, bool> predicate = IsEven; int expected = 18; Assert.Equal(expected, source.LastOrDefault(predicate)); } [Fact] public void IListPredicateTrueForSomeRunOnce() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 }; Func<int, bool> predicate = IsEven; int expected = 18; Assert.Equal(expected, source.RunOnce().LastOrDefault(predicate)); } [Fact] public void EmptyNotIListSource() { IEnumerable<int?> source = Enumerable.Repeat((int?)4, 0); Assert.Null(source.LastOrDefault(x => true)); Assert.Null(source.LastOrDefault(x => false)); } [Fact] public void OneElementNotIListTruePredicate() { IEnumerable<int> source = ForceNotCollection(new[] { 4 }); Func<int, bool> predicate = IsEven; int expected = 4; Assert.Equal(expected, source.LastOrDefault(predicate)); } [Fact] public void ManyElementsNotIListPredicateFalseForAll() { IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21 }); Func<int, bool> predicate = IsEven; int expected = default(int); Assert.Equal(expected, source.LastOrDefault(predicate)); } [Fact] public void NotIListPredicateTrueOnlyForLast() { IEnumerable<int> source = ForceNotCollection(new int[] { 9, 5, 1, 3, 17, 21, 50 }); Func<int, bool> predicate = IsEven; int expected = 50; Assert.Equal(expected, source.LastOrDefault(predicate)); } [Fact] public void NotIListPredicateTrueForSome() { IEnumerable<int> source = ForceNotCollection(new int[] { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 }); Func<int, bool> predicate = IsEven; int expected = 18; Assert.Equal(expected, source.LastOrDefault(predicate)); } [Fact] public void NotIListPredicateTrueForSomeRunOnce() { IEnumerable<int> source = ForceNotCollection(new int[] { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 }); Func<int, bool> predicate = IsEven; int expected = 18; Assert.Equal(expected, source.RunOnce().LastOrDefault(predicate)); } [Fact] public void NullSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).LastOrDefault()); } [Fact] public void NullSourcePredicateUsed() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).LastOrDefault(i => i != 2)); } [Fact] public void NullPredicate() { Func<int, bool> predicate = null; AssertExtensions.Throws<ArgumentNullException>("predicate", () => Enumerable.Range(0, 3).LastOrDefault(predicate)); } } }
using System.IO; using System.Linq; using System.Text; using LibGit2Sharp.Tests.TestHelpers; using Xunit; namespace LibGit2Sharp.Tests { public class DiffTreeToTargetFixture : BaseFixture { private static void SetUpSimpleDiffContext(IRepository repo) { var fullpath = Touch(repo.Info.WorkingDirectory, "file.txt", "hello\n"); Commands.Stage(repo, fullpath); repo.Commit("Initial commit", Constants.Signature, Constants.Signature); File.AppendAllText(fullpath, "world\n"); Commands.Stage(repo,fullpath); File.AppendAllText(fullpath, "!!!\n"); } [Fact] /* * No direct git equivalent but should output * * diff --git a/file.txt b/file.txt * index ce01362..4f125e3 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1,3 @@ * hello * +world * +!!! */ public void CanCompareASimpleTreeAgainstTheWorkDir() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { SetUpSimpleDiffContext(repo); using (var changes = repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory)) { Assert.Single(changes.Modified); } using (var patch = repo.Diff.Compare<Patch>(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory)) { var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index ce01362..4f125e3 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1,3 @@\n") .Append(" hello\n") .Append("+world\n") .Append("+!!!\n"); Assert.Equal(expected.ToString(), patch); } } } [Fact] public void CanCompareAMoreComplexTreeAgainstTheWorkdir() { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Tree tree = repo.Head.Tip.Tree; using (var changes = repo.Diff.Compare<TreeChanges>(tree, DiffTargets.WorkingDirectory)) { Assert.NotNull(changes); Assert.Equal(6, changes.Count()); Assert.Equal(new[] { "deleted_staged_file.txt", "deleted_unstaged_file.txt" }, changes.Deleted.Select(tec => tec.Path)); Assert.Equal(new[] { "new_tracked_file.txt", "new_untracked_file.txt" }, changes.Added.Select(tec => tec.Path)); Assert.Equal(new[] { "modified_staged_file.txt", "modified_unstaged_file.txt" }, changes.Modified.Select(tec => tec.Path)); } } } [Fact] /* * $ git diff HEAD * diff --git a/file.txt b/file.txt * index ce01362..4f125e3 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1,3 @@ * hello * +world * +!!! */ public void CanCompareASimpleTreeAgainstTheWorkDirAndTheIndex() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { SetUpSimpleDiffContext(repo); using (var changes = repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.Index | DiffTargets.WorkingDirectory)) { Assert.Single(changes.Modified); } using (var patch = repo.Diff.Compare<Patch>(repo.Head.Tip.Tree, DiffTargets.Index | DiffTargets.WorkingDirectory)) { var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index ce01362..4f125e3 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1,3 @@\n") .Append(" hello\n") .Append("+world\n") .Append("+!!!\n"); Assert.Equal(expected.ToString(), patch); } } } [Fact] /* * $ git diff * * $ git diff HEAD * diff --git a/file.txt b/file.txt * deleted file mode 100644 * index ce01362..0000000 * --- a/file.txt * +++ /dev/null * @@ -1 +0,0 @@ * -hello * * $ git diff --cached * diff --git a/file.txt b/file.txt * deleted file mode 100644 * index ce01362..0000000 * --- a/file.txt * +++ /dev/null * @@ -1 +0,0 @@ * -hello */ public void ShowcaseTheDifferenceBetweenTheTwoKindOfComparison() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { SetUpSimpleDiffContext(repo); var fullpath = Path.Combine(repo.Info.WorkingDirectory, "file.txt"); File.Move(fullpath, fullpath + ".bak"); Commands.Stage(repo, fullpath); File.Move(fullpath + ".bak", fullpath); FileStatus state = repo.RetrieveStatus("file.txt"); Assert.Equal(FileStatus.DeletedFromIndex | FileStatus.NewInWorkdir, state); using (var wrkDirToIdxToTree = repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.Index | DiffTargets.WorkingDirectory)) { Assert.Single(wrkDirToIdxToTree.Deleted); Assert.Empty(wrkDirToIdxToTree.Modified); } using (var patch = repo.Diff.Compare<Patch>(repo.Head.Tip.Tree, DiffTargets.Index | DiffTargets.WorkingDirectory)) { var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("deleted file mode 100644\n") .Append("index ce01362..0000000\n") .Append("--- a/file.txt\n") .Append("+++ /dev/null\n") .Append("@@ -1 +0,0 @@\n") .Append("-hello\n"); Assert.Equal(expected.ToString(), patch); } using (var wrkDirToTree = repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory)) { Assert.Empty(wrkDirToTree.Deleted); Assert.Single(wrkDirToTree.Modified); } using (var patch = repo.Diff.Compare<Patch>(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory)) { var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index ce01362..4f125e3 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1,3 @@\n") .Append(" hello\n") .Append("+world\n") .Append("+!!!\n"); Assert.Equal(expected.ToString(), patch); } } } [Fact] /* * $ git diff --cached * diff --git a/file.txt b/file.txt * index ce01362..94954ab 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1,2 @@ * hello * +world */ public void CanCompareASimpleTreeAgainstTheIndex() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { SetUpSimpleDiffContext(repo); using (var changes = repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.Index)) { Assert.Single(changes.Modified); } using (var patch = repo.Diff.Compare<Patch>(repo.Head.Tip.Tree, DiffTargets.Index)) { var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index ce01362..94954ab 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1,2 @@\n") .Append(" hello\n") .Append("+world\n"); Assert.Equal(expected.ToString(), patch); } } } /* * $ git diff --cached * diff --git a/deleted_staged_file.txt b/deleted_staged_file.txt * deleted file mode 100644 * index 5605472..0000000 * --- a/deleted_staged_file.txt * +++ /dev/null * @@ -1 +0,0 @@ * -things * diff --git a/modified_staged_file.txt b/modified_staged_file.txt * index 15d2ecc..e68bcc7 100644 * --- a/modified_staged_file.txt * +++ b/modified_staged_file.txt * @@ -1 +1,2 @@ * +a change * more files! * diff --git a/new_tracked_file.txt b/new_tracked_file.txt * new file mode 100644 * index 0000000..935a81d * --- /dev/null * +++ b/new_tracked_file.txt * @@ -0,0 +1 @@ * +a new file */ [Fact] public void CanCompareAMoreComplexTreeAgainstTheIndex() { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Tree tree = repo.Head.Tip.Tree; using (var changes = repo.Diff.Compare<TreeChanges>(tree, DiffTargets.Index)) { Assert.NotNull(changes); Assert.Equal(3, changes.Count()); Assert.Equal("deleted_staged_file.txt", changes.Deleted.Single().Path); Assert.Equal("new_tracked_file.txt", changes.Added.Single().Path); Assert.Equal("modified_staged_file.txt", changes.Modified.Single().Path); } } } /* * $ git diff --cached -- "deleted_staged_file.txt" "1/branch_file.txt" "I-do/not-exist" * diff --git a/deleted_staged_file.txt b/deleted_staged_file.txt * deleted file mode 100644 * index 5605472..0000000 * --- a/deleted_staged_file.txt * +++ /dev/null * @@ -1 +0,0 @@ * -things */ [Fact] public void CanCompareASubsetofTheTreeAgainstTheIndex() { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Tree tree = repo.Head.Tip.Tree; using (var changes = repo.Diff.Compare<TreeChanges>(tree, DiffTargets.Index, new[] { "deleted_staged_file.txt", "1/branch_file.txt" })) { Assert.NotNull(changes); Assert.Single(changes); Assert.Equal("deleted_staged_file.txt", changes.Deleted.Single().Path); } } } private static void AssertCanCompareASubsetOfTheTreeAgainstTheIndex(TreeChanges changes) { Assert.NotNull(changes); Assert.Single(changes); Assert.Equal("deleted_staged_file.txt", changes.Deleted.Single().Path); } [Fact] public void CanCompareASubsetofTheTreeAgainstTheIndexWithLaxExplicitPathsValidationAndANonExistentPath() { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Tree tree = repo.Head.Tip.Tree; using (var changes = repo.Diff.Compare<TreeChanges>(tree, DiffTargets.Index, new[] { "deleted_staged_file.txt", "1/branch_file.txt", "I-do/not-exist" }, new ExplicitPathsOptions { ShouldFailOnUnmatchedPath = false })) { AssertCanCompareASubsetOfTheTreeAgainstTheIndex(changes); } using (var changes = repo.Diff.Compare<TreeChanges>(tree, DiffTargets.Index, new[] { "deleted_staged_file.txt", "1/branch_file.txt", "I-do/not-exist" })) { AssertCanCompareASubsetOfTheTreeAgainstTheIndex(changes); } } } [Fact] public void ComparingASubsetofTheTreeAgainstTheIndexWithStrictExplicitPathsValidationAndANonExistentPathThrows() { var path = SandboxStandardTestRepoGitDir(); using (var repo = new Repository(path)) { Tree tree = repo.Head.Tip.Tree; Assert.Throws<UnmatchedPathException>(() => repo.Diff.Compare<TreeChanges>(tree, DiffTargets.Index, new[] { "deleted_staged_file.txt", "1/branch_file.txt", "I-do/not-exist" }, new ExplicitPathsOptions())); } } [Fact] /* * $ git init . * $ echo -ne 'a' > file.txt * $ git add . * $ git commit -m "No line ending" * $ echo -ne '\n' >> file.txt * $ git add . * $ git diff --cached * diff --git a/file.txt b/file.txt * index 2e65efe..7898192 100644 * --- a/file.txt * +++ b/file.txt * @@ -1 +1 @@ * -a * \ No newline at end of file * +a */ public void CanCopeWithEndOfFileNewlineChanges() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { var fullpath = Touch(repo.Info.WorkingDirectory, "file.txt", "a"); Commands.Stage(repo, "file.txt"); repo.Commit("Add file without line ending", Constants.Signature, Constants.Signature); File.AppendAllText(fullpath, "\n"); Commands.Stage(repo, "file.txt"); using (var changes = repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.Index)) { Assert.Single(changes.Modified); } using (var patch = repo.Diff.Compare<Patch>(repo.Head.Tip.Tree, DiffTargets.Index)) { var expected = new StringBuilder() .Append("diff --git a/file.txt b/file.txt\n") .Append("index 2e65efe..7898192 100644\n") .Append("--- a/file.txt\n") .Append("+++ b/file.txt\n") .Append("@@ -1 +1 @@\n") .Append("-a\n") .Append("\\ No newline at end of file\n") .Append("+a\n"); Assert.Equal(expected.ToString(), patch); Assert.Equal(1, patch.LinesAdded); Assert.Equal(1, patch.LinesDeleted); } } } [Fact] public void ComparingATreeInABareRepositoryAgainstTheWorkDirOrTheIndexThrows() { string path = SandboxBareTestRepo(); using (var repo = new Repository(path)) { Assert.Throws<BareRepositoryException>( () => repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory)); Assert.Throws<BareRepositoryException>( () => repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.Index)); Assert.Throws<BareRepositoryException>( () => repo.Diff.Compare<TreeChanges>(repo.Head.Tip.Tree, DiffTargets.WorkingDirectory | DiffTargets.Index)); } } [Fact] public void CanCompareANullTreeAgainstTheIndex() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { SetUpSimpleDiffContext(repo); using (var changes = repo.Diff.Compare<TreeChanges>(null, DiffTargets.Index)) { Assert.Single(changes); Assert.Single(changes.Added); Assert.Equal("file.txt", changes.Added.Single().Path); } } } [Fact] public void CanCompareANullTreeAgainstTheWorkdir() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { SetUpSimpleDiffContext(repo); using (var changes = repo.Diff.Compare<TreeChanges>(null, DiffTargets.WorkingDirectory)) { Assert.Single(changes); Assert.Single(changes.Added); Assert.Equal("file.txt", changes.Added.Single().Path); } } } [Fact] public void CanCompareANullTreeAgainstTheWorkdirAndTheIndex() { string repoPath = InitNewRepository(); using (var repo = new Repository(repoPath)) { SetUpSimpleDiffContext(repo); using (var changes = repo.Diff.Compare<TreeChanges>(null, DiffTargets.WorkingDirectory | DiffTargets.Index)) { Assert.Single(changes); Assert.Single(changes.Added); Assert.Equal("file.txt", changes.Added.Single().Path); } } } } }
/* * OANDA v20 REST API * * The full OANDA v20 REST API Specification. This specification defines how to interact with v20 Accounts, Trades, Orders, Pricing and more. * * OpenAPI spec version: 3.0.15 * Contact: [email protected] * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Oanda.RestV20.Model { /// <summary> /// A filter that can be used when fetching Transactions /// </summary> /// <value>A filter that can be used when fetching Transactions</value> [JsonConverter(typeof(StringEnumConverter))] public enum TransactionFilter { /// <summary> /// Enum ORDER for "ORDER" /// </summary> [EnumMember(Value = "ORDER")] ORDER, /// <summary> /// Enum FUNDING for "FUNDING" /// </summary> [EnumMember(Value = "FUNDING")] FUNDING, /// <summary> /// Enum ADMIN for "ADMIN" /// </summary> [EnumMember(Value = "ADMIN")] ADMIN, /// <summary> /// Enum CREATE for "CREATE" /// </summary> [EnumMember(Value = "CREATE")] CREATE, /// <summary> /// Enum CLOSE for "CLOSE" /// </summary> [EnumMember(Value = "CLOSE")] CLOSE, /// <summary> /// Enum REOPEN for "REOPEN" /// </summary> [EnumMember(Value = "REOPEN")] REOPEN, /// <summary> /// Enum CLIENTCONFIGURE for "CLIENT_CONFIGURE" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE")] CLIENTCONFIGURE, /// <summary> /// Enum CLIENTCONFIGUREREJECT for "CLIENT_CONFIGURE_REJECT" /// </summary> [EnumMember(Value = "CLIENT_CONFIGURE_REJECT")] CLIENTCONFIGUREREJECT, /// <summary> /// Enum TRANSFERFUNDS for "TRANSFER_FUNDS" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS")] TRANSFERFUNDS, /// <summary> /// Enum TRANSFERFUNDSREJECT for "TRANSFER_FUNDS_REJECT" /// </summary> [EnumMember(Value = "TRANSFER_FUNDS_REJECT")] TRANSFERFUNDSREJECT, /// <summary> /// Enum MARKETORDER for "MARKET_ORDER" /// </summary> [EnumMember(Value = "MARKET_ORDER")] MARKETORDER, /// <summary> /// Enum MARKETORDERREJECT for "MARKET_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_ORDER_REJECT")] MARKETORDERREJECT, /// <summary> /// Enum LIMITORDER for "LIMIT_ORDER" /// </summary> [EnumMember(Value = "LIMIT_ORDER")] LIMITORDER, /// <summary> /// Enum LIMITORDERREJECT for "LIMIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "LIMIT_ORDER_REJECT")] LIMITORDERREJECT, /// <summary> /// Enum STOPORDER for "STOP_ORDER" /// </summary> [EnumMember(Value = "STOP_ORDER")] STOPORDER, /// <summary> /// Enum STOPORDERREJECT for "STOP_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_ORDER_REJECT")] STOPORDERREJECT, /// <summary> /// Enum MARKETIFTOUCHEDORDER for "MARKET_IF_TOUCHED_ORDER" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER")] MARKETIFTOUCHEDORDER, /// <summary> /// Enum MARKETIFTOUCHEDORDERREJECT for "MARKET_IF_TOUCHED_ORDER_REJECT" /// </summary> [EnumMember(Value = "MARKET_IF_TOUCHED_ORDER_REJECT")] MARKETIFTOUCHEDORDERREJECT, /// <summary> /// Enum TAKEPROFITORDER for "TAKE_PROFIT_ORDER" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER")] TAKEPROFITORDER, /// <summary> /// Enum TAKEPROFITORDERREJECT for "TAKE_PROFIT_ORDER_REJECT" /// </summary> [EnumMember(Value = "TAKE_PROFIT_ORDER_REJECT")] TAKEPROFITORDERREJECT, /// <summary> /// Enum STOPLOSSORDER for "STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER")] STOPLOSSORDER, /// <summary> /// Enum STOPLOSSORDERREJECT for "STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "STOP_LOSS_ORDER_REJECT")] STOPLOSSORDERREJECT, /// <summary> /// Enum TRAILINGSTOPLOSSORDER for "TRAILING_STOP_LOSS_ORDER" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER")] TRAILINGSTOPLOSSORDER, /// <summary> /// Enum TRAILINGSTOPLOSSORDERREJECT for "TRAILING_STOP_LOSS_ORDER_REJECT" /// </summary> [EnumMember(Value = "TRAILING_STOP_LOSS_ORDER_REJECT")] TRAILINGSTOPLOSSORDERREJECT, /// <summary> /// Enum ONECANCELSALLORDER for "ONE_CANCELS_ALL_ORDER" /// </summary> [EnumMember(Value = "ONE_CANCELS_ALL_ORDER")] ONECANCELSALLORDER, /// <summary> /// Enum ONECANCELSALLORDERREJECT for "ONE_CANCELS_ALL_ORDER_REJECT" /// </summary> [EnumMember(Value = "ONE_CANCELS_ALL_ORDER_REJECT")] ONECANCELSALLORDERREJECT, /// <summary> /// Enum ONECANCELSALLORDERTRIGGERED for "ONE_CANCELS_ALL_ORDER_TRIGGERED" /// </summary> [EnumMember(Value = "ONE_CANCELS_ALL_ORDER_TRIGGERED")] ONECANCELSALLORDERTRIGGERED, /// <summary> /// Enum ORDERFILL for "ORDER_FILL" /// </summary> [EnumMember(Value = "ORDER_FILL")] ORDERFILL, /// <summary> /// Enum ORDERCANCEL for "ORDER_CANCEL" /// </summary> [EnumMember(Value = "ORDER_CANCEL")] ORDERCANCEL, /// <summary> /// Enum ORDERCANCELREJECT for "ORDER_CANCEL_REJECT" /// </summary> [EnumMember(Value = "ORDER_CANCEL_REJECT")] ORDERCANCELREJECT, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFY for "ORDER_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY")] ORDERCLIENTEXTENSIONSMODIFY, /// <summary> /// Enum ORDERCLIENTEXTENSIONSMODIFYREJECT for "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "ORDER_CLIENT_EXTENSIONS_MODIFY_REJECT")] ORDERCLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFY for "TRADE_CLIENT_EXTENSIONS_MODIFY" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY")] TRADECLIENTEXTENSIONSMODIFY, /// <summary> /// Enum TRADECLIENTEXTENSIONSMODIFYREJECT for "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT" /// </summary> [EnumMember(Value = "TRADE_CLIENT_EXTENSIONS_MODIFY_REJECT")] TRADECLIENTEXTENSIONSMODIFYREJECT, /// <summary> /// Enum MARGINCALLENTER for "MARGIN_CALL_ENTER" /// </summary> [EnumMember(Value = "MARGIN_CALL_ENTER")] MARGINCALLENTER, /// <summary> /// Enum MARGINCALLEXTEND for "MARGIN_CALL_EXTEND" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXTEND")] MARGINCALLEXTEND, /// <summary> /// Enum MARGINCALLEXIT for "MARGIN_CALL_EXIT" /// </summary> [EnumMember(Value = "MARGIN_CALL_EXIT")] MARGINCALLEXIT, /// <summary> /// Enum DELAYEDTRADECLOSURE for "DELAYED_TRADE_CLOSURE" /// </summary> [EnumMember(Value = "DELAYED_TRADE_CLOSURE")] DELAYEDTRADECLOSURE, /// <summary> /// Enum DAILYFINANCING for "DAILY_FINANCING" /// </summary> [EnumMember(Value = "DAILY_FINANCING")] DAILYFINANCING, /// <summary> /// Enum RESETRESETTABLEPL for "RESET_RESETTABLE_PL" /// </summary> [EnumMember(Value = "RESET_RESETTABLE_PL")] RESETRESETTABLEPL } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using ILCompiler.DependencyAnalysisFramework; using Internal.IL; using Internal.Runtime; using Internal.Text; using Internal.TypeSystem; using Debug = System.Diagnostics.Debug; using GenericVariance = Internal.Runtime.GenericVariance; namespace ILCompiler.DependencyAnalysis { /// <summary> /// Given a type, EETypeNode writes an EEType data structure in the format expected by the runtime. /// /// Format of an EEType: /// /// Field Size | Contents /// ----------------+----------------------------------- /// UInt16 | Component Size. For arrays this is the element type size, for strings it is 2 (.NET uses /// | UTF16 character encoding), for generic type definitions it is the number of generic parameters, /// | and 0 for all other types. /// | /// UInt16 | EETypeKind (Normal, Array, Pointer type). Flags for: IsValueType, IsCrossModule, HasPointers, /// | HasOptionalFields, IsInterface, IsGeneric. Top 5 bits are used for enum CorElementType to /// | record whether it's back by an Int32, Int16 etc /// | /// Uint32 | Base size. /// | /// [Pointer Size] | Related type. Base type for regular types. Element type for arrays / pointer types. /// | /// UInt16 | Number of VTable slots (X) /// | /// UInt16 | Number of interfaces implemented by type (Y) /// | /// UInt32 | Hash code /// | /// [Pointer Size] | Pointer to containing TypeManager indirection cell /// | /// X * [Ptr Size] | VTable entries (optional) /// | /// Y * [Ptr Size] | Pointers to interface map data structures (optional) /// | /// [Pointer Size] | Pointer to finalizer method (optional) /// | /// [Pointer Size] | Pointer to optional fields (optional) /// | /// [Pointer Size] | Pointer to the generic type argument of a Nullable&lt;T&gt; (optional) /// | /// [Pointer Size] | Pointer to the generic type definition EEType (optional) /// | /// [Pointer Size] | Pointer to the generic argument and variance info (optional) /// </summary> public partial class EETypeNode : ObjectNode, ISymbolNode, IEETypeNode { protected TypeDesc _type; internal EETypeOptionalFieldsBuilder _optionalFieldsBuilder = new EETypeOptionalFieldsBuilder(); internal EETypeOptionalFieldsNode _optionalFieldsNode; public EETypeNode(NodeFactory factory, TypeDesc type) { if (type.IsCanonicalDefinitionType(CanonicalFormKind.Any)) Debug.Assert(this is CanonicalDefinitionEETypeNode); else if (type.IsCanonicalSubtype(CanonicalFormKind.Any)) Debug.Assert(this is CanonicalEETypeNode); Debug.Assert(!type.IsRuntimeDeterminedSubtype); _type = type; _optionalFieldsNode = new EETypeOptionalFieldsNode(this); // Note: The fact that you can't create invalid EETypeNode is used from many places that grab // an EETypeNode from the factory with the sole purpose of making sure the validation has run // and that the result of the positive validation is "cached" (by the presence of an EETypeNode). CheckCanGenerateEEType(factory, type); } protected override string GetName() => this.GetMangledName(); public override bool ShouldSkipEmittingObjectNode(NodeFactory factory) { // If there is a constructed version of this node in the graph, emit that instead if (ConstructedEETypeNode.CreationAllowed(_type)) return ((DependencyNode)factory.ConstructedTypeSymbol(_type)).Marked; return false; } public TypeDesc Type => _type; public override ObjectNodeSection Section { get { if (_type.Context.Target.IsWindows) return ObjectNodeSection.ReadOnlyDataSection; else return ObjectNodeSection.DataSection; } } public int MinimumObjectSize => _type.Context.Target.PointerSize * 3; protected virtual bool EmitVirtualSlotsAndInterfaces => false; internal bool HasOptionalFields { get { return _optionalFieldsBuilder.IsAtLeastOneFieldUsed(); } } internal byte[] GetOptionalFieldsData(NodeFactory factory) { return _optionalFieldsBuilder.GetBytes(); } public override bool StaticDependenciesAreComputed => true; public void SetDispatchMapIndex(int index) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.DispatchMap, checked((uint)index)); } public static string GetMangledName(TypeDesc type, NameMangler nameMangler) { return "__EEType_" + nameMangler.GetMangledTypeName(type); } public virtual void AppendMangledName(NameMangler nameMangler, Utf8StringBuilder sb) { sb.Append("__EEType_").Append(nameMangler.GetMangledTypeName(_type)); } public int Offset => GCDescSize; public override bool IsShareable => IsTypeNodeShareable(_type); public static bool IsTypeNodeShareable(TypeDesc type) { return type.IsParameterizedType || type.IsFunctionPointer || type is InstantiatedType; } protected override DependencyList ComputeNonRelocationBasedDependencies(NodeFactory factory) { DependencyList dependencies = new DependencyList(); // Include the optional fields by default. We don't know if optional fields will be needed until // all of the interface usage has been stabilized. If we end up not needing it, the EEType node will not // generate any relocs to it, and the optional fields node will instruct the object writer to skip // emitting it. dependencies.Add(new DependencyListEntry(_optionalFieldsNode, "Optional fields")); return dependencies; } public override ObjectData GetData(NodeFactory factory, bool relocsOnly) { ObjectDataBuilder objData = new ObjectDataBuilder(factory); objData.RequireInitialPointerAlignment(); objData.AddSymbol(this); ComputeOptionalEETypeFields(factory, relocsOnly); OutputGCDesc(ref objData); OutputComponentSize(ref objData); OutputFlags(factory, ref objData); OutputBaseSize(ref objData); OutputRelatedType(factory, ref objData); // Avoid consulting VTable slots until they're guaranteed complete during final data emission if (EmitVirtualSlotsAndInterfaces && !relocsOnly) { OutputVirtualSlotAndInterfaceCount(factory, ref objData); } else { objData.EmitShort(0); objData.EmitShort(0); } objData.EmitInt(_type.GetHashCode()); objData.EmitPointerReloc(factory.TypeManagerIndirection); if (EmitVirtualSlotsAndInterfaces) { // Avoid consulting VTable slots until they're guaranteed complete during final data emission if (!relocsOnly) { OutputVirtualSlots(factory, ref objData, _type, _type); } OutputInterfaceMap(factory, ref objData); } OutputFinalizerMethod(factory, ref objData); OutputOptionalFields(factory, ref objData); OutputNullableTypeParameter(factory, ref objData); OutputGenericInstantiationDetails(factory, ref objData); return objData.ToObjectData(); } /// <summary> /// Returns the offset within an EEType of the beginning of VTable entries /// </summary> /// <param name="pointerSize">The size of a pointer in bytes in the target architecture</param> public static int GetVTableOffset(int pointerSize) { return 16 + 2 * pointerSize; } protected virtual int GCDescSize => 0; protected virtual void OutputGCDesc(ref ObjectDataBuilder builder) { // Non-constructed EETypeNodes get no GC Desc Debug.Assert(GCDescSize == 0); } private void OutputComponentSize(ref ObjectDataBuilder objData) { if (_type.IsArray) { int elementSize = ((ArrayType)_type).ElementType.GetElementSize(); // We validated that this will fit the short when the node was constructed. No need for nice messages. objData.EmitShort((short)checked((ushort)elementSize)); } else if (_type.IsString) { objData.EmitShort(2); } else { objData.EmitShort(0); } } private void OutputFlags(NodeFactory factory, ref ObjectDataBuilder objData) { UInt16 flags = EETypeBuilderHelpers.ComputeFlags(_type); if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime flags |= (UInt16)EETypeFlags.GenericVarianceFlag; } if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type)) { // Runtime casting logic relies on all interface types implemented on arrays // to have the variant flag set (even if all the arguments are non-variant). // This supports e.g. casting uint[] to ICollection<int> flags |= (UInt16)EETypeFlags.GenericVarianceFlag; } ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory); // If the related type (base type / array element type / pointee type) is not part of this compilation group, and // the output binaries will be multi-file (not multiple object files linked together), indicate to the runtime // that it should indirect through the import address table if (relatedTypeNode != null && relatedTypeNode.RepresentsIndirectionCell) { flags |= (UInt16)EETypeFlags.RelatedTypeViaIATFlag; } // Todo: Generic Type Definition EETypes if (HasOptionalFields) { flags |= (UInt16)EETypeFlags.OptionalFieldsFlag; } objData.EmitShort((short)flags); } protected virtual void OutputBaseSize(ref ObjectDataBuilder objData) { int pointerSize = _type.Context.Target.PointerSize; int objectSize; if (_type.IsDefType) { objectSize = pointerSize + ((DefType)_type).InstanceByteCount; // +pointerSize for SyncBlock if (_type.IsValueType) objectSize += pointerSize; // + EETypePtr field inherited from System.Object } else if (_type.IsArray) { objectSize = 3 * pointerSize; // SyncBlock + EETypePtr + Length if (_type.IsMdArray) objectSize += 2 * _type.Context.GetWellKnownType(WellKnownType.Int32).GetElementSize() * ((ArrayType)_type).Rank; } else if (_type.IsPointer) { // These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime. objData.EmitInt(ParameterizedTypeShapeConstants.Pointer); return; } else if (_type.IsByRef) { // These never get boxed and don't have a base size. Use a sentinel value recognized by the runtime. objData.EmitInt(ParameterizedTypeShapeConstants.ByRef); return; } else throw new NotImplementedException(); objectSize = AlignmentHelper.AlignUp(objectSize, pointerSize); objectSize = Math.Max(MinimumObjectSize, objectSize); if (_type.IsString) { // If this is a string, throw away objectSize we computed so far. Strings are special. // SyncBlock + EETypePtr + length + firstChar objectSize = 2 * pointerSize + _type.Context.GetWellKnownType(WellKnownType.Int32).GetElementSize() + _type.Context.GetWellKnownType(WellKnownType.Char).GetElementSize(); } objData.EmitInt(objectSize); } protected static TypeDesc GetFullCanonicalTypeForCanonicalType(TypeDesc type) { if (type.IsCanonicalSubtype(CanonicalFormKind.Specific)) { return type.ConvertToCanonForm(CanonicalFormKind.Specific); } else if (type.IsCanonicalSubtype(CanonicalFormKind.Universal)) { return type.ConvertToCanonForm(CanonicalFormKind.Universal); } else { return type; } } protected virtual ISymbolNode GetBaseTypeNode(NodeFactory factory) { return _type.BaseType != null ? factory.NecessaryTypeSymbol(_type.BaseType) : null; } private ISymbolNode GetRelatedTypeNode(NodeFactory factory) { ISymbolNode relatedTypeNode = null; if (_type.IsArray || _type.IsPointer || _type.IsByRef) { var parameterType = ((ParameterizedType)_type).ParameterType; relatedTypeNode = factory.NecessaryTypeSymbol(parameterType); } else { TypeDesc baseType = _type.BaseType; if (baseType != null) { relatedTypeNode = GetBaseTypeNode(factory); } } return relatedTypeNode; } protected virtual void OutputRelatedType(NodeFactory factory, ref ObjectDataBuilder objData) { ISymbolNode relatedTypeNode = GetRelatedTypeNode(factory); if (relatedTypeNode != null) { objData.EmitPointerReloc(relatedTypeNode); } else { objData.EmitZeroPointer(); } } protected virtual void OutputVirtualSlotAndInterfaceCount(NodeFactory factory, ref ObjectDataBuilder objData) { Debug.Assert(EmitVirtualSlotsAndInterfaces); int virtualSlotCount = 0; TypeDesc currentTypeSlice = _type.GetClosestDefType(); while (currentTypeSlice != null) { if (currentTypeSlice.HasGenericDictionarySlot()) virtualSlotCount++; virtualSlotCount += factory.VTable(currentTypeSlice).Slots.Count; currentTypeSlice = currentTypeSlice.BaseType; } objData.EmitShort(checked((short)virtualSlotCount)); objData.EmitShort(checked((short)_type.RuntimeInterfaces.Length)); } protected virtual void OutputVirtualSlots(NodeFactory factory, ref ObjectDataBuilder objData, TypeDesc implType, TypeDesc declType) { Debug.Assert(EmitVirtualSlotsAndInterfaces); declType = declType.GetClosestDefType(); var baseType = declType.BaseType; if (baseType != null) OutputVirtualSlots(factory, ref objData, implType, baseType); // The generic dictionary pointer occupies the first slot of each type vtable slice if (declType.HasGenericDictionarySlot()) { // Note: Canonical type instantiations always have a generic dictionary vtable slot, but it's empty if (declType.IsCanonicalSubtype(CanonicalFormKind.Any)) objData.EmitZeroPointer(); else objData.EmitPointerReloc(factory.TypeGenericDictionary(declType)); } // Actual vtable slots follow IReadOnlyList<MethodDesc> virtualSlots = factory.VTable(declType).Slots; for (int i = 0; i < virtualSlots.Count; i++) { MethodDesc declMethod = virtualSlots[i]; // No generic virtual methods can appear in the vtable! Debug.Assert(!declMethod.HasInstantiation); MethodDesc implMethod = implType.GetClosestDefType().FindVirtualFunctionTargetMethodOnObjectType(declMethod); if (!implMethod.IsAbstract) { MethodDesc canonImplMethod = implMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); objData.EmitPointerReloc(factory.MethodEntrypoint(canonImplMethod, implMethod.OwningType.IsValueType)); } else { objData.EmitZeroPointer(); } } } protected virtual void OutputInterfaceMap(NodeFactory factory, ref ObjectDataBuilder objData) { Debug.Assert(EmitVirtualSlotsAndInterfaces); foreach (var itf in _type.RuntimeInterfaces) { objData.EmitPointerReloc(factory.NecessaryTypeSymbol(itf)); } } private void OutputFinalizerMethod(NodeFactory factory, ref ObjectDataBuilder objData) { MethodDesc finalizerMethod = _type.GetFinalizer(); if (finalizerMethod != null) { MethodDesc canonFinalizerMethod = finalizerMethod.GetCanonMethodTarget(CanonicalFormKind.Specific); objData.EmitPointerReloc(factory.MethodEntrypoint(canonFinalizerMethod)); } } private void OutputOptionalFields(NodeFactory factory, ref ObjectDataBuilder objData) { if (HasOptionalFields) { objData.EmitPointerReloc(_optionalFieldsNode); } } private void OutputNullableTypeParameter(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.IsNullable) { objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.Instantiation[0])); } } private void OutputGenericInstantiationDetails(NodeFactory factory, ref ObjectDataBuilder objData) { if (_type.HasInstantiation && !_type.IsTypeDefinition) { objData.EmitPointerReloc(factory.NecessaryTypeSymbol(_type.GetTypeDefinition())); GenericCompositionDetails details; if (_type.GetTypeDefinition() == factory.ArrayOfTEnumeratorType) { // Generic array enumerators use special variance rules recognized by the runtime details = new GenericCompositionDetails(_type.Instantiation, new[] { GenericVariance.ArrayCovariant }); } else if (factory.TypeSystemContext.IsGenericArrayInterfaceType(_type)) { // Runtime casting logic relies on all interface types implemented on arrays // to have the variant flag set (even if all the arguments are non-variant). // This supports e.g. casting uint[] to ICollection<int> details = new GenericCompositionDetails(_type, forceVarianceInfo: true); } else details = new GenericCompositionDetails(_type); objData.EmitPointerReloc(factory.GenericComposition(details)); } } /// <summary> /// Populate the OptionalFieldsRuntimeBuilder if any optional fields are required. /// </summary> protected internal virtual void ComputeOptionalEETypeFields(NodeFactory factory, bool relocsOnly) { ComputeRareFlags(factory); ComputeNullableValueOffset(); if (!relocsOnly) ComputeICastableVirtualMethodSlots(factory); ComputeValueTypeFieldPadding(); } void ComputeRareFlags(NodeFactory factory) { uint flags = 0; if (_type.IsNullable) { flags |= (uint)EETypeRareFlags.IsNullableFlag; } if (factory.TypeSystemContext.HasLazyStaticConstructor(_type)) { flags |= (uint)EETypeRareFlags.HasCctorFlag; } if (EETypeBuilderHelpers.ComputeRequiresAlign8(_type)) { flags |= (uint)EETypeRareFlags.RequiresAlign8Flag; } if (_type.IsDefType && ((DefType)_type).IsHfa) { flags |= (uint)EETypeRareFlags.IsHFAFlag; } foreach (DefType itf in _type.RuntimeInterfaces) { if (itf == factory.ICastableInterface) { flags |= (uint)EETypeRareFlags.ICastableFlag; break; } } if ((_type is MetadataType) && !_type.IsInterface && ((MetadataType)_type).IsAbstract) { flags |= (uint)EETypeRareFlags.IsAbstractClassFlag; } if (flags != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.RareFlags, flags); } } /// <summary> /// To support boxing / unboxing, the offset of the value field of a Nullable type is recorded on the EEType. /// This is variable according to the alignment requirements of the Nullable&lt;T&gt; type parameter. /// </summary> void ComputeNullableValueOffset() { if (!_type.IsNullable) return; var field = _type.GetKnownField("value"); // In the definition of Nullable<T>, the first field should be the boolean representing "hasValue" Debug.Assert(field.Offset > 0); // The contract with the runtime states the Nullable value offset is stored with the boolean "hasValue" size subtracted // to get a small encoding size win. _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.NullableValueOffset, (uint)field.Offset - 1); } /// <summary> /// ICastable is a special interface whose two methods are not invoked using regular interface dispatch. /// Instead, their VTable slots are recorded on the EEType of an object implementing ICastable and are /// called directly. /// </summary> protected virtual void ComputeICastableVirtualMethodSlots(NodeFactory factory) { if (_type.IsInterface || !EmitVirtualSlotsAndInterfaces) return; foreach (DefType itf in _type.RuntimeInterfaces) { if (itf == factory.ICastableInterface) { MethodDesc isInstDecl = itf.GetKnownMethod("IsInstanceOfInterface", null); MethodDesc getImplTypeDecl = itf.GetKnownMethod("GetImplType", null); MethodDesc isInstMethodImpl = _type.ResolveInterfaceMethodTarget(isInstDecl); MethodDesc getImplTypeMethodImpl = _type.ResolveInterfaceMethodTarget(getImplTypeDecl); int isInstMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, isInstMethodImpl); int getImplTypeMethodSlot = VirtualMethodSlotHelper.GetVirtualMethodSlot(factory, getImplTypeMethodImpl); Debug.Assert(isInstMethodSlot != -1 && getImplTypeMethodSlot != -1); _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableIsInstSlot, (uint)isInstMethodSlot); _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ICastableGetImplTypeSlot, (uint)getImplTypeMethodSlot); } } } void ComputeValueTypeFieldPadding() { // All objects that can have appreciable which can be derived from size compute ValueTypeFieldPadding. // Unfortunately, the name ValueTypeFieldPadding is now wrong to avoid integration conflicts. // Interfaces, sealed types, and non-DefTypes cannot be derived from if (_type.IsInterface || !_type.IsDefType || (_type.IsSealed() && !_type.IsValueType)) return; DefType defType = _type as DefType; Debug.Assert(defType != null); uint valueTypeFieldPadding = checked((uint)(defType.InstanceByteCount - defType.InstanceByteCountUnaligned)); uint valueTypeFieldPaddingEncoded = EETypeBuilderHelpers.ComputeValueTypeFieldPaddingFieldValue(valueTypeFieldPadding, (uint)defType.InstanceFieldAlignment); if (valueTypeFieldPaddingEncoded != 0) { _optionalFieldsBuilder.SetFieldValue(EETypeOptionalFieldTag.ValueTypeFieldPadding, valueTypeFieldPaddingEncoded); } } protected override void OnMarked(NodeFactory context) { //Debug.Assert(_type.IsTypeDefinition || !_type.HasSameTypeDefinition(context.ArrayOfTClass), "Asking for Array<T> EEType"); } /// <summary> /// Validates that it will be possible to create an EEType for '<paramref name="type"/>'. /// </summary> public static void CheckCanGenerateEEType(NodeFactory factory, TypeDesc type) { // Don't validate generic definitons if (type.IsGenericDefinition) { return; } // System.__Canon or System.__UniversalCanon if(type.IsCanonicalDefinitionType(CanonicalFormKind.Any)) { return; } // It must be possible to create an EEType for the base type of this type TypeDesc baseType = type.BaseType; if (baseType != null) { // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(baseType)); } // We need EETypes for interfaces foreach (var intf in type.RuntimeInterfaces) { // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(GetFullCanonicalTypeForCanonicalType(intf)); } // Validate classes, structs, enums, interfaces, and delegates DefType defType = type as DefType; if (defType != null) { // Ensure we can compute the type layout defType.ComputeInstanceLayout(InstanceLayoutKind.TypeAndFields); // // The fact that we generated an EEType means that someone can call RuntimeHelpers.RunClassConstructor. // We need to make sure this is possible. // if (factory.TypeSystemContext.HasLazyStaticConstructor(defType)) { defType.ComputeStaticFieldLayout(StaticLayoutKind.StaticRegionSizesAndFields); } // Make sure instantiation length matches the expectation // TODO: it might be more resonable for the type system to enforce this (also for methods) if (defType.Instantiation.Length != defType.GetTypeDefinition().Instantiation.Length) { throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } foreach (TypeDesc typeArg in defType.Instantiation) { // ByRefs, pointers, function pointers, and System.Void are never valid instantiation arguments if (typeArg.IsByRef || typeArg.IsPointer || typeArg.IsFunctionPointer || typeArg.IsVoid) { throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } // TODO: validate constraints } // Check the type doesn't have bogus MethodImpls or overrides and we can get the finalizer. defType.GetFinalizer(); } // Validate parameterized types ParameterizedType parameterizedType = type as ParameterizedType; if (parameterizedType != null) { TypeDesc parameterType = parameterizedType.ParameterType; // Make sure EEType can be created for this. factory.NecessaryTypeSymbol(parameterType); if (parameterizedType.IsArray) { if (parameterType.IsPointer || parameterType.IsFunctionPointer) { // Arrays of pointers and function pointers are not currently supported throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } int elementSize = parameterType.GetElementSize(); if (elementSize >= ushort.MaxValue) { // Element size over 64k can't be encoded in the GCDesc throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadValueClassTooLarge, parameterType); } if (((ArrayType)parameterizedType).Rank > 32) { throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadRankTooLarge, type); } } // Validate we're not constructing a type over a ByRef if (parameterType.IsByRef) { // CLR compat note: "ldtoken int32&&" will actually fail with a message about int32&; "ldtoken int32&[]" // will fail with a message about being unable to create an array of int32&. This is a middle ground. throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } // It might seem reasonable to disallow array of void, but the CLR doesn't prevent that too hard. // E.g. "newarr void" will fail, but "newarr void[]" or "ldtoken void[]" will succeed. } // Function pointer EETypes are not currently supported if (type.IsFunctionPointer) { throw new TypeSystemException.TypeLoadException(ExceptionStringID.ClassLoadGeneral, type); } } } }
// // MetadataSystem.cs // // Author: // Jb Evain ([email protected]) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Cecil.Metadata; namespace Mono.Cecil { struct Range { public uint Start; public uint Length; public Range (uint index, uint length) { this.Start = index; this.Length = length; } } sealed class MetadataSystem { internal AssemblyNameReference [] AssemblyReferences; internal ModuleReference [] ModuleReferences; internal TypeDefinition [] Types; internal TypeReference [] TypeReferences; internal FieldDefinition [] Fields; internal MethodDefinition [] Methods; internal MemberReference [] MemberReferences; internal Dictionary<uint, uint []> NestedTypes; internal Dictionary<uint, uint> ReverseNestedTypes; internal Dictionary<uint, MetadataToken []> Interfaces; internal Dictionary<uint, Row<ushort, uint>> ClassLayouts; internal Dictionary<uint, uint> FieldLayouts; internal Dictionary<uint, uint> FieldRVAs; internal Dictionary<MetadataToken, uint> FieldMarshals; internal Dictionary<MetadataToken, Row<ElementType, uint>> Constants; internal Dictionary<uint, MetadataToken []> Overrides; internal Dictionary<MetadataToken, Range> CustomAttributes; internal Dictionary<MetadataToken, Range> SecurityDeclarations; internal Dictionary<uint, Range> Events; internal Dictionary<uint, Range> Properties; internal Dictionary<uint, Row<MethodSemanticsAttributes, MetadataToken>> Semantics; internal Dictionary<uint, Row<PInvokeAttributes, uint, uint>> PInvokes; internal Dictionary<MetadataToken, Range> GenericParameters; internal Dictionary<uint, MetadataToken []> GenericConstraints; static Dictionary<string, Row<ElementType, bool>> primitive_value_types; static void InitializePrimitives () { primitive_value_types = new Dictionary<string, Row<ElementType, bool>> (18, StringComparer.Ordinal) { { "Void", new Row<ElementType, bool> (ElementType.Void, false) }, { "Boolean", new Row<ElementType, bool> (ElementType.Boolean, true) }, { "Char", new Row<ElementType, bool> (ElementType.Char, true) }, { "SByte", new Row<ElementType, bool> (ElementType.I1, true) }, { "Byte", new Row<ElementType, bool> (ElementType.U1, true) }, { "Int16", new Row<ElementType, bool> (ElementType.I2, true) }, { "UInt16", new Row<ElementType, bool> (ElementType.U2, true) }, { "Int32", new Row<ElementType, bool> (ElementType.I4, true) }, { "UInt32", new Row<ElementType, bool> (ElementType.U4, true) }, { "Int64", new Row<ElementType, bool> (ElementType.I8, true) }, { "UInt64", new Row<ElementType, bool> (ElementType.U8, true) }, { "Single", new Row<ElementType, bool> (ElementType.R4, true) }, { "Double", new Row<ElementType, bool> (ElementType.R8, true) }, { "String", new Row<ElementType, bool> (ElementType.String, false) }, { "TypedReference", new Row<ElementType, bool> (ElementType.TypedByRef, false) }, { "IntPtr", new Row<ElementType, bool> (ElementType.I, true) }, { "UIntPtr", new Row<ElementType, bool> (ElementType.U, true) }, { "Object", new Row<ElementType, bool> (ElementType.Object, false) }, }; } public static void TryProcessPrimitiveTypeReference (TypeReference type) { if (type.Namespace != "System") return; var scope = type.scope; if (scope == null || scope.MetadataScopeType != MetadataScopeType.AssemblyNameReference) return; Row<ElementType, bool> primitive_data; if (!TryGetPrimitiveData (type, out primitive_data)) return; type.etype = primitive_data.Col1; type.IsValueType = primitive_data.Col2; } public static bool TryGetPrimitiveElementType (TypeDefinition type, out ElementType etype) { etype = ElementType.None; if (type.Namespace != "System") return false; Row<ElementType, bool> primitive_data; if (TryGetPrimitiveData (type, out primitive_data) &&Mixin .IsPrimitive (primitive_data.Col1)) { etype = primitive_data.Col1; return true; } return false; } static bool TryGetPrimitiveData (TypeReference type, out Row<ElementType, bool> primitive_data) { if (primitive_value_types == null) InitializePrimitives (); return primitive_value_types.TryGetValue (type.Name, out primitive_data); } public void Clear () { if (NestedTypes != null) NestedTypes.Clear (); if (ReverseNestedTypes != null) ReverseNestedTypes.Clear (); if (Interfaces != null) Interfaces.Clear (); if (ClassLayouts != null) ClassLayouts.Clear (); if (FieldLayouts != null) FieldLayouts.Clear (); if (FieldRVAs != null) FieldRVAs.Clear (); if (FieldMarshals != null) FieldMarshals.Clear (); if (Constants != null) Constants.Clear (); if (Overrides != null) Overrides.Clear (); if (CustomAttributes != null) CustomAttributes.Clear (); if (SecurityDeclarations != null) SecurityDeclarations.Clear (); if (Events != null) Events.Clear (); if (Properties != null) Properties.Clear (); if (Semantics != null) Semantics.Clear (); if (PInvokes != null) PInvokes.Clear (); if (GenericParameters != null) GenericParameters.Clear (); if (GenericConstraints != null) GenericConstraints.Clear (); } public TypeDefinition GetTypeDefinition (uint rid) { if (rid < 1 || rid > Types.Length) return null; return Types [rid - 1]; } public void AddTypeDefinition (TypeDefinition type) { Types [type.token.RID - 1] = type; } public TypeReference GetTypeReference (uint rid) { if (rid < 1 || rid > TypeReferences.Length) return null; return TypeReferences [rid - 1]; } public void AddTypeReference (TypeReference type) { TypeReferences [type.token.RID - 1] = type; } public FieldDefinition GetFieldDefinition (uint rid) { if (rid < 1 || rid > Fields.Length) return null; return Fields [rid - 1]; } public void AddFieldDefinition (FieldDefinition field) { Fields [field.token.RID - 1] = field; } public MethodDefinition GetMethodDefinition (uint rid) { if (rid < 1 || rid > Methods.Length) return null; return Methods [rid - 1]; } public void AddMethodDefinition (MethodDefinition method) { Methods [method.token.RID - 1] = method; } public MemberReference GetMemberReference (uint rid) { if (rid < 1 || rid > MemberReferences.Length) return null; return MemberReferences [rid - 1]; } public void AddMemberReference (MemberReference member) { MemberReferences [member.token.RID - 1] = member; } public bool TryGetNestedTypeMapping (TypeDefinition type, out uint [] mapping) { return NestedTypes.TryGetValue (type.token.RID, out mapping); } public void SetNestedTypeMapping (uint type_rid, uint [] mapping) { NestedTypes [type_rid] = mapping; } public void RemoveNestedTypeMapping (TypeDefinition type) { NestedTypes.Remove (type.token.RID); } public bool TryGetReverseNestedTypeMapping (TypeDefinition type, out uint declaring) { return ReverseNestedTypes.TryGetValue (type.token.RID, out declaring); } public void SetReverseNestedTypeMapping (uint nested, uint declaring) { ReverseNestedTypes.Add (nested, declaring); } public void RemoveReverseNestedTypeMapping (TypeDefinition type) { ReverseNestedTypes.Remove (type.token.RID); } public bool TryGetInterfaceMapping (TypeDefinition type, out MetadataToken [] mapping) { return Interfaces.TryGetValue (type.token.RID, out mapping); } public void SetInterfaceMapping (uint type_rid, MetadataToken [] mapping) { Interfaces [type_rid] = mapping; } public void RemoveInterfaceMapping (TypeDefinition type) { Interfaces.Remove (type.token.RID); } public void AddPropertiesRange (uint type_rid, Range range) { Properties.Add (type_rid, range); } public bool TryGetPropertiesRange (TypeDefinition type, out Range range) { return Properties.TryGetValue (type.token.RID, out range); } public void RemovePropertiesRange (TypeDefinition type) { Properties.Remove (type.token.RID); } public void AddEventsRange (uint type_rid, Range range) { Events.Add (type_rid, range); } public bool TryGetEventsRange (TypeDefinition type, out Range range) { return Events.TryGetValue (type.token.RID, out range); } public void RemoveEventsRange (TypeDefinition type) { Events.Remove (type.token.RID); } public bool TryGetGenericParameterRange (IGenericParameterProvider owner, out Range range) { return GenericParameters.TryGetValue (owner.MetadataToken, out range); } public void RemoveGenericParameterRange (IGenericParameterProvider owner) { GenericParameters.Remove (owner.MetadataToken); } public bool TryGetCustomAttributeRange (ICustomAttributeProvider owner, out Range range) { return CustomAttributes.TryGetValue (owner.MetadataToken, out range); } public void RemoveCustomAttributeRange (ICustomAttributeProvider owner) { CustomAttributes.Remove (owner.MetadataToken); } public bool TryGetSecurityDeclarationRange (ISecurityDeclarationProvider owner, out Range range) { return SecurityDeclarations.TryGetValue (owner.MetadataToken, out range); } public void RemoveSecurityDeclarationRange (ISecurityDeclarationProvider owner) { SecurityDeclarations.Remove (owner.MetadataToken); } public bool TryGetGenericConstraintMapping (GenericParameter generic_parameter, out MetadataToken [] mapping) { return GenericConstraints.TryGetValue (generic_parameter.token.RID, out mapping); } public void SetGenericConstraintMapping (uint gp_rid, MetadataToken [] mapping) { GenericConstraints [gp_rid] = mapping; } public void RemoveGenericConstraintMapping (GenericParameter generic_parameter) { GenericConstraints.Remove (generic_parameter.token.RID); } public bool TryGetOverrideMapping (MethodDefinition method, out MetadataToken [] mapping) { return Overrides.TryGetValue (method.token.RID, out mapping); } public void SetOverrideMapping (uint rid, MetadataToken [] mapping) { Overrides [rid] = mapping; } public void RemoveOverrideMapping (MethodDefinition method) { Overrides.Remove (method.token.RID); } public TypeDefinition GetFieldDeclaringType (uint field_rid) { return BinaryRangeSearch (Types, field_rid, true); } public TypeDefinition GetMethodDeclaringType (uint method_rid) { return BinaryRangeSearch (Types, method_rid, false); } static TypeDefinition BinaryRangeSearch (TypeDefinition [] types, uint rid, bool field) { int min = 0; int max = types.Length - 1; while (min <= max) { int mid = min + ((max - min) / 2); var type = types [mid]; var range = field ? type.fields_range : type.methods_range; if (rid < range.Start) max = mid - 1; else if (rid >= range.Start + range.Length) min = mid + 1; else return type; } return null; } } }
#if UNITY_PURCHASING || UNITY_UNIFIED_IAP using UnityEngine.Events; using UnityEngine.UI; using System.IO; using System.Collections.Generic; namespace UnityEngine.Purchasing { [RequireComponent(typeof(Button))] [AddComponentMenu("Unity IAP/IAP Button")] [HelpURL("https://docs.unity3d.com/Manual/UnityIAP.html")] public class IAPButton : MonoBehaviour { public enum ButtonType { Purchase, Restore } [System.Serializable] public class OnPurchaseCompletedEvent : UnityEvent<Product> { }; [System.Serializable] public class OnPurchaseFailedEvent : UnityEvent<Product, PurchaseFailureReason> { }; [HideInInspector] public string productId; [Tooltip("The type of this button, can be either a purchase or a restore button")] public ButtonType buttonType = ButtonType.Purchase; [Tooltip("Consume the product immediately after a successful purchase")] public bool consumePurchase = true; [Tooltip("Event fired after a successful purchase of this product")] public OnPurchaseCompletedEvent onPurchaseComplete; [Tooltip("Event fired after a failed purchase of this product")] public OnPurchaseFailedEvent onPurchaseFailed; [Tooltip("[Optional] Displays the localized title from the app store")] public Text titleText; [Tooltip("[Optional] Displays the localized description from the app store")] public Text descriptionText; [Tooltip("[Optional] Displays the localized price from the app store")] public Text priceText; void Start() { Button button = GetComponent<Button>(); if (buttonType == ButtonType.Purchase) { if (button) { button.onClick.AddListener(PurchaseProduct); } if (string.IsNullOrEmpty(productId)) { Debug.LogError("IAPButton productId is empty"); } if (!CodelessIAPStoreListener.Instance.HasProductInCatalog(productId)) { Debug.LogWarning("The product catalog has no product with the ID \"" + productId + "\""); } } else if (buttonType == ButtonType.Restore) { if (button) { button.onClick.AddListener(Restore); } } } void OnEnable() { if (buttonType == ButtonType.Purchase) { CodelessIAPStoreListener.Instance.AddButton(this); if (CodelessIAPStoreListener.initializationComplete) { UpdateText(); } } } void OnDisable() { if (buttonType == ButtonType.Purchase) { CodelessIAPStoreListener.Instance.RemoveButton(this); } } void PurchaseProduct() { if (buttonType == ButtonType.Purchase) { Debug.Log("IAPButton.PurchaseProduct() with product ID: " + productId); CodelessIAPStoreListener.Instance.InitiatePurchase(productId); } } void Restore() { if (buttonType == ButtonType.Restore) { if (Application.platform == RuntimePlatform.WSAPlayerX86 || Application.platform == RuntimePlatform.WSAPlayerX64 || Application.platform == RuntimePlatform.WSAPlayerARM) { CodelessIAPStoreListener.Instance.ExtensionProvider.GetExtension<IMicrosoftExtensions>() .RestoreTransactions(); } else if (Application.platform == RuntimePlatform.IPhonePlayer || Application.platform == RuntimePlatform.OSXPlayer || Application.platform == RuntimePlatform.tvOS) { CodelessIAPStoreListener.Instance.ExtensionProvider.GetExtension<IAppleExtensions>() .RestoreTransactions(OnTransactionsRestored); } else if (Application.platform == RuntimePlatform.Android && StandardPurchasingModule.Instance().appStore == AppStore.SamsungApps) { CodelessIAPStoreListener.Instance.ExtensionProvider.GetExtension<ISamsungAppsExtensions>() .RestoreTransactions(OnTransactionsRestored); } else if (Application.platform == RuntimePlatform.Android && StandardPurchasingModule.Instance().appStore == AppStore.GooglePlay) { CodelessIAPStoreListener.Instance.ExtensionProvider.GetExtension<IGooglePlayStoreExtensions>() .RestoreTransactions(OnTransactionsRestored); } else { Debug.LogWarning(Application.platform.ToString() + " is not a supported platform for the Codeless IAP restore button"); } } } void OnTransactionsRestored(bool success) { Debug.Log("Transactions restored: " + success); } /** * Invoked to process a purchase of the product associated with this button */ public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs e) { Debug.Log(string.Format("IAPButton.ProcessPurchase(PurchaseEventArgs {0} - {1})", e, e.purchasedProduct.definition.id)); onPurchaseComplete.Invoke(e.purchasedProduct); return (consumePurchase) ? PurchaseProcessingResult.Complete : PurchaseProcessingResult.Pending; } /** * Invoked on a failed purchase of the product associated with this button */ public void OnPurchaseFailed(Product product, PurchaseFailureReason reason) { Debug.Log(string.Format("IAPButton.OnPurchaseFailed(Product {0}, PurchaseFailureReason {1})", product, reason)); onPurchaseFailed.Invoke(product, reason); } internal void UpdateText() { var product = CodelessIAPStoreListener.Instance.GetProduct(productId); if (product != null) { if (titleText != null) { titleText.text = product.metadata.localizedTitle; } if (descriptionText != null) { descriptionText.text = product.metadata.localizedDescription; } if (priceText != null) { priceText.text = product.metadata.localizedPriceString; } } } } } #endif
// StreamManipulator.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { /// <summary> /// This class allows us to retrieve a specified number of bits from /// the input buffer, as well as copy big byte blocks. /// /// It uses an int buffer to store up to 31 bits for direct /// manipulation. This guarantees that we can get at least 16 bits, /// but we only need at most 15, so this is all safe. /// /// There are some optimizations in this class, for example, you must /// never peek more than 8 bits more than needed, and you must first /// peek bits before you may drop them. This is not a general purpose /// class but optimized for the behaviour of the Inflater. /// /// authors of the original java version : John Leuner, Jochen Hoenicke /// </summary> public class StreamManipulator { #region Constructors /// <summary> /// Constructs a default StreamManipulator with all buffers empty /// </summary> public StreamManipulator() { } #endregion /// <summary> /// Get the next sequence of bits but don't increase input pointer. bitCount must be /// less or equal 16 and if this call succeeds, you must drop /// at least n - 8 bits in the next call. /// </summary> /// <param name="bitCount">The number of bits to peek.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. */ /// </returns> public int PeekBits(int bitCount) { if (bitsInBuffer_ < bitCount) { if (windowStart_ == windowEnd_) { return -1; // ok } buffer_ |= (uint)((window_[windowStart_++] & 0xff | (window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_); bitsInBuffer_ += 16; } return (int)(buffer_ & ((1 << bitCount) - 1)); } /// <summary> /// Drops the next n bits from the input. You should have called PeekBits /// with a bigger or equal n before, to make sure that enough bits are in /// the bit buffer. /// </summary> /// <param name="bitCount">The number of bits to drop.</param> public void DropBits(int bitCount) { buffer_ >>= bitCount; bitsInBuffer_ -= bitCount; } /// <summary> /// Gets the next n bits and increases input pointer. This is equivalent /// to <see cref="PeekBits"/> followed by <see cref="DropBits"/>, except for correct error handling. /// </summary> /// <param name="bitCount">The number of bits to retrieve.</param> /// <returns> /// the value of the bits, or -1 if not enough bits available. /// </returns> public int GetBits(int bitCount) { int bits = PeekBits(bitCount); if (bits >= 0) { DropBits(bitCount); } return bits; } /// <summary> /// Gets the number of bits available in the bit buffer. This must be /// only called when a previous PeekBits() returned -1. /// </summary> /// <returns> /// the number of bits available. /// </returns> public int AvailableBits { get { return bitsInBuffer_; } } /// <summary> /// Gets the number of bytes available. /// </summary> /// <returns> /// The number of bytes available. /// </returns> public int AvailableBytes { get { return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3); } } /// <summary> /// Skips to the next byte boundary. /// </summary> public void SkipToByteBoundary() { buffer_ >>= (bitsInBuffer_ & 7); bitsInBuffer_ &= ~7; } /// <summary> /// Returns true when SetInput can be called /// </summary> public bool IsNeedingInput { get { return windowStart_ == windowEnd_; } } /// <summary> /// Copies bytes from input buffer to output buffer starting /// at output[offset]. You have to make sure, that the buffer is /// byte aligned. If not enough bytes are available, copies fewer /// bytes. /// </summary> /// <param name="output"> /// The buffer to copy bytes to. /// </param> /// <param name="offset"> /// The offset in the buffer at which copying starts /// </param> /// <param name="length"> /// The length to copy, 0 is allowed. /// </param> /// <returns> /// The number of bytes copied, 0 if no bytes were available. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// Length is less than zero /// </exception> /// <exception cref="InvalidOperationException"> /// Bit buffer isnt byte aligned /// </exception> public int CopyBytes(byte[] output, int offset, int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length"); } if ((bitsInBuffer_ & 7) != 0) { // bits_in_buffer may only be 0 or a multiple of 8 throw new InvalidOperationException("Bit buffer is not byte aligned!"); } int count = 0; while ((bitsInBuffer_ > 0) && (length > 0)) { output[offset++] = (byte) buffer_; buffer_ >>= 8; bitsInBuffer_ -= 8; length--; count++; } if (length == 0) { return count; } int avail = windowEnd_ - windowStart_; if (length > avail) { length = avail; } System.Array.Copy(window_, windowStart_, output, offset, length); windowStart_ += length; if (((windowStart_ - windowEnd_) & 1) != 0) { // We always want an even number of bytes in input, see peekBits buffer_ = (uint)(window_[windowStart_++] & 0xff); bitsInBuffer_ = 8; } return count + length; } /// <summary> /// Resets state and empties internal buffers /// </summary> public void Reset() { buffer_ = 0; windowStart_ = windowEnd_ = bitsInBuffer_ = 0; } /// <summary> /// Add more input for consumption. /// Only call when IsNeedingInput returns true /// </summary> /// <param name="buffer">data to be input</param> /// <param name="offset">offset of first byte of input</param> /// <param name="count">number of bytes of input to add.</param> public void SetInput(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("offset"); #else throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif } if ( count < 0 ) { #if NETCF_1_0 throw new ArgumentOutOfRangeException("count"); #else throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif } if (windowStart_ < windowEnd_) { throw new InvalidOperationException("Old input was not completely processed"); } int end = offset + count; // We want to throw an ArrayIndexOutOfBoundsException early. // Note the check also handles integer wrap around. if ((offset > end) || (end > buffer.Length) ) { throw new ArgumentOutOfRangeException("count"); } if ((count & 1) != 0) { // We always want an even number of bytes in input, see PeekBits buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_); bitsInBuffer_ += 8; } window_ = buffer; windowStart_ = offset; windowEnd_ = end; } #region Instance Fields private byte[] window_; private int windowStart_; private int windowEnd_; private uint buffer_; private int bitsInBuffer_; #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Text; using Orleans.CodeGenerator.Analysis; namespace Orleans.CodeGenerator.MSBuild { public class CodeGeneratorCommand { private const string AbstractionsAssemblyShortName = "Orleans.Core.Abstractions"; private static readonly int[] SuppressCompilerWarnings = { 162, // CS0162 - Unreachable code detected. 219, // CS0219 - The variable 'V' is assigned but its value is never used. 414, // CS0414 - The private field 'F' is assigned but its value is never used. 618, // CS0616 - Member is obsolete. 649, // CS0649 - Field 'F' is never assigned to, and will always have its default value. 693, // CS0693 - Type parameter 'type parameter' has the same name as the type parameter from outer type 'T' 1591, // CS1591 - Missing XML comment for publicly visible type or member 'Type_or_Member' 1998 // CS1998 - This async method lacks 'await' operators and will run synchronously }; /// <summary> /// The MSBuild project path. /// </summary> public string ProjectPath { get; set; } /// <summary> /// The optional ProjectGuid. /// </summary> public string ProjectGuid { get; set; } /// <summary> /// The output type, such as Exe, or Library. /// </summary> public string OutputType { get; set; } /// <summary> /// The target path of the compilation. /// </summary> public string TargetPath { get; set; } /// <summary> /// The source files. /// </summary> public List<string> Compile { get; } = new List<string>(); /// <summary> /// The libraries referenced by the project. /// </summary> public List<string> Reference { get; } = new List<string>(); /// <summary> /// The defined constants for the project. /// </summary> public List<string> DefineConstants { get; } = new List<string>(); /// <summary> /// The file which holds the generated code. /// </summary> public string CodeGenOutputFile { get; set; } /// <summary> /// The project's assembly name, important for id calculations. /// </summary> public string AssemblyName { get; set; } /// <summary> /// Whether or not to add <see cref="DebuggerStepThroughAttribute"/> to generated code. /// </summary> public bool DebuggerStepThrough { get; set; } public async Task<bool> Execute(CancellationToken cancellationToken) { var stopwatch = Stopwatch.StartNew(); var projectName = Path.GetFileNameWithoutExtension(ProjectPath); var projectId = !string.IsNullOrEmpty(ProjectGuid) && Guid.TryParse(ProjectGuid, out var projectIdGuid) ? ProjectId.CreateFromSerialized(projectIdGuid) : ProjectId.CreateNewId(); var languageName = GetLanguageName(ProjectPath); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Default, projectName, AssemblyName, languageName, ProjectPath, TargetPath, CreateCompilationOptions(this), documents: GetDocuments(Compile, projectId), metadataReferences: GetMetadataReferences(Reference), parseOptions: new CSharpParseOptions(preprocessorSymbols: this.DefineConstants) ); var workspace = new AdhocWorkspace(); workspace.AddProject(projectInfo); var project = workspace.CurrentSolution.Projects.Single(); stopwatch.Restart(); var compilation = await project.GetCompilationAsync(cancellationToken); stopwatch.Restart(); if (!compilation.SyntaxTrees.Any()) { Console.WriteLine($"Skipping empty project, {compilation.AssemblyName}."); return true; } if (compilation.ReferencedAssemblyNames.All(name => name.Name != AbstractionsAssemblyShortName)) { Console.WriteLine($"Project {compilation.AssemblyName} does not reference {AbstractionsAssemblyShortName} (references: {string.Join(", ", compilation.ReferencedAssemblyNames)})"); return false; } var options = new CodeGeneratorOptions { DebuggerStepThrough = this.DebuggerStepThrough }; var generator = new CodeGenerator(new CodeGeneratorExecutionContext { Compilation = compilation }, options); var syntax = generator.GenerateCode(cancellationToken); stopwatch.Restart(); var normalized = syntax.NormalizeWhitespace(); stopwatch.Restart(); var sourceBuilder = new StringBuilder(); sourceBuilder.AppendLine("// <auto-generated />"); sourceBuilder.AppendLine("#if !EXCLUDE_GENERATED_CODE"); foreach (var warningNum in SuppressCompilerWarnings) sourceBuilder.AppendLine($"#pragma warning disable {warningNum}"); sourceBuilder.AppendLine(normalized.ToFullString()); foreach (var warningNum in SuppressCompilerWarnings) sourceBuilder.AppendLine($"#pragma warning restore {warningNum}"); sourceBuilder.AppendLine("#endif"); var source = sourceBuilder.ToString(); stopwatch.Restart(); if (File.Exists(this.CodeGenOutputFile)) { using (var reader = new StreamReader(this.CodeGenOutputFile)) { var existing = await reader.ReadToEndAsync(); if (string.Equals(source, existing, StringComparison.Ordinal)) { return true; } } } using (var sourceWriter = new StreamWriter(this.CodeGenOutputFile)) { await sourceWriter.WriteAsync(source); } return true; } private static IEnumerable<DocumentInfo> GetDocuments(List<string> sources, ProjectId projectId) => sources ?.Where(File.Exists) .Select(x => DocumentInfo.Create( DocumentId.CreateNewId(projectId), Path.GetFileName(x), loader: TextLoader.From( TextAndVersion.Create( SourceText.From(File.ReadAllText(x)), VersionStamp.Create())), filePath: x)) ?? Array.Empty<DocumentInfo>(); private static IEnumerable<MetadataReference> GetMetadataReferences(List<string> references) => references ?.Where(File.Exists) .Select(x => MetadataReference.CreateFromFile(x)) ?? (IEnumerable<MetadataReference>)Array.Empty<MetadataReference>(); private static string GetLanguageName(string projectPath) { switch (Path.GetExtension(projectPath)) { case ".csproj": return LanguageNames.CSharp; case string ext when !string.IsNullOrWhiteSpace(ext): throw new NotSupportedException($"Projects of type {ext} are not supported."); default: throw new InvalidOperationException("Could not determine supported language from project path"); } } private static CompilationOptions CreateCompilationOptions(CodeGeneratorCommand command) { OutputKind kind; switch (command.OutputType) { case "Exe": kind = OutputKind.ConsoleApplication; break; case "Module": kind = OutputKind.NetModule; break; case "Winexe": kind = OutputKind.WindowsApplication; break; default: case "Library": kind = OutputKind.DynamicallyLinkedLibrary; break; } return new CSharpCompilationOptions(kind) .WithMetadataImportOptions(MetadataImportOptions.All) .WithAllowUnsafe(true) .WithConcurrentBuild(true) .WithOptimizationLevel(OptimizationLevel.Debug); } } public class CodeGeneratorExecutionContext : IGeneratorExecutionContext { public Compilation Compilation { get; init; } public CancellationToken CancellationToken => CancellationToken.None; public void ReportDiagnostic(Diagnostic diagnostic) { Console.WriteLine($"[{diagnostic.Id}] {diagnostic.Severity} at {diagnostic.Location}: {diagnostic.GetMessage()}"); } } }
/* * Copyright 2004,2006 The Poderosa Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * $Id: TelnetSSHPlugin.cs,v 1.4 2011/10/27 23:21:59 kzmi Exp $ */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Diagnostics; using Poderosa.Plugins; using Poderosa.Commands; using Poderosa.Terminal; using Poderosa.ConnectionParam; using Poderosa.Protocols; using Poderosa.Forms; using Poderosa.MacroEngine; using System.Threading.Tasks; [assembly: PluginDeclaration(typeof(Poderosa.Sessions.TelnetSSHPlugin))] namespace Poderosa.Sessions { [PluginInfo(ID = "org.poderosa.telnet_ssh", Version = VersionInfo.PODEROSA_VERSION, Author = VersionInfo.PROJECT_NAME, Dependencies = "org.poderosa.core.window")] internal class TelnetSSHPlugin : PluginBase { private static TelnetSSHPlugin _instance; private ICommandManager _commandManager; private LoginDialogCommand _loginDialogCommand; private LoginMenuGroup _loginMenuGroup; private LoginToolBarComponent _loginToolBarComponent; private IMacroEngine _macroEngine; public static TelnetSSHPlugin Instance { get { return _instance; } } public override void InitializePlugin(IPoderosaWorld poderosa) { base.InitializePlugin(poderosa); _instance = this; IPluginManager pm = poderosa.PluginManager; _commandManager = (ICommandManager)pm.FindPlugin("org.poderosa.core.commands", typeof(ICommandManager)); _loginDialogCommand = new LoginDialogCommand(); _commandManager.Register(_loginDialogCommand); IExtensionPoint ep = pm.FindExtensionPoint("org.poderosa.menu.file"); _loginMenuGroup = new LoginMenuGroup(); ep.RegisterExtension(_loginMenuGroup); IExtensionPoint toolbar = pm.FindExtensionPoint("org.poderosa.core.window.toolbar"); _loginToolBarComponent = new LoginToolBarComponent(); toolbar.RegisterExtension(_loginToolBarComponent); } public IPoderosaMenuGroup TelnetSSHMenuGroup { get { return _loginMenuGroup; } } public IToolBarComponent TelnetSSHToolBar { get { return _loginToolBarComponent; } } public IMacroEngine MacroEngine { get { if (_macroEngine == null) { _macroEngine = _poderosaWorld.PluginManager.FindPlugin("org.poderosa.macro", typeof(IMacroEngine)) as IMacroEngine; } return _macroEngine; } } private class LoginMenuGroup : IPoderosaMenuGroup, IPositionDesignation { public IPoderosaMenu[] ChildMenus { get { return new IPoderosaMenu[] { new LoginMenuItem() }; } } public bool IsVolatileContent { get { return false; } } public bool ShowSeparator { get { return true; } } public IAdaptable GetAdapter(Type adapter) { return _instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); } public IAdaptable DesignationTarget { get { return null; } } public PositionType DesignationPosition { get { return PositionType.First; } } } private class LoginMenuItem : IPoderosaMenuItem { public IPoderosaCommand AssociatedCommand { get { return _instance._loginDialogCommand; } } public string Text { get { return TEnv.Strings.GetString("Menu.NewConnection"); } } public bool IsEnabled(ICommandTarget target) { return true; } public bool IsChecked(ICommandTarget target) { return false; } public IAdaptable GetAdapter(Type adapter) { return _instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); } } private class LoginToolBarComponent : IToolBarComponent, IPositionDesignation { public IAdaptable DesignationTarget { get { return null; } } public PositionType DesignationPosition { get { return PositionType.First; } } public bool ShowSeparator { get { return true; } } public IToolBarElement[] ToolBarElements { get { return new IToolBarElement[] { new ToolBarCommandButtonImpl(_instance._loginDialogCommand, Poderosa.TerminalSession.Properties.Resources.NewConnection16x16) }; } } public IAdaptable GetAdapter(Type adapter) { return _instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); } } private class LoginDialogCommand : IGeneralCommand { public CommandResult InternalExecute(ICommandTarget target, params IAdaptable[] args) { IPoderosaMainWindow window = (IPoderosaMainWindow)target.GetAdapter(typeof(IPoderosaMainWindow)); if (window == null) return CommandResult.Ignored; TelnetSSHLoginDialog dlg = new TelnetSSHLoginDialog(window); dlg.ApplyParam(); CommandResult res = CommandResult.Cancelled; //Task.Run(() => { if (dlg.ShowDialog() == DialogResult.OK) { ITerminalConnection con = dlg.Result; if (con != null) { ISessionManager sm = (ISessionManager)TelnetSSHPlugin.Instance.PoderosaWorld.PluginManager.FindPlugin("org.poderosa.core.sessions", typeof(ISessionManager)); TerminalSession ts = new TerminalSession(con, dlg.TerminalSettings); sm.StartNewSession(ts, (IPoderosaView)dlg.TargetView.GetAdapter(typeof(IPoderosaView))); sm.ActivateDocument(ts.Terminal.IDocument, ActivateReason.InternalAction); IAutoExecMacroParameter autoExecParam = con.Destination.GetAdapter(typeof(IAutoExecMacroParameter)) as IAutoExecMacroParameter; if (autoExecParam != null && autoExecParam.AutoExecMacroPath != null && TelnetSSHPlugin.Instance.MacroEngine != null) { TelnetSSHPlugin.Instance.MacroEngine.RunMacro(autoExecParam.AutoExecMacroPath, ts); } return CommandResult.Succeeded; } } dlg.Dispose(); } //); return res; } public string CommandID { get { return "org.poderosa.session.telnetSSH"; } } public Keys DefaultShortcutKey { get { return Keys.Alt | Keys.N; } } public string Description { get { return TEnv.Strings.GetString("Command.TelnetSSH"); } } public ICommandCategory CommandCategory { get { return ConnectCommandCategory._instance; } } public bool CanExecute(ICommandTarget target) { return true; } public IAdaptable GetAdapter(Type adapter) { return _instance.PoderosaWorld.AdapterManager.GetAdapter(this, adapter); } } } }
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; // <auto-generated /> namespace Northwind { /// <summary> /// Strongly-typed collection for the CustomerDemographic class. /// </summary> [Serializable] public partial class CustomerDemographicCollection : ActiveList<CustomerDemographic, CustomerDemographicCollection> { public CustomerDemographicCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>CustomerDemographicCollection</returns> public CustomerDemographicCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { CustomerDemographic 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 CustomerDemographics table. /// </summary> [Serializable] public partial class CustomerDemographic : ActiveRecord<CustomerDemographic>, IActiveRecord { #region .ctors and Default Settings public CustomerDemographic() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public CustomerDemographic(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public CustomerDemographic(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public CustomerDemographic(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("CustomerDemographics", TableType.Table, DataService.GetInstance("Northwind")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarCustomerTypeID = new TableSchema.TableColumn(schema); colvarCustomerTypeID.ColumnName = "CustomerTypeID"; colvarCustomerTypeID.DataType = DbType.String; colvarCustomerTypeID.MaxLength = 10; colvarCustomerTypeID.AutoIncrement = false; colvarCustomerTypeID.IsNullable = false; colvarCustomerTypeID.IsPrimaryKey = true; colvarCustomerTypeID.IsForeignKey = false; colvarCustomerTypeID.IsReadOnly = false; colvarCustomerTypeID.DefaultSetting = @""; colvarCustomerTypeID.ForeignKeyTableName = ""; schema.Columns.Add(colvarCustomerTypeID); TableSchema.TableColumn colvarCustomerDesc = new TableSchema.TableColumn(schema); colvarCustomerDesc.ColumnName = "CustomerDesc"; colvarCustomerDesc.DataType = DbType.String; colvarCustomerDesc.MaxLength = 1073741823; colvarCustomerDesc.AutoIncrement = false; colvarCustomerDesc.IsNullable = true; colvarCustomerDesc.IsPrimaryKey = false; colvarCustomerDesc.IsForeignKey = false; colvarCustomerDesc.IsReadOnly = false; colvarCustomerDesc.DefaultSetting = @""; colvarCustomerDesc.ForeignKeyTableName = ""; schema.Columns.Add(colvarCustomerDesc); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["Northwind"].AddSchema("CustomerDemographics",schema); } } #endregion #region Props [XmlAttribute("CustomerTypeID")] [Bindable(true)] public string CustomerTypeID { get { return GetColumnValue<string>(Columns.CustomerTypeID); } set { SetColumnValue(Columns.CustomerTypeID, value); } } [XmlAttribute("CustomerDesc")] [Bindable(true)] public string CustomerDesc { get { return GetColumnValue<string>(Columns.CustomerDesc); } set { SetColumnValue(Columns.CustomerDesc, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } public Northwind.CustomerCustomerDemoCollection CustomerCustomerDemoRecords() { return new Northwind.CustomerCustomerDemoCollection().Where(CustomerCustomerDemo.Columns.CustomerTypeID, CustomerTypeID).Load(); } #endregion //no foreign key tables defined (0) #region Many To Many Helpers public Northwind.CustomerCollection GetCustomerCollection() { return CustomerDemographic.GetCustomerCollection(this.CustomerTypeID); } public static Northwind.CustomerCollection GetCustomerCollection(string varCustomerTypeID) { SubSonic.QueryCommand cmd = new SubSonic.QueryCommand("SELECT * FROM [dbo].[Customers] INNER JOIN [CustomerCustomerDemo] ON [Customers].[CustomerID] = [CustomerCustomerDemo].[CustomerID] WHERE [CustomerCustomerDemo].[CustomerTypeID] = @CustomerTypeID", CustomerDemographic.Schema.Provider.Name); cmd.AddParameter("@CustomerTypeID", varCustomerTypeID, DbType.String); IDataReader rdr = SubSonic.DataService.GetReader(cmd); CustomerCollection coll = new CustomerCollection(); coll.LoadAndCloseReader(rdr); return coll; } public static void SaveCustomerMap(string varCustomerTypeID, CustomerCollection items) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerTypeID] = @CustomerTypeID", CustomerDemographic.Schema.Provider.Name); cmdDel.AddParameter("@CustomerTypeID", varCustomerTypeID, DbType.String); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (Customer item in items) { CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo(); varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", varCustomerTypeID); varCustomerCustomerDemo.SetColumnValue("CustomerID", item.GetPrimaryKeyValue()); varCustomerCustomerDemo.Save(); } } public static void SaveCustomerMap(string varCustomerTypeID, System.Web.UI.WebControls.ListItemCollection itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerTypeID] = @CustomerTypeID", CustomerDemographic.Schema.Provider.Name); cmdDel.AddParameter("@CustomerTypeID", varCustomerTypeID, DbType.String); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (System.Web.UI.WebControls.ListItem l in itemList) { if (l.Selected) { CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo(); varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", varCustomerTypeID); varCustomerCustomerDemo.SetColumnValue("CustomerID", l.Value); varCustomerCustomerDemo.Save(); } } } public static void SaveCustomerMap(string varCustomerTypeID , string[] itemList) { QueryCommandCollection coll = new SubSonic.QueryCommandCollection(); //delete out the existing QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerTypeID] = @CustomerTypeID", CustomerDemographic.Schema.Provider.Name); cmdDel.AddParameter("@CustomerTypeID", varCustomerTypeID, DbType.String); coll.Add(cmdDel); DataService.ExecuteTransaction(coll); foreach (string item in itemList) { CustomerCustomerDemo varCustomerCustomerDemo = new CustomerCustomerDemo(); varCustomerCustomerDemo.SetColumnValue("CustomerTypeID", varCustomerTypeID); varCustomerCustomerDemo.SetColumnValue("CustomerID", item); varCustomerCustomerDemo.Save(); } } public static void DeleteCustomerMap(string varCustomerTypeID) { QueryCommand cmdDel = new QueryCommand("DELETE FROM [CustomerCustomerDemo] WHERE [CustomerCustomerDemo].[CustomerTypeID] = @CustomerTypeID", CustomerDemographic.Schema.Provider.Name); cmdDel.AddParameter("@CustomerTypeID", varCustomerTypeID, DbType.String); DataService.ExecuteQuery(cmdDel); } #endregion #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCustomerTypeID,string varCustomerDesc) { CustomerDemographic item = new CustomerDemographic(); item.CustomerTypeID = varCustomerTypeID; item.CustomerDesc = varCustomerDesc; 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(string varCustomerTypeID,string varCustomerDesc) { CustomerDemographic item = new CustomerDemographic(); item.CustomerTypeID = varCustomerTypeID; item.CustomerDesc = varCustomerDesc; 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 CustomerTypeIDColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CustomerDescColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string CustomerTypeID = @"CustomerTypeID"; public static string CustomerDesc = @"CustomerDesc"; } #endregion #region Update PK Collections public void SetPKValues() { } #endregion #region Deep Save public void DeepSave() { Save(); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using Palaso.Code; using Palaso.Data; using Palaso.i18n; using Palaso.Lift; using Palaso.Reporting; using Palaso.Text; //using Palaso.UI.WindowsForms.i18n; namespace Palaso.DictionaryServices.Model { /// <summary> /// A Lexical Entry is what makes up our lexicon/dictionary. In /// some languages/dictionaries, these will be indistinguishable from "words". /// In others, words are made up of lexical entries. /// </summary> public class LexEntry: PalasoDataObject, IClonableGeneric<LexEntry> { private MultiText _lexicalForm; private Guid _guid; /// <summary> /// This use for keeping track of the item when importing an then exporting again, /// like for merging. The user doesn't edit this, and if it is null that's fine, /// the exporter will make up a reasonable one. /// </summary> private string _id; private int _orderForRoundTripping; private int _orderInFile; private BindingList<LexSense> _senses; //NB: to help with possible confusion: as of wesay 0.9 (oct 2010), wesay doesn't use these lists (it just shoves them in embedded xml), but SOLID does private BindingList<LexVariant> _variants; private BindingList<LexNote> _notes; private BindingList<LexPhonetic> _pronunciations; private BindingList<LexEtymology> _etymologies; private DateTime _creationTime; private DateTime _modificationTime; private bool _isBeingDeleted; private bool _isDirty; [NonSerialized] private bool _modifiedTimeIsLocked; //!!What!! Is this done this way so that we don't end up storing // the data in the object database? public new class WellKnownProperties: PalasoDataObject.WellKnownProperties { public static string Citation = "citation"; public static string LexicalUnit = "EntryLexicalForm"; public static string BaseForm = "BaseForm"; public static string CrossReference = "confer"; public static string Sense = "sense"; public static string FlagSkipBaseform = "flag-skip-BaseForm"; public static string LiteralMeaning = "literal-meaning"; public static bool Contains(string fieldName) { List<string> list = new List<string>(new string[] { LexicalUnit, Citation, BaseForm, CrossReference, Sense, LiteralMeaning }); return list.Contains(fieldName); } } ; public LexEntry(): this(null, Guid.NewGuid()) {} public LexEntry(string id, Guid guid): base(null) { DateTime now = PreciseDateTime.UtcNow; _isDirty = true; Init(id, guid, now, now); } private void Init(string id, Guid guid, DateTime creationTime, DateTime modifiedTime) { ModificationTime = modifiedTime; ModifiedTimeIsLocked = true; Id = id; if (guid == Guid.Empty) { _guid = Guid.NewGuid(); } else { _guid = guid; } _lexicalForm = new MultiText(this); _senses = new BindingList<LexSense>(); _variants = new BindingList<LexVariant>(); _notes = new BindingList<LexNote>(); _pronunciations = new BindingList<LexPhonetic>(); _etymologies = new BindingList<LexEtymology>(); CreationTime = creationTime; WireUpEvents(); ModifiedTimeIsLocked = false; } public LexEntry Clone() { var clone = new LexEntry(); clone._lexicalForm = (MultiText) _lexicalForm.Clone(); //_lexicalForm and Guid must have been set before _id is set if(_id != null) { clone.GetOrCreateId(false); } clone.OrderForRoundTripping = _orderForRoundTripping; clone._orderInFile = _orderInFile; foreach (var senseToClone in _senses) { clone._senses.Add(senseToClone.Clone()); } foreach (var lexVariantToClone in Variants) { clone.Variants.Add((LexVariant) lexVariantToClone.Clone()); } foreach (var lexNoteToClone in Notes) { clone.Notes.Add((LexNote) lexNoteToClone.Clone()); } foreach (var pronunciationToClone in _pronunciations) { clone._pronunciations.Add((LexPhonetic) pronunciationToClone.Clone()); } foreach (var etymologyToClone in _etymologies) { clone._etymologies.Add((LexEtymology)etymologyToClone.Clone()); } foreach (var keyValuePairToClone in Properties) { clone.AddProperty(keyValuePairToClone.Key, keyValuePairToClone.Value.Clone()); } return clone; } public override bool Equals(object other) { if (!(other is LexEntry)) return false; return Equals((LexEntry) other); } public bool Equals(LexEntry other) { if (other == null) return false; if (!_lexicalForm.Equals(other._lexicalForm)) return false; if (!_orderForRoundTripping.Equals(other._orderForRoundTripping)) return false; if (!_orderInFile.Equals(other._orderInFile)) return false; if (!_senses.SequenceEqual(other._senses)) return false; if (!_variants.SequenceEqual(other._variants)) return false; if (!_notes.SequenceEqual(other._notes)) return false; if (!_pronunciations.SequenceEqual(other._pronunciations)) return false; if (!_etymologies.SequenceEqual(other._etymologies)) return false; if (!base.Equals(other)) return false; return true; } public override string ToString() { //hack if (_lexicalForm != null) { return _lexicalForm.GetFirstAlternative(); } else { return ""; } } protected override void WireUpEvents() { Debug.Assert(CreationTime.Kind == DateTimeKind.Utc); Debug.Assert(ModificationTime.Kind == DateTimeKind.Utc); base.WireUpEvents(); WireUpChild(_lexicalForm); WireUpList(_senses, "senses"); WireUpList(_variants, "variants"); } public IEnumerable<string> PropertiesInUse { get { return base.PropertiesInUse.Concat(Senses.SelectMany(sense => sense.PropertiesInUse)); } } public override void SomethingWasModified(string propertyModified) { base.SomethingWasModified(propertyModified); ModificationTime = PreciseDateTime.UtcNow; _isDirty = true; //too soon to make id: this method is called after first keystroke // GetOrCreateId(false); } public void Clean() { _isDirty = false; } public override void NotifyPropertyChanged(string propertyName) { if(!_isBeingDeleted) base.NotifyPropertyChanged(propertyName); } public string GetOrCreateId(bool doCreateEvenIfNoLexemeForm) { if (String.IsNullOrEmpty(_id)) { //review: I think we could rapidly search the db for exact id matches, //so we could come up with a smaller id... but this has the nice //property of being somewhat readable and unique even across merges if (!String.IsNullOrEmpty(_lexicalForm.GetFirstAlternative())) { _id = _lexicalForm.GetFirstAlternative().Trim().Normalize( NormalizationForm.FormD) + "_" + Guid; NotifyPropertyChanged("id"); } else if (doCreateEvenIfNoLexemeForm) { _id = "Id'dPrematurely_" + Guid; NotifyPropertyChanged("id"); } } return _id; } /// <summary> /// /// </summary> /// <remarks>The signature here is MultiText rather than LexicalFormMultiText because we want /// to hide this (hopefully temporary) performance implementation detail. </remarks> public MultiText LexicalForm { get { return _lexicalForm; } } public DateTime CreationTime { get { return GetSafeDateTime(_creationTime); } set { Debug.Assert(value.Kind == DateTimeKind.Utc); //_creationTime = value; //converting time to LiftFormatResolution _creationTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second, value.Kind); } } private static DateTime GetSafeDateTime(DateTime dt) { //workaround db4o 6 bug if (dt.Kind != DateTimeKind.Utc) { return new DateTime(dt.Ticks, DateTimeKind.Utc); } return dt; } public DateTime ModificationTime { get { return GetSafeDateTime(_modificationTime); } set { if (!ModifiedTimeIsLocked) { Debug.Assert(value.Kind == DateTimeKind.Utc); //_modificationTime = value; //converting time to LiftFormatResolution _modificationTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second, value.Kind); _isDirty = true; } } } public IList<LexSense> Senses { get { return _senses; } } /// <summary> /// NOTE: in oct 2010, wesay does not yet use this field, but SOLID does /// </summary> public IList<LexVariant> Variants { get { return _variants; } } /// <summary> /// NOTE: in oct 2010, wesay does not yet use this field, as it only handles a single, typeless note and uses the well-known-properties approach /// </summary> public IList<LexNote> Notes { get { return _notes; } } /// <summary> /// NOTE: in oct 2010, wesay does not yet use this field, but SOLID does /// </summary> public IList<LexPhonetic> Pronunciations { get { return _pronunciations; } } /// <summary> /// NOTE: in oct 2010, wesay does not yet use this field, but SOLID does /// </summary> public IList<LexEtymology> Etymologies { get { return _etymologies; } } /// <summary> /// Used to track this entry across programs, for the purpose of merging and such. /// </summary> public Guid Guid { get { return _guid; } set { if (_guid != value) { _guid = value; NotifyPropertyChanged("GUID"); } } } public override bool IsEmpty { get { return Senses.Count == 0 && LexicalForm.Empty && !HasProperties; } } /// <summary> /// This use for keeping track of the item when importing an then exporting again, /// like for merging. Also used for relations (e.g. superentry). we purposefully /// delay making one of these (if we aren't contructed with one) in order to give /// time to get a LexemeForm to make the id more readable. /// </summary> public string Id { get { return GetOrCreateId(false); } set { string id = value; if (value != null) { id = value.Trim().Normalize(NormalizationForm.FormD); if (id.Length == 0) { id = null; } } _id = id; } } public override void CleanUpAfterEditting() { if (IsBeingDeleted) { return; } base.CleanUpAfterEditting(); foreach (LexSense sense in _senses) { sense.CleanUpAfterEditting(); } //enhance if ever WeSay does variants, we may need to add this kind of cleanup CleanUpEmptyObjects(); } public override void CleanUpEmptyObjects() { if (IsBeingDeleted) { return; } Logger.WriteMinorEvent("LexEntry CleanUpEmptyObjects()"); base.CleanUpEmptyObjects(); for (int i = 0;i < _senses.Count;i++) { _senses[i].CleanUpEmptyObjects(); } // remove any senses that are empty int count = _senses.Count; for (int i = count - 1;i >= 0;i--) { if (_senses[i].IsEmptyForPurposesOfDeletion) { _senses.RemoveAt(i); } } if (count != _senses.Count) { Logger.WriteMinorEvent("Empty sense removed"); OnEmptyObjectsRemoved(); } } public LexSense GetOrCreateSenseWithMeaning(MultiText meaning) //Switch to meaning { foreach (LexSense sense in Senses) { #if GlossMeaning if (meaning.HasFormWithSameContent(sense.Gloss)) #else if (meaning.HasFormWithSameContent(sense.Definition)) #endif { return sense; } } LexSense newSense = new LexSense(); Senses.Add(newSense); #if GlossMeaning newSense.Gloss.MergeIn(meaning); #else newSense.Definition.MergeIn(meaning); #endif return newSense; } public string GetToolTipText() { string s = ""; foreach (LexSense sense in Senses) { string x = sense.Definition.GetFirstAlternative(); if (string.IsNullOrEmpty(x)) { x = sense.Gloss.GetFirstAlternative(); } s += x + ", "; } if (s == "") { return StringCatalog.Get("~No Senses"); } return s.Substring(0, s.Length - 2); // chop off the trailing separator } /// <summary> /// checks if it looks like the user has added info. this is used when changing spelling /// in a word-gathering task /// </summary> public bool IsEmptyExceptForLexemeFormForPurposesOfDeletion { get { if (LexicalForm.Count > 1) { return false; } foreach (LexSense sense in _senses) { if (!sense.IsEmptyForPurposesOfDeletion) { return false; } } if (HasPropertiesForPurposesOfDeletion) { return false; } return true; } } /// <summary> /// this is used to prevent things like cleanup of an object that is being deleted, which /// can lead to update notifications that get the dispossed entry back in the db, or in some cache /// </summary> public bool IsBeingDeleted { get { return _isBeingDeleted; } set { _isBeingDeleted = value; } } /// <summary> /// used during import so we don't accidentally change the modified time while building up the entry /// </summary> public bool ModifiedTimeIsLocked { get { return _modifiedTimeIsLocked; } set { _modifiedTimeIsLocked = value; } } public MultiText CitationForm { get { return GetOrCreateProperty<MultiText>(WellKnownProperties.Citation); } } /// <summary> /// The name here is to remind us that our homograph number /// system doesn't know how to take this into account /// </summary> public int OrderForRoundTripping { get { return _orderForRoundTripping; } set { _orderForRoundTripping = value; NotifyPropertyChanged("order"); } } public int OrderInFile { get { return this._orderInFile; } set { this._orderInFile = value; NotifyPropertyChanged("order"); } } public MultiText VirtualHeadWord { get { MultiText headword = new MultiText(); headword.MergeIn(LexicalForm); headword.MergeIn(CitationForm); return headword; } } public bool IsDirty { get { return _isDirty; } //ideally, this wouldn't be needed, but in making the homograph merger, I (jh) found that adding a property (a citation form) // left _isDirty still false. I dont have the stomach to spend a day figure out why, so I'm making this setable. set { _isDirty = value; } } public LanguageForm GetHeadWord(string writingSystemId) { if (string.IsNullOrEmpty(writingSystemId)) { throw new ArgumentException("writingSystemId"); } MultiText citationMT = GetProperty<MultiText>(WellKnownProperties.Citation); LanguageForm headWord; if (citationMT == null || (headWord = citationMT.Find(writingSystemId)) == null) { headWord = LexicalForm.Find(writingSystemId); } return headWord; } /// <summary> /// this is safer /// </summary> /// <param name="writingSystemId"></param> /// <returns>string.emtpy if no headword</returns> public string GetHeadWordForm(string writingSystemId) { LanguageForm form = GetHeadWord(writingSystemId); if (form == null) { return string.Empty; } return form.Form; } public void AddRelationTarget(string relationName, string targetId) { LexRelationCollection relations = GetOrCreateProperty<LexRelationCollection>(relationName); relations.Relations.Add(new LexRelation(relationName, targetId, this)); } public string GetSimpleFormForLogging() { string formForLogging ; try { formForLogging = LexicalForm.GetFirstAlternative(); } catch (Exception) { formForLogging="(unknown)"; } return formForLogging; } /// <summary> /// used by SILCAWL list /// </summary> public string GetSomeMeaningToUseInAbsenseOfHeadWord(string writingSystemId) { var s = Senses.FirstOrDefault(); if(s==null) return "?NoMeaning?"; var gloss=s.Gloss.GetExactAlternative(writingSystemId); if (string.IsNullOrEmpty(gloss)) { var def = s.Definition.GetExactAlternative(writingSystemId); if(string.IsNullOrEmpty(def)) return "?NoGlossOrDef?"; return def; } return gloss; } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>AdGroupAd</c> resource.</summary> public sealed partial class AdGroupAdName : gax::IResourceName, sys::IEquatable<AdGroupAdName> { /// <summary>The possible contents of <see cref="AdGroupAdName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>. /// </summary> CustomerAdGroupAd = 1, } private static gax::PathTemplate s_customerAdGroupAd = new gax::PathTemplate("customers/{customer_id}/adGroupAds/{ad_group_id_ad_id}"); /// <summary>Creates a <see cref="AdGroupAdName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AdGroupAdName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AdGroupAdName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AdGroupAdName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AdGroupAdName"/> with the pattern /// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AdGroupAdName"/> constructed from the provided ids.</returns> public static AdGroupAdName FromCustomerAdGroupAd(string customerId, string adGroupId, string adId) => new AdGroupAdName(ResourceNameType.CustomerAdGroupAd, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAdName"/> with pattern /// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAdName"/> with pattern /// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string adId) => FormatCustomerAdGroupAd(customerId, adGroupId, adId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupAdName"/> with pattern /// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupAdName"/> with pattern /// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c>. /// </returns> public static string FormatCustomerAdGroupAd(string customerId, string adGroupId, string adId) => s_customerAdGroupAd.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId)))}"); /// <summary>Parses the given resource name string into a new <see cref="AdGroupAdName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c></description></item> /// </list> /// </remarks> /// <param name="adGroupAdName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AdGroupAdName"/> if successful.</returns> public static AdGroupAdName Parse(string adGroupAdName) => Parse(adGroupAdName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupAdName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAdName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AdGroupAdName"/> if successful.</returns> public static AdGroupAdName Parse(string adGroupAdName, bool allowUnparsed) => TryParse(adGroupAdName, allowUnparsed, out AdGroupAdName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAdName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c></description></item> /// </list> /// </remarks> /// <param name="adGroupAdName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAdName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupAdName, out AdGroupAdName result) => TryParse(adGroupAdName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupAdName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupAdName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupAdName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string adGroupAdName, bool allowUnparsed, out AdGroupAdName result) { gax::GaxPreconditions.CheckNotNull(adGroupAdName, nameof(adGroupAdName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupAd.TryParseName(adGroupAdName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupAd(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(adGroupAdName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AdGroupAdName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adId = null, string adGroupId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdId = adId; AdGroupId = adGroupId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="AdGroupAdName"/> class from the component parts of pattern /// <c>customers/{customer_id}/adGroupAds/{ad_group_id}~{ad_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adId">The <c>Ad</c> ID. Must not be <c>null</c> or empty.</param> public AdGroupAdName(string customerId, string adGroupId, string adId) : this(ResourceNameType.CustomerAdGroupAd, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), adId: gax::GaxPreconditions.CheckNotNullOrEmpty(adId, nameof(adId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Ad</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdId { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroupAd: return s_customerAdGroupAd.Expand(CustomerId, $"{AdGroupId}~{AdId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AdGroupAdName); /// <inheritdoc/> public bool Equals(AdGroupAdName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AdGroupAdName a, AdGroupAdName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AdGroupAdName a, AdGroupAdName b) => !(a == b); } public partial class AdGroupAd { /// <summary> /// <see cref="AdGroupAdName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AdGroupAdName ResourceNameAsAdGroupAdName { get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupAdName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property. /// </summary> internal AdGroupName AdGroupAsAdGroupName { get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true); set => AdGroup = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupAdLabelName"/>-typed view over the <see cref="Labels"/> resource name property. /// </summary> internal gax::ResourceNameList<AdGroupAdLabelName> LabelsAsAdGroupAdLabelNames { get => new gax::ResourceNameList<AdGroupAdLabelName>(Labels, s => string.IsNullOrEmpty(s) ? null : AdGroupAdLabelName.Parse(s, allowUnparsed: true)); } } }
// Copyright 2018, Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using Google.Apis.Json; using Newtonsoft.Json; namespace FirebaseAdmin.Messaging { /// <summary> /// Represents the <a href="https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html"> /// aps dictionary</a> that is part of every APNs message. /// </summary> public sealed class Aps { private static readonly NewtonsoftJsonSerializer Serializer = NewtonsoftJsonSerializer.Instance; /// <summary> /// Gets or sets an advanced alert configuration to be included in the message. It is an /// error to set both <see cref="Alert"/> and <see cref="AlertString"/> properties /// together. /// </summary> [JsonIgnore] public ApsAlert Alert { get; set; } /// <summary> /// Gets or sets the alert text to be included in the message. To specify a more advanced /// alert configuration, use the <see cref="Alert"/> property instead. It is an error to /// set both <see cref="Alert"/> and <see cref="AlertString"/> properties together. /// </summary> [JsonIgnore] public string AlertString { get; set; } /// <summary> /// Gets or sets the badge to be displayed with the message. Set to 0 to remove the badge. /// When not specified, the badge will remain unchanged. /// </summary> [JsonProperty("badge")] public int? Badge { get; set; } /// <summary> /// Gets or sets the name of a sound file in your app's main bundle or in the /// <c>Library/Sounds</c> folder of your app's container directory. Specify the /// string <c>default</c> to play the system sound. It is an error to set both /// <see cref="Sound"/> and <see cref="CriticalSound"/> properties together. /// </summary> [JsonIgnore] public string Sound { get; set; } /// <summary> /// Gets or sets the critical alert sound to be played with the message. It is an error to /// set both <see cref="Sound"/> and <see cref="CriticalSound"/> properties together. /// </summary> [JsonIgnore] public CriticalSound CriticalSound { get; set; } /// <summary> /// Gets or sets a value indicating whether to configure a background update notification. /// </summary> [JsonIgnore] public bool ContentAvailable { get; set; } /// <summary> /// Gets or sets a value indicating whether to include the <c>mutable-content</c> property /// in the message. When set, this property allows clients to modify the notification via /// app extensions. /// </summary> [JsonIgnore] public bool MutableContent { get; set; } /// <summary> /// Gets or sets the type of the notification. /// </summary> [JsonProperty("category")] public string Category { get; set; } /// <summary> /// Gets or sets the app-specific identifier for grouping notifications. /// </summary> [JsonProperty("thread-id")] public string ThreadId { get; set; } /// <summary> /// Gets or sets a collection of arbitrary key-value data to be included in the <c>aps</c> /// dictionary. This is exposed as an <see cref="IDictionary{TKey, TValue}"/> to support /// correct deserialization of custom properties. /// </summary> [JsonExtensionData] public IDictionary<string, object> CustomData { get; set; } /// <summary> /// Gets or sets the alert configuration of the <c>aps</c> dictionary. Read from either /// <see cref="Alert"/> or <see cref="AlertString"/> property. /// </summary> [JsonProperty("alert")] private object AlertObject { get { object alert = this.AlertString; if (string.IsNullOrEmpty(alert as string)) { alert = this.Alert; } else if (this.Alert != null) { throw new ArgumentException( "Multiple specifications for alert (Alert and AlertString"); } return alert; } set { if (value == null) { return; } else if (value.GetType() == typeof(string)) { this.AlertString = (string)value; } else if (value.GetType() == typeof(ApsAlert)) { this.Alert = (ApsAlert)value; } else { var json = Serializer.Serialize(value); this.Alert = Serializer.Deserialize<ApsAlert>(json); } } } /// <summary> /// Gets or sets the sound configuration of the <c>aps</c> dictionary. Read from either /// <see cref="Sound"/> or <see cref="CriticalSound"/> property. /// </summary> [JsonProperty("sound")] private object SoundObject { get { object sound = this.Sound; if (string.IsNullOrEmpty(sound as string)) { sound = this.CriticalSound; } else if (this.CriticalSound != null) { throw new ArgumentException( "Multiple specifications for sound (CriticalSound and Sound"); } return sound; } set { if (value == null) { return; } else if (value.GetType() == typeof(string)) { this.Sound = (string)value; } else if (value.GetType() == typeof(CriticalSound)) { this.CriticalSound = (CriticalSound)value; } else { var json = Serializer.Serialize(value); this.CriticalSound = Serializer.Deserialize<CriticalSound>(json); } } } /// <summary> /// Gets or sets the integer representation of the <see cref="ContentAvailable"/> property, /// which is how APNs expects it. /// </summary> [JsonProperty("content-available")] private int? ContentAvailableInt { get { return this.ContentAvailable ? 1 : (int?)null; } set { this.ContentAvailable = value == 1; } } /// <summary> /// Gets or sets the integer representation of the <see cref="MutableContent"/> property, /// which is how APNs expects it. /// </summary> [JsonProperty("mutable-content")] private int? MutableContentInt { get { return this.MutableContent ? 1 : (int?)null; } set { this.MutableContent = value == 1; } } /// <summary> /// Copies this Aps dictionary, and validates the content of it to ensure that it can be /// serialized into the JSON format expected by the FCM and APNs services. /// </summary> internal Aps CopyAndValidate() { var copy = new Aps { AlertObject = this.AlertObject, Badge = this.Badge, ContentAvailable = this.ContentAvailable, MutableContent = this.MutableContent, Category = this.Category, SoundObject = this.SoundObject, ThreadId = this.ThreadId, }; var customData = this.CustomData?.ToDictionary(e => e.Key, e => e.Value); if (customData?.Count > 0) { var serializer = NewtonsoftJsonSerializer.Instance; var json = serializer.Serialize(copy); var standardProperties = serializer.Deserialize<Dictionary<string, object>>(json); var duplicates = customData.Keys .Where(customKey => standardProperties.ContainsKey(customKey)) .ToList(); if (duplicates.Any()) { throw new ArgumentException( $"Multiple specifications for Aps keys: {string.Join(",", duplicates)}"); } copy.CustomData = customData; } copy.Alert = copy.Alert?.CopyAndValidate(); copy.CriticalSound = copy.CriticalSound?.CopyAndValidate(); return copy; } } }
// AGUIControlBase.cs // // Author: // Atte Vuorinen <[email protected]> // // Copyright (c) 2014 Atte Vuorinen // // 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 UnityEngine; using System.Collections; using System.Collections.Generic; public class AGUIControlBase : MonoBehaviour { #region Static /// <summary> /// Gets the AGUI base or add it if GameObject doesn't have it. /// </summary> /// <returns>The AGUI base.</returns> /// <param name="go">GameObject.</param> public static AGUIControlBase GetAGUIBase(GameObject go) { return GHelper.GetComponent<AGUIControlBase>(go); } #endregion #region Header public class LinkedControl { public enum CallerType { Null, Busy, Normal, Hover } public Vector3 position = Vector3.zero; public Vector3 screenPosition = Vector3.zero; public AGUIController caller = null; public List<AGUIControlBase> bases = new List<AGUIControlBase>(); public List<Touch> touches = new List<Touch>(); public CallerType callerType = CallerType.Null; //Delegates// public VoidBaseDelegate onHover; public BoolBaseDelegate onHovered; public VoidBaseDelegate onClick; public VoidBaseDelegate onDoubleClick; public VoidBaseDelegate onHold; public BoolBaseDelegate onPress; public Vector2BaseDelegate onDrag; } public delegate void VoidBaseDelegate(AGUIControlBase cont); public delegate void BoolBaseDelegate(AGUIControlBase cont, bool boolean); public delegate void Vector2BaseDelegate(AGUIControlBase cont, Vector2 vector); private GLinker<LinkedControl> m_linker = new GLinker<LinkedControl>(); private LinkedControl m_link; #endregion #region Properties /// <summary> /// Gets the bases. /// </summary> /// <value>The bases.</value> public List<AGUIControlBase> Bases { get { //TODO: Better system for this! CheckLink(); return new List<AGUIControlBase>(m_link.bases); } } /// <summary> /// Gets or sets the touches. /// </summary> /// <value>The touches.</value> public List<Touch> Touches { get { CheckLink(); return m_link.touches; } set { CheckLink(); m_link.touches = value; } } /// <summary> /// Gets or sets the position. /// Position is set by AGUIController using input positions. /// </summary> /// <value>The position.</value> public Vector3 Position { get { CheckLink(); return m_link.position; } set { CheckLink(); m_link.position = value; } } /// <summary> /// Gets or sets the screen space Position. /// </summary> /// <value>The screen position.</value> public Vector3 ScreenPosition { get { CheckLink(); return m_link.screenPosition; } set { CheckLink(); m_link.screenPosition = value; } } /// <summary> /// Gets the caller. /// </summary> /// <value>The caller.</value> public AGUIController Caller { get { CheckLink(); return m_link.caller; } private set { CheckLink(); m_link.caller = value; } } /// <summary> /// Gets the type of the caller. /// </summary> /// <value>The type of the caller.</value> public LinkedControl.CallerType CallerType { get { CheckLink(); return m_link.callerType; } private set { CheckLink(); m_link.callerType = value; } } #endregion #region Delegates /// <summary> /// Gets or sets the onHover delegate. /// </summary> /// <value>The on hover.</value> public VoidBaseDelegate onHover { get { CheckLink(); return m_link.onHover; } set { CheckLink(); m_link.onHover = value; } } /// <summary> /// Gets or sets the onHovered delegate. /// </summary> /// <value>The on hovered.</value> public BoolBaseDelegate onHovered { get { CheckLink(); return m_link.onHovered; } set { CheckLink(); m_link.onHovered = value; } } /// <summary> /// Gets or sets the onClick delegate. /// </summary> /// <value>The on click.</value> public VoidBaseDelegate onClick { get { CheckLink(); return m_link.onClick; } set { CheckLink(); m_link.onClick = value; } } /// <summary> /// Gets or sets the onDoubleClick delegate. /// </summary> /// <value>The on double click.</value> public VoidBaseDelegate onDoubleClick { get { CheckLink(); return m_link.onDoubleClick; } set { CheckLink(); m_link.onDoubleClick = value; } } /// <summary> /// Gets or sets the onHold delegate. /// </summary> /// <value>The on hold.</value> public VoidBaseDelegate onHold { get { CheckLink(); return m_link.onHold; } set { CheckLink(); m_link.onHold = value; } } /// <summary> /// Gets or sets the onPress delegate. /// </summary> /// <value>The on press.</value> public BoolBaseDelegate onPress { get { CheckLink(); return m_link.onPress; } set { CheckLink(); m_link.onPress = value; } } /// <summary> /// Gets or sets the onDrag delegate. /// </summary> /// <value>The on drag.</value> public Vector2BaseDelegate onDrag { get { CheckLink(); return m_link.onDrag; } set { CheckLink(); m_link.onDrag = value; } } #endregion #region Body /// <summary> /// Determines whether this instance is called. /// </summary> /// <returns><c>true</c> if this instance is called; otherwise, <c>false</c>.</returns> public bool IsCalled() { return m_link != null && Caller != null; } /// <summary> /// Sets the caller to be normal. /// </summary> /// <param name="caller">Caller.</param> public void SetCaller(AGUIController caller) { SetCaller(caller,LinkedControl.CallerType.Normal); } /// <summary> /// Sets the caller. /// </summary> /// <param name="manager">Manager.</param> /// <param name="hover">If set to <c>true</c> hover.</param> public void SetCaller(AGUIController caller, LinkedControl.CallerType type) { CheckLink(); Caller = caller; if(Caller == null) { CallerType = LinkedControl.CallerType.Null; } else { CallerType = type; } } /// <summary> /// Awake this instance. /// </summary> protected virtual void Awake() { if(!m_linker.IsInited) { m_linker.checkLinks = delegate(ref GLinker<LinkedControl> gLinker) { foreach(AGUIControlBase cBase in GetComponents<AGUIControlBase>()) { if(gLinker.CheckLink(cBase.m_linker)) { gLinker = cBase.m_linker; return true; } } return false; }; m_linker.setLinks = delegate(ref GLinker<LinkedControl> gLinker) { AGUIControlBase[] bases = GetComponents<AGUIControlBase>(); for(int i = 0; i < bases.Length; i++) { bases[i].m_linker = gLinker; } return true; }; m_linker.InitLink(); m_linker.LinkedInstance = new LinkedControl(); } m_link = m_linker.LinkedInstance; } /// <summary> /// Raises the enable event. /// </summary> protected virtual void OnEnable() { CheckLink(); m_link.bases.Add(this); } /// <summary> /// Raises the disable event. /// </summary> protected virtual void OnDisable() { CheckLink(); m_link.bases.Remove(this); } /// <summary> /// Checks the active rules. /// </summary> /// <returns><c>true</c>, if active rules was checked, <c>false</c> otherwise.</returns> private bool CheckActiveRules() { CheckLink(); return enabled && gameObject.activeInHierarchy; } /// <summary> /// Checks the link. /// </summary> private void CheckLink() { if(m_link == null || !m_linker.IsInited) { this.Awake(); } } #endregion #region Invoke //All invoke methods need caller, so it won't be called using GDelegates! //Hover// /// <summary> /// Invokes the hover. /// </summary> public void InvokeHover(AGUIController caller) { if(!CheckActiveRules()) { return; } foreach(AGUIControlBase bases in Bases) { bases.OnHover(); if(bases.onHover != null) { bases.onHover(this); } } } /// <summary> /// Invokes the hovered. /// </summary> /// <param name="isHovered">If set to <c>true</c> is hovered.</param> public void InvokeHovered(AGUIController caller,bool isHovered) { if(!CheckActiveRules()) { return; } foreach(AGUIControlBase bases in Bases) { bases.OnHovered(isHovered); if(bases.onHovered != null) { bases.onHovered(this,isHovered); } } } //Mouse & Touch// /// <summary> /// Invokes the click. /// </summary> public void InvokeClick(AGUIController caller) { if(!CheckActiveRules()) { return; } foreach(AGUIControlBase bases in Bases) { bases.OnClick(); if(bases.onClick != null) { bases.onClick(this); } } } /// <summary> /// Invokes the double click. /// </summary> public void InvokeDoubleClick(AGUIController caller) { if(!CheckActiveRules()) { return; } foreach(AGUIControlBase bases in Bases) { bases.OnDoubleClick(); if(bases.onDoubleClick != null) { bases.onDoubleClick(this); } } } /// <summary> /// Invokes the hold. /// </summary> public void InvokeHold(AGUIController caller) { if(!CheckActiveRules()) { return; } foreach(AGUIControlBase bases in Bases) { bases.OnHold(); if(bases.onHold != null) { bases.onHold(this); } } } /// <summary> /// Invokes the press. /// </summary> /// <param name="isPressed">If set to <c>true</c> is pressed.</param> public void InvokePress(AGUIController caller,bool isPressed) { if(!CheckActiveRules()) { return; } foreach(AGUIControlBase bases in Bases) { bases.OnPress(isPressed); if(bases.onPress != null) { bases.onPress(this,isPressed); } } } /// <summary> /// Invokes the drag. /// </summary> /// <param name="delta">Delta.</param> public void InvokeDrag(AGUIController caller,Vector2 delta) { if(!CheckActiveRules()) { return; } foreach(AGUIControlBase bases in Bases) { bases.OnDrag(delta); if(bases.onDrag != null) { bases.onDrag(this, delta); } } } #endregion #region Virtuals //Hover// /// <summary> /// OnHover base. /// Is called when mouse or "touch" is over the game object. /// </summary> protected virtual void OnHover() { } /// <summary> /// OnHovered base. /// Is called when hover begins or ends. /// </summary> /// <param name="isHovered">If set to <c>true</c> is hovered.</param> protected virtual void OnHovered(bool isHovered) { } //Mouse & Touch// /// <summary> /// OnClick base. /// Is called when game object is clicked or tapped. /// </summary> protected virtual void OnClick() { } /// <summary> /// OnDoubleClick base. /// Is called when game object is double clicked or tapped. /// </summary> protected virtual void OnDoubleClick() { } /// <summary> /// OnHold base. /// Is called when game object is begin holded. /// </summary> protected virtual void OnHold() { } /// <summary> /// OnPress base. /// Is called when you hold begins or ends. /// </summary> /// <param name="isPressed">If set to <c>true</c> is pressed.</param> protected virtual void OnPress(bool isPressed) { } /// <summary> /// OnDrag base. /// Is called when you drag game object. /// </summary> /// <param name="delta">Delta.</param> protected virtual void OnDrag(Vector2 delta) { } #endregion }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Runtime.Remoting.Lifetime; using System.Threading; using OpenMetaverse; using Nini.Config; using OpenSim; using OpenSim.Framework; using OpenSim.Region.CoreModules.World.LightShare; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api.Plugins; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared.Api.Interfaces; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.Api { [Serializable] public class LS_Api : MarshalByRefObject, ILS_Api, IScriptApi { internal IScriptEngine m_ScriptEngine; internal SceneObjectPart m_host; internal bool m_LSFunctionsEnabled = false; internal IScriptModuleComms m_comms = null; public void Initialize( IScriptEngine scriptEngine, SceneObjectPart host, TaskInventoryItem item, WaitHandle coopSleepHandle) { m_ScriptEngine = scriptEngine; m_host = host; if (m_ScriptEngine.Config.GetBoolean("AllowLightShareFunctions", false)) m_LSFunctionsEnabled = true; m_comms = m_ScriptEngine.World.RequestModuleInterface<IScriptModuleComms>(); if (m_comms == null) m_LSFunctionsEnabled = false; } public override Object InitializeLifetimeService() { ILease lease = (ILease)base.InitializeLifetimeService(); if (lease.CurrentState == LeaseState.Initial) { lease.InitialLeaseTime = TimeSpan.FromMinutes(0); // lease.RenewOnCallTime = TimeSpan.FromSeconds(10.0); // lease.SponsorshipTimeout = TimeSpan.FromMinutes(1.0); } return lease; } public Scene World { get { return m_ScriptEngine.World; } } /// <summary> /// Dumps an error message on the debug console. /// </summary> internal void LSShoutError(string message) { if (message.Length > 1023) message = message.Substring(0, 1023); World.SimChat(Utils.StringToBytes(message), ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.ParentGroup.RootPart.AbsolutePosition, m_host.Name, m_host.UUID, true); IWorldComm wComm = m_ScriptEngine.World.RequestModuleInterface<IWorldComm>(); wComm.DeliverMessage(ChatTypeEnum.Shout, ScriptBaseClass.DEBUG_CHANNEL, m_host.Name, m_host.UUID, message); } /// <summary> /// Get the current Windlight scene /// </summary> /// <returns>List of windlight parameters</returns> public LSL_List lsGetWindlightScene(LSL_List rules) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return new LSL_List(); } m_host.AddScriptLPS(1); RegionLightShareData wl = m_host.ParentGroup.Scene.RegionInfo.WindlightSettings; LSL_List values = new LSL_List(); int idx = 0; while (idx < rules.Length) { LSL_Integer ruleInt = rules.GetLSLIntegerItem(idx); uint rule = (uint)ruleInt; LSL_List toadd = new LSL_List(); switch (rule) { case (int)ScriptBaseClass.WL_AMBIENT: toadd.Add(new LSL_Rotation(wl.ambient.X, wl.ambient.Y, wl.ambient.Z, wl.ambient.W)); break; case (int)ScriptBaseClass.WL_BIG_WAVE_DIRECTION: toadd.Add(new LSL_Vector(wl.bigWaveDirection.X, wl.bigWaveDirection.Y, 0.0f)); break; case (int)ScriptBaseClass.WL_BLUE_DENSITY: toadd.Add(new LSL_Rotation(wl.blueDensity.X, wl.blueDensity.Y, wl.blueDensity.Z, wl.blueDensity.W)); break; case (int)ScriptBaseClass.WL_BLUR_MULTIPLIER: toadd.Add(new LSL_Float(wl.blurMultiplier)); break; case (int)ScriptBaseClass.WL_CLOUD_COLOR: toadd.Add(new LSL_Rotation(wl.cloudColor.X, wl.cloudColor.Y, wl.cloudColor.Z, wl.cloudColor.W)); break; case (int)ScriptBaseClass.WL_CLOUD_COVERAGE: toadd.Add(new LSL_Float(wl.cloudCoverage)); break; case (int)ScriptBaseClass.WL_CLOUD_DETAIL_XY_DENSITY: toadd.Add(new LSL_Vector(wl.cloudDetailXYDensity.X, wl.cloudDetailXYDensity.Y, wl.cloudDetailXYDensity.Z)); break; case (int)ScriptBaseClass.WL_CLOUD_SCALE: toadd.Add(new LSL_Float(wl.cloudScale)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X: toadd.Add(new LSL_Float(wl.cloudScrollX)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X_LOCK: toadd.Add(new LSL_Integer(wl.cloudScrollXLock ? 1 : 0)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y: toadd.Add(new LSL_Float(wl.cloudScrollY)); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y_LOCK: toadd.Add(new LSL_Integer(wl.cloudScrollYLock ? 1 : 0)); break; case (int)ScriptBaseClass.WL_CLOUD_XY_DENSITY: toadd.Add(new LSL_Vector(wl.cloudXYDensity.X, wl.cloudXYDensity.Y, wl.cloudXYDensity.Z)); break; case (int)ScriptBaseClass.WL_DENSITY_MULTIPLIER: toadd.Add(new LSL_Float(wl.densityMultiplier)); break; case (int)ScriptBaseClass.WL_DISTANCE_MULTIPLIER: toadd.Add(new LSL_Float(wl.distanceMultiplier)); break; case (int)ScriptBaseClass.WL_DRAW_CLASSIC_CLOUDS: toadd.Add(new LSL_Integer(wl.drawClassicClouds ? 1 : 0)); break; case (int)ScriptBaseClass.WL_EAST_ANGLE: toadd.Add(new LSL_Float(wl.eastAngle)); break; case (int)ScriptBaseClass.WL_FRESNEL_OFFSET: toadd.Add(new LSL_Float(wl.fresnelOffset)); break; case (int)ScriptBaseClass.WL_FRESNEL_SCALE: toadd.Add(new LSL_Float(wl.fresnelScale)); break; case (int)ScriptBaseClass.WL_HAZE_DENSITY: toadd.Add(new LSL_Float(wl.hazeDensity)); break; case (int)ScriptBaseClass.WL_HAZE_HORIZON: toadd.Add(new LSL_Float(wl.hazeHorizon)); break; case (int)ScriptBaseClass.WL_HORIZON: toadd.Add(new LSL_Rotation(wl.horizon.X, wl.horizon.Y, wl.horizon.Z, wl.horizon.W)); break; case (int)ScriptBaseClass.WL_LITTLE_WAVE_DIRECTION: toadd.Add(new LSL_Vector(wl.littleWaveDirection.X, wl.littleWaveDirection.Y, 0.0f)); break; case (int)ScriptBaseClass.WL_MAX_ALTITUDE: toadd.Add(new LSL_Integer(wl.maxAltitude)); break; case (int)ScriptBaseClass.WL_NORMAL_MAP_TEXTURE: toadd.Add(new LSL_Key(wl.normalMapTexture.ToString())); break; case (int)ScriptBaseClass.WL_REFLECTION_WAVELET_SCALE: toadd.Add(new LSL_Vector(wl.reflectionWaveletScale.X, wl.reflectionWaveletScale.Y, wl.reflectionWaveletScale.Z)); break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_ABOVE: toadd.Add(new LSL_Float(wl.refractScaleAbove)); break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_BELOW: toadd.Add(new LSL_Float(wl.refractScaleBelow)); break; case (int)ScriptBaseClass.WL_SCENE_GAMMA: toadd.Add(new LSL_Float(wl.sceneGamma)); break; case (int)ScriptBaseClass.WL_STAR_BRIGHTNESS: toadd.Add(new LSL_Float(wl.starBrightness)); break; case (int)ScriptBaseClass.WL_SUN_GLOW_FOCUS: toadd.Add(new LSL_Float(wl.sunGlowFocus)); break; case (int)ScriptBaseClass.WL_SUN_GLOW_SIZE: toadd.Add(new LSL_Float(wl.sunGlowSize)); break; case (int)ScriptBaseClass.WL_SUN_MOON_COLOR: toadd.Add(new LSL_Rotation(wl.sunMoonColor.X, wl.sunMoonColor.Y, wl.sunMoonColor.Z, wl.sunMoonColor.W)); break; case (int)ScriptBaseClass.WL_SUN_MOON_POSITION: toadd.Add(new LSL_Float(wl.sunMoonPosition)); break; case (int)ScriptBaseClass.WL_UNDERWATER_FOG_MODIFIER: toadd.Add(new LSL_Float(wl.underwaterFogModifier)); break; case (int)ScriptBaseClass.WL_WATER_COLOR: toadd.Add(new LSL_Vector(wl.waterColor.X, wl.waterColor.Y, wl.waterColor.Z)); break; case (int)ScriptBaseClass.WL_WATER_FOG_DENSITY_EXPONENT: toadd.Add(new LSL_Float(wl.waterFogDensityExponent)); break; } if (toadd.Length > 0) { values.Add(ruleInt); values.Add(toadd.Data[0]); } idx++; } return values; } private RegionLightShareData getWindlightProfileFromRules(LSL_List rules) { RegionLightShareData wl = (RegionLightShareData)m_host.ParentGroup.Scene.RegionInfo.WindlightSettings.Clone(); // LSL_List values = new LSL_List(); int idx = 0; while (idx < rules.Length) { uint rule = (uint)rules.GetLSLIntegerItem(idx); LSL_Types.Quaternion iQ; LSL_Types.Vector3 iV; switch (rule) { case (int)ScriptBaseClass.WL_SUN_MOON_POSITION: idx++; wl.sunMoonPosition = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_AMBIENT: idx++; iQ = rules.GetQuaternionItem(idx); wl.ambient = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_BIG_WAVE_DIRECTION: idx++; iV = rules.GetVector3Item(idx); wl.bigWaveDirection = new Vector2((float)iV.x, (float)iV.y); break; case (int)ScriptBaseClass.WL_BLUE_DENSITY: idx++; iQ = rules.GetQuaternionItem(idx); wl.blueDensity = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_BLUR_MULTIPLIER: idx++; wl.blurMultiplier = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_CLOUD_COLOR: idx++; iQ = rules.GetQuaternionItem(idx); wl.cloudColor = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_CLOUD_COVERAGE: idx++; wl.cloudCoverage = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_CLOUD_DETAIL_XY_DENSITY: idx++; iV = rules.GetVector3Item(idx); wl.cloudDetailXYDensity = iV; break; case (int)ScriptBaseClass.WL_CLOUD_SCALE: idx++; wl.cloudScale = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X: idx++; wl.cloudScrollX = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_X_LOCK: idx++; wl.cloudScrollXLock = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y: idx++; wl.cloudScrollY = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_CLOUD_SCROLL_Y_LOCK: idx++; wl.cloudScrollYLock = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; break; case (int)ScriptBaseClass.WL_CLOUD_XY_DENSITY: idx++; iV = rules.GetVector3Item(idx); wl.cloudXYDensity = iV; break; case (int)ScriptBaseClass.WL_DENSITY_MULTIPLIER: idx++; wl.densityMultiplier = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_DISTANCE_MULTIPLIER: idx++; wl.distanceMultiplier = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_DRAW_CLASSIC_CLOUDS: idx++; wl.drawClassicClouds = rules.GetLSLIntegerItem(idx).value == 1 ? true : false; break; case (int)ScriptBaseClass.WL_EAST_ANGLE: idx++; wl.eastAngle = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_FRESNEL_OFFSET: idx++; wl.fresnelOffset = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_FRESNEL_SCALE: idx++; wl.fresnelScale = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_HAZE_DENSITY: idx++; wl.hazeDensity = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_HAZE_HORIZON: idx++; wl.hazeHorizon = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_HORIZON: idx++; iQ = rules.GetQuaternionItem(idx); wl.horizon = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_LITTLE_WAVE_DIRECTION: idx++; iV = rules.GetVector3Item(idx); wl.littleWaveDirection = new Vector2((float)iV.x, (float)iV.y); break; case (int)ScriptBaseClass.WL_MAX_ALTITUDE: idx++; wl.maxAltitude = (ushort)rules.GetLSLIntegerItem(idx).value; break; case (int)ScriptBaseClass.WL_NORMAL_MAP_TEXTURE: idx++; wl.normalMapTexture = new UUID(rules.GetLSLStringItem(idx).m_string); break; case (int)ScriptBaseClass.WL_REFLECTION_WAVELET_SCALE: idx++; iV = rules.GetVector3Item(idx); wl.reflectionWaveletScale = iV; break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_ABOVE: idx++; wl.refractScaleAbove = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_REFRACT_SCALE_BELOW: idx++; wl.refractScaleBelow = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_SCENE_GAMMA: idx++; wl.sceneGamma = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_STAR_BRIGHTNESS: idx++; wl.starBrightness = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_SUN_GLOW_FOCUS: idx++; wl.sunGlowFocus = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_SUN_GLOW_SIZE: idx++; wl.sunGlowSize = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_SUN_MOON_COLOR: idx++; iQ = rules.GetQuaternionItem(idx); wl.sunMoonColor = new Vector4((float)iQ.x, (float)iQ.y, (float)iQ.z, (float)iQ.s); break; case (int)ScriptBaseClass.WL_UNDERWATER_FOG_MODIFIER: idx++; wl.underwaterFogModifier = (float)rules.GetLSLFloatItem(idx); break; case (int)ScriptBaseClass.WL_WATER_COLOR: idx++; iV = rules.GetVector3Item(idx); wl.waterColor = iV; break; case (int)ScriptBaseClass.WL_WATER_FOG_DENSITY_EXPONENT: idx++; wl.waterFogDensityExponent = (float)rules.GetLSLFloatItem(idx); break; } idx++; } return wl; } /// <summary> /// Set the current Windlight scene /// </summary> /// <param name="rules"></param> /// <returns>success: true or false</returns> public int lsSetWindlightScene(LSL_List rules) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return 0; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { ScenePresence sp = World.GetScenePresence(m_host.OwnerID); if (sp == null || sp.GodLevel < 200) { LSShoutError("lsSetWindlightScene can only be used by estate managers or owners."); return 0; } } int success = 0; m_host.AddScriptLPS(1); if (LightShareModule.EnableWindlight) { RegionLightShareData wl = getWindlightProfileFromRules(rules); wl.valid = true; m_host.ParentGroup.Scene.StoreWindlightProfile(wl); success = 1; } else { LSShoutError("Windlight module is disabled"); return 0; } return success; } public void lsClearWindlightScene() { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { ScenePresence sp = World.GetScenePresence(m_host.OwnerID); if (sp == null || sp.GodLevel < 200) { LSShoutError("lsSetWindlightScene can only be used by estate managers or owners."); return; } } m_host.ParentGroup.Scene.RegionInfo.WindlightSettings.valid = false; if (m_host.ParentGroup.Scene.SimulationDataService != null) m_host.ParentGroup.Scene.SimulationDataService.RemoveRegionWindlightSettings(m_host.ParentGroup.Scene.RegionInfo.RegionID); m_host.ParentGroup.Scene.EventManager.TriggerOnSaveNewWindlightProfile(); } /// <summary> /// Set the current Windlight scene to a target avatar /// </summary> /// <param name="rules"></param> /// <returns>success: true or false</returns> public int lsSetWindlightSceneTargeted(LSL_List rules, LSL_Key target) { if (!m_LSFunctionsEnabled) { LSShoutError("LightShare functions are not enabled."); return 0; } if (!World.RegionInfo.EstateSettings.IsEstateManagerOrOwner(m_host.OwnerID)) { ScenePresence sp = World.GetScenePresence(m_host.OwnerID); if (sp == null || sp.GodLevel < 200) { LSShoutError("lsSetWindlightSceneTargeted can only be used by estate managers or owners."); return 0; } } int success = 0; m_host.AddScriptLPS(1); if (LightShareModule.EnableWindlight) { RegionLightShareData wl = getWindlightProfileFromRules(rules); World.EventManager.TriggerOnSendNewWindlightProfileTargeted(wl, new UUID(target.m_string)); success = 1; } else { LSShoutError("Windlight module is disabled"); return 0; } return success; } } }
/* The MIT License (MIT) Copyright (c) 2016 Maksim Volkau 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 AddOrUpdateServiceFactory all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Cumulus.DryIoc { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; /// <summary>Compiles expression to delegate by emitting the IL directly. /// The emitter is ~10 times faster than Expression.Compile.</summary> public static partial class FastExpressionCompiler { // ReSharper disable once RedundantAssignment static partial void TryCompile<TDelegate>(ref TDelegate compileDelegate, Expression bodyExpr, ParameterExpression[] paramExprs, Type[] paramTypes, Type returnType) where TDelegate : class { compileDelegate = TryCompile<TDelegate>(bodyExpr, paramExprs, paramTypes, returnType); } /// <summary>Compiles expression to delegate by emitting the IL. /// If sub-expressions are not supported by emitter, then the method returns null. /// The usage should be calling the method, if result is null then calling the Expression.Compile.</summary> /// <param name="bodyExpr">Lambda body.</param> /// <param name="paramExprs">Lambda parameter expressions.</param> /// <param name="paramTypes">The types of parameters.</param> /// <param name="returnType">The return type.</param> /// <returns>Result delegate or null, if unable to compile.</returns> public static TDelegate TryCompile<TDelegate>( Expression bodyExpr, ParameterExpression[] paramExprs, Type[] paramTypes, Type returnType) where TDelegate : class { var constantExprs = new List<ConstantExpression>(); if (!TryCollectBoundConstants(bodyExpr, constantExprs)) return null; object closure = null; ClosureInfo closureInfo = null; DynamicMethod method; if (constantExprs.Count == 0) { method = new DynamicMethod(string.Empty, returnType, paramTypes, typeof(FastExpressionCompiler).Module, skipVisibility: true); } else { var constants = new object[constantExprs.Count]; var constantCount = constants.Length; for (var i = constantCount - 1; i >= 0; i--) constants[i] = constantExprs[i].Value; if (constantCount <= Closure.CreateMethods.Length) { var createClosureMethod = Closure.CreateMethods[constantCount - 1]; var constantTypes = new Type[constantCount]; for (var i = 0; i < constantCount; i++) constantTypes[i] = constantExprs[i].Type; var createClosure = createClosureMethod.MakeGenericMethod(constantTypes); closure = createClosure.Invoke(null, constants); var fields = closure.GetType().GetTypeInfo().DeclaredFields; var fieldsArray = fields as FieldInfo[] ?? fields.ToArray(); closureInfo = new ClosureInfo(constantExprs, fieldsArray); } else { var arrayClosure = new ArrayClosure(constants); closure = arrayClosure; closureInfo = new ClosureInfo(constantExprs); } var closureType = closure.GetType(); var closureAndParamTypes = GetClosureAndParamTypes(paramTypes, closureType); method = new DynamicMethod(string.Empty, returnType, closureAndParamTypes, closureType, skipVisibility: true); } var il = method.GetILGenerator(); var emitted = EmittingVisitor.TryEmit(bodyExpr, paramExprs, il, closureInfo); if (emitted) { il.Emit(OpCodes.Ret); return (TDelegate)(object)method.CreateDelegate(typeof(TDelegate), closure); } return null; } private static Type[] GetClosureAndParamTypes(Type[] paramTypes, Type closureType) { var paramCount = paramTypes.Length; var closureAndParamTypes = new Type[paramCount + 1]; closureAndParamTypes[0] = closureType; if (paramCount == 1) closureAndParamTypes[1] = paramTypes[0]; else if (paramCount > 1) Array.Copy(paramTypes, 0, closureAndParamTypes, 1, paramCount); return closureAndParamTypes; } private sealed class ClosureInfo { public readonly IList<ConstantExpression> ConstantExpressions; public readonly FieldInfo[] ConstantClosureFields; public readonly bool IsClosureArray; public ClosureInfo(IList<ConstantExpression> constantExpressions, FieldInfo[] constantClosureFields = null) { ConstantExpressions = constantExpressions; ConstantClosureFields = constantClosureFields; IsClosureArray = constantClosureFields == null; } } #region Closures // todo: perf: test if Activator.CreateInstance is faster than method Invoke. internal static class Closure { public static readonly MethodInfo[] CreateMethods = typeof(Closure).GetTypeInfo().DeclaredMethods.ToArray(); public static Closure<T1> CreateClosure<T1>(T1 v1) { return new Closure<T1>(v1); } public static Closure<T1, T2> CreateClosure<T1, T2>(T1 v1, T2 v2) { return new Closure<T1, T2>(v1, v2); } public static Closure<T1, T2, T3> CreateClosure<T1, T2, T3>(T1 v1, T2 v2, T3 v3) { return new Closure<T1, T2, T3>(v1, v2, v3); } public static Closure<T1, T2, T3, T4> CreateClosure<T1, T2, T3, T4>(T1 v1, T2 v2, T3 v3, T4 v4) { return new Closure<T1, T2, T3, T4>(v1, v2, v3, v4); } public static Closure<T1, T2, T3, T4, T5> CreateClosure<T1, T2, T3, T4, T5>(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { return new Closure<T1, T2, T3, T4, T5>(v1, v2, v3, v4, v5); } public static Closure<T1, T2, T3, T4, T5, T6> CreateClosure<T1, T2, T3, T4, T5, T6>(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { return new Closure<T1, T2, T3, T4, T5, T6>(v1, v2, v3, v4, v5, v6); } public static Closure<T1, T2, T3, T4, T5, T6, T7> CreateClosure<T1, T2, T3, T4, T5, T6, T7>(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) { return new Closure<T1, T2, T3, T4, T5, T6, T7>(v1, v2, v3, v4, v5, v6, v7); } public static Closure<T1, T2, T3, T4, T5, T6, T7, T8> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8>( T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { return new Closure<T1, T2, T3, T4, T5, T6, T7, T8>(v1, v2, v3, v4, v5, v6, v7, v8); } public static Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8, T9>( T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { return new Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9>(v1, v2, v3, v4, v5, v6, v7, v8, v9); } public static Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> CreateClosure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { return new Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(v1, v2, v3, v4, v5, v6, v7, v8, v9, v10); } } internal sealed class Closure<T1> { public T1 V1; public Closure(T1 v1) { V1 = v1; } } internal sealed class Closure<T1, T2> { public T1 V1; public T2 V2; public Closure(T1 v1, T2 v2) { V1 = v1; V2 = v2; } } internal sealed class Closure<T1, T2, T3> { public T1 V1; public T2 V2; public T3 V3; public Closure(T1 v1, T2 v2, T3 v3) { V1 = v1; V2 = v2; V3 = v3; } } internal sealed class Closure<T1, T2, T3, T4> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public Closure(T1 v1, T2 v2, T3 v3, T4 v4) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; } } internal sealed class Closure<T1, T2, T3, T4, T5> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public T7 V7; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; V7 = v7; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public T7 V7; public T8 V8; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; V7 = v7; V8 = v8; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public T7 V7; public T8 V8; public T9 V9; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; V7 = v7; V8 = v8; V9 = v9; } } internal sealed class Closure<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> { public T1 V1; public T2 V2; public T3 V3; public T4 V4; public T5 V5; public T6 V6; public T7 V7; public T8 V8; public T9 V9; public T10 V10; public Closure(T1 v1, T2 v2, T3 v3, T4 v4, T5 v5, T6 v6, T7 v7, T8 v8, T9 v9, T10 v10) { V1 = v1; V2 = v2; V3 = v3; V4 = v4; V5 = v5; V6 = v6; V7 = v7; V8 = v8; V9 = v9; V10 = v10; } } internal sealed class ArrayClosure { public readonly object[] Constants; public static FieldInfo ArrayField = typeof(ArrayClosure).GetTypeInfo().DeclaredFields.First(f => !f.IsStatic); public ArrayClosure(object[] constants) { Constants = constants; } } #endregion #region Collect Bound Constants private static bool IsBoundConstant(object value) { return value != null && !(value is int || value is double || value is bool || value is string || value is Type || value.GetType().IsEnum); } private static bool TryCollectBoundConstants(Expression expr, List<ConstantExpression> constants) { if (expr == null) return false; switch (expr.NodeType) { case ExpressionType.Constant: var constantExpr = (ConstantExpression)expr; var constantValue = constantExpr.Value; if (constantValue is Delegate) // Note: skip Delegate constant as it is required complex il emitting return false; if (IsBoundConstant(constantValue)) constants.Add(constantExpr); break; case ExpressionType.Call: return TryCollectBoundConstants(((MethodCallExpression)expr).Object, constants) && TryCollectBoundConstants(((MethodCallExpression)expr).Arguments, constants); case ExpressionType.MemberAccess: return TryCollectBoundConstants(((MemberExpression)expr).Expression, constants); case ExpressionType.New: return TryCollectBoundConstants(((NewExpression)expr).Arguments, constants); case ExpressionType.NewArrayInit: return TryCollectBoundConstants(((NewArrayExpression)expr).Expressions, constants); // property initializer case ExpressionType.MemberInit: var memberInitExpr = (MemberInitExpression)expr; if (!TryCollectBoundConstants(memberInitExpr.NewExpression, constants)) return false; var memberBindings = memberInitExpr.Bindings; for (var i = 0; i < memberBindings.Count; ++i) { var memberBinding = memberBindings[i]; if (memberBinding.BindingType == MemberBindingType.Assignment && !TryCollectBoundConstants(((MemberAssignment)memberBinding).Expression, constants)) return false; } break; default: var unaryExpr = expr as UnaryExpression; if (unaryExpr != null) return TryCollectBoundConstants(unaryExpr.Operand, constants); var binaryExpr = expr as BinaryExpression; if (binaryExpr != null) return TryCollectBoundConstants(binaryExpr.Left, constants) && TryCollectBoundConstants(binaryExpr.Right, constants); break; } return true; } private static bool TryCollectBoundConstants(IList<Expression> exprs, List<ConstantExpression> constants) { var count = exprs.Count; for (var i = 0; i < count; i++) if (!TryCollectBoundConstants(exprs[i], constants)) return false; return true; } #endregion /// <summary>Supports emitting of selected expressions, e.g. lambdaExpr are not supported yet. /// When emitter find not supported expression it will return false from <see cref="TryEmit"/>, so I could fallback /// to normal and slow Expression.Compile.</summary> private static class EmittingVisitor { public static bool TryEmit(Expression expr, IList<ParameterExpression> paramExprs, ILGenerator il, ClosureInfo closure) { switch (expr.NodeType) { case ExpressionType.Parameter: return EmitParameter((ParameterExpression)expr, paramExprs, il, closure); case ExpressionType.Convert: return EmitConvert((UnaryExpression)expr, paramExprs, il, closure); case ExpressionType.ArrayIndex: return EmitArrayIndex((BinaryExpression)expr, paramExprs, il, closure); case ExpressionType.Constant: return EmitConstant((ConstantExpression)expr, il, closure); case ExpressionType.New: return EmitNew((NewExpression)expr, paramExprs, il, closure); case ExpressionType.NewArrayInit: return EmitNewArray((NewArrayExpression)expr, paramExprs, il, closure); case ExpressionType.MemberInit: return EmitMemberInit((MemberInitExpression)expr, paramExprs, il, closure); case ExpressionType.Call: return EmitMethodCall((MethodCallExpression)expr, paramExprs, il, closure); case ExpressionType.MemberAccess: return EmitMemberAccess((MemberExpression)expr, paramExprs, il, closure); case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: return EmitComparison((BinaryExpression)expr, paramExprs, il, closure); default: // Not supported yet: nested lambdas (Invoke) return false; } } private static bool EmitParameter(ParameterExpression p, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var pIndex = ps.IndexOf(p); if (pIndex == -1) return false; if (closure != null) pIndex += 1; switch (pIndex) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (pIndex <= byte.MaxValue) il.Emit(OpCodes.Ldarg_S, (byte)pIndex); else il.Emit(OpCodes.Ldarg, pIndex); break; } return true; } private static bool EmitBinary(BinaryExpression b, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var ok = TryEmit(b.Left, ps, il, closure); if (ok) ok = TryEmit(b.Right, ps, il, closure); // skips TryEmit(b.Conversion) for NodeType.Coalesce (?? operation) return ok; } private static bool EmitMany(IList<Expression> es, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { for (int i = 0, n = es.Count; i < n; i++) if (!TryEmit(es[i], ps, il, closure)) return false; return true; } private static bool EmitConvert(UnaryExpression node, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var ok = TryEmit(node.Operand, ps, il, closure); if (ok) { var convertTargetType = node.Type; if (convertTargetType == typeof(object)) return false; il.Emit(OpCodes.Castclass, convertTargetType); } return ok; } private static bool EmitConstant(ConstantExpression constantExpr, ILGenerator il, ClosureInfo closure) { var constant = constantExpr.Value; if (constant == null) { il.Emit(OpCodes.Ldnull); } else if (constant is int || constant.GetType().IsEnum) { EmitLoadConstantInt(il, (int)constant); } else if (constant is double) { il.Emit(OpCodes.Ldc_R8, (double)constant); } else if (constant is bool) { il.Emit((bool)constant ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); } else if (constant is string) { il.Emit(OpCodes.Ldstr, (string)constant); } else if (constant is Type) { il.Emit(OpCodes.Ldtoken, (Type)constant); var getTypeFromHandle = typeof(Type).GetMethod("GetTypeFromHandle"); il.Emit(OpCodes.Call, getTypeFromHandle); } else if (closure != null) { var constantIndex = closure.ConstantExpressions.IndexOf(constantExpr); if (constantIndex == -1) return false; // load closure argument: Closure or Closure Array il.Emit(OpCodes.Ldarg_0); if (!closure.IsClosureArray) { // load closure field il.Emit(OpCodes.Ldfld, closure.ConstantClosureFields[constantIndex]); } else { // load array field il.Emit(OpCodes.Ldfld, ArrayClosure.ArrayField); // load array item index EmitLoadConstantInt(il, constantIndex); // load item from index il.Emit(OpCodes.Ldelem_Ref); // case if needed var castType = constantExpr.Type; if (castType != typeof(object)) il.Emit(OpCodes.Castclass, castType); } } else { return false; } // boxing the value type, otherwise we can get a strange result when 0 is treated as Null. if (constantExpr.Type == typeof(object) && constant != null && constant.GetType().IsValueType()) il.Emit(OpCodes.Box, constant.GetType()); return true; } private static bool EmitNew(NewExpression n, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var ok = EmitMany(n.Arguments, ps, il, closure); if (ok) il.Emit(OpCodes.Newobj, n.Constructor); return ok; } private static bool EmitNewArray(NewArrayExpression na, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var elems = na.Expressions; var arrType = na.Type; var elemType = arrType.GetElementType(); var isElemOfValueType = elemType.IsValueType; var arrVar = il.DeclareLocal(arrType); EmitLoadConstantInt(il, elems.Count); il.Emit(OpCodes.Newarr, elemType); il.Emit(OpCodes.Stloc, arrVar); var ok = true; for (int i = 0, n = elems.Count; i < n && ok; i++) { il.Emit(OpCodes.Ldloc, arrVar); EmitLoadConstantInt(il, i); // loading element address for later copying of value into it. if (isElemOfValueType) il.Emit(OpCodes.Ldelema, elemType); ok = TryEmit(elems[i], ps, il, closure); if (ok) { if (isElemOfValueType) il.Emit(OpCodes.Stobj, elemType); // store element of value type by array element address else il.Emit(OpCodes.Stelem_Ref); } } il.Emit(OpCodes.Ldloc, arrVar); return ok; } private static bool EmitArrayIndex(BinaryExpression ai, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var ok = EmitBinary(ai, ps, il, closure); if (ok) il.Emit(OpCodes.Ldelem_Ref); return ok; } private static bool EmitMemberInit(MemberInitExpression mi, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var ok = EmitNew(mi.NewExpression, ps, il, closure); if (!ok) return false; var obj = il.DeclareLocal(mi.Type); il.Emit(OpCodes.Stloc, obj); var bindings = mi.Bindings; for (int i = 0, n = bindings.Count; i < n; i++) { var binding = bindings[i]; if (binding.BindingType != MemberBindingType.Assignment) return false; il.Emit(OpCodes.Ldloc, obj); ok = TryEmit(((MemberAssignment)binding).Expression, ps, il, closure); if (!ok) return false; var prop = binding.Member as PropertyInfo; if (prop != null) { var setMethod = prop.GetSetMethod(); if (setMethod == null) return false; EmitMethodCall(setMethod, il); } else { var field = binding.Member as FieldInfo; if (field == null) return false; il.Emit(OpCodes.Stfld, field); } } il.Emit(OpCodes.Ldloc, obj); return true; } private static bool EmitMethodCall(MethodCallExpression m, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var ok = true; if (m.Object != null) ok = TryEmit(m.Object, ps, il, closure); if (ok && m.Arguments.Count != 0) ok = EmitMany(m.Arguments, ps, il, closure); if (ok) EmitMethodCall(m.Method, il); return ok; } private static bool EmitMemberAccess(MemberExpression m, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { if (m.Expression != null) { var ok = TryEmit(m.Expression, ps, il, closure); if (!ok) return false; } var field = m.Member as FieldInfo; if (field != null) { il.Emit(field.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, field); return true; } var property = m.Member as PropertyInfo; if (property != null) { var getMethod = property.GetGetMethod(); if (getMethod == null) return false; EmitMethodCall(getMethod, il); } return true; } private static bool EmitComparison(BinaryExpression c, IList<ParameterExpression> ps, ILGenerator il, ClosureInfo closure) { var ok = EmitBinary(c, ps, il, closure); if (ok) { switch (c.NodeType) { case ExpressionType.Equal: il.Emit(OpCodes.Ceq); break; case ExpressionType.LessThan: il.Emit(OpCodes.Clt); break; case ExpressionType.GreaterThan: il.Emit(OpCodes.Cgt); break; case ExpressionType.NotEqual: il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); break; case ExpressionType.LessThanOrEqual: il.Emit(OpCodes.Cgt); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); break; case ExpressionType.GreaterThanOrEqual: il.Emit(OpCodes.Clt); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); break; } } return ok; } private static void EmitMethodCall(MethodInfo method, ILGenerator il) { il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); } private static void EmitLoadConstantInt(ILGenerator il, int i) { switch (i) { case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; default: il.Emit(OpCodes.Ldc_I4, i); break; } } } } }
using J2N.Threading.Atomic; using Lucene.Net.Analysis; using Lucene.Net.Analysis.TokenAttributes; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using NUnit.Framework; using System; using System.IO; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using IndexInput = Lucene.Net.Store.IndexInput; using IOContext = Lucene.Net.Store.IOContext; using Lucene41PostingsFormat = Lucene.Net.Codecs.Lucene41.Lucene41PostingsFormat; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper; using RAMDirectory = Lucene.Net.Store.RAMDirectory; using TestUtil = Lucene.Net.Util.TestUtil; /// <summary> /// this testcase tests whether multi-level skipping is being used /// to reduce I/O while skipping through posting lists. /// /// Skipping in general is already covered by several other /// testcases. /// /// </summary> [TestFixture] public class TestMultiLevelSkipList : LuceneTestCase { internal class CountingRAMDirectory : MockDirectoryWrapper { private readonly TestMultiLevelSkipList outerInstance; public CountingRAMDirectory(TestMultiLevelSkipList outerInstance, Directory @delegate) : base(Random, @delegate) { this.outerInstance = outerInstance; } public override IndexInput OpenInput(string fileName, IOContext context) { IndexInput @in = base.OpenInput(fileName, context); if (fileName.EndsWith(".frq", StringComparison.Ordinal)) { @in = new CountingStream(outerInstance, @in); } return @in; } } [SetUp] public override void SetUp() { base.SetUp(); counter = 0; } [Test] public virtual void TestSimpleSkip() { Directory dir = new CountingRAMDirectory(this, new RAMDirectory()); IndexWriter writer = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new PayloadAnalyzer()).SetCodec(TestUtil.AlwaysPostingsFormat(new Lucene41PostingsFormat())).SetMergePolicy(NewLogMergePolicy())); Term term = new Term("test", "a"); for (int i = 0; i < 5000; i++) { Document d1 = new Document(); d1.Add(NewTextField(term.Field, term.Text(), Field.Store.NO)); writer.AddDocument(d1); } writer.Commit(); writer.ForceMerge(1); writer.Dispose(); AtomicReader reader = GetOnlySegmentReader(DirectoryReader.Open(dir)); for (int i = 0; i < 2; i++) { counter = 0; DocsAndPositionsEnum tp = reader.GetTermPositionsEnum(term); CheckSkipTo(tp, 14, 185); // no skips CheckSkipTo(tp, 17, 190); // one skip on level 0 CheckSkipTo(tp, 287, 200); // one skip on level 1, two on level 0 // this test would fail if we had only one skip level, // because than more bytes would be read from the freqStream CheckSkipTo(tp, 4800, 250); // one skip on level 2 } } public virtual void CheckSkipTo(DocsAndPositionsEnum tp, int target, int maxCounter) { tp.Advance(target); if (maxCounter < counter) { Assert.Fail("Too many bytes read: " + counter + " vs " + maxCounter); } Assert.AreEqual(target, tp.DocID, "Wrong document " + tp.DocID + " after skipTo target " + target); Assert.AreEqual(1, tp.Freq, "Frequency is not 1: " + tp.Freq); tp.NextPosition(); BytesRef b = tp.GetPayload(); Assert.AreEqual(1, b.Length); Assert.AreEqual((sbyte)target, (sbyte)b.Bytes[b.Offset], "Wrong payload for the target " + target + ": " + (sbyte)b.Bytes[b.Offset]); } private class PayloadAnalyzer : Analyzer { internal readonly AtomicInt32 payloadCount = new AtomicInt32(-1); protected internal override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, true); return new TokenStreamComponents(tokenizer, new PayloadFilter(payloadCount, tokenizer)); } } private class PayloadFilter : TokenFilter { internal IPayloadAttribute payloadAtt; internal AtomicInt32 payloadCount; protected internal PayloadFilter(AtomicInt32 payloadCount, TokenStream input) : base(input) { this.payloadCount = payloadCount; payloadAtt = AddAttribute<IPayloadAttribute>(); } public sealed override bool IncrementToken() { bool hasNext = m_input.IncrementToken(); if (hasNext) { payloadAtt.Payload = new BytesRef(new[] { (byte)payloadCount.IncrementAndGet() }); } return hasNext; } } private int counter = 0; // Simply extends IndexInput in a way that we are able to count the number // of bytes read internal class CountingStream : IndexInput { private readonly TestMultiLevelSkipList outerInstance; internal IndexInput input; internal CountingStream(TestMultiLevelSkipList outerInstance, IndexInput input) : base("CountingStream(" + input + ")") { this.outerInstance = outerInstance; this.input = input; } public override byte ReadByte() { outerInstance.counter++; return this.input.ReadByte(); } public override void ReadBytes(byte[] b, int offset, int len) { outerInstance.counter += len; this.input.ReadBytes(b, offset, len); } protected override void Dispose(bool disposing) { if (disposing) { this.input.Dispose(); } } public override long GetFilePointer() { return this.input.GetFilePointer(); } public override void Seek(long pos) { this.input.Seek(pos); } public override long Length => this.input.Length; public override object Clone() { return new CountingStream(outerInstance, (IndexInput)this.input.Clone()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class SelectTest { private readonly ITestOutputHelper _log; public SelectTest(ITestOutputHelper output) { _log = output; } private const int SmallTimeoutMicroseconds = 10 * 1000; private const int FailTimeoutMicroseconds = 30 * 1000 * 1000; [PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value [Theory] [InlineData(90, 0)] [InlineData(0, 90)] [InlineData(45, 45)] public void Select_ReadWrite_AllReady_ManySockets(int reads, int writes) { Select_ReadWrite_AllReady(reads, writes); } [Theory] [InlineData(1, 0)] [InlineData(0, 1)] [InlineData(2, 2)] public void Select_ReadWrite_AllReady(int reads, int writes) { var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray(); var writePairs = Enumerable.Range(0, writes).Select(_ => CreateConnectedSockets()).ToArray(); try { foreach (var pair in readPairs) { pair.Value.Send(new byte[1] { 42 }); } var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray()); var writeList = new List<Socket>(writePairs.Select(p => p.Key).ToArray()); Socket.Select(readList, writeList, null, FailTimeoutMicroseconds); // Since no buffers are full, all writes should be available. Assert.Equal(writePairs.Length, writeList.Count); // We could wake up from Select for writes even if reads are about to become available, // so there's very little we can assert if writes is non-zero. if (writes == 0 && reads > 0) { Assert.InRange(readList.Count, 1, readPairs.Length); } // When we do the select again, the lists shouldn't change at all, as they've already // been filtered to ones that were ready. int readListCountBefore = readList.Count; int writeListCountBefore = writeList.Count; Socket.Select(readList, writeList, null, FailTimeoutMicroseconds); Assert.Equal(readListCountBefore, readList.Count); Assert.Equal(writeListCountBefore, writeList.Count); } finally { DisposeSockets(readPairs); DisposeSockets(writePairs); } } [PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value [Fact] public void Select_ReadError_NoneReady_ManySockets() { Select_ReadError_NoneReady(45, 45); } [Theory] [InlineData(1, 0)] [InlineData(0, 1)] [InlineData(2, 2)] public void Select_ReadError_NoneReady(int reads, int errors) { var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray(); var errorPairs = Enumerable.Range(0, errors).Select(_ => CreateConnectedSockets()).ToArray(); try { var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray()); var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray()); Socket.Select(readList, null, errorList, SmallTimeoutMicroseconds); Assert.Empty(readList); Assert.Empty(errorList); } finally { DisposeSockets(readPairs); DisposeSockets(errorPairs); } } [PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value public void Select_Read_OneReadyAtATime_ManySockets(int reads) { Select_Read_OneReadyAtATime(90); // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation } [Theory] [InlineData(2)] public void Select_Read_OneReadyAtATime(int reads) { var rand = new Random(42); var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToList(); try { while (readPairs.Count > 0) { int next = rand.Next(0, readPairs.Count); readPairs[next].Value.Send(new byte[1] { 42 }); var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray()); Socket.Select(readList, null, null, FailTimeoutMicroseconds); Assert.Equal(1, readList.Count); Assert.Same(readPairs[next].Key, readList[0]); readPairs.RemoveAt(next); } } finally { DisposeSockets(readPairs); } } [PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value [ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/989 public void Select_Error_OneReadyAtATime() { const int Errors = 90; // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation var rand = new Random(42); var errorPairs = Enumerable.Range(0, Errors).Select(_ => CreateConnectedSockets()).ToList(); try { while (errorPairs.Count > 0) { int next = rand.Next(0, errorPairs.Count); errorPairs[next].Value.Send(new byte[1] { 42 }, SocketFlags.OutOfBand); var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray()); Socket.Select(null, null, errorList, FailTimeoutMicroseconds); Assert.Equal(1, errorList.Count); Assert.Same(errorPairs[next].Key, errorList[0]); errorPairs.RemoveAt(next); } } finally { DisposeSockets(errorPairs); } } [Theory] [InlineData(SelectMode.SelectRead)] [InlineData(SelectMode.SelectError)] public void Poll_NotReady(SelectMode mode) { KeyValuePair<Socket, Socket> pair = CreateConnectedSockets(); try { Assert.False(pair.Key.Poll(SmallTimeoutMicroseconds, mode)); } finally { pair.Key.Dispose(); pair.Value.Dispose(); } } [Theory] [InlineData(-1)] [InlineData(FailTimeoutMicroseconds)] public void Poll_ReadReady_LongTimeouts(int microsecondsTimeout) { KeyValuePair<Socket, Socket> pair = CreateConnectedSockets(); try { Task.Delay(1).ContinueWith(_ => pair.Value.Send(new byte[1] { 42 }), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); Assert.True(pair.Key.Poll(microsecondsTimeout, SelectMode.SelectRead)); } finally { pair.Key.Dispose(); pair.Value.Dispose(); } } private static KeyValuePair<Socket, Socket> CreateConnectedSockets() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.LingerState = new LingerOption(true, 0); listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.LingerState = new LingerOption(true, 0); Task<Socket> acceptTask = listener.AcceptAsync(); client.Connect(listener.LocalEndPoint); Socket server = acceptTask.GetAwaiter().GetResult(); return new KeyValuePair<Socket, Socket>(client, server); } } private static void DisposeSockets(IEnumerable<KeyValuePair<Socket, Socket>> sockets) { foreach (var pair in sockets) { pair.Key.Dispose(); pair.Value.Dispose(); } } [OuterLoop] [Fact] public static void Select_AcceptNonBlocking_Success() { using (Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listenSocket.BindToAnonymousPort(IPAddress.Loopback); listenSocket.Blocking = false; listenSocket.Listen(5); Task t = Task.Run(() => { DoAccept(listenSocket, 5); }); // Loop, doing connections and pausing between for (int i = 0; i < 5; i++) { Thread.Sleep(50); using (Socket connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { connectSocket.Connect(listenSocket.LocalEndPoint); } } // Give the task 5 seconds to complete; if not, assume it's hung. bool completed = t.Wait(5000); Assert.True(completed); } } public static void DoAccept(Socket listenSocket, int connectionsToAccept) { int connectionCount = 0; while (true) { var ls = new List<Socket> { listenSocket }; Socket.Select(ls, null, null, 1000000); if (ls.Count > 0) { while (true) { try { Socket s = listenSocket.Accept(); s.Close(); connectionCount++; } catch (SocketException e) { Assert.Equal(e.SocketErrorCode, SocketError.WouldBlock); //No more requests in queue break; } if (connectionCount == connectionsToAccept) { return; } } } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using BurnSystems.Logging; using DatenMeister.Core.EMOF.Interface.Common; using DatenMeister.Core.EMOF.Interface.Identifiers; using DatenMeister.Core.EMOF.Interface.Reflection; using DatenMeister.Core.Functions.Queries; using DatenMeister.Core.Helper; using DatenMeister.Core.Models; using DatenMeister.Core.Runtime.Workspaces; using DatenMeister.Core.Uml.Helper; namespace DatenMeister.Forms { /// <summary> /// Contains some helper methods for forms /// </summary> public class FormMethods { /// <summary> /// Logger being used /// </summary> private static readonly ClassLogger Logger = new ClassLogger(typeof(FormMethods)); /// <summary> /// Stores the workspacelogic /// </summary> private readonly IWorkspaceLogic _workspaceLogic; public FormMethods(IWorkspaceLogic workspaceLogic) { _workspaceLogic = workspaceLogic; } /// <summary> /// Performs a verification of the form and returns false, if the form is not in a valid state /// </summary> /// <param name="form">Form to be evaluated</param> /// <returns>true, if the form is valid</returns> public static bool ValidateForm(IObject form) { var fields = form.getOrDefault<IReflectiveCollection>(_DatenMeister._Forms._DetailForm.field); if (fields != null) { if (!ValidateFields(fields)) return false; } var tabs = form.getOrDefault<IReflectiveCollection>(_DatenMeister._Forms._ExtentForm.tab); if (tabs != null) { foreach (var tab in tabs.OfType<IObject>()) { if (!ValidateForm(tab)) return false; } } return true; } /// <summary> /// Checks, if there is a duplicated name of the fields /// </summary> /// <param name="fields">Fields to be enumerated</param> /// <returns>true, if there are no duplications</returns> private static bool ValidateFields(IEnumerable fields) { var randomGuid = Guid.NewGuid(); var set = new HashSet<string>(); foreach (var field in fields.OfType<IObject>()) { var preName = field.getOrDefault<string>(_DatenMeister._Forms._FieldData.name); var isAttached = field.getOrDefault<bool>(_DatenMeister._Forms._FieldData.isAttached); var name = isAttached ? randomGuid + preName : preName; if (set.Contains(name) && !string.IsNullOrEmpty(name)) { Logger.Warn($"Field '{name}' is included twice. Validation of form failed"); return false; } set.Add(name); } return true; } /// <summary> /// Checks if the given element already has a metaclass within the form /// </summary> /// <param name="form">Form to be checked</param> /// <returns>true, if the form already contains a metaclass form</returns> public static bool HasMetaClassFieldInForm(IObject form) { var formAndFields = _DatenMeister.TheOne.Forms; return form .get<IReflectiveCollection>(_DatenMeister._Forms._DetailForm.field) .OfType<IElement>() .Any(x => x.getMetaClass()?.equals(formAndFields.__MetaClassElementFieldData) ?? false); } /// <summary> /// Checks if the given element already has a metaclass within the form /// </summary> /// <param name="extent">Defines the extent</param> /// <param name="fields">Enumeration fo fields</param> /// <returns>true, if the form already contains a metaclass form</returns> public bool HasMetaClassFieldInForm(IExtent extent, IEnumerable<object> fields) { var typesWorkspace = _workspaceLogic.GetTypesWorkspace(); return fields .OfType<IElement>() .Any(x => x.getMetaClass()?.equals(_DatenMeister.TheOne.Forms.__MetaClassElementFieldData) ?? false); } /// <summary> /// Looks for the given field in the form and returns it, if it is available /// </summary> /// <param name="form">Form to be evaluated</param> /// <param name="fieldName">Name of the field</param> /// <returns>The found element or null, if not found</returns> public static IElement? GetField(IElement form, string fieldName) { if (_DatenMeister._Forms._DetailForm.field != _DatenMeister._Forms._ListForm.field) throw new InvalidOperationException("Something ugly happened here: _FormAndFields._ExtentForm.tab != _FormAndFields._DetailForm.tab"); var fields = form.get<IReflectiveCollection>(_DatenMeister._Forms._DetailForm.field); return fields .WhenPropertyHasValue(_DatenMeister._Forms._FieldData.name, fieldName) .OfType<IElement>() .FirstOrDefault(); } /// <summary> /// Gets the enumeration of the detail forms which are in embedded into the tabs /// </summary> /// <param name="form">Form to be checked</param> /// <returns>Enumeration of the detail forms</returns> public static IEnumerable<IElement> GetDetailForms(IElement form) { foreach (var tab in form.get<IReflectiveCollection>(_DatenMeister._Forms._ExtentForm.tab)) { if (tab is IElement asElement && asElement.getMetaClass()?.equals(_DatenMeister.TheOne.Forms.__DetailForm) == true) { yield return asElement; } } } /// <summary> /// Gets the enumeration of the detail forms which are in embedded into the tabs /// </summary> /// <param name="form">Form to be checked</param> /// <returns>Enumeration of the detail forms</returns> public static IEnumerable<IElement> GetListForms(IElement form) { foreach (var tab in form.get<IReflectiveCollection>(_DatenMeister._Forms._ExtentForm.tab)) { if (tab is IElement asElement && asElement.getMetaClass()?.equals(_DatenMeister.TheOne.Forms.__ListForm) == true) { yield return asElement; } } } /// <summary> /// Gets the list tab listing the items of the properties /// </summary> /// <param name="form">Form to be evaluated</param> /// <param name="propertyName">Name of the property to which the propertyname shall belong</param> /// <returns>The found element</returns> public static IElement? GetListTabForPropertyName(IElement form, string propertyName) { if (_DatenMeister._Forms._ExtentForm.tab != _DatenMeister._Forms._DetailForm.tab) throw new InvalidOperationException("Something ugly happened here: _FormAndFields._ExtentForm.tab != _FormAndFields._DetailForm.tab"); var tabs = form.getOrDefault<IReflectiveCollection>(_DatenMeister._Forms._ExtentForm.tab); foreach (var tab in tabs.OfType<IElement>()) { if (ClassifierMethods.IsSpecializedClassifierOf(tab.getMetaClass(), _DatenMeister.TheOne.Forms.__ListForm)) { var property = tab.getOrDefault<string>(_DatenMeister._Forms._ListForm.property); if (property == propertyName) { return tab; } } } return null; } /// <summary> /// Gets the default view mode for a certain object by querying the view mode instances as /// given in the in the management workspace /// </summary> /// <param name="extent">Extent whose view mode is requested</param> /// <returns>Found element or null if not found</returns> public IElement? GetDefaultViewMode(IExtent? extent) { var managementWorkspace = _workspaceLogic.GetManagementWorkspace(); var extentTypes = extent?.GetConfiguration()?.ExtentTypes; if (extentTypes != null) { foreach (var extentType in extentTypes) { var result = managementWorkspace .GetAllDescendentsOfType(_DatenMeister.TheOne.Forms.__ViewMode) .WhenPropertyHasValue(_DatenMeister._Forms._ViewMode.defaultExtentType, extentType) .OfType<IElement>() .FirstOrDefault(); if (result != null) { return result; } } } return managementWorkspace .GetAllDescendentsOfType(_DatenMeister.TheOne.Forms.__ViewMode) .WhenPropertyHasValue(_DatenMeister._Forms._ViewMode.id, "Default") .OfType<IElement>() .FirstOrDefault(); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Checky.Slack.TestEditor.Areas.HelpPage.ModelDescriptions; using Checky.Slack.TestEditor.Areas.HelpPage.Models; namespace Checky.Slack.TestEditor.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * [email protected]. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * ***************************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudioTools.Project; namespace Microsoft.VisualStudioTools.Navigation { /// <summary> /// Inplementation of the service that builds the information to expose to the symbols /// navigation tools (class view or object browser) from the source files inside a /// hierarchy. /// </summary> internal abstract partial class LibraryManager : IDisposable, IVsRunningDocTableEvents { private readonly CommonPackage/*!*/ _package; private readonly Dictionary<uint, TextLineEventListener> _documents; private readonly Dictionary<IVsHierarchy, HierarchyInfo> _hierarchies = new Dictionary<IVsHierarchy,HierarchyInfo>(); private readonly Dictionary<ModuleId, LibraryNode> _files; private readonly Library _library; private readonly IVsEditorAdaptersFactoryService _adapterFactory; private uint _objectManagerCookie; private uint _runningDocTableCookie; public LibraryManager(CommonPackage/*!*/ package) { Contract.Assert(package != null); _package = package; _documents = new Dictionary<uint, TextLineEventListener>(); _library = new Library(new Guid(CommonConstants.LibraryGuid)); _library.LibraryCapabilities = (_LIB_FLAGS2)_LIB_FLAGS.LF_PROJECT; _files = new Dictionary<ModuleId, LibraryNode>(); var model = ((IServiceContainer)package).GetService(typeof(SComponentModel)) as IComponentModel; _adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>(); // Register our library now so it'll be available for find all references RegisterLibrary(); } public Library Library { get { return _library; } } protected abstract LibraryNode CreateLibraryNode(LibraryNode parent, IScopeNode subItem, string namePrefix, IVsHierarchy hierarchy, uint itemid); public virtual LibraryNode CreateFileLibraryNode(LibraryNode parent, HierarchyNode hierarchy, string name, string filename, LibraryNodeType libraryNodeType) { return new LibraryNode(null, name, filename, libraryNodeType); } private object GetPackageService(Type/*!*/ type) { return ((System.IServiceProvider)_package).GetService(type); } private void RegisterForRDTEvents() { if (0 != _runningDocTableCookie) { return; } IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Do not throw here in case of error, simply skip the registration. rdt.AdviseRunningDocTableEvents(this, out _runningDocTableCookie); } } private void UnregisterRDTEvents() { if (0 == _runningDocTableCookie) { return; } IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Do not throw in case of error. rdt.UnadviseRunningDocTableEvents(_runningDocTableCookie); } _runningDocTableCookie = 0; } #region ILibraryManager Members public void RegisterHierarchy(IVsHierarchy hierarchy) { if ((null == hierarchy) || _hierarchies.ContainsKey(hierarchy)) { return; } RegisterLibrary(); var commonProject = hierarchy.GetProject().GetCommonProject(); HierarchyListener listener = new HierarchyListener(hierarchy, this); var node = _hierarchies[hierarchy] = new HierarchyInfo( listener, new ProjectLibraryNode(commonProject) ); _library.AddNode(node.ProjectLibraryNode); listener.StartListening(true); RegisterForRDTEvents(); } private void RegisterLibrary() { if (0 == _objectManagerCookie) { IVsObjectManager2 objManager = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2; if (null == objManager) { return; } Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( objManager.RegisterSimpleLibrary(_library, out _objectManagerCookie)); } } public void UnregisterHierarchy(IVsHierarchy hierarchy) { if ((null == hierarchy) || !_hierarchies.ContainsKey(hierarchy)) { return; } HierarchyInfo info = _hierarchies[hierarchy]; if (null != info) { info.Listener.Dispose(); } _hierarchies.Remove(hierarchy); _library.RemoveNode(info.ProjectLibraryNode); if (0 == _hierarchies.Count) { UnregisterRDTEvents(); } lock (_files) { ModuleId[] keys = new ModuleId[_files.Keys.Count]; _files.Keys.CopyTo(keys, 0); foreach (ModuleId id in keys) { if (hierarchy.Equals(id.Hierarchy)) { _library.RemoveNode(_files[id]); _files.Remove(id); } } } // Remove the document listeners. uint[] docKeys = new uint[_documents.Keys.Count]; _documents.Keys.CopyTo(docKeys, 0); foreach (uint id in docKeys) { TextLineEventListener docListener = _documents[id]; if (hierarchy.Equals(docListener.FileID.Hierarchy)) { _documents.Remove(id); docListener.Dispose(); } } } public void RegisterLineChangeHandler(uint document, TextLineChangeEvent lineChanged, Action<IVsTextLines> onIdle) { _documents[document].OnFileChangedImmediate += delegate(object sender, TextLineChange[] changes, int fLast) { lineChanged(sender, changes, fLast); }; _documents[document].OnFileChanged += (sender, args) => onIdle(args.TextBuffer); } #endregion #region Library Member Production /// <summary> /// Overridden in the base class to receive notifications of when a file should /// be analyzed for inclusion in the library. The derived class should queue /// the parsing of the file and when it's complete it should call FileParsed /// with the provided LibraryTask and an IScopeNode which provides information /// about the members of the file. /// </summary> protected virtual void OnNewFile(LibraryTask task) { } /// <summary> /// Called by derived class when a file has been parsed. The caller should /// provide the LibraryTask received from the OnNewFile call and an IScopeNode /// which represents the contents of the library. /// /// It is safe to call this method from any thread. /// </summary> protected void FileParsed(LibraryTask task, IScopeNode scope) { try { var project = task.ModuleID.Hierarchy.GetProject().GetCommonProject(); HierarchyNode fileNode = fileNode = project.NodeFromItemId(task.ModuleID.ItemID); HierarchyInfo parent; if (fileNode == null || !_hierarchies.TryGetValue(task.ModuleID.Hierarchy, out parent)) { return; } LibraryNode module = CreateFileLibraryNode( parent.ProjectLibraryNode, fileNode, System.IO.Path.GetFileName(task.FileName), task.FileName, LibraryNodeType.Classes ); // TODO: Creating the module tree should be done lazily as needed // Currently we replace the entire tree and rely upon the libraries // update count to invalidate the whole thing. We could do this // finer grained and only update the changed nodes. But then we // need to make sure we're not mutating lists which are handed out. CreateModuleTree(module, scope, task.FileName + ":", task.ModuleID); if (null != task.ModuleID) { LibraryNode previousItem = null; lock (_files) { if (_files.TryGetValue(task.ModuleID, out previousItem)) { _files.Remove(task.ModuleID); parent.ProjectLibraryNode.RemoveNode(previousItem); } } } parent.ProjectLibraryNode.AddNode(module); _library.Update(); if (null != task.ModuleID) { lock (_files) { _files.Add(task.ModuleID, module); } } } catch (COMException) { // we're shutting down and can't get the project } } private void CreateModuleTree(LibraryNode current, IScopeNode scope, string namePrefix, ModuleId moduleId) { if ((null == scope) || (null == scope.NestedScopes)) { return; } foreach (IScopeNode subItem in scope.NestedScopes) { LibraryNode newNode = CreateLibraryNode(current, subItem, namePrefix, moduleId.Hierarchy, moduleId.ItemID); string newNamePrefix = namePrefix; current.AddNode(newNode); if ((newNode.NodeType & LibraryNodeType.Classes) != LibraryNodeType.None) { newNamePrefix = namePrefix + newNode.Name + "."; } // Now use recursion to get the other types. CreateModuleTree(newNode, subItem, newNamePrefix, moduleId); } } #endregion #region Hierarchy Events private void OnNewFile(object sender, HierarchyEventArgs args) { IVsHierarchy hierarchy = sender as IVsHierarchy; if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) { return; } ITextBuffer buffer = null; if (null != args.TextBuffer) { buffer = _adapterFactory.GetDocumentBuffer(args.TextBuffer); } var id = new ModuleId(hierarchy, args.ItemID); OnNewFile(new LibraryTask(args.CanonicalName, buffer, new ModuleId(hierarchy, args.ItemID))); } /// <summary> /// Handles the delete event, checking to see if this is a project item. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void OnDeleteFile(object sender, HierarchyEventArgs args) { IVsHierarchy hierarchy = sender as IVsHierarchy; if (null == hierarchy || IsNonMemberItem(hierarchy, args.ItemID)) { return; } OnDeleteFile(hierarchy, args); } /// <summary> /// Does a delete w/o checking if it's a non-meber item, for handling the /// transition from member item to non-member item. /// </summary> private void OnDeleteFile(IVsHierarchy hierarchy, HierarchyEventArgs args) { ModuleId id = new ModuleId(hierarchy, args.ItemID); LibraryNode node = null; lock (_files) { if (_files.TryGetValue(id, out node)) { _files.Remove(id); } } if (null != node) { _library.RemoveNode(node); } } private void IsNonMemberItemChanged(object sender, HierarchyEventArgs args) { IVsHierarchy hierarchy = sender as IVsHierarchy; if (null == hierarchy) { return; } if (!IsNonMemberItem(hierarchy, args.ItemID)) { OnNewFile(hierarchy, args); } else { OnDeleteFile(hierarchy, args); } } /// <summary> /// Checks whether this hierarchy item is a project member (on disk items from show all /// files aren't considered project members). /// </summary> protected bool IsNonMemberItem(IVsHierarchy hierarchy, uint itemId) { object val; int hr = hierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_IsNonMemberItem, out val); return ErrorHandler.Succeeded(hr) && (bool)val; } #endregion #region IVsRunningDocTableEvents Members public int OnAfterAttributeChange(uint docCookie, uint grfAttribs) { if ((grfAttribs & (uint)(__VSRDTATTRIB.RDTA_MkDocument)) == (uint)__VSRDTATTRIB.RDTA_MkDocument) { IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt != null) { uint flags, readLocks, editLocks, itemid; IVsHierarchy hier; IntPtr docData = IntPtr.Zero; string moniker; int hr; try { hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out editLocks, out moniker, out hier, out itemid, out docData); TextLineEventListener listner; if (_documents.TryGetValue(docCookie, out listner)) { listner.FileName = moniker; } } finally { if (IntPtr.Zero != docData) { Marshal.Release(docData); } } } } return VSConstants.S_OK; } public int OnAfterDocumentWindowHide(uint docCookie, IVsWindowFrame pFrame) { return VSConstants.S_OK; } public int OnAfterFirstDocumentLock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { return VSConstants.S_OK; } public int OnAfterSave(uint docCookie) { return VSConstants.S_OK; } public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) { // Check if this document is in the list of the documents. if (_documents.ContainsKey(docCookie)) { return VSConstants.S_OK; } // Get the information about this document from the RDT. IVsRunningDocumentTable rdt = GetPackageService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null != rdt) { // Note that here we don't want to throw in case of error. uint flags; uint readLocks; uint writeLoks; string documentMoniker; IVsHierarchy hierarchy; uint itemId; IntPtr unkDocData; int hr = rdt.GetDocumentInfo(docCookie, out flags, out readLocks, out writeLoks, out documentMoniker, out hierarchy, out itemId, out unkDocData); try { if (Microsoft.VisualStudio.ErrorHandler.Failed(hr) || (IntPtr.Zero == unkDocData)) { return VSConstants.S_OK; } // Check if the herarchy is one of the hierarchies this service is monitoring. if (!_hierarchies.ContainsKey(hierarchy)) { // This hierarchy is not monitored, we can exit now. return VSConstants.S_OK; } // Check the file to see if a listener is required. if (_package.IsRecognizedFile(documentMoniker)) { return VSConstants.S_OK; } // Create the module id for this document. ModuleId docId = new ModuleId(hierarchy, itemId); // Try to get the text buffer. IVsTextLines buffer = Marshal.GetObjectForIUnknown(unkDocData) as IVsTextLines; // Create the listener. TextLineEventListener listener = new TextLineEventListener(buffer, documentMoniker, docId); // Set the event handler for the change event. Note that there is no difference // between the AddFile and FileChanged operation, so we can use the same handler. listener.OnFileChanged += new EventHandler<HierarchyEventArgs>(OnNewFile); // Add the listener to the dictionary, so we will not create it anymore. _documents.Add(docCookie, listener); } finally { if (IntPtr.Zero != unkDocData) { Marshal.Release(unkDocData); } } } // Always return success. return VSConstants.S_OK; } public int OnBeforeLastDocumentUnlock(uint docCookie, uint dwRDTLockType, uint dwReadLocksRemaining, uint dwEditLocksRemaining) { if ((0 != dwEditLocksRemaining) || (0 != dwReadLocksRemaining)) { return VSConstants.S_OK; } TextLineEventListener listener; if (!_documents.TryGetValue(docCookie, out listener) || (null == listener)) { return VSConstants.S_OK; } using (listener) { _documents.Remove(docCookie); // Now make sure that the information about this file are up to date (e.g. it is // possible that Class View shows something strange if the file was closed without // saving the changes). HierarchyEventArgs args = new HierarchyEventArgs(listener.FileID.ItemID, listener.FileName); OnNewFile(listener.FileID.Hierarchy, args); } return VSConstants.S_OK; } #endregion public void OnIdle(IOleComponentManager compMgr) { foreach (TextLineEventListener listener in _documents.Values) { if (compMgr.FContinueIdle() == 0) { break; } listener.OnIdle(); } } #region IDisposable Members public void Dispose() { // Dispose all the listeners. foreach (var info in _hierarchies.Values) { info.Listener.Dispose(); } _hierarchies.Clear(); foreach (TextLineEventListener textListener in _documents.Values) { textListener.Dispose(); } _documents.Clear(); // Remove this library from the object manager. if (0 != _objectManagerCookie) { IVsObjectManager2 mgr = GetPackageService(typeof(SVsObjectManager)) as IVsObjectManager2; if (null != mgr) { mgr.UnregisterLibrary(_objectManagerCookie); } _objectManagerCookie = 0; } // Unregister this object from the RDT events. UnregisterRDTEvents(); } #endregion class HierarchyInfo { public readonly HierarchyListener Listener; public readonly ProjectLibraryNode ProjectLibraryNode; public HierarchyInfo(HierarchyListener listener, ProjectLibraryNode projectLibNode) { Listener = listener; ProjectLibraryNode = projectLibNode; } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>ThirdPartyAppAnalyticsLink</c> resource.</summary> public sealed partial class ThirdPartyAppAnalyticsLinkName : gax::IResourceName, sys::IEquatable<ThirdPartyAppAnalyticsLinkName> { /// <summary>The possible contents of <see cref="ThirdPartyAppAnalyticsLinkName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c> /// . /// </summary> CustomerCustomerLink = 1, } private static gax::PathTemplate s_customerCustomerLink = new gax::PathTemplate("customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}"); /// <summary> /// Creates a <see cref="ThirdPartyAppAnalyticsLinkName"/> containing an unparsed resource name. /// </summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ThirdPartyAppAnalyticsLinkName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static ThirdPartyAppAnalyticsLinkName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ThirdPartyAppAnalyticsLinkName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ThirdPartyAppAnalyticsLinkName"/> with the pattern /// <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerLinkId">The <c>CustomerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="ThirdPartyAppAnalyticsLinkName"/> constructed from the provided ids. /// </returns> public static ThirdPartyAppAnalyticsLinkName FromCustomerCustomerLink(string customerId, string customerLinkId) => new ThirdPartyAppAnalyticsLinkName(ResourceNameType.CustomerCustomerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerLinkId, nameof(customerLinkId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ThirdPartyAppAnalyticsLinkName"/> with /// pattern <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerLinkId">The <c>CustomerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ThirdPartyAppAnalyticsLinkName"/> with pattern /// <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </returns> public static string Format(string customerId, string customerLinkId) => FormatCustomerCustomerLink(customerId, customerLinkId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ThirdPartyAppAnalyticsLinkName"/> with /// pattern <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerLinkId">The <c>CustomerLink</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ThirdPartyAppAnalyticsLinkName"/> with pattern /// <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c>. /// </returns> public static string FormatCustomerCustomerLink(string customerId, string customerLinkId) => s_customerCustomerLink.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(customerLinkId, nameof(customerLinkId))); /// <summary> /// Parses the given resource name string into a new <see cref="ThirdPartyAppAnalyticsLinkName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="thirdPartyAppAnalyticsLinkName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="ThirdPartyAppAnalyticsLinkName"/> if successful.</returns> public static ThirdPartyAppAnalyticsLinkName Parse(string thirdPartyAppAnalyticsLinkName) => Parse(thirdPartyAppAnalyticsLinkName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ThirdPartyAppAnalyticsLinkName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="thirdPartyAppAnalyticsLinkName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ThirdPartyAppAnalyticsLinkName"/> if successful.</returns> public static ThirdPartyAppAnalyticsLinkName Parse(string thirdPartyAppAnalyticsLinkName, bool allowUnparsed) => TryParse(thirdPartyAppAnalyticsLinkName, allowUnparsed, out ThirdPartyAppAnalyticsLinkName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ThirdPartyAppAnalyticsLinkName"/> /// instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="thirdPartyAppAnalyticsLinkName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ThirdPartyAppAnalyticsLinkName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string thirdPartyAppAnalyticsLinkName, out ThirdPartyAppAnalyticsLinkName result) => TryParse(thirdPartyAppAnalyticsLinkName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ThirdPartyAppAnalyticsLinkName"/> /// instance; optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="thirdPartyAppAnalyticsLinkName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ThirdPartyAppAnalyticsLinkName"/>, or <c>null</c> if parsing /// failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string thirdPartyAppAnalyticsLinkName, bool allowUnparsed, out ThirdPartyAppAnalyticsLinkName result) { gax::GaxPreconditions.CheckNotNull(thirdPartyAppAnalyticsLinkName, nameof(thirdPartyAppAnalyticsLinkName)); gax::TemplatedResourceName resourceName; if (s_customerCustomerLink.TryParseName(thirdPartyAppAnalyticsLinkName, out resourceName)) { result = FromCustomerCustomerLink(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(thirdPartyAppAnalyticsLinkName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ThirdPartyAppAnalyticsLinkName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string customerLinkId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; CustomerLinkId = customerLinkId; } /// <summary> /// Constructs a new instance of a <see cref="ThirdPartyAppAnalyticsLinkName"/> class from the component parts /// of pattern <c>customers/{customer_id}/thirdPartyAppAnalyticsLinks/{customer_link_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="customerLinkId">The <c>CustomerLink</c> ID. Must not be <c>null</c> or empty.</param> public ThirdPartyAppAnalyticsLinkName(string customerId, string customerLinkId) : this(ResourceNameType.CustomerCustomerLink, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), customerLinkId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerLinkId, nameof(customerLinkId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>CustomerLink</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string CustomerLinkId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCustomerLink: return s_customerCustomerLink.Expand(CustomerId, CustomerLinkId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ThirdPartyAppAnalyticsLinkName); /// <inheritdoc/> public bool Equals(ThirdPartyAppAnalyticsLinkName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ThirdPartyAppAnalyticsLinkName a, ThirdPartyAppAnalyticsLinkName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ThirdPartyAppAnalyticsLinkName a, ThirdPartyAppAnalyticsLinkName b) => !(a == b); } public partial class ThirdPartyAppAnalyticsLink { /// <summary> /// <see cref="ThirdPartyAppAnalyticsLinkName"/>-typed view over the <see cref="ResourceName"/> resource name /// property. /// </summary> internal ThirdPartyAppAnalyticsLinkName ResourceNameAsThirdPartyAppAnalyticsLinkName { get => string.IsNullOrEmpty(ResourceName) ? null : ThirdPartyAppAnalyticsLinkName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace TaxonomyMenuInjectWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Web; using System.Net; using System.IO; using Microsoft.Xrm.Portal; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; namespace Adxstudio.Xrm.Commerce { /// <summary> /// Used to provide Paypal actions for connecting to paypal and processing paypal data. /// </summary> public class PayPalHelper { public const string SandboxURL = "https://www.sandbox.paypal.com/us/cgi-bin/webscr"; public const string LiveURL = "https://www.paypal.com/cgi-bin/webscr"; /// <summary> /// The base Paypal URL /// </summary> public string PayPalBaseUrl { get; private set; } public string PayPalAccountEmail { get; private set; } public PayPalHelper(IPortalContext xrm) : this(GetPaypalBaseUrl(xrm), GetPaypalAccountEmail(xrm)) { } public PayPalHelper(string baseURL, string accountEmail) { PayPalBaseUrl = baseURL; PayPalAccountEmail = accountEmail; } /// <summary> /// Creates the URL used to submit verification to paypal. /// </summary> /// <param name="values"></param> /// <returns></returns> public string GetSubmitUrl(Dictionary<string, string> values) { StringBuilder url = new StringBuilder(); if (values.ContainsKey("cmd") && values.ContainsKey("business")) { //Do I need to check if dict contains "upload" and put it right after "cmd"???? url.AppendFormat("{0}?cmd={1}&business={2}", PayPalBaseUrl, values["cmd"], values["business"]); } else { throw new Exception("Invalid Paypal submit URL. No value for cmd or business found in query string"); } foreach (var value in values) { if (value.Key == "cmd" || value.Key == "business") { continue; } if (value.Key.Contains("amount") || value.Key.Contains("shipping") || value.Key.Contains("handling")) { if (decimal.Parse(value.Value) != 0.00M) { url.AppendFormat("&{0}={1:f2}", value.Key, decimal.Parse(value.Value)); } } url.AppendFormat("&{0}={1}", value.Key, HttpUtility.UrlEncode(value.Value)); } return url.ToString(); } public WebResponse GetPaymentWebResponse(string incomingReqStr) { var newReq = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl); //Set values for the request back newReq.Method = "POST"; newReq.ContentType = "application/x-www-form-urlencoded"; var newRequestStr = incomingReqStr + "&cmd=_notify-validate"; newReq.ContentLength = newRequestStr.Length; //write out the full parameters into the request var streamOut = new StreamWriter(newReq.GetRequestStream(), System.Text.Encoding.ASCII); streamOut.Write(newRequestStr); streamOut.Close(); //Send request back to Paypal and receive response var response = newReq.GetResponse(); return response; } public static string GetPaypalBaseUrl(IPortalContext xrm) { var paypalBaseUrl = xrm.ServiceContext.GetSiteSettingValueByName(xrm.Website, "Ecommerce/Paypal/PaypalBaseUrl"); if (string.IsNullOrWhiteSpace(paypalBaseUrl)) { paypalBaseUrl = SandboxURL; } return paypalBaseUrl; } public static string GetPaypalAccountEmail(IPortalContext xrm) { var website = xrm.Website; var accountEmailSetting = xrm.ServiceContext.CreateQuery("adx_sitesetting") .Where(ss => ss.GetAttributeValue<EntityReference>("adx_websiteid") == website.ToEntityReference()) .FirstOrDefault(purl => purl.GetAttributeValue<string>("adx_name") == "Ecommerce/Paypal/AccountEmail"); if (accountEmailSetting == null) { throw new Exception("An account email for PayPal must be provided as a site setting. Use site setting PayPal/AccountEmail."); } var accountEmail = accountEmailSetting.GetAttributeValue<string>("adx_value"); return accountEmail; } public bool VerifyIPNOrder(NameValueCollection values, IPortalContext xrm) { var dict = ToDictionary(values); return VerifyIPNOrder(dict, xrm); } public bool VerifyIPNOrder(Dictionary<string, string> values, IPortalContext xrm) { System.Diagnostics.Debug.Write("Now verifying the IPN order..."); var context = xrm.ServiceContext; //check the payment_status is Completed if (values["payment_status"] != "Completed") { System.Diagnostics.Debug.Write("The payment_status is not completed..."); return false; } if (!values.ContainsKey("invoice")) { System.Diagnostics.Debug.Write("There is no invoice set..."); return false; } //for aggregated data if (values.ContainsKey("item_name")) { //then we are dealing with aggregated data if (values["item_name"] != "Aggregated Items") { return false; } } else { if (!ItemizedDataVerification(values, context)) return false; } //check that receiver_email is your Primary PayPal email if (!values.ContainsKey("receiver_email")) { if (values["receiver_email"] != PayPalAccountEmail) { return false; } } //otherwise, we are golden! return true; } private static bool ItemizedDataVerification(Dictionary<string, string> values, OrganizationServiceContext context) { System.Diagnostics.Debug.Write("We are performing itemized data verification..."); //for itemized data int count = 1; while (values.ContainsKey(string.Format("item_number{0}", count))) { var guid = Guid.Parse(values[string.Format("item_number{0}", count)]); var quantity = decimal.Parse(values[string.Format("quantity{0}", count)] ?? "0.0"); var gross = decimal.Parse(values[string.Format("mc_gross_{0}", count)] ?? "0.0"); var shipping = decimal.Parse(values[string.Format("mc_shipping{0}", count)] ?? "0.0"); var handling = decimal.Parse(values[string.Format("mc_handling{0}", count)] ?? "0.0"); var tax = decimal.Parse(values[string.Format("tax{0}", count)] ?? "0.0"); var price = gross - shipping - handling - tax; var quoteLineItem = context.CreateQuery("quotedetail").FirstOrDefault( sci => sci.GetAttributeValue<Guid>("quotedetailid") == guid); if (quoteLineItem == null) { return false; } var quoteLineItemQuantity = quoteLineItem.GetAttributeValue<decimal?>("quantity").GetValueOrDefault(0); var quoteLineQuotedPrice = quoteLineItem.GetAttributeValue<Money>("priceperunit") == null ? 0 : quoteLineItem.GetAttributeValue<Money>("priceperunit").Value; if ((quoteLineItemQuantity != quantity) || (quoteLineQuotedPrice * quoteLineItemQuantity != price)) { return false; } count++; } return true; } public static Dictionary<string, string> ToDictionary(NameValueCollection source) { return source.Cast<string>().Select(s => new { Key = s, Value = source[s] }).ToDictionary(p => p.Key, p => p.Value); } public static string GetPayPalPdtIdentityToken(IPortalContext xrm) { var token = xrm.ServiceContext.GetSiteSettingValueByName(xrm.Website, "Ecommerce/PayPal/PDTIdentityToken"); return token; } /// <summary> /// Send a request to PayPal to get the Payment Data Transfer (PDT) response to confirm successful payment. /// https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/paymentdatatransfer/ /// </summary> /// <param name="identityToken">PDT Identity Token specified in "Website Payment Preference" under the PayPal merchant account.</param> /// <param name="transactionId">The transaction ID sent to us on the return URL via a HTTP GET as name/value pair tx=transactionID</param> public IPayPalPaymentDataTransferResponse GetPaymentDataTransferResponse(string identityToken, string transactionId) { var query = string.Format("cmd=_notify-synch&tx={0}&at={1}", transactionId, identityToken); var request = (HttpWebRequest)WebRequest.Create(PayPalBaseUrl); request.Method = WebRequestMethods.Http.Post; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = query.Length; var streamOut = new StreamWriter(request.GetRequestStream(), Encoding.ASCII); streamOut.Write(query); streamOut.Close(); var streamIn = new StreamReader(request.GetResponse().GetResponseStream()); var response = streamIn.ReadToEnd(); streamIn.Close(); return new PayPalPaymentDataTransferResponse(response); } public enum PaymentDataTransferStatus { Success = 1, Fail = 2, Unknown = 3 } /// <summary> /// PayPal returns related variables for PDT message. /// https://developer.paypal.com/docs/classic/ipn/integration-guide/IPNandPDTVariables/ /// </summary> public interface IPayPalPaymentDataTransferResponse { PaymentDataTransferStatus Status { get; } Dictionary<string, string> Details { get; } } public class PayPalPaymentDataTransferResponse : IPayPalPaymentDataTransferResponse { public PaymentDataTransferStatus Status { get; private set; } public Dictionary<string, string> Details { get; private set; } public PayPalPaymentDataTransferResponse(string response) { Details = new Dictionary<string, string>(); if (string.IsNullOrWhiteSpace(response)) { Status = PaymentDataTransferStatus.Unknown; return; } using (var reader = new StringReader(response)) { var line = reader.ReadLine(); if (line == "FAIL") { Status = PaymentDataTransferStatus.Fail; return; } if (line == "SUCCESS") { Status = PaymentDataTransferStatus.Success; var results = new Dictionary<string, string>(); while ((line = reader.ReadLine()) != null) { results.Add(line.Split('=')[0], line.Split('=')[1]); } Details = results; return; } } Status = PaymentDataTransferStatus.Unknown; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.DotNet.RemoteExecutor; using Xunit; public class Outside { public class Inside { public void GenericMethod<T>() { } public void TwoGenericMethod<T, U>() { } } public void GenericMethod<T>() { } public void TwoGenericMethod<T, U>() { } } public class Outside<T> { public class Inside<U> { public void GenericMethod<V>() { } public void TwoGenericMethod<V, W>() { } } public void GenericMethod<U>() { } public void TwoGenericMethod<U, V>() { } } namespace System.Tests { public partial class TypeTests { [Fact] public void FilterName_Get_ReturnsExpected() { Assert.NotNull(Type.FilterName); Assert.Same(Type.FilterName, Type.FilterName); Assert.NotSame(Type.FilterName, Type.FilterNameIgnoreCase); } [Theory] [InlineData("FilterName_Invoke_DelegateFiltersExpectedMembers", true)] [InlineData(" FilterName_Invoke_DelegateFiltersExpectedMembers ", true)] [InlineData("*", true)] [InlineData(" * ", true)] [InlineData(" Filter* ", true)] [InlineData("FilterName_Invoke_DelegateFiltersExpectedMembe*", true)] [InlineData("FilterName_Invoke_DelegateFiltersExpectedMember*", true)] [InlineData("filterName_Invoke_DelegateFiltersExpectedMembers", false)] [InlineData("FilterName_Invoke_DelegateFiltersExpectedMemberss*", false)] [InlineData("FilterName", false)] [InlineData("*FilterName", false)] [InlineData("", false)] [InlineData(" ", false)] public void FilterName_Invoke_DelegateFiltersExpectedMembers(string filterCriteria, bool expected) { MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers)); Assert.Equal(expected, Type.FilterName(mi, filterCriteria)); } [Fact] public void FilterName_InvalidFilterCriteria_ThrowsInvalidFilterCriteriaException() { MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers)); Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterName(mi, null)); Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterName(mi, new object())); } [Fact] public void FilterNameIgnoreCase_Get_ReturnsExpected() { Assert.NotNull(Type.FilterNameIgnoreCase); Assert.Same(Type.FilterNameIgnoreCase, Type.FilterNameIgnoreCase); Assert.NotSame(Type.FilterNameIgnoreCase, Type.FilterName); } [Theory] [InlineData("FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers", true)] [InlineData("filternameignorecase_invoke_delegatefiltersexpectedmembers", true)] [InlineData(" filterNameIgnoreCase_Invoke_DelegateFiltersexpectedMembers ", true)] [InlineData("*", true)] [InlineData(" * ", true)] [InlineData(" fIlTeR* ", true)] [InlineData("FilterNameIgnoreCase_invoke_delegateFiltersExpectedMembe*", true)] [InlineData("FilterNameIgnoreCase_invoke_delegateFiltersExpectedMember*", true)] [InlineData("filterName_Invoke_DelegateFiltersExpectedMembers", false)] [InlineData("filterNameIgnoreCase_Invoke_DelegateFiltersExpectedMemberss", false)] [InlineData("FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMemberss*", false)] [InlineData("filterNameIgnoreCase", false)] [InlineData("*FilterNameIgnoreCase", false)] [InlineData("", false)] [InlineData(" ", false)] public void FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers(string filterCriteria, bool expected) { MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterNameIgnoreCase_Invoke_DelegateFiltersExpectedMembers)); Assert.Equal(expected, Type.FilterNameIgnoreCase(mi, filterCriteria)); } [Fact] public void FilterNameIgnoreCase_InvalidFilterCriteria_ThrowsInvalidFilterCriteriaException() { MethodInfo mi = typeof(TypeTests).GetMethod(nameof(FilterName_Invoke_DelegateFiltersExpectedMembers)); Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterNameIgnoreCase(mi, null)); Assert.Throws<InvalidFilterCriteriaException>(() => Type.FilterNameIgnoreCase(mi, new object())); } public static IEnumerable<object[]> FindMembers_TestData() { yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "HelloWorld", 0 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "FilterName_Invoke_DelegateFiltersExpectedMembers", 1 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "FilterName_Invoke_Delegate*", 1 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterName, "filterName_Invoke_Delegate*", 0 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "HelloWorld", 0 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "FilterName_Invoke_DelegateFiltersExpectedMembers", 1 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "FilterName_Invoke_Delegate*", 1 }; yield return new object[] { MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance, Type.FilterNameIgnoreCase, "filterName_Invoke_Delegate*", 1 }; } [Theory] [MemberData(nameof(FindMembers_TestData))] public void FindMembers_Invoke_ReturnsExpected(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria, int expectedLength) { Assert.Equal(expectedLength, typeof(TypeTests).FindMembers(memberType, bindingAttr, filter, filterCriteria).Length); } [Theory] [InlineData(typeof(int), typeof(int))] [InlineData(typeof(int[]), typeof(int[]))] [InlineData(typeof(Outside<int>), typeof(Outside<int>))] public void TypeHandle(Type t1, Type t2) { RuntimeTypeHandle r1 = t1.TypeHandle; RuntimeTypeHandle r2 = t2.TypeHandle; Assert.Equal(r1, r2); Assert.Equal(t1, Type.GetTypeFromHandle(r1)); Assert.Equal(t1, Type.GetTypeFromHandle(r2)); } [Fact] public void GetTypeFromDefaultHandle() { Assert.Null(Type.GetTypeFromHandle(default(RuntimeTypeHandle))); } [Theory] [InlineData(typeof(int[]), 1)] [InlineData(typeof(int[,,]), 3)] public void GetArrayRank_Get_ReturnsExpected(Type t, int expected) { Assert.Equal(expected, t.GetArrayRank()); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(IList<int>))] [InlineData(typeof(IList<>))] public void GetArrayRank_NonArrayType_ThrowsArgumentException(Type t) { AssertExtensions.Throws<ArgumentException>(null, () => t.GetArrayRank()); } [Theory] [InlineData(typeof(int), typeof(int[]))] public void MakeArrayType_Invoke_ReturnsExpected(Type t, Type tArrayExpected) { Type tArray = t.MakeArrayType(); Assert.Equal(tArrayExpected, tArray); Assert.Equal(t, tArray.GetElementType()); Assert.True(tArray.IsArray); Assert.True(tArray.HasElementType); string s1 = t.ToString(); string s2 = tArray.ToString(); Assert.Equal(s2, s1 + "[]"); } [Theory] [InlineData(typeof(int))] public void MakeByRefType_Invoke_ReturnsExpected(Type t) { Type tRef1 = t.MakeByRefType(); Type tRef2 = t.MakeByRefType(); Assert.Equal(tRef1, tRef2); Assert.True(tRef1.IsByRef); Assert.True(tRef1.HasElementType); Assert.Equal(t, tRef1.GetElementType()); string s1 = t.ToString(); string s2 = tRef1.ToString(); Assert.Equal(s2, s1 + "&"); } [Theory] [InlineData("System.Nullable`1[System.Int32]", typeof(int?))] [InlineData("System.Int32*", typeof(int*))] [InlineData("System.Int32**", typeof(int**))] [InlineData("Outside`1", typeof(Outside<>))] [InlineData("Outside`1+Inside`1", typeof(Outside<>.Inside<>))] [InlineData("Outside[]", typeof(Outside[]))] [InlineData("Outside[,,]", typeof(Outside[,,]))] [InlineData("Outside[][]", typeof(Outside[][]))] [InlineData("Outside`1[System.Nullable`1[System.Boolean]]", typeof(Outside<bool?>))] public void GetTypeByName_ValidType_ReturnsExpected(string typeName, Type expectedType) { Assert.Equal(expectedType, Type.GetType(typeName, throwOnError: false, ignoreCase: false)); Assert.Equal(expectedType, Type.GetType(typeName.ToLower(), throwOnError: false, ignoreCase: true)); } [Theory] [InlineData("system.nullable`1[system.int32]", typeof(TypeLoadException), false)] [InlineData("System.NonExistingType", typeof(TypeLoadException), false)] [InlineData("", typeof(TypeLoadException), false)] [InlineData("System.Int32[,*,]", typeof(ArgumentException), false)] [InlineData("Outside`2", typeof(TypeLoadException), false)] [InlineData("Outside`1[System.Boolean, System.Int32]", typeof(ArgumentException), true)] public void GetTypeByName_Invalid(string typeName, Type expectedException, bool alwaysThrowsException) { if (!alwaysThrowsException) { Assert.Null(Type.GetType(typeName, throwOnError: false, ignoreCase: false)); } Assert.Throws(expectedException, () => Type.GetType(typeName, throwOnError: true, ignoreCase: false)); } [Fact] public void GetTypeByName_InvokeViaReflection_Success() { MethodInfo method = typeof(Type).GetMethod("GetType", new[] { typeof(string) }); object result = method.Invoke(null, new object[] { "System.Tests.TypeTests" }); Assert.Equal(typeof(TypeTests), result); } [Fact] public void Delimiter() { Assert.Equal('.', Type.Delimiter); } [Theory] [InlineData(typeof(bool), TypeCode.Boolean)] [InlineData(typeof(byte), TypeCode.Byte)] [InlineData(typeof(char), TypeCode.Char)] [InlineData(typeof(DateTime), TypeCode.DateTime)] [InlineData(typeof(decimal), TypeCode.Decimal)] [InlineData(typeof(double), TypeCode.Double)] [InlineData(null, TypeCode.Empty)] [InlineData(typeof(short), TypeCode.Int16)] [InlineData(typeof(int), TypeCode.Int32)] [InlineData(typeof(long), TypeCode.Int64)] [InlineData(typeof(object), TypeCode.Object)] [InlineData(typeof(System.Nullable), TypeCode.Object)] [InlineData(typeof(Nullable<int>), TypeCode.Object)] [InlineData(typeof(Dictionary<,>), TypeCode.Object)] [InlineData(typeof(Exception), TypeCode.Object)] [InlineData(typeof(sbyte), TypeCode.SByte)] [InlineData(typeof(float), TypeCode.Single)] [InlineData(typeof(string), TypeCode.String)] [InlineData(typeof(ushort), TypeCode.UInt16)] [InlineData(typeof(uint), TypeCode.UInt32)] [InlineData(typeof(ulong), TypeCode.UInt64)] public void GetTypeCode_ValidType_ReturnsExpected(Type t, TypeCode typeCode) { Assert.Equal(typeCode, Type.GetTypeCode(t)); } [Fact] public void ReflectionOnlyGetType() { Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType(null, true, false)); Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType("", true, true)); Assert.Throws<PlatformNotSupportedException>(() => Type.ReflectionOnlyGetType("System.Tests.TypeTests", false, true)); } } public class TypeTestsExtended { public class ContextBoundClass : ContextBoundObject { public string Value = "The Value property."; } static string s_testAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestLoadAssembly.dll"); static string testtype = "System.Collections.Generic.Dictionary`2[[Program, Foo], [Program, Foo]]"; private static Func<AssemblyName, Assembly> assemblyloader = (aName) => aName.Name == "TestLoadAssembly" ? Assembly.LoadFrom(@".\TestLoadAssembly.dll") : null; private static Func<Assembly, string, bool, Type> typeloader = (assem, name, ignore) => assem == null ? Type.GetType(name, false, ignore) : assem.GetType(name, false, ignore); [Fact] public void GetTypeByName() { RemoteInvokeOptions options = new RemoteInvokeOptions(); RemoteExecutor.Invoke(() => { string test1 = testtype; Type t1 = Type.GetType(test1, (aName) => aName.Name == "Foo" ? Assembly.LoadFrom(s_testAssemblyPath) : null, typeloader, true ); Assert.NotNull(t1); string test2 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program, TestLoadAssembly]]"; Type t2 = Type.GetType(test2, assemblyloader, typeloader, true); Assert.NotNull(t2); Assert.Equal(t1, t2); return RemoteExecutor.SuccessExitCode; }, options).Dispose(); } [Theory] [InlineData("System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [Program2, TestLoadAssembly]]")] [InlineData("")] public void GetTypeByName_NoSuchType_ThrowsTypeLoadException(string typeName) { RemoteExecutor.Invoke(marshalledTypeName => { Assert.Throws<TypeLoadException>(() => Type.GetType(marshalledTypeName, assemblyloader, typeloader, true)); Assert.Null(Type.GetType(marshalledTypeName, assemblyloader, typeloader, false)); return RemoteExecutor.SuccessExitCode; }, typeName).Dispose(); } [Fact] public void GetTypeByNameCaseSensitiveTypeloadFailure() { RemoteInvokeOptions options = new RemoteInvokeOptions(); RemoteExecutor.Invoke(() => { //Type load failure due to case sensitive search of type Ptogram string test3 = "System.Collections.Generic.Dictionary`2[[Program, TestLoadAssembly], [program, TestLoadAssembly]]"; Assert.Throws<TypeLoadException>(() => Type.GetType(test3, assemblyloader, typeloader, true, false //case sensitive )); //non throwing version Type t2 = Type.GetType(test3, assemblyloader, typeloader, false, //no throw false ); Assert.Null(t2); return RemoteExecutor.SuccessExitCode; }, options).Dispose(); } [Fact] public void IsContextful() { Assert.True(!typeof(TypeTestsExtended).IsContextful); Assert.True(!typeof(ContextBoundClass).IsContextful); } #region GetInterfaceMap tests public static IEnumerable<object[]> GetInterfaceMap_TestData() { yield return new object[] { typeof(ISimpleInterface), typeof(SimpleType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(ISimpleInterface).GetMethod("Method"), typeof(SimpleType).GetMethod("Method")), new Tuple<MethodInfo, MethodInfo>(typeof(ISimpleInterface).GetMethod("GenericMethod"), typeof(SimpleType).GetMethod("GenericMethod")) } }; yield return new object[] { typeof(IGenericInterface<object>), typeof(DerivedType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(IGenericInterface<object>).GetMethod("Method"), typeof(DerivedType).GetMethod("Method", new Type[] { typeof(object) })), } }; yield return new object[] { typeof(IGenericInterface<string>), typeof(DerivedType), new Tuple<MethodInfo, MethodInfo>[] { new Tuple<MethodInfo, MethodInfo>(typeof(IGenericInterface<string>).GetMethod("Method"), typeof(DerivedType).GetMethod("Method", new Type[] { typeof(string) })), } }; } [Theory] [MemberData(nameof(GetInterfaceMap_TestData))] public void GetInterfaceMap(Type interfaceType, Type classType, Tuple<MethodInfo, MethodInfo>[] expectedMap) { InterfaceMapping actualMapping = classType.GetInterfaceMap(interfaceType); Assert.Equal(interfaceType, actualMapping.InterfaceType); Assert.Equal(classType, actualMapping.TargetType); Assert.Equal(expectedMap.Length, actualMapping.InterfaceMethods.Length); Assert.Equal(expectedMap.Length, actualMapping.TargetMethods.Length); for (int i = 0; i < expectedMap.Length; i++) { Assert.Contains(expectedMap[i].Item1, actualMapping.InterfaceMethods); int index = Array.IndexOf(actualMapping.InterfaceMethods, expectedMap[i].Item1); Assert.Equal(expectedMap[i].Item2, actualMapping.TargetMethods[index]); } } interface ISimpleInterface { void Method(); void GenericMethod<T>(); } class SimpleType : ISimpleInterface { public void Method() { } public void GenericMethod<T>() { } } interface IGenericInterface<T> { void Method(T arg); } class GenericBaseType<T> : IGenericInterface<T> { public void Method(T arg) { } } class DerivedType : GenericBaseType<object>, IGenericInterface<string> { public void Method(string arg) { } } #endregion } public class NonGenericClass { } public class NonGenericSubClassOfNonGeneric : NonGenericClass { } public class GenericClass<T> { } public class NonGenericSubClassOfGeneric : GenericClass<string> { } public class GenericClass<T, U> { } public abstract class AbstractClass { } public struct NonGenericStruct { } public ref struct RefStruct { } public struct GenericStruct<T> { } public struct GenericStruct<T, U> { } public interface NonGenericInterface { } public interface GenericInterface<T> { } public interface GenericInterface<T, U> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Stratus.Utilities; using UnityEditor; using UnityEngine; namespace Stratus { public static class SerializedPropertyExtensions { /// <summary> /// Gets the owning object of a specific type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="property"></param> /// <param name="fieldInfo"></param> /// <returns></returns> public static T GetObject<T>(this SerializedProperty property, FieldInfo fieldInfo) where T : class { object obj = fieldInfo.GetValue(property.serializedObject.targetObject); Type type = obj.GetType(); if (obj == null) { return null; } T actualObject = null; //if (typeof(IEnumerable).IsAssignableFrom(obj.GetType())) if (type.IsArray)// || type.IsGenericType) { int index = Convert.ToInt32(new string(property.propertyPath.Where(c => char.IsDigit(c)).ToArray())); actualObject = ((T[])obj)[index]; } else { actualObject = obj as T; } return actualObject; } /// <summary> /// Get the object the serialized property holds by using reflection /// </summary> /// <typeparam name="T">The object type that the property contains</typeparam> /// <param name="property"></param> /// <returns>Returns the object type T if it is the type the property actually contains</returns> public static T GetValue<T>(this SerializedProperty property) { return GetNestedObject<T>(property.propertyPath, GetSerializedPropertyRootComponent(property)); } /// <summary> /// Get the object the serialized property holds by using reflection /// </summary> /// <typeparam name="T">The object type that the property contains</typeparam> /// <param name="property"></param> /// <returns>Returns the object type T if it is the type the property actually contains</returns> public static T GetParent<T>(this SerializedProperty property) { //Iterate to parent object of the value, necessary if it is a nested object object obj = GetSerializedPropertyRootComponent(property); string[] fieldStructure = property.propertyPath.Split('.'); for (int i = 0; i < fieldStructure.Length - 1; i++) { obj = obj.GetFieldOrPropertyValue<object>(fieldStructure[i]); } return (T)obj; } /// <summary> /// Set the value of a field of the property with the type T /// </summary> /// <typeparam name="T">The type of the field that is set</typeparam> /// <param name="property">The serialized property that should be set</param> /// <param name="value">The new value for the specified property</param> /// <returns>Returns if the operation was successful or failed</returns> public static bool SetValue<T>(this SerializedProperty property, T value) { //Iterate to parent object of the value, necessary if it is a nested object object obj = GetSerializedPropertyRootComponent(property); string[] fieldStructure = property.propertyPath.Split('.'); for (int i = 0; i < fieldStructure.Length - 1; i++) { obj = obj.GetFieldOrPropertyValue<object>(fieldStructure[i]); } string fieldName = fieldStructure.Last(); return obj.SetFieldOrPropertyValue(fieldName, value); } /// <summary> /// Get the component of a serialized property /// </summary> /// <param name="property">The property that is part of the component</param> /// <returns>The root component of the property</returns> public static Component GetSerializedPropertyRootComponent(SerializedProperty property) { return (Component)property.serializedObject.targetObject; } /// <summary> /// Iterates through objects to handle objects that are nested in the root object /// </summary> /// <typeparam name="T">The type of the nested object</typeparam> /// <param name="path">Path to the object through other properties e.g. PlayerInformation.Health</param> /// <param name="obj">The root object from which this path leads to the property</param> /// <param name="includeAllBases">Include base classes and interfaces as well</param> /// <returns>Returns the nested object casted to the type T</returns> public static T GetNestedObject<T>(string path, object obj, bool includeAllBases = false) { foreach (string part in path.Split('.')) { obj = obj.GetFieldOrPropertyValue<object>(part, includeAllBases); } return (T)obj; } /// <summary> /// Iterates through objects to handle objects that are nested in the root object /// </summary> /// <typeparam name="T">The type of the nested object</typeparam> /// <param name="path">Path to the object through other properties e.g. PlayerInformation.Health</param> /// <param name="obj">The root object from which this path leads to the property</param> /// <param name="includeAllBases">Include base classes and interfaces as well</param> /// <returns>Returns the nested object casted to the type T</returns> public static T GetNestedObjectUntil<T>(string path, object obj, bool includeAllBases = false) { foreach (string part in path.Split('.')) { obj = obj.GetFieldOrPropertyValue<object>(part, includeAllBases); if (obj is T) { return (T)obj; } } return default(T); } //public static T GetFieldOrPropertyValue<T>(string memberName, object obj, bool includeAllBases = false, // BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) //{ // FieldInfo field = obj.GetType().GetField(memberName, bindings); // if (field != null) // { // return (T)field.GetValue(obj); // } // // PropertyInfo property = obj.GetType().GetProperty(memberName, bindings); // if (property != null) // { // return (T)property.GetValue(obj, null); // } // // if (includeAllBases) // { // foreach (Type type in GetBaseClassesAndInterfaces(obj.GetType())) // { // field = type.GetField(memberName, bindings); // if (field != null) // { // return (T)field.GetValue(obj); // } // // property = type.GetProperty(memberName, bindings); // if (property != null) // { // return (T)property.GetValue(obj, null); // } // } // } // // return default(T); //} //public static bool SetFieldOrPropertyValue(string fieldName, object obj, object value, bool includeAllBases = false, BindingFlags bindings = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) //{ // FieldInfo field = obj.GetType().GetField(fieldName, bindings); // if (field != null) // { // field.SetValue(obj, value); // return true; // } // // PropertyInfo property = obj.GetType().GetProperty(fieldName, bindings); // if (property != null) // { // property.SetValue(obj, value, null); // return true; // } // // if (includeAllBases) // { // Type objectType = obj.GetType(); // foreach (Type type in objectType.GetBaseClassesAndInterfaces()) // { // field = type.GetField(fieldName, bindings); // if (field != null) // { // field.SetValue(obj, value); // return true; // } // // property = type.GetProperty(fieldName, bindings); // if (property != null) // { // property.SetValue(obj, value, null); // return true; // } // } // } // return false; //} /// This is a way to get a field name string in such a manner that the compiler will /// generate errors for invalid fields. Much better than directly using strings. /// Usage: instead of /// <example> /// "m_MyField"; /// </example> /// do this: /// <example> /// MyClass myclass = null; /// SerializedPropertyHelper.PropertyName( () => myClass.m_MyField); /// </example> public static string PropertyName(Expression<Func<object>> exp) { MemberExpression body = exp.Body as MemberExpression; if (body == null) { UnaryExpression ubody = (UnaryExpression)exp.Body; body = ubody.Operand as MemberExpression; } return body.Member.Name; } /// <summary> /// Generates a hash unique to this specific property on its specific object. /// Useful for mapping metadata to the editor representation of one of its specific properties. /// </summary> /// <param name="property"></param> /// <returns></returns> public static int GetPropertyObjectHash(this SerializedProperty property) { int h1 = property.serializedObject.targetObject.GetHashCode(); int h2 = property.propertyPath.GetHashCode(); return ((h1 << 5) + h1) ^ h2; } /// <summary> /// Get the visible children of a given SerializedProperty /// </summary> /// <param name="property"></param> /// <returns></returns> public static IEnumerable<SerializedProperty> GetVisibleChildren(this SerializedProperty property) { if (property.hasChildren == false) { yield break; } bool checkNext = false; property = property.Copy(); SerializedProperty next = property.Copy(); // We only consider checking next if we're not the root property (which can't have a next) if (property.depth != -1) { checkNext = next.NextVisible(false); } if (property.NextVisible(true)) { do { if (checkNext && SerializedProperty.EqualContents(property, next)) { yield break; } yield return property; } while (property.NextVisible(false)); } } /// Usage: instead of /// <example> /// mySerializedObject.FindProperty("m_MyField"); /// </example> /// do this: /// <example> /// MyClass myclass = null; /// mySerializedObject.FindProperty( () => myClass.m_MyField); /// </example> public static SerializedProperty FindProperty(this SerializedObject obj, Expression<Func<object>> exp) { return obj.FindProperty(PropertyName(exp)); } /// Usage: instead of /// <example> /// mySerializedProperty.FindPropertyRelative("m_MyField"); /// </example> /// do this: /// <example> /// MyClass myclass = null; /// mySerializedProperty.FindPropertyRelative( () => myClass.m_MyField); /// </example> public static SerializedProperty FindPropertyRelative(this SerializedProperty obj, Expression<Func<object>> exp) { return obj.FindPropertyRelative(PropertyName(exp)); } /// <summary> /// Retrieves the FieldInfo for the field behind this serialized property /// </summary> /// <param name="property"></param> /// <returns></returns> public static FieldInfo GetFieldInfo(this SerializedProperty property) { Type objectType = property.serializedObject.targetObject.GetType(); return objectType.GetField(property.name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance); } /// <summary> /// Retrieves the Type of the field behind this serialized property /// </summary> /// <param name="property"></param> /// <returns></returns> public static Type GetFieldType(this SerializedProperty property) { Type objectType = property.serializedObject.targetObject.GetType(); Type type = objectType.GetField(property.name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance).FieldType; return type; } /// <summary> /// Retrieves all the attributes for the field behind this serialized property /// </summary> /// <param name="property"></param> /// <returns></returns> public static Attribute[] GetFieldAttributes(this SerializedProperty property) { FieldInfo fi = property.GetFieldInfo(); if (fi == null) throw new MissingFieldException($"No field info for {property.name}"); var attributes = CustomAttributeExtensions.GetCustomAttributes<Attribute>(fi); return attributes != null ? attributes.ToArray() : new Attribute[] { }; } public static int GetHashCodeForPropertyPathWithoutArrayIndex(this SerializedProperty prop) { return StratusReflection.GetProperty<int>("hashCodeForPropertyPathWithoutArrayIndex", typeof(SerializedProperty), prop); } public static int GetInspectorMode(this SerializedObject prop) { return StratusReflection.GetProperty<int>("inspectorMode", typeof(SerializedObject), prop); } /// <summary> /// Splits a given property into each of its multiple values. /// If it has a single value, only the same property is returned. /// </summary> public static IEnumerable<SerializedProperty> Multiple(this SerializedProperty property) { if (property.hasMultipleDifferentValues) { return property.serializedObject.targetObjects.Select(o => new SerializedObject(o).FindProperty(property.propertyPath)); } else { return new[] { property }; } } } }
// 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 ShuffleDouble1() { var test = new ImmBinaryOpTest__ShuffleDouble1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.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 (Avx.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(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.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(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmBinaryOpTest__ShuffleDouble1 { private struct TestStruct { public Vector256<Double> _fld1; public Vector256<Double> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__ShuffleDouble1 testClass) { var result = Avx.Shuffle(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Double>>() / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector256<Double> _clsVar1; private static Vector256<Double> _clsVar2; private Vector256<Double> _fld1; private Vector256<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static ImmBinaryOpTest__ShuffleDouble1() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); } public ImmBinaryOpTest__ShuffleDouble1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Double>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.Shuffle( Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.Shuffle( Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.Shuffle( Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)), 1 ); 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(Avx).GetMethod(nameof(Avx.Shuffle), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.Shuffle), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.Shuffle), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.Shuffle( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr); var result = Avx.Shuffle(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Shuffle(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr)); var result = Avx.Shuffle(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__ShuffleDouble1(); var result = Avx.Shuffle(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.Shuffle(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.Shuffle(test._fld1, test._fld2, 1); 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 RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector256<Double>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Double>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(left[1])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[3]) != BitConverter.DoubleToInt64Bits(right[2])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.Shuffle)}<Double>(Vector256<Double>.1, Vector256<Double>): {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 System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Cache; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.EntityBase; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.Factories; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.Relators; using Umbraco.Core.Persistence.SqlSyntax; 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 { public DictionaryRepository(IScopeUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider syntax) : base(work, cache, logger, syntax) { } protected override IRepositoryCachePolicy<IDictionaryItem, int> CreateCachePolicy(IRuntimeCacheProvider runtimeCache) { var options = new RepositoryCachePolicyOptions { //allow zero to be cached GetAllCacheAllowZeroCount = true }; return new SingleItemsOnlyRepositoryCachePolicy<IDictionaryItem, int>(runtimeCache, options); } #region Overrides of RepositoryBase<int,DictionaryItem> protected override IDictionaryItem PerformGet(int id) { var sql = GetBaseQuery(false) .Where(GetBaseWhereClause(), new { Id = id }) //must be sorted this way for the relator to work .OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); var dto = Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql).FirstOrDefault(); if (dto == null) return null; var entity = ConvertFromDto(dto); //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) { var sql = GetBaseQuery(false).Where("cmsDictionary.pk > 0"); if (ids.Any()) { sql.Where("cmsDictionary.pk in (@ids)", new { ids = ids }); } //must be sorted this way for the relator to work sql.OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql) .Select(dto => ConvertFromDto(dto)); } protected override IEnumerable<IDictionaryItem> PerformGetByQuery(IQuery<IDictionaryItem> query) { var sqlClause = GetBaseQuery(false); var translator = new SqlTranslator<IDictionaryItem>(sqlClause, query); var sql = translator.Translate(); //must be sorted this way for the relator to work sql.OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql) .Select(x => ConvertFromDto(x)); } #endregion #region Overrides of PetaPocoRepositoryBase<int,DictionaryItem> protected override Sql GetBaseQuery(bool isCount) { var sql = new Sql(); if (isCount) { sql.Select("COUNT(*)") .From<DictionaryDto>(SqlSyntax); } else { sql.Select("*") .From<DictionaryDto>(SqlSyntax) .LeftJoin<LanguageTextDto>(SqlSyntax) .On<DictionaryDto, LanguageTextDto>(SqlSyntax, 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>(); } protected override Guid NodeObjectTypeId { get { throw new NotImplementedException(); } } #endregion #region Unit of Work Implementation protected override void PersistNewItem(IDictionaryItem entity) { var dictionaryItem = ((DictionaryItem) entity); dictionaryItem.AddingEntity(); foreach (var translation in dictionaryItem.Translations) translation.Value = translation.Value.ToValidXmlString(); var factory = new DictionaryItemFactory(); var dto = factory.BuildDto(dictionaryItem); var id = Convert.ToInt32(Database.Insert(dto)); dictionaryItem.Id = id; var translationFactory = new DictionaryTranslationFactory(dictionaryItem.Key); foreach (var translation in dictionaryItem.Translations) { var textDto = translationFactory.BuildDto(translation); translation.Id = Convert.ToInt32(Database.Insert(textDto)); translation.Key = dictionaryItem.Key; } dictionaryItem.ResetDirtyProperties(); } protected override void PersistUpdatedItem(IDictionaryItem entity) { ((Entity)entity).UpdatingEntity(); foreach (var translation in entity.Translations) translation.Value = translation.Value.ToValidXmlString(); var factory = new DictionaryItemFactory(); var dto = factory.BuildDto(entity); Database.Update(dto); var translationFactory = new DictionaryTranslationFactory(entity.Key); foreach (var translation in entity.Translations) { var textDto = translationFactory.BuildDto(translation); if (translation.HasIdentity) { Database.Update(textDto); } else { translation.Id = Convert.ToInt32(Database.Insert(textDto)); translation.Key = entity.Key; } } entity.ResetDirtyProperties(); //Clear the cache entries that exist by uniqueid/item key IsolatedCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(entity.ItemKey)); IsolatedCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(entity.Key)); } 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 }); //Clear the cache entries that exist by uniqueid/item key IsolatedCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(entity.ItemKey)); IsolatedCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(entity.Key)); entity.DeletedDate = DateTime.Now; } 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 }); //Clear the cache entries that exist by uniqueid/item key IsolatedCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(dto.Key)); IsolatedCache.ClearCacheItem(GetCacheIdKey<IDictionaryItem>(dto.UniqueId)); } } #endregion protected IDictionaryItem ConvertFromDto(DictionaryDto dto) { var factory = new DictionaryItemFactory(); var entity = factory.BuildEntity(dto); var list = new List<IDictionaryTranslation>(); foreach (var textDto in dto.LanguageTextDtos) { if (textDto.LanguageId <= 0) continue; var translationFactory = new DictionaryTranslationFactory(dto.UniqueId); list.Add(translationFactory.BuildEntity(textDto)); } entity.Translations = list; return entity; } public IDictionaryItem Get(Guid uniqueId) { // note: normal to use GlobalCache here since we're passing it to a new repository using (var uniqueIdRepo = new DictionaryByUniqueIdRepository(this, UnitOfWork, GlobalCache, Logger, SqlSyntax)) { return uniqueIdRepo.Get(uniqueId); } } public IDictionaryItem Get(string key) { // note: normal to use GlobalCache here since we're passing it to a new repository using (var keyRepo = new DictionaryByKeyRepository(this, UnitOfWork, GlobalCache, Logger, SqlSyntax)) { return keyRepo.Get(key); } } private IEnumerable<IDictionaryItem> GetRootDictionaryItems() { var query = Query<IDictionaryItem>.Builder.Where(x => x.ParentId == null); return GetByQuery(query); } public Dictionary<string, Guid> GetDictionaryItemKeyMap() { var columns = new[] { "key", "id" }.Select(x => (object) SqlSyntax.GetQuotedColumnName(x)).ToArray(); var sql = new Sql().Select(columns).From<DictionaryDto>(SqlSyntax); return Database.Fetch<DictionaryItemKeyIdDto>(sql).ToDictionary(x => x.Key, x => x.Id); } private class DictionaryItemKeyIdDto { public string Key { get; set; } public Guid Id { get; set; } } public IEnumerable<IDictionaryItem> GetDictionaryItemDescendants(Guid? parentId) { //This methods will look up children at each level, since we do not store a path for dictionary (ATM), we need to do a recursive // lookup to get descendants. Currently this is the most efficient way to do it Func<Guid[], IEnumerable<IEnumerable<IDictionaryItem>>> getItemsFromParents = guids => { //needs to be in groups of 2000 because we are doing an IN clause and there's a max parameter count that can be used. return guids.InGroupsOf(2000) .Select(@group => { var sqlClause = GetBaseQuery(false) .Where<DictionaryDto>(x => x.Parent != null) .Where(string.Format("{0} IN (@parentIds)", SqlSyntax.GetQuotedColumnName("parent")), new { parentIds = @group }); var translator = new SqlTranslator<IDictionaryItem>(sqlClause, Query<IDictionaryItem>.Builder); var sql = translator.Translate(); //must be sorted this way for the relator to work sql.OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql) .Select(x => ConvertFromDto(x)); }); }; var childItems = parentId.HasValue == false ? new[] { GetRootDictionaryItems() } : getItemsFromParents(new[] { parentId.Value }); return childItems.SelectRecursive(items => getItemsFromParents(items.Select(x => x.Key).ToArray())).SelectMany(items => items); } private class DictionaryByUniqueIdRepository : SimpleGetRepository<Guid, IDictionaryItem, DictionaryDto> { private readonly DictionaryRepository _dictionaryRepository; public DictionaryByUniqueIdRepository(DictionaryRepository dictionaryRepository, IScopeUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) { _dictionaryRepository = dictionaryRepository; } protected override IEnumerable<DictionaryDto> PerformFetch(Sql sql) { //must be sorted this way for the relator to work sql.OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql); } protected override Sql GetBaseQuery(bool isCount) { return _dictionaryRepository.GetBaseQuery(isCount); } protected override string GetBaseWhereClause() { return "cmsDictionary." + SqlSyntax.GetQuotedColumnName("id") + " = @Id"; } protected override IDictionaryItem ConvertToEntity(DictionaryDto dto) { return _dictionaryRepository.ConvertFromDto(dto); } protected override object GetBaseWhereClauseArguments(Guid id) { return new { Id = id }; } protected override string GetWhereInClauseForGetAll() { return "cmsDictionary." + SqlSyntax.GetQuotedColumnName("id") + " in (@ids)"; } protected override IRepositoryCachePolicy<IDictionaryItem, Guid> CreateCachePolicy(IRuntimeCacheProvider runtimeCache) { var options = new RepositoryCachePolicyOptions { //allow zero to be cached GetAllCacheAllowZeroCount = true }; return new SingleItemsOnlyRepositoryCachePolicy<IDictionaryItem, Guid>(runtimeCache, options); } } private class DictionaryByKeyRepository : SimpleGetRepository<string, IDictionaryItem, DictionaryDto> { private readonly DictionaryRepository _dictionaryRepository; public DictionaryByKeyRepository(DictionaryRepository dictionaryRepository, IScopeUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) { _dictionaryRepository = dictionaryRepository; } protected override IEnumerable<DictionaryDto> PerformFetch(Sql sql) { //must be sorted this way for the relator to work sql.OrderBy<DictionaryDto>(x => x.UniqueId, SqlSyntax); return Database.Fetch<DictionaryDto, LanguageTextDto, DictionaryDto>(new DictionaryLanguageTextRelator().Map, sql); } protected override Sql GetBaseQuery(bool isCount) { return _dictionaryRepository.GetBaseQuery(isCount); } protected override string GetBaseWhereClause() { return "cmsDictionary." + SqlSyntax.GetQuotedColumnName("key") + " = @Id"; } protected override IDictionaryItem ConvertToEntity(DictionaryDto dto) { return _dictionaryRepository.ConvertFromDto(dto); } protected override object GetBaseWhereClauseArguments(string id) { return new { Id = id }; } protected override string GetWhereInClauseForGetAll() { return "cmsDictionary." + SqlSyntax.GetQuotedColumnName("key") + " in (@ids)"; } protected override IRepositoryCachePolicy<IDictionaryItem, string> CreateCachePolicy(IRuntimeCacheProvider runtimeCache) { var options = new RepositoryCachePolicyOptions { //allow zero to be cached GetAllCacheAllowZeroCount = true }; return new SingleItemsOnlyRepositoryCachePolicy<IDictionaryItem, string>(runtimeCache, options); } } } }
// 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.Numerics; using Internal.Runtime.CompilerServices; namespace System { // This is a port of the `Dragon4` implementation here: http://www.ryanjuckett.com/programming/printing-floating-point-numbers/part-2/ // The backing algorithm and the proofs behind it are described in more detail here: https://www.cs.indiana.edu/~dyb/pubs/FP-Printing-PLDI96.pdf internal static partial class Number { public static void Dragon4Double(double value, int cutoffNumber, bool isSignificantDigits, ref NumberBuffer number) { double v = double.IsNegative(value) ? -value : value; Debug.Assert(v > 0); Debug.Assert(double.IsFinite(v)); ulong mantissa = ExtractFractionAndBiasedExponent(value, out int exponent); uint mantissaHighBitIdx = 0; bool hasUnequalMargins = false; if ((mantissa >> DiyFp.DoubleImplicitBitIndex) != 0) { mantissaHighBitIdx = DiyFp.DoubleImplicitBitIndex; hasUnequalMargins = (mantissa == (1UL << DiyFp.DoubleImplicitBitIndex)); } else { Debug.Assert(mantissa != 0); mantissaHighBitIdx = (uint)BitOperations.Log2(mantissa); } int length = (int)(Dragon4(mantissa, exponent, mantissaHighBitIdx, hasUnequalMargins, cutoffNumber, isSignificantDigits, number.Digits, out int decimalExponent)); number.Scale = decimalExponent + 1; number.Digits[length] = (byte)('\0'); number.DigitsCount = length; } public static unsafe void Dragon4Single(float value, int cutoffNumber, bool isSignificantDigits, ref NumberBuffer number) { float v = float.IsNegative(value) ? -value : value; Debug.Assert(v > 0); Debug.Assert(float.IsFinite(v)); uint mantissa = ExtractFractionAndBiasedExponent(value, out int exponent); uint mantissaHighBitIdx = 0; bool hasUnequalMargins = false; if ((mantissa >> DiyFp.SingleImplicitBitIndex) != 0) { mantissaHighBitIdx = DiyFp.SingleImplicitBitIndex; hasUnequalMargins = (mantissa == (1U << DiyFp.SingleImplicitBitIndex)); } else { Debug.Assert(mantissa != 0); mantissaHighBitIdx = (uint)BitOperations.Log2(mantissa); } int length = (int)(Dragon4(mantissa, exponent, mantissaHighBitIdx, hasUnequalMargins, cutoffNumber, isSignificantDigits, number.Digits, out int decimalExponent)); number.Scale = decimalExponent + 1; number.Digits[length] = (byte)('\0'); number.DigitsCount = length; } // This is an implementation of the Dragon4 algorithm to convert a binary number in floating-point format to a decimal number in string format. // The function returns the number of digits written to the output buffer and the output is not NUL terminated. // // The floating point input value is (mantissa * 2^exponent). // // See the following papers for more information on the algorithm: // "How to Print Floating-Point Numbers Accurately" // Steele and White // http://kurtstephens.com/files/p372-steele.pdf // "Printing Floating-Point Numbers Quickly and Accurately" // Burger and Dybvig // http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.4656&rep=rep1&type=pdf private static unsafe uint Dragon4(ulong mantissa, int exponent, uint mantissaHighBitIdx, bool hasUnequalMargins, int cutoffNumber, bool isSignificantDigits, Span<byte> buffer, out int decimalExponent) { int curDigit = 0; Debug.Assert(buffer.Length > 0); // We deviate from the original algorithm and just assert that the mantissa // is not zero. Comparing to zero is fine since the caller should have set // the implicit bit of the mantissa, meaning it would only ever be zero if // the extracted exponent was also zero. And the assertion is fine since we // require that the DoubleToNumber handle zero itself. Debug.Assert(mantissa != 0); // Compute the initial state in integral form such that // value = scaledValue / scale // marginLow = scaledMarginLow / scale BigInteger scale; // positive scale applied to value and margin such that they can be represented as whole numbers BigInteger scaledValue; // scale * mantissa BigInteger scaledMarginLow; // scale * 0.5 * (distance between this floating-point number and its immediate lower value) // For normalized IEEE floating-point values, each time the exponent is incremented the margin also doubles. // That creates a subset of transition numbers where the high margin is twice the size of the low margin. BigInteger* pScaledMarginHigh; BigInteger optionalMarginHigh; if (hasUnequalMargins) { if (exponent > 0) // We have no fractional component { // 1) Expand the input value by multiplying out the mantissa and exponent. // This represents the input value in its whole number representation. // 2) Apply an additional scale of 2 such that later comparisons against the margin values are simplified. // 3) Set the margin value to the loweset mantissa bit's scale. // scaledValue = 2 * 2 * mantissa * 2^exponent scaledValue = new BigInteger(4 * mantissa); scaledValue.ShiftLeft((uint)(exponent)); // scale = 2 * 2 * 1 scale = new BigInteger(4); // scaledMarginLow = 2 * 2^(exponent - 1) BigInteger.Pow2((uint)(exponent), out scaledMarginLow); // scaledMarginHigh = 2 * 2 * 2^(exponent + 1) BigInteger.Pow2((uint)(exponent + 1), out optionalMarginHigh); } else // We have a fractional exponent { // In order to track the mantissa data as an integer, we store it as is with a large scale // scaledValue = 2 * 2 * mantissa scaledValue = new BigInteger(4 * mantissa); // scale = 2 * 2 * 2^(-exponent) BigInteger.Pow2((uint)(-exponent + 2), out scale); // scaledMarginLow = 2 * 2^(-1) scaledMarginLow = new BigInteger(1); // scaledMarginHigh = 2 * 2 * 2^(-1) optionalMarginHigh = new BigInteger(2); } // The high and low margins are different pScaledMarginHigh = &optionalMarginHigh; } else { if (exponent > 0) // We have no fractional component { // 1) Expand the input value by multiplying out the mantissa and exponent. // This represents the input value in its whole number representation. // 2) Apply an additional scale of 2 such that later comparisons against the margin values are simplified. // 3) Set the margin value to the lowest mantissa bit's scale. // scaledValue = 2 * mantissa*2^exponent scaledValue = new BigInteger(2 * mantissa); scaledValue.ShiftLeft((uint)(exponent)); // scale = 2 * 1 scale = new BigInteger(2); // scaledMarginLow = 2 * 2^(exponent-1) BigInteger.Pow2((uint)(exponent), out scaledMarginLow); } else // We have a fractional exponent { // In order to track the mantissa data as an integer, we store it as is with a large scale // scaledValue = 2 * mantissa scaledValue = new BigInteger(2 * mantissa); // scale = 2 * 2^(-exponent) BigInteger.Pow2((uint)(-exponent + 1), out scale); // scaledMarginLow = 2 * 2^(-1) scaledMarginLow = new BigInteger(1); } // The high and low margins are equal pScaledMarginHigh = &scaledMarginLow; } // Compute an estimate for digitExponent that will be correct or undershoot by one. // // This optimization is based on the paper "Printing Floating-Point Numbers Quickly and Accurately" by Burger and Dybvig http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.4656&rep=rep1&type=pdf // // We perform an additional subtraction of 0.69 to increase the frequency of a failed estimate because that lets us take a faster branch in the code. // 0.69 is chosen because 0.69 + log10(2) is less than one by a reasonable epsilon that will account for any floating point error. // // We want to set digitExponent to floor(log10(v)) + 1 // v = mantissa * 2^exponent // log2(v) = log2(mantissa) + exponent; // log10(v) = log2(v) * log10(2) // floor(log2(v)) = mantissaHighBitIdx + exponent; // log10(v) - log10(2) < (mantissaHighBitIdx + exponent) * log10(2) <= log10(v) // log10(v) < (mantissaHighBitIdx + exponent) * log10(2) + log10(2) <= log10(v) + log10(2) // floor(log10(v)) < ceil((mantissaHighBitIdx + exponent) * log10(2)) <= floor(log10(v)) + 1 const double Log10V2 = 0.30102999566398119521373889472449; int digitExponent = (int)(Math.Ceiling(((int)(mantissaHighBitIdx) + exponent) * Log10V2 - 0.69)); // Divide value by 10^digitExponent. if (digitExponent > 0) { // The exponent is positive creating a division so we multiply up the scale. scale.MultiplyPow10((uint)(digitExponent)); } else if (digitExponent < 0) { // The exponent is negative creating a multiplication so we multiply up the scaledValue, scaledMarginLow and scaledMarginHigh. BigInteger.Pow10((uint)(-digitExponent), out BigInteger pow10); scaledValue.Multiply(ref pow10); scaledMarginLow.Multiply(ref pow10); if (pScaledMarginHigh != &scaledMarginLow) { BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh); } } // If (value >= 1), our estimate for digitExponent was too low if (BigInteger.Compare(ref scaledValue, ref scale) >= 0) { // The exponent estimate was incorrect. // Increment the exponent and don't perform the premultiply needed for the first loop iteration. digitExponent = digitExponent + 1; } else { // The exponent estimate was correct. // Multiply larger by the output base to prepare for the first loop iteration. scaledValue.Multiply10(); scaledMarginLow.Multiply10(); if (pScaledMarginHigh != &scaledMarginLow) { BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh); } } // Compute the cutoff exponent (the exponent of the final digit to print). // Default to the maximum size of the output buffer. int cutoffExponent = digitExponent - buffer.Length; if (cutoffNumber != -1) { int desiredCutoffExponent = 0; if (isSignificantDigits) { // We asked for a specific number of significant digits. Debug.Assert(cutoffNumber > 0); desiredCutoffExponent = digitExponent - cutoffNumber; } else { // We asked for a specific number of fractional digits. Debug.Assert(cutoffNumber >= 0); desiredCutoffExponent = -cutoffNumber; } if (desiredCutoffExponent > cutoffExponent) { // Only select the new cutoffExponent if it won't overflow the destination buffer. cutoffExponent = desiredCutoffExponent; } } // Output the exponent of the first digit we will print decimalExponent = digitExponent - 1; // In preparation for calling BigInteger.HeuristicDivie(), we need to scale up our values such that the highest block of the denominator is greater than or equal to 8. // We also need to guarantee that the numerator can never have a length greater than the denominator after each loop iteration. // This requires the highest block of the denominator to be less than or equal to 429496729 which is the highest number that can be multiplied by 10 without overflowing to a new block. Debug.Assert(scale.GetLength() > 0); uint hiBlock = scale.GetBlock((uint)(scale.GetLength() - 1)); if ((hiBlock < 8) || (hiBlock > 429496729)) { // Perform a bit shift on all values to get the highest block of the denominator into the range [8,429496729]. // We are more likely to make accurate quotient estimations in BigInteger.HeuristicDivide() with higher denominator values so we shift the denominator to place the highest bit at index 27 of the highest block. // This is safe because (2^28 - 1) = 268435455 which is less than 429496729. // This means that all values with a highest bit at index 27 are within range. Debug.Assert(hiBlock != 0); uint hiBlockLog2 = (uint)BitOperations.Log2(hiBlock); Debug.Assert((hiBlockLog2 < 3) || (hiBlockLog2 > 27)); uint shift = (32 + 27 - hiBlockLog2) % 32; scale.ShiftLeft(shift); scaledValue.ShiftLeft(shift); scaledMarginLow.ShiftLeft(shift); if (pScaledMarginHigh != &scaledMarginLow) { BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh); } } // These values are used to inspect why the print loop terminated so we can properly round the final digit. bool low; // did the value get within marginLow distance from zero bool high; // did the value get within marginHigh distance from one uint outputDigit; // current digit being output if (cutoffNumber == -1) { Debug.Assert(isSignificantDigits); // For the unique cutoff mode, we will try to print until we have reached a level of precision that uniquely distinguishes this value from its neighbors. // If we run out of space in the output buffer, we terminate early. while (true) { digitExponent = digitExponent - 1; // divide out the scale to extract the digit outputDigit = BigInteger.HeuristicDivide(ref scaledValue, ref scale); Debug.Assert(outputDigit < 10); // update the high end of the value BigInteger.Add(ref scaledValue, ref *pScaledMarginHigh, out BigInteger scaledValueHigh); // stop looping if we are far enough away from our neighboring values or if we have reached the cutoff digit low = BigInteger.Compare(ref scaledValue, ref scaledMarginLow) < 0; high = BigInteger.Compare(ref scaledValueHigh, ref scale) > 0; if (low || high || (digitExponent == cutoffExponent)) { break; } // store the output digit buffer[curDigit] = (byte)('0' + outputDigit); curDigit += 1; // multiply larger by the output base scaledValue.Multiply10(); scaledMarginLow.Multiply10(); if (pScaledMarginHigh != &scaledMarginLow) { BigInteger.Multiply(ref scaledMarginLow, 2, ref *pScaledMarginHigh); } } } else { Debug.Assert((cutoffNumber > 0) || ((cutoffNumber == 0) && !isSignificantDigits)); // For length based cutoff modes, we will try to print until we have exhausted all precision (i.e. all remaining digits are zeros) or until we reach the desired cutoff digit. low = false; high = false; while (true) { digitExponent = digitExponent - 1; // divide out the scale to extract the digit outputDigit = BigInteger.HeuristicDivide(ref scaledValue, ref scale); Debug.Assert(outputDigit < 10); if (scaledValue.IsZero() || (digitExponent <= cutoffExponent)) { break; } // store the output digit buffer[curDigit] = (byte)('0' + outputDigit); curDigit += 1; // multiply larger by the output base scaledValue.Multiply10(); } } // round off the final digit // default to rounding down if value got too close to 0 bool roundDown = low; if (low == high) // is it legal to round up and down { // round to the closest digit by comparing value with 0.5. // // To do this we need to convert the inequality to large integer values. // compare(value, 0.5) // compare(scale * value, scale * 0.5) // compare(2 * scale * value, scale) scaledValue.Multiply(2); int compare = BigInteger.Compare(ref scaledValue, ref scale); roundDown = compare < 0; // if we are directly in the middle, round towards the even digit (i.e. IEEE rouding rules) if (compare == 0) { roundDown = (outputDigit & 1) == 0; } } // print the rounded digit if (roundDown) { buffer[curDigit] = (byte)('0' + outputDigit); curDigit += 1; } else if (outputDigit == 9) // handle rounding up { // find the first non-nine prior digit while (true) { // if we are at the first digit if (curDigit == 0) { // output 1 at the next highest exponent buffer[curDigit] = (byte)('1'); curDigit += 1; decimalExponent += 1; break; } curDigit -= 1; if (buffer[curDigit] != '9') { // increment the digit buffer[curDigit] += 1; curDigit += 1; break; } } } else { // values in the range [0,8] can perform a simple round up buffer[curDigit] = (byte)('0' + outputDigit + 1); curDigit += 1; } // return the number of digits output uint outputLen = (uint)(curDigit); Debug.Assert(outputLen <= buffer.Length); return outputLen; } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; namespace PCSComUtils.Admin.DS { public class sys_RoleWCDS { public sys_RoleWCDS() { } private const string THIS = "PCSComUtils.Admin.DS.sys_RoleWCDS"; //************************************************************************** /// <Description> /// This method uses to add data to sys_RoleWC /// </Description> /// <Inputs> /// sys_RoleWCVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, November 16, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { sys_RoleWCVO objObject = (sys_RoleWCVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO sys_RoleWC(" + sys_RoleWCTable.ROLEID_FLD + "," + sys_RoleWCTable.WORKCENTERID_FLD + ")" + "VALUES(?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleWCTable.ROLEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_RoleWCTable.ROLEID_FLD].Value = objObject.RoleID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleWCTable.WORKCENTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_RoleWCTable.WORKCENTERID_FLD].Value = objObject.WorkCenterID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from sys_RoleWC /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + sys_RoleWCTable.TABLE_NAME + " WHERE " + "RoleWCID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// DeleteByWorkCenterID /// </summary> /// <param name="pintWorkCenterID"></param> /// <author>Trada</author> /// <date>Thursday, Nov 17 2005</date> public void DeleteByWorkCenterID(int pintWorkCenterID) { const string METHOD_NAME = THIS + ".DeleteByWorkCenterID()"; string strSql = String.Empty; strSql= "DELETE " + sys_RoleWCTable.TABLE_NAME + " WHERE " + sys_RoleWCTable.WORKCENTERID_FLD + "=" + pintWorkCenterID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from sys_RoleWC /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// sys_RoleWCVO /// </Outputs> /// <Returns> /// sys_RoleWCVO /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, November 16, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + sys_RoleWCTable.ROLEWCID_FLD + "," + sys_RoleWCTable.ROLEID_FLD + "," + sys_RoleWCTable.WORKCENTERID_FLD + " FROM " + sys_RoleWCTable.TABLE_NAME +" WHERE " + sys_RoleWCTable.ROLEWCID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); sys_RoleWCVO objObject = new sys_RoleWCVO(); while (odrPCS.Read()) { objObject.RoleWCID = int.Parse(odrPCS[sys_RoleWCTable.ROLEWCID_FLD].ToString().Trim()); objObject.RoleID = int.Parse(odrPCS[sys_RoleWCTable.ROLEID_FLD].ToString().Trim()); objObject.WorkCenterID = int.Parse(odrPCS[sys_RoleWCTable.WORKCENTERID_FLD].ToString().Trim()); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to sys_RoleWC /// </Description> /// <Inputs> /// sys_RoleWCVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; sys_RoleWCVO objObject = (sys_RoleWCVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE sys_RoleWC SET " + sys_RoleWCTable.ROLEID_FLD + "= ?" + "," + sys_RoleWCTable.WORKCENTERID_FLD + "= ?" +" WHERE " + sys_RoleWCTable.ROLEWCID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleWCTable.ROLEID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_RoleWCTable.ROLEID_FLD].Value = objObject.RoleID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleWCTable.WORKCENTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_RoleWCTable.WORKCENTERID_FLD].Value = objObject.WorkCenterID; ocmdPCS.Parameters.Add(new OleDbParameter(sys_RoleWCTable.ROLEWCID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[sys_RoleWCTable.ROLEWCID_FLD].Value = objObject.RoleWCID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { if (ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from sys_RoleWC /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, November 16, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + sys_RoleWCTable.ROLEWCID_FLD + "," + sys_RoleWCTable.ROLEID_FLD + "," + sys_RoleWCTable.WORKCENTERID_FLD + " FROM " + sys_RoleWCTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,sys_RoleWCTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// GetDataByRoleID /// </summary> /// <param name="pintRoleID"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Thursday, Nov 17 2005</date> public DataTable GetDataByRoleID(int pintRoleID) { const string METHOD_NAME = THIS + ".GetDataByRoleID()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + sys_RoleWCTable.ROLEWCID_FLD + "," + sys_RoleWCTable.ROLEID_FLD + "," + sys_RoleWCTable.WORKCENTERID_FLD + " FROM " + sys_RoleWCTable.TABLE_NAME + " WHERE " + sys_RoleWCTable.ROLEID_FLD + " = " + pintRoleID.ToString(); Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,sys_RoleWCTable.TABLE_NAME); return dstPCS.Tables[0]; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// CheckHasID /// </summary> /// <param name="pintWorkCenterID"></param> /// <param name="pintRoleID"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Thursday, Nov 17 2005</date> public bool CheckHasID(int pintWorkCenterID, int pintRoleID) { const string METHOD_NAME = THIS + ".CheckHasID()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + sys_RoleWCTable.ROLEWCID_FLD + "," + sys_RoleWCTable.ROLEID_FLD + "," + sys_RoleWCTable.WORKCENTERID_FLD + " FROM " + sys_RoleWCTable.TABLE_NAME + " WHERE " + sys_RoleWCTable.WORKCENTERID_FLD + " = " + pintWorkCenterID.ToString() + " AND " + sys_RoleWCTable.ROLEID_FLD + " = " + pintRoleID.ToString(); Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,sys_RoleWCTable.TABLE_NAME); if (dstPCS.Tables[0].Rows.Count > 0) { return true; } else return false; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// HungLa /// </Authors> /// <History> /// Wednesday, November 16, 2005 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + sys_RoleWCTable.ROLEWCID_FLD + "," + sys_RoleWCTable.ROLEID_FLD + "," + sys_RoleWCTable.WORKCENTERID_FLD + " FROM " + sys_RoleWCTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,sys_RoleWCTable.TABLE_NAME); } catch(OleDbException ex) { if(ex.Errors.Count > 1) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
// 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 OLEDB.Test.ModuleCore; using System.IO; using XmlCoreTest.Common; namespace System.Xml.Tests { //////////////////////////////////////////////////////////////// // Module // //////////////////////////////////////////////////////////////// [TestModule(Name = "Name Table", Desc = "Test for Get and Add methods")] public partial class CNameTableTestModule : CTestModule { //Accessors private string _TestData = null; public string TestData { get { return _TestData; } } public override int Init(object objParam) { int ret = base.Init(objParam); _TestData = Path.Combine(FilePathUtil.GetTestDataPath(), @"XmlReader"); // Create global usage test files string strFile = String.Empty; NameTable_TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC); return ret; } public override int Terminate(object objParam) { return base.Terminate(objParam); } } //////////////////////////////////////////////////////////////// // TestCase TCBase // //////////////////////////////////////////////////////////////// public partial class TCBase : CTestCase { public enum ENAMETABLE_VER { VERIFY_WITH_GETSTR, VERIFY_WITH_GETCHAR, VERIFY_WITH_ADDSTR, VERIFY_WITH_ADDCHAR, }; private ENAMETABLE_VER _eNTVer; public ENAMETABLE_VER NameTableVer { get { return _eNTVer; } set { _eNTVer = value; } } public static string WRONG_EXCEPTION = "Catching Wrong Exception"; protected static string BigStr = new String('Z', (1 << 20) - 1); protected XmlReader DataReader; public override int Init(object objParam) { if (GetDescription() == "VerifyWGetString") { NameTableVer = ENAMETABLE_VER.VERIFY_WITH_GETSTR; } else if (GetDescription() == "VerifyWGetChar") { NameTableVer = ENAMETABLE_VER.VERIFY_WITH_GETCHAR; } else if (GetDescription() == "VerifyWAddString") { NameTableVer = ENAMETABLE_VER.VERIFY_WITH_ADDSTR; } else if (GetDescription() == "VerifyWAddChar") { NameTableVer = ENAMETABLE_VER.VERIFY_WITH_ADDCHAR; } else throw (new Exception()); int ival = base.Init(objParam); ReloadSource(); if (TEST_PASS == ival) { while (DataReader.Read() == true) ; } return ival; } protected void ReloadSource() { if (DataReader != null) { DataReader.Dispose(); } string strFile = NameTable_TestFiles.GetTestFileName(EREADER_TYPE.GENERIC); DataReader = XmlReader.Create(FilePathUtil.getStream(strFile), new XmlReaderSettings() { DtdProcessing = DtdProcessing.Ignore });//new XmlTextReader(strFile); } public void VerifyNameTable(object objActual, string str, char[] ach, int offset, int length) { VerifyNameTableGet(objActual, str, ach, offset, length); VerifyNameTableAdd(objActual, str, ach, offset, length); } public void VerifyNameTableGet(object objActual, string str, char[] ach, int offset, int length) { object objExpected = null; if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_GETSTR) { objExpected = DataReader.NameTable.Get(str); CError.WriteLine("VerifyNameTableWGetStr"); CError.Compare(objActual, objExpected, "VerifyNameTableWGetStr"); } else if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_GETCHAR) { objExpected = DataReader.NameTable.Get(ach, offset, length); CError.WriteLine("VerifyNameTableWGetChar"); CError.Compare(objActual, objExpected, "VerifyNameTableWGetChar"); } } public void VerifyNameTableAdd(object objActual, string str, char[] ach, int offset, int length) { object objExpected = null; if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_ADDSTR) { objExpected = DataReader.NameTable.Add(ach, offset, length); CError.WriteLine("VerifyNameTableWAddStr"); CError.Compare(objActual, objExpected, "VerifyNameTableWAddStr"); } else if (NameTableVer == ENAMETABLE_VER.VERIFY_WITH_ADDCHAR) { objExpected = DataReader.NameTable.Add(str); CError.WriteLine("VerifyNameTableWAddChar"); CError.Compare(objActual, objExpected, "VerifyNameTableWAddChar"); } } } //////////////////////////////////////////////////////////////// // TestCase TCRecord NameTable.Get // //////////////////////////////////////////////////////////////// //[TestCase(Name="NameTable(Get) VerifyWGetChar", Desc="VerifyWGetChar")] //[TestCase(Name="NameTable(Get) VerifyWGetString", Desc="VerifyWGetString")] //[TestCase(Name="NameTable(Get) VerifyWAddString", Desc="VerifyWAddString")] //[TestCase(Name="NameTable(Get) VerifyWAddChar", Desc="VerifyWAddChar")] public partial class TCRecordNameTableGet : TCBase { public static char[] chInv = { 'U', 'n', 'a', 't', 'o', 'm', 'i', 'z', 'e', 'd' }; public static char[] chVal = { 'P', 'L', 'A', 'Y' }; public static char[] chValW1EndExtra = { 'P', 'L', 'A', 'Y', 'Y' }; public static char[] chValW1FrExtra = { 'P', 'P', 'L', 'A', 'Y' }; public static char[] chValW1Fr1EndExtra = { 'P', 'P', 'L', 'A', 'Y', 'Y' }; public static char[] chValWEndExtras = { 'P', 'L', 'A', 'Y', 'Y', 'Y' }; public static char[] chValWFrExtras = { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'L', 'A', 'Y' }; public static char[] chValWFrEndExtras = { 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'L', 'A', 'Y', 'Y', 'Y' }; public static string[] strPerVal = { "PLYA", "PALY", "PAYL", "PYLA", "PYAL", "LPAY", "LPYA", "LAPY", "LAYP", "LYPA", "LYAP", "ALPY", "ALYP", "APLY", "APYL", "AYLP", "AYPL", "YLPA", "YLAP", "YPLA", "YPAL", "YALP", "YAPL", }; public static string[] strPerValCase = { "pLAY", "plAY", "plaY", "play", "plAY", "plaY", "pLaY", "pLay", "pLAy", "PlAY", "PlaY", "Play", "PLaY", "PLAy" }; public static string strInv = "Unatomized"; public static string strVal = "PLAY"; [Variation("GetUnAutomized", Pri = 0)] public int Variation_1() { object objActual = DataReader.NameTable.Get(strInv); object objActual1 = DataReader.NameTable.Get(strInv); CError.Compare(objActual, null, CurVariation.Desc); CError.Compare(objActual1, null, CurVariation.Desc); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTableGet(objActual, strInv, chInv, 0, chInv.Length); return TEST_PASS; } [Variation("Get Atomized String", Pri = 0)] public int Variation_2() { object objActual = DataReader.NameTable.Get(chVal, 0, chVal.Length); object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chVal, 0, chVal.Length); return TEST_PASS; } [Variation("Get Atomized String with end padded", Pri = 0)] public int Variation_3() { object objActual = DataReader.NameTable.Get(chValW1EndExtra, 0, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValW1EndExtra, 0, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1EndExtra, 0, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with front and end padded", Pri = 0)] public int Variation_4() { object objActual = DataReader.NameTable.Get(chValW1Fr1EndExtra, 1, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValW1Fr1EndExtra, 1, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1Fr1EndExtra, 1, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with front padded", Pri = 0)] public int Variation_5() { object objActual = DataReader.NameTable.Get(chValW1FrExtra, 1, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValW1FrExtra, 1, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1FrExtra, 1, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with end multi-padded", Pri = 0)] public int Variation_6() { object objActual = DataReader.NameTable.Get(chValWEndExtras, 0, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValWEndExtras, 0, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWEndExtras, 0, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with front and end multi-padded", Pri = 0)] public int Variation_7() { object objActual = DataReader.NameTable.Get(chValWFrEndExtras, 6, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValWFrEndExtras, 6, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWFrEndExtras, 6, strVal.Length); return TEST_PASS; } [Variation("Get Atomized String with front multi-padded", Pri = 0)] public int Variation_8() { object objActual = DataReader.NameTable.Get(chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length); object objActual1 = DataReader.NameTable.Get(chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWFrExtras, chValWFrExtras.Length - strVal.Length, strVal.Length); return TEST_PASS; } [Variation("Get Invalid permutation of valid string", Pri = 0)] public int Variation_9() { for (int i = 0; i < strPerVal.Length; i++) { char[] ach = strPerVal[i].ToCharArray(); object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length); CError.Compare(objActual, null, CurVariation.Desc); CError.Compare(objActual1, null, CurVariation.Desc); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTableGet(objActual, strPerVal[i], ach, 0, ach.Length); } return TEST_PASS; } [Variation("Get Valid Super String")] public int Variation_10() { string filename = null; NameTable_TestFiles.CreateTestFile(ref filename, EREADER_TYPE.BIG_ELEMENT_SIZE); XmlReader rDataReader = XmlReader.Create(FilePathUtil.getStream(filename)); while (rDataReader.Read() == true) ; XmlNameTable nt = rDataReader.NameTable; object objTest1 = nt.Get(BigStr + "Z"); object objTest2 = nt.Get(BigStr + "X"); object objTest3 = nt.Get(BigStr + "Y"); if (objTest1 != null) { throw new CTestException(CTestBase.TEST_FAIL, "objTest1 is not null"); } if (objTest2 == null) { throw new CTestException(CTestBase.TEST_FAIL, "objTest2 is null"); } if (objTest3 == null) { throw new CTestException(CTestBase.TEST_FAIL, "objTest3 is null"); } if ((objTest1 == objTest2) || (objTest1 == objTest3) || (objTest2 == objTest3)) throw new CTestException(CTestBase.TEST_FAIL, "objTest1 is equal to objTest2, or objTest3"); return TEST_PASS; } [Variation("Get invalid Super String")] public int Variation_11() { int size = (1 << 24); string str = ""; char[] ach = str.ToCharArray(); bool fRetry = false; for (; ;) { try { str = new String('Z', size); ach = str.ToCharArray(); } catch (OutOfMemoryException exc) { size >>= 1; CError.WriteLine(exc + " : " + exc.Message + " Retry with " + size); fRetry = true; } if (size < (1 << 30)) { fRetry = true; } if (fRetry) { CError.WriteLine("Tested size == " + size); if (str == null) CError.WriteLine("string is null"); break; } } object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTableGet(objActual, str, ach, 0, ach.Length); return TEST_PASS; } [Variation("Get empty string, valid offset and length = 0", Pri = 0)] public int Variation_12() { string str = String.Empty; char[] ach = str.ToCharArray(); object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, 0); object objActual2 = DataReader.NameTable.Get(str); CError.Compare(objActual, objActual1, "Char with StringEmpty"); CError.Compare(String.Empty, objActual1, "Char with StringEmpty"); CError.Compare(String.Empty, objActual2, "StringEmpty"); VerifyNameTable(objActual, str, ach, 0, 0); return TEST_PASS; } [Variation("Get empty string, valid offset and length = 1", Pri = 0)] public int Variation_13() { char[] ach = new char[] { }; try { object objActual = DataReader.NameTable.Get(ach, 0, 1); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get null char[], valid offset and length = 0", Pri = 0)] public int Variation_14() { char[] ach = null; object objActual = DataReader.NameTable.Add(ach, 0, 0); CError.Compare(String.Empty, objActual, "Char with null"); return TEST_PASS; } [Variation("Get null string", Pri = 0)] public int Variation_15() { string str = null; try { object objActual = DataReader.NameTable.Get(str); } catch (ArgumentNullException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get null char[], valid offset and length = 1", Pri = 0)] public int Variation_16() { char[] ach = null; try { object objActual = DataReader.NameTable.Add(ach, 0, 1); } catch (NullReferenceException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid length, length = 0", Pri = 0)] public int Variation_17() { object objActual = DataReader.NameTable.Get(chVal, 0, 0); object objActual1 = DataReader.NameTable.Get(chVal, 0, 0); CError.WriteLine("Here " + chVal.ToString()); CError.WriteLine("Here2 " + DataReader.NameTable.Get(chVal, 0, 0)); if (DataReader.NameTable.Get(chVal, 0, 0) == String.Empty) CError.WriteLine("here"); if (DataReader.NameTable.Get(chVal, 0, 0) == null) CError.WriteLine("null"); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, String.Empty, chVal, 0, 0); return TEST_PASS; } [Variation("Get valid string, invalid length, length = Length+1", Pri = 0)] public int Variation_18() { try { object objActual = DataReader.NameTable.Get(chVal, 0, chVal.Length + 1); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid length, length = max_int", Pri = 0)] public int Variation_19() { try { object objActual = DataReader.NameTable.Get(chVal, 0, Int32.MaxValue); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid length, length = -1", Pri = 0)] public int Variation_20() { object objActual = DataReader.NameTable.Get(chVal, 0, -1); CError.WriteLine("HERE " + objActual); return TEST_PASS; } [Variation("Get valid string, invalid offset > Length", Pri = 0)] public int Variation_21() { try { object objActual = DataReader.NameTable.Get(chVal, chVal.Length + 1, chVal.Length); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid offset = max_int", Pri = 0)] public int Variation_22() { try { object objActual = DataReader.NameTable.Get(chVal, Int32.MaxValue, chVal.Length); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid offset = Length", Pri = 0)] public int Variation_23() { try { object objActual = DataReader.NameTable.Get(chVal, chVal.Length, chVal.Length); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid offset -1", Pri = 0)] public int Variation_24() { try { object objActual = DataReader.NameTable.Get(chVal, -1, chVal.Length); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Get valid string, invalid offset and length", Pri = 0)] public int Variation_25() { try { object objActual = DataReader.NameTable.Get(chVal, -1, -1); } catch (IndexOutOfRangeException exc) { CError.WriteLine(exc + " : " + exc.Message); return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } //////////////////////////////////////////////////////////////// // TestCase TCRecord NameTable.Add // //////////////////////////////////////////////////////////////// //[TestCase(Name="NameTable(Add) VerifyWGetString", Desc="VerifyWGetString")] //[TestCase(Name="NameTable(Add) VerifyWGetChar", Desc="VerifyWGetChar")] //[TestCase(Name="NameTable(Add) VerifyWAddString", Desc="VerifyWAddString")] //[TestCase(Name="NameTable(Add) VerifyWAddChar", Desc="VerifyWAddChar")] public partial class TCRecordNameTableAdd : TCBase { public static char[] chVal = { 'F', 'O', 'O' }; public static char[] chValW1EndExtra = { 'F', 'O', 'O', 'O' }; public static char[] chValW1FrExtra = { 'F', 'F', 'O', 'O', 'O' }; public static char[] chValW1Fr1EndExtra = { 'F', 'F', 'O', 'O', 'O' }; public static char[] chValWEndExtras = { 'F', 'O', 'O', 'O', 'O', 'O' }; public static char[] chValWFrExtras = { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'O', 'O', 'O' }; public static char[] chValWFrEndExtras = { 'F', 'F', 'F', 'F', 'F', 'F', 'F', 'O', 'O', 'O', 'O', 'O' }; public static string[] strPerVal = { "OFO", "OOF" }; public static string[] strPerValCase = { "fOO", "foO", "foo", "FoO", "Foo", "FOo" }; public static string strVal = "FOO"; public static string strWhitespaceVal = "WITH WHITESPACE"; public static string strAlphaNumVal = "WITH1Number"; public static string strSignVal = "+SIGN-"; [Variation("Add a new atomized string (padded with chars at the end), valid offset and length = str_length", Pri = 0)] public int Variation_1() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValWEndExtras, 0, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValWEndExtras, 0, strVal.Length); if (objActual == objActual1) CError.WriteLine(objActual + " and ", objActual1); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWEndExtras, 0, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded with chars at both front and end), valid offset and length = str_length", Pri = 0)] public int Variation_2() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWFrExtras, 6, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded with chars at the front), valid offset and length = str_length", Pri = 0)] public int Variation_3() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValWFrEndExtras, 6, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValWFrEndExtras, 6, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded a char at the end), valid offset and length = str_length", Pri = 0)] public int Variation_4() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValW1EndExtra, 0, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValW1EndExtra, 0, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1EndExtra, 0, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded with a char at both front and end), valid offset and length = str_length", Pri = 0)] public int Variation_5() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValW1Fr1EndExtra, 1, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValW1Fr1EndExtra, 1, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1Fr1EndExtra, 1, strVal.Length); return TEST_PASS; } [Variation("Add a new atomized string (padded with a char at the front), valid offset and length = str_length", Pri = 0)] public int Variation_6() { ReloadSource(); object objActual = DataReader.NameTable.Add(chValW1FrExtra, 1, strVal.Length); object objActual1 = DataReader.NameTable.Add(chValW1FrExtra, 1, strVal.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual, strVal, chValW1FrExtra, 1, strVal.Length); return TEST_PASS; } [Variation("Add new string between 1M - 2M in size, valid offset and length")] public int Variation_7() { char[] chTest = BigStr.ToCharArray(); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual2 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objActual2, CurVariation.Desc); VerifyNameTable(objActual1, BigStr, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add an existing atomized string (with Max string for test: 1-2M), valid offset and valid length")] public int Variation_8() { //////////////////////////// // Add strings again and verify string filename = null; NameTable_TestFiles.CreateTestFile(ref filename, EREADER_TYPE.BIG_ELEMENT_SIZE); XmlReader rDataReader = XmlReader.Create(FilePathUtil.getStream(filename)); while (rDataReader.Read() == true) ; XmlNameTable nt = rDataReader.NameTable; string strTest = BigStr + "X"; char[] chTest = strTest.ToCharArray(); Object objActual1 = nt.Add(chTest, 0, chTest.Length); Object objActual2 = nt.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objActual2, "Comparing objActual1 and objActual2"); CError.Compare(objActual1, nt.Get(chTest, 0, chTest.Length), "Comparing objActual1 and GetCharArray"); CError.Compare(objActual1, nt.Get(strTest), "Comparing objActual1 and GetString"); CError.Compare(objActual1, nt.Add(strTest), "Comparing objActual1 and AddString"); NameTable_TestFiles.RemoveDataReader(EREADER_TYPE.BIG_ELEMENT_SIZE); return TEST_PASS; } [Variation("Add new string, and do Get with a combination of the same string in different order", Pri = 0)] public int Variation_9() { ReloadSource(); // Add string Object objAdded = DataReader.NameTable.Add(strVal); // Look for permutations of strings, should be null. for (int i = 0; i < strPerVal.Length; i++) { char[] ach = strPerVal[i].ToCharArray(); object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length); CError.Compare(objActual, null, CurVariation.Desc); CError.Compare(objActual, objActual1, CurVariation.Desc); } return TEST_PASS; } [Variation("Add new string, and Add a combination of the same string in different case, all are different objects", Pri = 0)] public int Variation_10() { ReloadSource(); // Add string Object objAdded = DataReader.NameTable.Add(strVal); // Look for permutations of strings, should be null. for (int i = 0; i < strPerValCase.Length; i++) { char[] ach = strPerValCase[i].ToCharArray(); object objActual = DataReader.NameTable.Add(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Add(ach, 0, ach.Length); CError.Compare(objActual, objActual1, CurVariation.Desc); VerifyNameTable(objActual1, strPerValCase[i], ach, 0, ach.Length); if (objAdded == objActual) { throw new Exception("\n Object are the same for " + strVal + " and " + strPerValCase[i]); } } return TEST_PASS; } [Variation("Add 1M new string, and do Get with the last char different than the original string", Pri = 0)] public int Variation_11() { object objAdded = DataReader.NameTable.Add(BigStr + "M"); object objActual = DataReader.NameTable.Get(BigStr + "D"); CError.Compare(objActual, null, CurVariation.Desc); return TEST_PASS; } [Variation("Add new alpha numeric, valid offset, valid length", Pri = 0)] public int Variation_12() { ReloadSource(); char[] chTest = strAlphaNumVal.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objAdded, CurVariation.Desc); VerifyNameTable(objAdded, strAlphaNumVal, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add new alpha numeric, valid offset, length= 0", Pri = 0)] public int Variation_13() { ReloadSource(); char[] chTest = strAlphaNumVal.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, 0); object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length); object objActual2 = DataReader.NameTable.Get(strVal); CError.Compare(objActual1, null, "Get should fail since Add with length=0 should fail"); CError.Compare(objActual1, objActual2, "Both Get should fail"); return TEST_PASS; } [Variation("Add new with whitespace, valid offset, valid length", Pri = 0)] public int Variation_14() { ReloadSource(); char[] chTest = strWhitespaceVal.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objAdded, CurVariation.Desc); VerifyNameTable(objAdded, strWhitespaceVal, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add new with sign characters, valid offset, valid length", Pri = 0)] public int Variation_15() { ReloadSource(); char[] chTest = strSignVal.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objAdded, CurVariation.Desc); VerifyNameTable(objAdded, strSignVal, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add new string between 1M - 2M in size, valid offset and length", Pri = 0)] public int Variation_16() { ReloadSource(); char[] chTest = BigStr.ToCharArray(); object objActual1 = DataReader.NameTable.Add(chTest, 0, chTest.Length); object objActual2 = DataReader.NameTable.Add(chTest, 0, chTest.Length); CError.Compare(objActual1, objActual2, CurVariation.Desc); VerifyNameTable(objActual1, BigStr, chTest, 0, chTest.Length); return TEST_PASS; } [Variation("Add new string, get object using permutations of upper & lowercase, should be null", Pri = 0)] public int Variation_17() { ReloadSource(); // Add string Object objAdded = DataReader.NameTable.Add(strVal); // Look for permutations of strings, should be null. for (int i = 0; i < strPerValCase.Length; i++) { char[] ach = strPerValCase[i].ToCharArray(); object objActual = DataReader.NameTable.Get(ach, 0, ach.Length); object objActual1 = DataReader.NameTable.Get(ach, 0, ach.Length); CError.Compare(objActual, null, CurVariation.Desc); CError.Compare(objActual, objActual1, CurVariation.Desc); } return TEST_PASS; } [Variation("Add an empty atomized string, valid offset and length = 0", Pri = 0)] public int Variation_18() { ReloadSource(); string strEmpty = String.Empty; object objAdded = DataReader.NameTable.Add(strEmpty); object objAdded1 = DataReader.NameTable.Add(strEmpty.ToCharArray(), 0, strEmpty.Length); object objActual1 = DataReader.NameTable.Get(strEmpty.ToCharArray(), 0, strEmpty.Length); object objActual2 = DataReader.NameTable.Get(strEmpty); CError.WriteLine("String " + DataReader.NameTable.Get(strEmpty)); CError.WriteLine("String " + objAdded1 + " String2 " + objAdded1); if (objAdded != objAdded1) CError.WriteLine("HERE"); CError.Compare(objActual1, objActual2, CurVariation.Desc); VerifyNameTable(objActual1, strEmpty, strEmpty.ToCharArray(), 0, 0); return TEST_PASS; } [Variation("Add an empty atomized string (array char only), valid offset and length = 1", Pri = 0)] public int Variation_19() { try { char[] chTest = String.Empty.ToCharArray(); object objAdded = DataReader.NameTable.Add(chTest, 0, 1); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a NULL atomized string, valid offset and length = 0", Pri = 0)] public int Variation_20() { object objAdded = DataReader.NameTable.Add(null, 0, 0); VerifyNameTable(objAdded, String.Empty, (String.Empty).ToCharArray(), 0, 0); return TEST_PASS; } [Variation("Add a NULL atomized string, valid offset and length = 1", Pri = 0)] public int Variation_21() { try { object objAdded = DataReader.NameTable.Add(null, 0, 1); } catch (NullReferenceException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid offset and length = 0", Pri = 0)] public int Variation_22() { ReloadSource(); object objAdded = DataReader.NameTable.Add(chVal, 0, 0); object objActual1 = DataReader.NameTable.Get(chVal, 0, chVal.Length); object objActual2 = DataReader.NameTable.Get(strVal); CError.Compare(objActual1, null, "Get should fail since Add with length=0 should fail"); CError.Compare(objActual1, objActual2, "Both Get should fail"); return TEST_PASS; } [Variation("Add a valid atomized string, valid offset and length > valid_length", Pri = 0)] public int Variation_23() { try { object objAdded = DataReader.NameTable.Add(chVal, 0, chVal.Length * 2); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid offset and length = max_int", Pri = 0)] public int Variation_24() { try { object objAdded = DataReader.NameTable.Add(chVal, 0, Int32.MaxValue); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid offset and length = - 1", Pri = 0)] public int Variation_25() { try { object objAdded = DataReader.NameTable.Add(chVal, 0, -1); } catch (ArgumentOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid length and offset > str_length", Pri = 0)] public int Variation_26() { try { object objAdded = DataReader.NameTable.Add(chVal, chVal.Length * 2, chVal.Length); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid length and offset = max_int", Pri = 0)] public int Variation_27() { try { object objAdded = DataReader.NameTable.Add(chVal, Int32.MaxValue, chVal.Length); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid length and offset = str_length", Pri = 0)] public int Variation_28() { try { object objAdded = DataReader.NameTable.Add(chVal, chVal.Length, chVal.Length); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, valid length and offset = - 1", Pri = 0)] public int Variation_29() { try { object objAdded = DataReader.NameTable.Add(chVal, -1, chVal.Length); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } [Variation("Add a valid atomized string, with both invalid offset and length", Pri = 0)] public int Variation_30() { try { object objAdded = DataReader.NameTable.Add(chVal, -1, -1); } catch (IndexOutOfRangeException) { return TEST_PASS; } throw new CTestException(CTestBase.TEST_FAIL, WRONG_EXCEPTION); } } }
// ----------------------------------------------------------------------- // <copyright file="ScreenSpaceLines3D.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- // This source is subject to the Microsoft Limited Permissive License. // See http://www.microsoft.com/resources/sharedsource/licensingbasics/limitedpermissivelicense.mspx // This file is based on the 3D Tools for Windows Presentation Foundation // project. For more information, see: // http://CodePlex.com/Wiki/View.aspx?ProjectName=3DTools //--------------------------------------------------------------------------- namespace Wpf3DTools { using System; using System.Windows; using System.Windows.Media; using System.Windows.Media.Media3D; /// <summary> /// ScreenSpaceLines3D are a 3D line primitive whose thickness /// is constant in 2D space post projection. /// This means that the lines do not become foreshortened as /// they recede from the camera as other 3D primitives do under /// a typical perspective projection. /// Example Usage: /// &lt;tools:ScreenSpaceLines3D /// Points="0,0,0 0,1,0 0,1,0 1,1,0 1,1,0 0,0,1" /// Thickness="5" Color="Red"&gt; /// "Screen space" is a bit of a misnomer as the line thickness /// is specified in the 2D coordinate system of the container /// Viewport3D, not the screen. /// </summary> public class ScreenSpaceLines3D : ModelVisual3D, IDisposable { /// <summary> /// Color property dependency property. /// </summary> public static readonly DependencyProperty ColorProperty = DependencyProperty.Register( "Color", typeof(Color), typeof(ScreenSpaceLines3D), new PropertyMetadata( Colors.White, OnColorChanged)); /// <summary> /// Points property dependency property. /// </summary> public static readonly DependencyProperty PointsProperty = DependencyProperty.Register( "Points", typeof(Point3DCollection), typeof(ScreenSpaceLines3D), new PropertyMetadata( null, OnPointsChanged)); /// <summary> /// Thickness property dependency property. /// </summary> public static readonly DependencyProperty ThicknessProperty = DependencyProperty.Register( "Thickness", typeof(double), typeof(ScreenSpaceLines3D), new PropertyMetadata( 1.0, OnThicknessChanged)); /// <summary> /// The geometry model. /// </summary> private readonly GeometryModel3D model; /// <summary> /// The mesh. /// </summary> private readonly MeshGeometry3D mesh; /// <summary> /// The visual to screen transform. /// </summary> private Matrix3D visualToScreen; /// <summary> /// The screen to visual transform. /// </summary> private Matrix3D screenToVisual; /// <summary> /// Track whether Dispose has been called /// </summary> private bool disposed = false; /// <summary> /// Whether the CompositionTarget is hooked for WPF rendering /// </summary> private bool hookedCompositionTarget = false; /// <summary> /// Initializes a new instance of the ScreenSpaceLines3D class /// </summary> public ScreenSpaceLines3D() { this.mesh = new MeshGeometry3D(); this.model = new GeometryModel3D(); this.model.Geometry = this.mesh; this.SetColor(this.Color); this.Content = this.model; this.Points = new Point3DCollection(); CompositionTarget.Rendering += this.OnRender; this.hookedCompositionTarget = true; } /// <summary> /// Finalizes an instance of the ScreenSpaceLines3D class. /// This destructor will run only if the Dispose method does not get called. /// </summary> ~ScreenSpaceLines3D() { this.Dispose(false); } /// <summary> /// Gets or sets the line color /// </summary> public Color Color { get { return (Color)this.GetValue(ColorProperty); } set { this.SetValue(ColorProperty, value); } } /// <summary> /// Gets or sets the line thickness /// </summary> public double Thickness { get { return (double)this.GetValue(ThicknessProperty); } set { this.SetValue(ThicknessProperty, value); } } /// <summary> /// Gets or sets the line points /// </summary> public Point3DCollection Points { get { return (Point3DCollection)this.GetValue(PointsProperty); } set { this.SetValue(PointsProperty, value); } } /// <summary> /// Dispose resources /// </summary> public void Dispose() { this.Dispose(true); // This object will be cleaned up by the Dispose method. GC.SuppressFinalize(this); } /// <summary> /// Unhooks the Composition target /// </summary> /// <param name="disposing">Whether the function was called from Dispose.</param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { this.UnhookCompositionTarget(); } } this.disposed = true; } /// <summary> /// Called when the color changes /// </summary> /// <param name="sender">The sender object.</param> /// <param name="args">The parameters.</param> private static void OnColorChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { ((ScreenSpaceLines3D)sender).SetColor((Color)args.NewValue); } /// <summary> /// Called when the thickness changes. /// </summary> /// <param name="sender">The sender object.</param> /// <param name="args">The parameters.</param> private static void OnThicknessChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { ((ScreenSpaceLines3D)sender).GeometryDirty(); } /// <summary> /// Called when the points change. /// </summary> /// <param name="sender">The sender object.</param> /// <param name="args">The parameters.</param> private static void OnPointsChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { ((ScreenSpaceLines3D)sender).GeometryDirty(); } /// <summary> /// Unhooks the Composition target if hooked /// </summary> private void UnhookCompositionTarget() { if (this.hookedCompositionTarget) { CompositionTarget.Rendering -= this.OnRender; } } /// <summary> /// Set the color for the lines /// </summary> /// <param name="color">The line color.</param> private void SetColor(Color color) { MaterialGroup unlitMaterial = new MaterialGroup(); unlitMaterial.Children.Add(new DiffuseMaterial(new SolidColorBrush(Colors.Black))); unlitMaterial.Children.Add(new EmissiveMaterial(new SolidColorBrush(color))); unlitMaterial.Freeze(); this.model.Material = unlitMaterial; this.model.BackMaterial = unlitMaterial; } /// <summary> /// Called when rendering. /// </summary> /// <param name="sender">The sender object.</param> /// <param name="e">The event args.</param> private void OnRender(object sender, EventArgs e) { if (this.Points.Count == 0 && this.mesh.Positions.Count == 0) { return; } if (this.UpdateTransforms()) { this.RebuildGeometry(); } } /// <summary> /// Called to force update. /// </summary> private void GeometryDirty() { // Force next call to UpdateTransforms() to return true. this.visualToScreen = MathUtils.ZeroMatrix; } /// <summary> /// Called to rebuild the visual lines. /// </summary> private void RebuildGeometry() { double halfThickness = this.Thickness / 2.0; int numLines = this.Points.Count / 2; Point3DCollection positions = new Point3DCollection(numLines * 4); for (int i = 0; i < numLines; i++) { int startIndex = i * 2; Point3D startPoint = this.Points[startIndex]; Point3D endPoint = this.Points[startIndex + 1]; this.AddSegment(positions, startPoint, endPoint, halfThickness); } positions.Freeze(); this.mesh.Positions = positions; Int32Collection indices = new Int32Collection(this.Points.Count * 3); for (int i = 0; i < this.Points.Count / 2; i++) { indices.Add((i * 4) + 2); indices.Add((i * 4) + 1); indices.Add((i * 4) + 0); indices.Add((i * 4) + 2); indices.Add((i * 4) + 3); indices.Add((i * 4) + 1); } indices.Freeze(); this.mesh.TriangleIndices = indices; } /// <summary> /// Called to add a line segment. /// </summary> /// <param name="positions">The point positions to link with lines.</param> /// <param name="startPoint">The start point.</param> /// <param name="endPoint">The end point.</param> /// <param name="halfThickness">The half thickness.</param> private void AddSegment(Point3DCollection positions, Point3D startPoint, Point3D endPoint, double halfThickness) { // NOTE: We want the vector below to be perpendicular post projection so // we need to compute the line direction in post-projective space. Vector3D lineDirection = (endPoint * this.visualToScreen) - (startPoint * this.visualToScreen); lineDirection.Z = 0; lineDirection.Normalize(); // NOTE: Implicit Rot(90) during construction to get a perpendicular vector. Vector delta = new Vector(-lineDirection.Y, lineDirection.X); delta *= halfThickness; Point3D pointOut1, pointOut2; this.Widen(startPoint, delta, out pointOut1, out pointOut2); positions.Add(pointOut1); positions.Add(pointOut2); this.Widen(endPoint, delta, out pointOut1, out pointOut2); positions.Add(pointOut1); positions.Add(pointOut2); } /// <summary> /// Called to widen line segments. /// </summary> /// <param name="pointIn">The input point positions.</param> /// <param name="delta">The difference to the initial line widths.</param> /// <param name="pointOut1">The output points with the delta added to X,Y position.</param> /// <param name="pointOut2">The output points with the delta subtracted from the X,Y position.</param> private void Widen(Point3D pointIn, Vector delta, out Point3D pointOut1, out Point3D pointOut2) { Point4D pointIn4 = (Point4D)pointIn; Point4D pointOut41 = pointIn4 * this.visualToScreen; Point4D pointOut42 = pointOut41; pointOut41.X += delta.X * pointOut41.W; pointOut41.Y += delta.Y * pointOut41.W; pointOut42.X -= delta.X * pointOut42.W; pointOut42.Y -= delta.Y * pointOut42.W; pointOut41 *= this.screenToVisual; pointOut42 *= this.screenToVisual; // NOTE: Z is not modified above, so we use the original Z below. pointOut1 = new Point3D( pointOut41.X / pointOut41.W, pointOut41.Y / pointOut41.W, pointOut41.Z / pointOut41.W); pointOut2 = new Point3D( pointOut42.X / pointOut42.W, pointOut42.Y / pointOut42.W, pointOut42.Z / pointOut42.W); } /// <summary> /// Called to Update Transforms. /// </summary> /// <returns>Returns true if successful.</returns> private bool UpdateTransforms() { Viewport3DVisual viewport; bool success; Matrix3D newVisualToScreen = MathUtils.TryTransformTo2DAncestor(this, out viewport, out success); if (!success || !newVisualToScreen.HasInverse) { this.mesh.Positions = null; return false; } if (this.visualToScreen == newVisualToScreen) { return false; } this.visualToScreen = this.screenToVisual = newVisualToScreen; this.screenToVisual.Invert(); return true; } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira ([email protected]) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.TypeSystem; namespace Boo.Lang.Compiler.Steps { //TODO: constant propagation (which allows precise unreachable branch detection) public class ConstantFolding : AbstractTransformerCompilerStep { public const string FoldedExpression = "foldedExpression"; override public void Run() { if (Errors.Count > 0) return; Visit(CompileUnit); } override public void OnModule(Module node) { Visit(node.Members); } object GetLiteralValue(Expression node) { switch (node.NodeType) { case NodeType.CastExpression: return GetLiteralValue(((CastExpression) node).Target); case NodeType.BoolLiteralExpression: return ((BoolLiteralExpression) node).Value; case NodeType.IntegerLiteralExpression: return ((IntegerLiteralExpression) node).Value; case NodeType.DoubleLiteralExpression: return ((DoubleLiteralExpression) node).Value; case NodeType.MemberReferenceExpression: { IField field = node.Entity as IField; if (null != field && field.IsLiteral) { if (field.Type.IsEnum) { object o = field.StaticValue; if (null != o && o != Error.Default) return o; } else { Expression e = field.StaticValue as Expression; return (null != e) ? GetLiteralValue(e) : field.StaticValue; } } break; } } return null; } override public void LeaveEnumMember(EnumMember node) { if (node.Initializer.NodeType == NodeType.IntegerLiteralExpression) return; IType type = node.Initializer.ExpressionType; if (null != type && (TypeSystemServices.IsIntegerNumber(type) || type.IsEnum)) { object val = GetLiteralValue(node.Initializer); if (null != val && val != Error.Default) node.Initializer = new IntegerLiteralExpression(Convert.ToInt64(val)); } return; } override public void LeaveBinaryExpression(BinaryExpression node) { if (AstUtil.GetBinaryOperatorKind(node.Operator) == BinaryOperatorKind.Assignment || node.Operator == BinaryOperatorType.ReferenceEquality || node.Operator == BinaryOperatorType.ReferenceInequality) return; if (null == node.Left.ExpressionType || null == node.Right.ExpressionType) return; object lhs = GetLiteralValue(node.Left); object rhs = GetLiteralValue(node.Right); if (null == lhs || null == rhs) return; Expression folded = null; IType lhsType = GetExpressionType(node.Left); IType rhsType = GetExpressionType(node.Right); if (TypeSystemServices.BoolType == lhsType && TypeSystemServices.BoolType == rhsType) { folded = GetFoldedBoolLiteral(node.Operator, Convert.ToBoolean(lhs), Convert.ToBoolean(rhs)); } else if (TypeSystemServices.IsFloatingPointNumber(lhsType) || TypeSystemServices.IsFloatingPointNumber(rhsType)) { folded = GetFoldedDoubleLiteral(node.Operator, Convert.ToDouble(lhs), Convert.ToDouble(rhs)); } else if (TypeSystemServices.IsIntegerNumber(lhsType) || lhsType.IsEnum) { bool lhsSigned = TypeSystemServices.IsSignedNumber(lhsType); bool rhsSigned = TypeSystemServices.IsSignedNumber(rhsType); if (lhsSigned == rhsSigned) //mixed signed/unsigned not supported for folding { folded = lhsSigned ? GetFoldedIntegerLiteral(node.Operator, Convert.ToInt64(lhs), Convert.ToInt64(rhs)) : GetFoldedIntegerLiteral(node.Operator, Convert.ToUInt64(lhs), Convert.ToUInt64(rhs)); } } if (null != folded) { folded.LexicalInfo = node.LexicalInfo; folded.ExpressionType = GetExpressionType(node); folded.Annotate(FoldedExpression, node); ReplaceCurrentNode(folded); } } override public void LeaveUnaryExpression(UnaryExpression node) { if (node.Operator == UnaryOperatorType.Explode || node.Operator == UnaryOperatorType.AddressOf || node.Operator == UnaryOperatorType.Indirection || node.Operator == UnaryOperatorType.LogicalNot) return; if (null == node.Operand.ExpressionType) return; object operand = GetLiteralValue(node.Operand); if (null == operand) return; Expression folded = null; IType operandType = GetExpressionType(node.Operand); if (TypeSystemServices.IsFloatingPointNumber(operandType)) { folded = GetFoldedDoubleLiteral(node.Operator, Convert.ToDouble(operand)); } else if (TypeSystemServices.IsIntegerNumber(operandType) || operandType.IsEnum) { folded = GetFoldedIntegerLiteral(node.Operator, Convert.ToInt64(operand)); } if (null != folded) { folded.LexicalInfo = node.LexicalInfo; folded.ExpressionType = GetExpressionType(node); ReplaceCurrentNode(folded); } } static BoolLiteralExpression GetFoldedBoolLiteral(BinaryOperatorType @operator, bool lhs, bool rhs) { bool result; switch (@operator) { //comparison case BinaryOperatorType.Equality: result = (lhs == rhs); break; case BinaryOperatorType.Inequality: result = (lhs != rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; //logical case BinaryOperatorType.And: result = lhs && rhs; break; case BinaryOperatorType.Or: result = lhs || rhs; break; default: return null; //not supported } return new BoolLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(BinaryOperatorType @operator, long lhs, long rhs) { long result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = (long) Math.Pow(lhs, rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; case BinaryOperatorType.ShiftLeft: result = lhs << (int) rhs; break; case BinaryOperatorType.ShiftRight: result = lhs >> (int) rhs; break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new IntegerLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(BinaryOperatorType @operator, ulong lhs, ulong rhs) { ulong result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = (ulong) Math.Pow(lhs, rhs); break; //bitwise case BinaryOperatorType.BitwiseOr: result = lhs | rhs; break; case BinaryOperatorType.BitwiseAnd: result = lhs & rhs; break; case BinaryOperatorType.ExclusiveOr: result = lhs ^ rhs; break; case BinaryOperatorType.ShiftLeft: result = lhs << (int) rhs; break; case BinaryOperatorType.ShiftRight: result = lhs >> (int) rhs; break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new IntegerLiteralExpression((long) result); } static LiteralExpression GetFoldedDoubleLiteral(BinaryOperatorType @operator, double lhs, double rhs) { double result; switch (@operator) { //arithmetic case BinaryOperatorType.Addition: result = lhs + rhs; break; case BinaryOperatorType.Subtraction: result = lhs - rhs; break; case BinaryOperatorType.Multiply: result = lhs * rhs; break; case BinaryOperatorType.Division: result = lhs / rhs; break; case BinaryOperatorType.Modulus: result = lhs % rhs; break; case BinaryOperatorType.Exponentiation: result = Math.Pow(lhs, rhs); break; //comparison case BinaryOperatorType.LessThan: return new BoolLiteralExpression(lhs < rhs); case BinaryOperatorType.LessThanOrEqual: return new BoolLiteralExpression(lhs <= rhs); case BinaryOperatorType.GreaterThan: return new BoolLiteralExpression(lhs > rhs); case BinaryOperatorType.GreaterThanOrEqual: return new BoolLiteralExpression(lhs >= rhs); case BinaryOperatorType.Equality: return new BoolLiteralExpression(lhs == rhs); case BinaryOperatorType.Inequality: return new BoolLiteralExpression(lhs != rhs); default: return null; //not supported } return new DoubleLiteralExpression(result); } static LiteralExpression GetFoldedIntegerLiteral(UnaryOperatorType @operator, long operand) { long result; switch (@operator) { case UnaryOperatorType.UnaryNegation: result = -operand; break; case UnaryOperatorType.OnesComplement: result = ~operand; break; default: return null; //not supported } return new IntegerLiteralExpression(result); } static LiteralExpression GetFoldedDoubleLiteral(UnaryOperatorType @operator, double operand) { double result; switch (@operator) { case UnaryOperatorType.UnaryNegation: result = -operand; break; default: return null; //not supported } return new DoubleLiteralExpression(result); } } }
#if IGOR_RUNTIME || UNITY_EDITOR using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace Igor { public class XMLSerializable : IXmlSerializable { public enum ModifiedState { Unmodified, Added, PreModify, Modified, Deleted } public static bool bSafeToLoad = false; public enum LinkType { LINK_NormalLink, LINK_StartLink, LINK_EndLink }; protected bool bReading = false; protected bool bEmbedded = false; protected int SerializedFromVersion = 0; protected XmlReader InternalReader = null; protected XmlWriter InternalWriter = null; protected string Filename = ""; protected bool bReadStartElement = false; public virtual string GetFilename() { return Filename; } #if UNITY_EDITOR public virtual void EditorSetFilename(string NewFilename) { Filename = NewFilename; } public virtual void EditorSetDisplayName(string NewName) { } public virtual string EditorGetDisplayName() { return Filename; } public virtual string EditorGetDragAndDropText() { return ""; } public virtual string EditorGetCompareString() { return ""; } #endif // UNITY_EDITOR public virtual void SerializeListOwnerPrefixFixup() { } public virtual void ListFixup<EntityType>(ref List<EntityLink<EntityType>> ListToFix, XMLSerializable Owner, string ListPrefix, LinkType ListType) where EntityType : LinkedEntity<EntityType>, new() { for(int CurrentEntry = 0; CurrentEntry < ListToFix.Count; ++CurrentEntry) { ListToFix[CurrentEntry].SetOwner(Owner); ListToFix[CurrentEntry].ListPrefix = ListPrefix; ListToFix[CurrentEntry].CurrentLinkType = ListType; } } public void InternalSerializeXML(XmlReader Reader, XmlWriter Writer) { if(Reader != null) { bReading = true; InternalReader = Reader; SerializeXML(); InternalReader.ReadEndElement(); InternalReader = null; } else { bReading = false; InternalWriter = Writer; SerializeXML(); InternalWriter = null; } } public virtual void SerializeXML() { } public void SerializeBegin(string ClassName, string TemplatedClassName1 = "", string TemplatedClassName2 = "") { string CombinedStringName = ClassName; if(CombinedStringName.Contains(".")) { CombinedStringName = CombinedStringName.Substring(CombinedStringName.IndexOf('.')); } if(TemplatedClassName1.Length > 0) { CombinedStringName += "Of" + (TemplatedClassName1.Contains(".") ? TemplatedClassName1.Substring(TemplatedClassName1.IndexOf('.') + 1) : TemplatedClassName1); if(TemplatedClassName2.Length > 0) { CombinedStringName += (TemplatedClassName2.Contains(".") ? TemplatedClassName2.Substring(TemplatedClassName2.IndexOf('.') + 1) : TemplatedClassName2); } } CombinedStringName = CombinedStringName.Replace('.', '_'); if(bReading) { if(!bEmbedded) { InternalReader.MoveToContent(); } if(!bReadStartElement) { InternalReader.ReadStartElement(CombinedStringName); } bReadStartElement = false; SerializedFromVersion = InternalReader.ReadElementContentAsInt("SerializeVersion", ""); } else { if(bEmbedded) { InternalWriter.WriteStartElement(CombinedStringName); } InternalWriter.WriteStartElement("SerializeVersion"); InternalWriter.WriteValue(TypeUtils.GetSerializeVersion()); InternalWriter.WriteEndElement(); SerializedFromVersion = TypeUtils.GetSerializeVersion(); } } public void SerializeString(string Key, ref string Value) { if(bReading) { Value = InternalReader.ReadElementContentAsString(Key, ""); } else { InternalWriter.WriteElementString(Key, Value); } } public void SerializeFloat(string Key, ref float Value) { if(bReading) { Value = InternalReader.ReadElementContentAsFloat(Key, ""); } else { InternalWriter.WriteElementString(Key, Value.ToString()); } } public void SerializeInt(string Key, ref int Value) { if(bReading) { Value = InternalReader.ReadElementContentAsInt(Key, ""); } else { InternalWriter.WriteElementString(Key, Value.ToString()); } } public void SerializeBool(string Key, ref bool Value) { if(bReading) { Value = InternalReader.ReadElementContentAsString(Key, "") == "True"; } else { InternalWriter.WriteElementString(Key, Value.ToString()); } } public void SerializeVector2(string Key, ref Vector2 Value) { if(bReading) { Value.x = InternalReader.ReadElementContentAsFloat(Key + ".x", ""); Value.y = InternalReader.ReadElementContentAsFloat(Key + ".y", ""); } else { InternalWriter.WriteElementString(Key + ".x", Value.x.ToString()); InternalWriter.WriteElementString(Key + ".y", Value.y.ToString()); } } public void SerializeVector3(string Key, ref Vector3 Value) { if(bReading) { Value.x = InternalReader.ReadElementContentAsFloat(Key + ".x", ""); Value.y = InternalReader.ReadElementContentAsFloat(Key + ".y", ""); Value.z = InternalReader.ReadElementContentAsFloat(Key + ".z", ""); } else { InternalWriter.WriteElementString(Key + ".x", Value.x.ToString()); InternalWriter.WriteElementString(Key + ".y", Value.y.ToString()); InternalWriter.WriteElementString(Key + ".z", Value.z.ToString()); } } public void SerializeVector4(string Key, ref Vector4 Value) { if(bReading) { Value.x = InternalReader.ReadElementContentAsFloat(Key + ".x", ""); Value.y = InternalReader.ReadElementContentAsFloat(Key + ".y", ""); Value.z = InternalReader.ReadElementContentAsFloat(Key + ".z", ""); Value.w = InternalReader.ReadElementContentAsFloat(Key + ".w", ""); } else { InternalWriter.WriteElementString(Key + ".x", Value.x.ToString()); InternalWriter.WriteElementString(Key + ".y", Value.y.ToString()); InternalWriter.WriteElementString(Key + ".z", Value.z.ToString()); InternalWriter.WriteElementString(Key + ".w", Value.w.ToString()); } } public void SerializeQuaternion(string Key, ref Quaternion Value) { if(bReading) { Value.x = InternalReader.ReadElementContentAsFloat(Key + ".x", ""); Value.y = InternalReader.ReadElementContentAsFloat(Key + ".y", ""); Value.z = InternalReader.ReadElementContentAsFloat(Key + ".z", ""); Value.w = InternalReader.ReadElementContentAsFloat(Key + ".w", ""); } else { InternalWriter.WriteElementString(Key + ".x", Value.x.ToString()); InternalWriter.WriteElementString(Key + ".y", Value.y.ToString()); InternalWriter.WriteElementString(Key + ".z", Value.z.ToString()); InternalWriter.WriteElementString(Key + ".w", Value.w.ToString()); } } public void SerializeDateTime(string Key, ref DateTime Value) { if(bReading) { int Day = InternalReader.ReadElementContentAsInt(Key + ".Day", ""); int Month = InternalReader.ReadElementContentAsInt(Key + ".Month", ""); int Year = InternalReader.ReadElementContentAsInt(Key + ".Year", ""); int Hour = InternalReader.ReadElementContentAsInt(Key + ".Hour", ""); int Minute = InternalReader.ReadElementContentAsInt(Key + ".Minute", ""); int Second = InternalReader.ReadElementContentAsInt(Key + ".Second", ""); Value = new DateTime(Year, Month, Day, Hour, Minute, Second); } else { InternalWriter.WriteElementString(Key + ".Day", Value.Day.ToString()); InternalWriter.WriteElementString(Key + ".Month", Value.Month.ToString()); InternalWriter.WriteElementString(Key + ".Year", Value.Year.ToString()); InternalWriter.WriteElementString(Key + ".Hour", Value.Hour.ToString()); InternalWriter.WriteElementString(Key + ".Minute", Value.Minute.ToString()); InternalWriter.WriteElementString(Key + ".Second", Value.Second.ToString()); } } public void SerializeEntityID(string Key, ref EntityID Value) { if(Value == null) { Value = new EntityID(); } SerializeInt(Key + "SerializedVersion", ref Value.SerializedVersion); SerializeString(Key + "Chapter", ref Value.ChapterFilename); SerializeString(Key + "Scene", ref Value.SceneFilename); SerializeString(Key + "Dialogue", ref Value.DialogueFilename); SerializeString(Key + "Conversation", ref Value.ConversationFilename); } public delegate void ToFromDelegate<SourceType, SavedType>(ref SourceType SourceIn, ref SavedType SavedIn); public void SerializeStringList<SourceType>(string ListName, string ElementName, ToFromDelegate<SourceType, string> FunctionDelegate, ref List<SourceType> ListToSerialize) { if(bReading) { bool isEmptyElement = InternalReader.IsEmptyElement; InternalReader.ReadStartElement(ListName); if (!isEmptyElement) { int CurrentDepth = InternalReader.Depth; while(InternalReader.Depth >= CurrentDepth) { InternalReader.ReadStartElement(ElementName); SourceType Temp = default(SourceType); string Content = InternalReader.ReadContentAsString(); FunctionDelegate(ref Temp, ref Content); if(Temp != null) { ListToSerialize.Add(Temp); } InternalReader.ReadEndElement(); } InternalReader.ReadEndElement(); } } else { InternalWriter.WriteStartElement(ListName); if(ListToSerialize.Count > 0) { foreach(SourceType CurrentSource in ListToSerialize) { SourceType CurrentSourceToRef = CurrentSource; string ContentToWrite = ""; FunctionDelegate(ref CurrentSourceToRef, ref ContentToWrite); InternalWriter.WriteElementString(ElementName, ContentToWrite); } } InternalWriter.WriteEndElement(); } } public void SerializeStringList(string ListName, string ElementName, ref List<string> ListToSerialize) { if(bReading) { bool isEmptyElement = InternalReader.IsEmptyElement; InternalReader.ReadStartElement(ListName); if (!isEmptyElement) { int CurrentDepth = InternalReader.Depth; while(InternalReader.Depth >= CurrentDepth) { InternalReader.ReadStartElement(ElementName); string Content = InternalReader.ReadContentAsString(); ListToSerialize.Add(Content); InternalReader.ReadEndElement(); } InternalReader.ReadEndElement(); } } else { InternalWriter.WriteStartElement(ListName); if(ListToSerialize.Count > 0) { foreach(string CurrentString in ListToSerialize) { InternalWriter.WriteElementString(ElementName, CurrentString); } } InternalWriter.WriteEndElement(); } } public void SerializeListEmbedded<ListType>(string ListName, string ElementName, ref List<ListType> ListToSerialize) where ListType : XMLSerializable, new() { if(bReading) { bool isEmptyElement = InternalReader.IsEmptyElement; InternalReader.ReadStartElement(ListName); if (!isEmptyElement) { int CurrentDepth = InternalReader.Depth; while(InternalReader.Depth >= CurrentDepth) { // InternalReader.ReadStartElement(ElementName); ListType NewElement = new ListType(); XMLSerializable.SerializeFromXMLEmbedded<ListType>(ref InternalReader, ref InternalWriter, ref NewElement); NewElement = (ListType)NewElement.ResolveIDPatching(); ListToSerialize.Add(NewElement); // InternalReader.ReadEndElement(); } InternalReader.ReadEndElement(); } } else { InternalWriter.WriteStartElement(ListName); if(ListToSerialize.Count > 0) { foreach(ListType CurrentElement in ListToSerialize) { ListType RefCurrentElement = CurrentElement; XMLSerializable.SerializeFromXMLEmbedded<ListType>(ref InternalReader, ref InternalWriter, ref RefCurrentElement); } } InternalWriter.WriteEndElement(); } } public void SerializeStringStringDictionaryEmbedded(string ListName, string KeyName, string ValueName, ref Dictionary<string, string> DictionaryToSerialize) { if(bReading) { bool isEmptyElement = InternalReader.IsEmptyElement; InternalReader.ReadStartElement(ListName); if (!isEmptyElement) { int CurrentDepth = InternalReader.Depth; while(InternalReader.Depth >= CurrentDepth) { string NewKey = ""; string NewValue = ""; SerializeString(KeyName, ref NewKey); SerializeString(ValueName, ref NewValue); #if UNITY_EDITOR if(DictionaryToSerialize.ContainsKey(NewKey)) { Debug.Log("Bad data! Key \"" + NewKey + "\" already exists!"); } else #endif // UNITY_EDITOR { DictionaryToSerialize.Add(NewKey, NewValue); } } InternalReader.ReadEndElement(); } } else { InternalWriter.WriteStartElement(ListName); if(DictionaryToSerialize.Count > 0) { foreach(KeyValuePair<string, string> CurrentElement in DictionaryToSerialize) { string RefCurrentKey = CurrentElement.Key; SerializeString(KeyName, ref RefCurrentKey); string RefCurrentValue = CurrentElement.Value; SerializeString(ValueName, ref RefCurrentValue); } } InternalWriter.WriteEndElement(); } } public void SerializeDictionaryStringFloatEmbedded(string ListName, string KeyName, string ValueName, ref Dictionary<string, float> DictionaryToSerialize) { if(bReading) { bool isEmptyElement = InternalReader.IsEmptyElement; InternalReader.ReadStartElement(ListName); if (!isEmptyElement) { int CurrentDepth = InternalReader.Depth; while(InternalReader.Depth >= CurrentDepth) { string NewKey = ""; float NewValue = 0.0f; SerializeString(KeyName, ref NewKey); SerializeFloat(ValueName, ref NewValue); #if UNITY_EDITOR if(DictionaryToSerialize.ContainsKey(NewKey)) { Debug.Log("Bad data! Key \"" + NewKey + "\" already exists!"); } else #endif // UNITY_EDITOR { DictionaryToSerialize.Add(NewKey, NewValue); } } InternalReader.ReadEndElement(); } } else { InternalWriter.WriteStartElement(ListName); if(DictionaryToSerialize.Count > 0) { foreach(KeyValuePair<string, float> CurrentElement in DictionaryToSerialize) { string RefCurrentKey = CurrentElement.Key; SerializeString(KeyName, ref RefCurrentKey); float RefCurrentValue = CurrentElement.Value; SerializeFloat(ValueName, ref RefCurrentValue); } } InternalWriter.WriteEndElement(); } } public void SerializeDictionaryEmbedded<KeyType, ValueType>(string ListName, string KeyName, string ValueName, ref Dictionary<KeyType, ValueType> DictionaryToSerialize) where KeyType : XMLSerializable, new() where ValueType : XMLSerializable, new() { if(bReading) { bool isEmptyElement = InternalReader.IsEmptyElement; InternalReader.ReadStartElement(ListName); if (!isEmptyElement) { int CurrentDepth = InternalReader.Depth; while(InternalReader.Depth >= CurrentDepth) { KeyType NewKey = new KeyType(); if(InternalReader.IsStartElement()) { string NextElementType = InternalReader.Name; object Temp = TypeUtils.GetNewObjectOfTypeString(NextElementType); if(typeof(KeyType).IsAssignableFrom(Temp.GetType())) { NewKey = (KeyType)Temp; } bReadStartElement = true; } XMLSerializable.SerializeFromXMLEmbedded<KeyType>(ref InternalReader, ref InternalWriter, ref NewKey); ValueType NewValue = new ValueType(); if(InternalReader.IsStartElement()) { string NextElementType = InternalReader.Name; object Temp = TypeUtils.GetNewObjectOfTypeString(NextElementType); if(typeof(ValueType).IsAssignableFrom(Temp.GetType())) { NewValue = (ValueType)Temp; } bReadStartElement = true; } XMLSerializable.SerializeFromXMLEmbedded<ValueType>(ref InternalReader, ref InternalWriter, ref NewValue); NewKey = (KeyType)NewKey.ResolveIDPatching(); NewValue = (ValueType)NewValue.ResolveIDPatching(); if(NewKey == null) { NewKey = new KeyType(); } if(NewValue == null) { NewValue = new ValueType(); } DictionaryToSerialize.Add(NewKey, NewValue); } InternalReader.ReadEndElement(); } } else { InternalWriter.WriteStartElement(ListName); if(DictionaryToSerialize.Count > 0) { foreach(KeyValuePair<KeyType, ValueType> CurrentElement in DictionaryToSerialize) { KeyType RefCurrentKey = CurrentElement.Key; XMLSerializable.SerializeFromXMLEmbedded<KeyType>(ref InternalReader, ref InternalWriter, ref RefCurrentKey); ValueType RefCurrentValue = CurrentElement.Value; XMLSerializable.SerializeFromXMLEmbedded<ValueType>(ref InternalReader, ref InternalWriter, ref RefCurrentValue); } } InternalWriter.WriteEndElement(); } } public void SerializeDictionaryStringEmbedded<ValueType>(string ListName, string KeyName, string ValueName, ref Dictionary<string, ValueType> DictionaryToSerialize) where ValueType : XMLSerializable, new() { if(bReading) { bool isEmptyElement = InternalReader.IsEmptyElement; InternalReader.ReadStartElement(ListName); if (!isEmptyElement) { int CurrentDepth = InternalReader.Depth; while(InternalReader.Depth >= CurrentDepth) { string NewKey = ""; SerializeString(KeyName, ref NewKey); ValueType NewValue = new ValueType(); if(InternalReader.IsStartElement()) { string NextElementType = InternalReader.Name; object Temp = TypeUtils.GetNewObjectOfTypeString(NextElementType); if(typeof(ValueType).IsAssignableFrom(Temp.GetType())) { NewValue = (ValueType)Temp; } bReadStartElement = true; } XMLSerializable.SerializeFromXMLEmbedded<ValueType>(ref InternalReader, ref InternalWriter, ref NewValue); NewValue = (ValueType)NewValue.ResolveIDPatching(); if(NewKey == null) { NewKey = ""; } if(NewValue == null) { NewValue = new ValueType(); } DictionaryToSerialize.Add(NewKey, NewValue); } InternalReader.ReadEndElement(); } } else { InternalWriter.WriteStartElement(ListName); if(DictionaryToSerialize.Count > 0) { foreach(KeyValuePair<string, ValueType> CurrentElement in DictionaryToSerialize) { string RefCurrentKey = CurrentElement.Key; SerializeString(KeyName, ref RefCurrentKey); ValueType RefCurrentValue = CurrentElement.Value; XMLSerializable.SerializeFromXMLEmbedded<ValueType>(ref InternalReader, ref InternalWriter, ref RefCurrentValue); } } InternalWriter.WriteEndElement(); } } public void SerializeDictionaryObjectFloatEmbedded<KeyType>(string ListName, string KeyName, string ValueName, ref Dictionary<KeyType, float> DictionaryToSerialize) where KeyType : XMLSerializable, new() { if(bReading) { bool isEmptyElement = InternalReader.IsEmptyElement; InternalReader.ReadStartElement(ListName); if (!isEmptyElement) { int CurrentDepth = InternalReader.Depth; while(InternalReader.Depth >= CurrentDepth) { KeyType NewKey = new KeyType(); float NewValue = 0.0f; XMLSerializable.SerializeFromXMLEmbedded<KeyType>(ref InternalReader, ref InternalWriter, ref NewKey); NewKey = (KeyType)NewKey.ResolveIDPatching(); SerializeFloat(ValueName, ref NewValue); if(NewKey == null) { NewKey = new KeyType(); } DictionaryToSerialize.Add(NewKey, NewValue); } InternalReader.ReadEndElement(); } } else { InternalWriter.WriteStartElement(ListName); if(DictionaryToSerialize.Count > 0) { foreach(KeyValuePair<KeyType, float> CurrentElement in DictionaryToSerialize) { KeyType RefCurrentKey = CurrentElement.Key; XMLSerializable.SerializeFromXMLEmbedded<KeyType>(ref InternalReader, ref InternalWriter, ref RefCurrentKey); float RefCurrentValue = CurrentElement.Value; SerializeFloat(ValueName, ref RefCurrentValue); } } InternalWriter.WriteEndElement(); } } public virtual XMLSerializable ResolveIDPatching() { return this; } public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { InternalSerializeXML(reader, null); } public void WriteXml(XmlWriter writer) { InternalSerializeXML(null, writer); } public static void GuaranteePathExists(string Filename) { if(Filename != "") { FileInfo FileNameInfo = new FileInfo(Filename); string FilePath = FileNameInfo.DirectoryName; Directory.CreateDirectory(FilePath); if(File.Exists(Filename)) { File.SetAttributes(Filename, FileAttributes.Normal); } } } public static void SerializeFromXML<SerializeType>(string Filename, ref SerializeType ToSerialize, bool bSaving, XmlSerializer Serializer = null) where SerializeType : XMLSerializable { if(bSaving) { XmlSerializer SpecificSerializer = Serializer; if(SpecificSerializer == null) { try { SpecificSerializer = new XmlSerializer(typeof(SerializeType)); } catch(Exception Ex) { if(Ex != null) { Debug.LogError("Error creating an XML serializer for type " + typeof(SerializeType).ToString() + "!! Exception message is\n" + Ex.Message + "\nAnd inner exception is\n" + Ex.InnerException.Message); } } } GuaranteePathExists(Filename); TextWriter SpecificWriter = new StreamWriter(Filename); try { SpecificSerializer.Serialize(SpecificWriter, ToSerialize); } catch(Exception Ex) { if(Ex != null) { Debug.LogError("Error serializing an XML file!! Exception message is\n" + Ex.Message + "\nAnd inner exception is\n" + Ex.InnerException.Message); } } ToSerialize.PostSerialize(); SpecificWriter.Close(); } else { if(!bSafeToLoad) { TypeUtils.RegisterAllTypes(); // ToSerialize = null; // return; } #if !UNITY_EDITOR if(Filename.StartsWith("Assets/Resources/")) { XmlSerializer SpecificSerializer = Serializer; if(SpecificSerializer == null) { SpecificSerializer = new XmlSerializer(typeof(SerializeType)); } string ResourcePath = Filename.Substring("Assets/Resources/".Length); ResourcePath = ResourcePath.Substring(0, ResourcePath.Length - 4); TextAsset XMLAsset = (TextAsset)Resources.Load(ResourcePath, typeof(TextAsset)); if(XMLAsset != null) { string RawXML = XMLAsset.text; TextReader SpecificReader = new StringReader(RawXML); ToSerialize = (SerializeType)SpecificSerializer.Deserialize(SpecificReader); ToSerialize.PostSerialize(); SpecificReader.Close(); } else { Debug.LogError("Failed to load XML from resource file with name " + ResourcePath); } } else { if(!Filename.Contains("GameSaves")) { Debug.LogError("Trying to serialize in an XML file that isn't in the resources folder. Filename is " + Filename); } #else { #endif if(File.Exists(Filename)) { XmlSerializer SpecificSerializer = Serializer; if(SpecificSerializer == null) { try { SpecificSerializer = new XmlSerializer(typeof(SerializeType)); } catch(Exception Ex) { if(Ex != null) { Debug.LogError("Error creating an XML deserializer for type " + typeof(SerializeType).ToString() + "!! Exception message is\n" + Ex.Message + "\nAnd inner exception is\n" + Ex.InnerException.Message); } } } TextReader SpecificReader = new StreamReader(Filename); try { ToSerialize = (SerializeType)SpecificSerializer.Deserialize(SpecificReader); } catch(Exception Ex) { if(Ex != null) { Debug.LogError("Error deserializing an XML file!! Exception message is\n" + Ex.Message + "\nAnd inner exception is\n" + Ex.InnerException != null ? Ex.InnerException.Message : ""); } } ToSerialize.PostSerialize(); SpecificReader.Close(); } } } } public static void SerializeFromXMLEmbedded<SerializeType>(ref XmlReader Reader, ref XmlWriter Writer, ref SerializeType ToSerialize) where SerializeType : XMLSerializable { ToSerialize.bEmbedded = true; ToSerialize.InternalSerializeXML(Reader, Writer); if(Writer != null) { Writer.WriteEndElement(); } ToSerialize.bEmbedded = false; } public virtual void PostSerialize() { CreateStaticNodesIfNotPresent(); } public virtual void CreateStaticNodesIfNotPresent() { } public virtual void PopulateToFromValue<GenericType>(ref GenericType LocalValue, ref GenericType ToFromInstanceValue, bool bFromInstance) { if(bFromInstance) { LocalValue = ToFromInstanceValue; } else { ToFromInstanceValue = LocalValue; } } } } #endif // IGOR_RUNTIME || UNITY_EDITOR
// <copyright file="DirichletTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Linq; using MathNet.Numerics.Distributions; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.DistributionTests.Multivariate { using Random = System.Random; /// <summary> /// Dirichlet distribution tests /// </summary> [TestFixture, Category("Distributions")] public class DirichletTests { /// <summary> /// Set-up test parameters. /// </summary> [SetUp] public void SetUp() { Control.CheckDistributionParameters = true; } /// <summary> /// Can create symmetric Dirichlet. /// </summary> [Test] public void CanCreateSymmetricDirichlet() { var d = new Dirichlet(0.3, 5); for (var i = 0; i < 5; i++) { Assert.AreEqual(0.3, d.Alpha[i]); } } /// <summary> /// Can create dirichlet. /// </summary> [Test] public void CanCreateDirichlet() { var alpha = new double[10]; for (var i = 0; i < 10; i++) { alpha[i] = i; } var d = new Dirichlet(alpha); for (var i = 0; i < 5; i++) { Assert.AreEqual(i, d.Alpha[i]); } } /// <summary> /// Fail create dirichlet with bad parameters. /// </summary> [Test] public void FailCreateDirichlet() { Assert.That(() => new Dirichlet(0.0, 5), Throws.ArgumentException); Assert.That(() => new Dirichlet(-0.1, 5), Throws.ArgumentException); } /// <summary> /// Has random source. /// </summary> [Test] public void HasRandomSource() { var d = new Dirichlet(0.3, 5); Assert.IsNotNull(d.RandomSource); } /// <summary> /// Can set random source. /// </summary> [Test] public void CanSetRandomSource() { GC.KeepAlive(new Dirichlet(0.3, 5) { RandomSource = new Random(0) }); } [Test] public void HasRandomSourceEvenAfterSetToNull() { var d = new Dirichlet(0.3, 5); Assert.DoesNotThrow(() => d.RandomSource = null); Assert.IsNotNull(d.RandomSource); } /// <summary> /// Can get dimension. /// </summary> [Test] public void CanGetDimension() { var d = new Dirichlet(0.3, 10); Assert.AreEqual(10, d.Dimension); } /// <summary> /// Can get alpha. /// </summary> [Test] public void CanGetAlpha() { var d = new Dirichlet(0.3, 10); for (var i = 0; i < 10; i++) { Assert.AreEqual(0.3, d.Alpha[i]); } } /// <summary> /// Validate mean. /// </summary> [Test] public void ValidateMean() { var d = new Dirichlet(0.3, 5); for (var i = 0; i < 5; i++) { AssertHelpers.AlmostEqualRelative(0.3 / 1.5, d.Mean[i], 15); } } /// <summary> /// Validate variance. /// </summary> [Test] public void ValidateVariance() { var alpha = new double[10]; var sum = 0.0; for (var i = 0; i < 10; i++) { alpha[i] = i; sum += i; } var d = new Dirichlet(alpha); for (var i = 0; i < 10; i++) { AssertHelpers.AlmostEqualRelative(i * (sum - i) / (sum * sum * (sum + 1.0)), d.Variance[i], 15); } } /// <summary> /// Validate density. /// </summary> /// <param name="x">Alphas array.</param> /// <param name="res">Expected value.</param> /// <remarks> /// Mathematica: InputForm[PDF[DirichletDistribution[{0.1, 0.3, 0.5, 0.8}], {0.01, 0.03, 0.5}]] /// </remarks> [TestCase(new[] { 0.01, 0.03, 0.5 }, 18.77225681167061)] [TestCase(new[] { 0.1, 0.2, 0.3, 0.4 }, 0.8314656481199253)] public void ValidateDensity(double[] x, double res) { var d = new Dirichlet(new[] { 0.1, 0.3, 0.5, 0.8 }); AssertHelpers.AlmostEqualRelative(res, d.Density(x), 12); } /// <summary> /// Validate density log. /// </summary> /// <param name="x">Alpha array.</param> [TestCase(new[] { 0.01, 0.03, 0.5, 0.5 })] [TestCase(new[] { 0.1, 0.2, 0.3, 0.4 })] public void ValidateDensityLn(double[] x) { var d = new Dirichlet(new[] { 0.1, 0.3, 0.5, 0.8 }); AssertHelpers.AlmostEqualRelative(d.DensityLn(x), Math.Log(d.Density(x)), 12); } /// <summary> /// Validate density log matches Beta for 2-dimension cases /// </summary> /// <param name="x">Alpha array.</param> [TestCase(0.01)] [TestCase(0.1)] [TestCase(0.4)] [TestCase(0.71)] public void ValidateBetaSpecialCaseDensityLn(double x) { var d = new Dirichlet(new[] { 0.1, 0.3 }); var beta = new Beta(0.1, 0.3); AssertHelpers.AlmostEqualRelative(d.DensityLn(new[] { x }), beta.DensityLn(x), 10); } /// <summary> /// Validate entropy. /// </summary> /// <param name="x">Alpha array.</param> [TestCase(new[] { 0.1, 0.3, 0.5, 0.8 })] [TestCase(new[] { 0.1, 0.2, 0.3, 0.4 })] public void ValidateEntropy(double[] x) { var d = new Dirichlet(x); var sum = x.Sum(t => (t - 1) * SpecialFunctions.DiGamma(t)); var res = SpecialFunctions.GammaLn(x.Sum()) + ((x.Sum() - x.Length) * SpecialFunctions.DiGamma(x.Sum())) - sum; AssertHelpers.AlmostEqualRelative(res, d.Entropy, 12); } /// <summary> /// Can sample symmetric dirichlet. /// </summary> [Test] public void CanSampleSymmetricDirichlet() { var d = new Dirichlet(1.0, 5); d.Sample(); } /// <summary> /// Can sample singular dirichlet. /// </summary> [Test] public void CanSampleSingularDirichlet() { var d = new Dirichlet(new[] { 2.0, 1.0, 0.0, 3.0 }); d.Sample(); } } }
#if UNITY_5_6_OR_NEWER && !UNITY_5_6_0 using System; using UnityEditor; using UnityEditor.Connect; using UnityEngine; using UnityEngine.Networking; using System.Collections.Generic; using System.Text; using System.Threading; using AppStoreModel; namespace AppStoresSupport { [CustomEditor(typeof(AppStoreSettings))] public class AppStoreSettingsEditor : Editor { private UnityClientInfo unityClientInfo; private XiaomiSettings xiaomi; private string clientSecret_in_memory; private string callbackUrl_in_memory; private string appSecret_in_memory; private bool appSecret_hidden = true; private bool ownerAuthed = false; private string callbackUrl_last; private string appId_last; private string appKey_last; private string appSecret_last; private const string STEP_GET_CLIENT = "get_client"; private const string STEP_UPDATE_CLIENT = "update_client"; private const string STEP_UPDATE_CLIENT_SECRET = "update_client_secret"; struct ReqStruct { public string currentStep; public string targetStep; public UnityWebRequest request; public GeneralResponse resp; } private Queue<ReqStruct> requestQueue = new Queue<ReqStruct>(); private class AppStoreStyles { public const string kNoUnityProjectIDErrorMessage = "Unity Project ID doesn't exist, please go to Window/Services to create one."; public const int kUnityProjectIDBoxHeight = 24; public const int kUnityClientBoxHeight = 110; public const int kXiaomiBoxHeight = 90; public const int kUnityClientIDButtonWidth = 160; public const int kSaveButtonWidth = 120; public const int kClientLabelWidth = 140; public const int kClientLabelHeight = 16; public const int kClientLabelWidthShort = 50; public const int kClientLabelHeightShort = 15; } private SerializedProperty unityClientID; private SerializedProperty unityClientKey; private SerializedProperty unityClientRSAPublicKey; private SerializedProperty xiaomiAppID; private SerializedProperty xiaomiAppKey; private SerializedProperty xiaomiIsTestMode; private bool isOperationRunning = false; void OnEnable() { // For unity client settings. unityClientID = serializedObject.FindProperty("UnityClientID"); unityClientKey = serializedObject.FindProperty("UnityClientKey"); unityClientRSAPublicKey = serializedObject.FindProperty("UnityClientRSAPublicKey"); // For Xiaomi settings. SerializedProperty xiaomiAppStoreSetting = serializedObject.FindProperty("XiaomiAppStoreSetting"); xiaomiAppID = xiaomiAppStoreSetting.FindPropertyRelative("AppID"); xiaomiAppKey = xiaomiAppStoreSetting.FindPropertyRelative("AppKey"); xiaomiIsTestMode = xiaomiAppStoreSetting.FindPropertyRelative("IsTestMode"); EditorApplication.update += CheckUpdate; InitializeSecrets(); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.BeginDisabledGroup(isOperationRunning); // Unity project id. EditorGUILayout.LabelField(new GUIContent("Unity Project ID")); GUILayout.BeginVertical(); GUILayout.Space(2); GUILayout.EndVertical(); using (new EditorGUILayout.VerticalScope("OL Box", GUILayout.Height(AppStoreStyles.kUnityProjectIDBoxHeight))) { GUILayout.FlexibleSpace(); string unityProjectID = Application.cloudProjectId; if (String.IsNullOrEmpty(unityProjectID)) { EditorGUILayout.LabelField(new GUIContent(AppStoreStyles.kNoUnityProjectIDErrorMessage)); GUILayout.FlexibleSpace(); return; } EditorGUILayout.LabelField(new GUIContent(Application.cloudProjectId)); GUILayout.FlexibleSpace(); } GUILayout.BeginVertical(); GUILayout.Space(10); GUILayout.EndVertical(); // Unity client settings. EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(new GUIContent("Unity Client Settings")); bool clientNotExists = String.IsNullOrEmpty(unityClientID.stringValue); string buttonLableString = "Generate Unity Client"; string target = STEP_GET_CLIENT; if (!clientNotExists) { if (String.IsNullOrEmpty (clientSecret_in_memory) || !AppStoreOnboardApi.loaded) { buttonLableString = "Load Unity Client"; } else { buttonLableString = "Update Client Secret"; target = STEP_UPDATE_CLIENT_SECRET; } } if (GUILayout.Button(buttonLableString, GUILayout.Width(AppStoreStyles.kUnityClientIDButtonWidth))) { isOperationRunning = true; Debug.Log (buttonLableString + "..."); if (target == STEP_UPDATE_CLIENT_SECRET) { clientSecret_in_memory = null; } callApiAsync (target); serializedObject.ApplyModifiedProperties(); this.Repaint (); AssetDatabase.SaveAssets(); } EditorGUILayout.EndHorizontal(); GUILayout.BeginVertical(); GUILayout.Space(2); GUILayout.EndVertical(); using (new EditorGUILayout.VerticalScope("OL Box", GUILayout.Height(AppStoreStyles.kUnityClientBoxHeight))) { GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); if (String.IsNullOrEmpty (unityClientID.stringValue)) { EditorGUILayout.LabelField ("Client ID", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.LabelField ("None"); } else { EditorGUILayout.LabelField ("Client ID", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.LabelField (strPrefix(unityClientID.stringValue), GUILayout.Width(AppStoreStyles.kClientLabelWidthShort)); if (GUILayout.Button ("Copy to Clipboard", GUILayout.Height(AppStoreStyles.kClientLabelHeight))) { TextEditor te = new TextEditor (); te.text = unityClientID.stringValue; te.SelectAll (); te.Copy (); } } EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); if (String.IsNullOrEmpty (unityClientKey.stringValue)) { EditorGUILayout.LabelField ("Client Key", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.LabelField ("None"); } else { EditorGUILayout.LabelField ("Client Key", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.LabelField (strPrefix(unityClientKey.stringValue), GUILayout.Width(AppStoreStyles.kClientLabelWidthShort)); if (GUILayout.Button ("Copy to Clipboard", GUILayout.Height(AppStoreStyles.kClientLabelHeight))) { TextEditor te = new TextEditor (); te.text = unityClientKey.stringValue; te.SelectAll (); te.Copy (); } } EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); if (String.IsNullOrEmpty (unityClientRSAPublicKey.stringValue)) { EditorGUILayout.LabelField ("Client RSA Public Key", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.LabelField ("None"); } else { EditorGUILayout.LabelField ("Client RSA Public Key", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.LabelField (strPrefix(unityClientRSAPublicKey.stringValue), GUILayout.Width(AppStoreStyles.kClientLabelWidthShort)); if (GUILayout.Button ("Copy to Clipboard", GUILayout.Height(AppStoreStyles.kClientLabelHeight))) { TextEditor te = new TextEditor (); te.text = unityClientRSAPublicKey.stringValue; te.SelectAll (); te.Copy (); } } EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginHorizontal(); if (String.IsNullOrEmpty (clientSecret_in_memory)) { EditorGUILayout.LabelField ("Client Secret", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.LabelField ("None"); } else { EditorGUILayout.LabelField ("Client Secret", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.LabelField (strPrefix(clientSecret_in_memory), GUILayout.Width(AppStoreStyles.kClientLabelWidthShort)); if (GUILayout.Button ("Copy to Clipboard", GUILayout.Height(AppStoreStyles.kClientLabelHeight))) { TextEditor te = new TextEditor (); te.text = clientSecret_in_memory; te.SelectAll (); te.Copy (); } } EditorGUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.Label("Callback URL", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); callbackUrl_in_memory = EditorGUILayout.TextField (String.IsNullOrEmpty(callbackUrl_in_memory)? "" : callbackUrl_in_memory); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); } GUILayout.BeginVertical(); GUILayout.Space(10); GUILayout.EndVertical(); // Xiaomi application settings. EditorGUILayout.LabelField(new GUIContent("Xiaomi App Settings")); GUILayout.BeginVertical(); GUILayout.Space(2); GUILayout.EndVertical(); using (new EditorGUILayout.VerticalScope("OL Box", GUILayout.Height(AppStoreStyles.kXiaomiBoxHeight))) { GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.Label("App ID", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.PropertyField (xiaomiAppID, GUIContent.none); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.Label("App Key", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.PropertyField (xiaomiAppKey, GUIContent.none); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.Label("App Secret", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); if (appSecret_hidden) { GUILayout.Label ("App Secret is Hidden"); } else { appSecret_in_memory = EditorGUILayout.TextField (String.IsNullOrEmpty (appSecret_in_memory) ? "" : appSecret_in_memory); } string hiddenButtonLabel = appSecret_hidden ? "Show" : "Hide"; if (GUILayout.Button (hiddenButtonLabel, GUILayout.Width(AppStoreStyles.kClientLabelWidthShort), GUILayout.Height(AppStoreStyles.kClientLabelHeightShort))) { appSecret_hidden = !appSecret_hidden; } GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.Label("Test Mode", GUILayout.Width(AppStoreStyles.kClientLabelWidth)); EditorGUILayout.PropertyField (xiaomiIsTestMode, GUIContent.none); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); } GUILayout.BeginVertical(); GUILayout.Space(10); GUILayout.EndVertical(); // Save the settings. EditorGUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Save All Settings", GUILayout.Width(AppStoreStyles.kSaveButtonWidth))) { isOperationRunning = true; Debug.Log ("Saving..."); if (clientNotExists) { Debug.LogError ("Please get/generate Unity Client first."); } else { if (callbackUrl_last != callbackUrl_in_memory || appId_last != xiaomiAppID.stringValue || appKey_last != xiaomiAppKey.stringValue || appSecret_last != appSecret_in_memory) { callApiAsync (STEP_UPDATE_CLIENT); } else { isOperationRunning = false; Debug.Log ("Unity Client Refreshed. Finished: " + STEP_UPDATE_CLIENT); } } serializedObject.ApplyModifiedProperties(); this.Repaint (); AssetDatabase.SaveAssets(); } GUILayout.FlexibleSpace(); EditorGUILayout.EndHorizontal(); serializedObject.ApplyModifiedProperties(); this.Repaint (); EditorGUI.EndDisabledGroup(); } string strPrefix(string str) { var preIndex = str.Length < 5 ? str.Length : 5; return str.Substring (0, preIndex) + "..."; } void callApiAsync(String targetStep) { if (targetStep == STEP_GET_CLIENT) { AppStoreOnboardApi.tokenInfo.access_token = null; } if (AppStoreOnboardApi.tokenInfo.access_token == null) { UnityOAuth.GetAuthorizationCodeAsync (AppStoreOnboardApi.oauthClientId, (response) => { if (response.AuthCode != null) { string authcode = response.AuthCode; UnityWebRequest request = AppStoreOnboardApi.GetAccessToken (authcode); TokenInfo tokenInfoResp = new TokenInfo (); ReqStruct reqStruct = new ReqStruct (); reqStruct.request = request; reqStruct.resp = tokenInfoResp; reqStruct.targetStep = targetStep; requestQueue.Enqueue (reqStruct); } else { Debug.Log ("Failed: " + response.Exception.ToString ()); isOperationRunning = false; } }); } else { UnityWebRequest request = AppStoreOnboardApi.GetUserId (); UserIdResponse userIdResp = new UserIdResponse (); ReqStruct reqStruct = new ReqStruct (); reqStruct.request = request; reqStruct.resp = userIdResp; reqStruct.targetStep = targetStep; requestQueue.Enqueue (reqStruct); } } void OnDestroy() { EditorApplication.update -= CheckUpdate; } void CheckUpdate() { CheckRequestUpdate(); } void InitializeSecrets() { // No need to initialize for invalid client settings. if (String.IsNullOrEmpty(unityClientID.stringValue)) { return; } if (!String.IsNullOrEmpty(clientSecret_in_memory)) { return; } // Start secret initialization. isOperationRunning = true; Debug.Log ("Loading existed client info..."); callApiAsync (STEP_GET_CLIENT); } void CheckRequestUpdate() { if (requestQueue.Count <= 0) { return; } ReqStruct reqStruct = requestQueue.Dequeue (); UnityWebRequest request = reqStruct.request; GeneralResponse resp = reqStruct.resp; if (request != null && request.isDone) { if (request.error != null) { if (request.responseCode == 404) { Debug.LogError ("Resouce not found."); isOperationRunning = false; } else if (request.responseCode == 403) { Debug.LogError ("Permision denied."); isOperationRunning = false; } else { Debug.LogError (request.error); isOperationRunning = false; } } else { if (request.downloadHandler.text.Contains(AppStoreOnboardApi.tokenExpiredInfo)) { UnityWebRequest newRequest = AppStoreOnboardApi.RefreshToken(); TokenInfo tokenInfoResp = new TokenInfo(); ReqStruct newReqStruct = new ReqStruct(); newReqStruct.request = newRequest; newReqStruct.resp = tokenInfoResp; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue(newReqStruct); } else { if (resp.GetType () == typeof(TokenInfo)) { resp = JsonUtility.FromJson<TokenInfo> (request.downloadHandler.text); AppStoreOnboardApi.tokenInfo.access_token = ((TokenInfo)resp).access_token; if (AppStoreOnboardApi.tokenInfo.refresh_token == null || AppStoreOnboardApi.tokenInfo.refresh_token == "") { AppStoreOnboardApi.tokenInfo.refresh_token = ((TokenInfo)resp).refresh_token; } UnityWebRequest newRequest = AppStoreOnboardApi.GetUserId (); UserIdResponse userIdResp = new UserIdResponse (); ReqStruct newReqStruct = new ReqStruct (); newReqStruct.request = newRequest; newReqStruct.resp = userIdResp; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue (newReqStruct); } else if (resp.GetType () == typeof(UserIdResponse)) { resp = JsonUtility.FromJson<UserIdResponse> (request.downloadHandler.text); AppStoreOnboardApi.userId = ((UserIdResponse)resp).sub; UnityWebRequest newRequest = AppStoreOnboardApi.GetOrgId (Application.cloudProjectId); OrgIdResponse orgIdResp = new OrgIdResponse (); ReqStruct newReqStruct = new ReqStruct (); newReqStruct.request = newRequest; newReqStruct.resp = orgIdResp; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue (newReqStruct); } else if (resp.GetType () == typeof(OrgIdResponse)) { resp = JsonUtility.FromJson<OrgIdResponse> (request.downloadHandler.text); AppStoreOnboardApi.orgId = ((OrgIdResponse)resp).org_foreign_key; UnityWebRequest newRequest = AppStoreOnboardApi.GetOrgRoles (); OrgRoleResponse orgRoleResp = new OrgRoleResponse (); ReqStruct newReqStruct = new ReqStruct (); newReqStruct.request = newRequest; newReqStruct.resp = orgRoleResp; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue (newReqStruct); } else if (resp.GetType () == typeof(OrgRoleResponse)) { resp = JsonUtility.FromJson<OrgRoleResponse> (request.downloadHandler.text); if (resp == null) { Debug.LogError ("Permision denied."); isOperationRunning = false; } List<string> roles = ((OrgRoleResponse)resp).roles; if (roles.Contains ("owner")) { ownerAuthed = true; if (reqStruct.targetStep == STEP_GET_CLIENT) { UnityWebRequest newRequest = AppStoreOnboardApi.GetUnityClientInfo (Application.cloudProjectId); UnityClientResponseWrapper clientRespWrapper = new UnityClientResponseWrapper (); ReqStruct newReqStruct = new ReqStruct (); newReqStruct.request = newRequest; newReqStruct.resp = clientRespWrapper; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue (newReqStruct); } else if (reqStruct.targetStep == STEP_UPDATE_CLIENT) { UnityClientInfo unityClientInfo = new UnityClientInfo(); unityClientInfo.ClientId = unityClientID.stringValue; string callbackUrl = callbackUrl_in_memory; // read xiaomi from user input XiaomiSettings xiaomi = new XiaomiSettings(); xiaomi.appId = xiaomiAppID.stringValue; xiaomi.appKey = xiaomiAppKey.stringValue; xiaomi.appSecret = appSecret_in_memory; UnityWebRequest newRequest = AppStoreOnboardApi.UpdateUnityClient (Application.cloudProjectId, unityClientInfo, xiaomi, callbackUrl); UnityClientResponse clientResp = new UnityClientResponse (); ReqStruct newReqStruct = new ReqStruct (); newReqStruct.request = newRequest; newReqStruct.resp = clientResp; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue (newReqStruct); } else if (reqStruct.targetStep == STEP_UPDATE_CLIENT_SECRET) { string clientId = unityClientID.stringValue; UnityWebRequest newRequest = AppStoreOnboardApi.UpdateUnityClientSecret (clientId); UnityClientResponse clientResp = new UnityClientResponse (); ReqStruct newReqStruct = new ReqStruct (); newReqStruct.request = newRequest; newReqStruct.resp = clientResp; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue (newReqStruct); } } else if (roles.Contains ("user") || roles.Contains ("manager")) { ownerAuthed = false; if (reqStruct.targetStep == STEP_GET_CLIENT) { UnityWebRequest newRequest = AppStoreOnboardApi.GetUnityClientInfo (Application.cloudProjectId); UnityClientResponseWrapper clientRespWrapper = new UnityClientResponseWrapper (); ReqStruct newReqStruct = new ReqStruct (); newReqStruct.request = newRequest; newReqStruct.resp = clientRespWrapper; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue (newReqStruct); } else { Debug.LogError ("Permision denied."); isOperationRunning = false; } } else { Debug.LogError ("Permision denied."); isOperationRunning = false; } } else if (resp.GetType () == typeof(UnityClientResponseWrapper)) { string raw = "{ \"array\": " + request.downloadHandler.text + "}"; resp = JsonUtility.FromJson<UnityClientResponseWrapper> (raw); // only one element in the list if (((UnityClientResponseWrapper)resp).array.Length > 0) { UnityClientResponse unityClientResp = ((UnityClientResponseWrapper)resp).array [0]; unityClientID.stringValue = unityClientResp.client_id; unityClientKey.stringValue = unityClientResp.client_secret; unityClientRSAPublicKey.stringValue = unityClientResp.channel.publicRSAKey; clientSecret_in_memory = unityClientResp.channel.channelSecret; callbackUrl_in_memory = unityClientResp.channel.callbackUrl; callbackUrl_last = callbackUrl_in_memory; foreach (ThirdPartySettingsResponse thirdPartySetting in unityClientResp.channel.thirdPartySettings) { if (thirdPartySetting.appType.Equals (AppStoreOnboardApi.xiaomiAppType, StringComparison.InvariantCultureIgnoreCase)) { xiaomiAppID.stringValue = thirdPartySetting.appId; xiaomiAppKey.stringValue = thirdPartySetting.appKey; appSecret_in_memory = thirdPartySetting.appSecret; appId_last = xiaomiAppID.stringValue; appKey_last = xiaomiAppKey.stringValue; appSecret_last = appSecret_in_memory; } } AppStoreOnboardApi.updateRev = unityClientResp.rev; Debug.Log ("Unity Client Refreshed. Finished: " + reqStruct.targetStep); AppStoreOnboardApi.loaded = true; isOperationRunning = false; serializedObject.ApplyModifiedProperties(); this.Repaint (); AssetDatabase.SaveAssets(); } else { // no client found, generate one. if (ownerAuthed) { UnityClientInfo unityClientInfo = new UnityClientInfo (); string callbackUrl = callbackUrl_in_memory; // read xiaomi from user input XiaomiSettings xiaomi = new XiaomiSettings (); xiaomi.appId = xiaomiAppID.stringValue; xiaomi.appKey = xiaomiAppKey.stringValue; xiaomi.appSecret = appSecret_in_memory; UnityWebRequest newRequest = AppStoreOnboardApi.GenerateUnityClient (Application.cloudProjectId, unityClientInfo, xiaomi, callbackUrl); UnityClientResponse clientResp = new UnityClientResponse (); ReqStruct newReqStruct = new ReqStruct (); newReqStruct.request = newRequest; newReqStruct.resp = clientResp; newReqStruct.targetStep = reqStruct.targetStep; requestQueue.Enqueue (newReqStruct); } else { Debug.LogError ("Permision denied."); isOperationRunning = false; } } } else if (resp.GetType () == typeof(UnityClientResponse)) { resp = JsonUtility.FromJson<UnityClientResponse> (request.downloadHandler.text); unityClientID.stringValue = ((UnityClientResponse)resp).client_id; unityClientKey.stringValue = ((UnityClientResponse)resp).client_secret; unityClientRSAPublicKey.stringValue = ((UnityClientResponse)resp).channel.publicRSAKey; clientSecret_in_memory = ((UnityClientResponse)resp).channel.channelSecret; callbackUrl_in_memory = ((UnityClientResponse)resp).channel.callbackUrl; callbackUrl_last = callbackUrl_in_memory; foreach (ThirdPartySettingsResponse thirdPartySetting in ((UnityClientResponse)resp).channel.thirdPartySettings) { if (thirdPartySetting.appType.Equals (AppStoreOnboardApi.xiaomiAppType, StringComparison.InvariantCultureIgnoreCase)) { xiaomiAppID.stringValue = thirdPartySetting.appId; xiaomiAppKey.stringValue = thirdPartySetting.appKey; appSecret_in_memory = thirdPartySetting.appSecret; appId_last = xiaomiAppID.stringValue; appKey_last = xiaomiAppKey.stringValue; appSecret_last = appSecret_in_memory; } } AppStoreOnboardApi.updateRev = ((UnityClientResponse)resp).rev; Debug.Log ("Unity Client Refreshed. Finished: " + reqStruct.targetStep); AppStoreOnboardApi.loaded = true; isOperationRunning = false; serializedObject.ApplyModifiedProperties(); this.Repaint (); AssetDatabase.SaveAssets(); } } } } else { requestQueue.Enqueue (reqStruct); } } } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Net.Security; using System.Runtime.InteropServices; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Threading; namespace System.Net { internal static partial class CertificateValidationPal { private static readonly object s_syncObject = new object(); private static volatile X509Store s_myCertStoreEx; private static volatile X509Store s_myMachineCertStoreEx; internal static SslPolicyErrors VerifyCertificateProperties( X509Chain chain, X509Certificate2 remoteCertificate, bool checkCertName, bool isServer, string hostName) { SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; if (!chain.Build(remoteCertificate) // Build failed on handle or on policy. && chain.SafeHandle.DangerousGetHandle() == IntPtr.Zero) // Build failed to generate a valid handle. { throw new CryptographicException(Marshal.GetLastWin32Error()); } if (checkCertName) { unsafe { uint status = 0; var eppStruct = new Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA() { cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.SSL_EXTRA_CERT_CHAIN_POLICY_PARA>(), dwAuthType = isServer ? Interop.Crypt32.AuthType.AUTHTYPE_SERVER : Interop.Crypt32.AuthType.AUTHTYPE_CLIENT, fdwChecks = 0, pwszServerName = null }; var cppStruct = new Interop.Crypt32.CERT_CHAIN_POLICY_PARA() { cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CHAIN_POLICY_PARA>(), dwFlags = 0, pvExtraPolicyPara = &eppStruct }; fixed (char* namePtr = hostName) { eppStruct.pwszServerName = namePtr; cppStruct.dwFlags |= (Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_ALL & ~Interop.Crypt32.CertChainPolicyIgnoreFlags.CERT_CHAIN_POLICY_IGNORE_INVALID_NAME_FLAG); SafeX509ChainHandle chainContext = chain.SafeHandle; status = Verify(chainContext, ref cppStruct); if (status == Interop.Crypt32.CertChainPolicyErrors.CERT_E_CN_NO_MATCH) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNameMismatch; } } } } X509ChainStatus[] chainStatusArray = chain.ChainStatus; if (chainStatusArray != null && chainStatusArray.Length != 0) { sslPolicyErrors |= SslPolicyErrors.RemoteCertificateChainErrors; } return sslPolicyErrors; } // // Extracts a remote certificate upon request. // internal static X509Certificate2 GetRemoteCertificate(SafeDeleteContext securityContext, out X509Certificate2Collection remoteCertificateCollection) { remoteCertificateCollection = null; if (securityContext == null) { return null; } if (GlobalLog.IsEnabled) { GlobalLog.Enter("CertificateValidationPal.Windows SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetRemoteCertificate()"); } X509Certificate2 result = null; SafeFreeCertContext remoteContext = null; try { remoteContext = SSPIWrapper.QueryContextAttributes(GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.RemoteCertificate) as SafeFreeCertContext; if (remoteContext != null && !remoteContext.IsInvalid) { result = new X509Certificate2(remoteContext.DangerousGetHandle()); } } finally { if (remoteContext != null && !remoteContext.IsInvalid) { remoteCertificateCollection = UnmanagedCertificateContext.GetRemoteCertificatesFromStoreContext(remoteContext); remoteContext.Dispose(); } } if (SecurityEventSource.Log.IsEnabled()) { SecurityEventSource.Log.RemoteCertificate(result == null ? "null" : result.ToString(true)); } if (GlobalLog.IsEnabled) { GlobalLog.Leave("CertificateValidationPal.Windows SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetRemoteCertificate()", (result == null ? "null" : result.Subject)); } return result; } // // Used only by client SSL code, never returns null. // internal static string[] GetRequestCertificateAuthorities(SafeDeleteContext securityContext) { Interop.SspiCli.IssuerListInfoEx issuerList = (Interop.SspiCli.IssuerListInfoEx)SSPIWrapper.QueryContextAttributes( GlobalSSPI.SSPISecureChannel, securityContext, Interop.SspiCli.ContextAttribute.IssuerListInfoEx); string[] issuers = Array.Empty<string>(); try { if (issuerList.cIssuers > 0) { unsafe { uint count = issuerList.cIssuers; issuers = new string[issuerList.cIssuers]; Interop.SspiCli._CERT_CHAIN_ELEMENT* pIL = (Interop.SspiCli._CERT_CHAIN_ELEMENT*)issuerList.aIssuers.DangerousGetHandle(); for (int i = 0; i < count; ++i) { Interop.SspiCli._CERT_CHAIN_ELEMENT* pIL2 = pIL + i; if (pIL2->cbSize <= 0) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecureChannel::GetIssuers()", "Interop.SspiCli._CERT_CHAIN_ELEMENT size is not positive: " + pIL2->cbSize.ToString()); } Debug.Fail("SecureChannel::GetIssuers()", "Interop.SspiCli._CERT_CHAIN_ELEMENT size is not positive: " + pIL2->cbSize.ToString()); } if (pIL2->cbSize > 0) { uint size = pIL2->cbSize; byte* ptr = (byte*)(pIL2->pCertContext); byte[] x = new byte[size]; for (int j = 0; j < size; j++) { x[j] = *(ptr + j); } X500DistinguishedName x500DistinguishedName = new X500DistinguishedName(x); issuers[i] = x500DistinguishedName.Name; if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(securityContext) + "::GetIssuers() IssuerListEx[" + i + "]:" + issuers[i]); } } } } } } finally { if (issuerList.aIssuers != null) { issuerList.aIssuers.Dispose(); } } return issuers; } // // Security: We temporarily reset thread token to open the cert store under process account. // internal static X509Store EnsureStoreOpened(bool isMachineStore) { X509Store store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; // TODO #3862 Investigate if this can be switched to either the static or Lazy<T> patterns. if (store == null) { lock (s_syncObject) { store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx; if (store == null) { // NOTE: that if this call fails we won't keep track and the next time we enter we will try to open the store again. StoreLocation storeLocation = isMachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser; store = new X509Store(StoreName.My, storeLocation); try { // For app-compat We want to ensure the store is opened under the **process** account. try { WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () => { store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel::EnsureStoreOpened() storeLocation:" + storeLocation + " returned store:" + store.GetHashCode().ToString("x")); } }); } catch { throw; } if (isMachineStore) { s_myMachineCertStoreEx = store; } else { s_myCertStoreEx = store; } return store; } catch (Exception exception) { if (exception is CryptographicException || exception is SecurityException) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SecureChannel::EnsureStoreOpened()", "Failed to open cert store, location:" + storeLocation + " exception:" + exception); } Debug.Fail("SecureChannel::EnsureStoreOpened()", "Failed to open cert store, location:" + storeLocation + " exception:" + exception); return null; } if (NetEventSource.Log.IsEnabled()) { NetEventSource.PrintError(NetEventSource.ComponentType.Security, SR.Format(SR.net_log_open_store_failed, storeLocation, exception)); } throw; } } } } return store; } private static uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp) { if (GlobalLog.IsEnabled) { GlobalLog.Enter("SecureChannel::VerifyChainPolicy", "chainContext=" + chainContext + ", options=" + String.Format("0x{0:x}", cpp.dwFlags)); } var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS(); status.cbSize = (uint)Marshal.SizeOf<Interop.Crypt32.CERT_CHAIN_POLICY_STATUS>(); bool errorCode = Interop.Crypt32.CertVerifyCertificateChainPolicy( (IntPtr)Interop.Crypt32.CertChainPolicy.CERT_CHAIN_POLICY_SSL, chainContext, ref cpp, ref status); if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel::VerifyChainPolicy() CertVerifyCertificateChainPolicy returned: " + errorCode); #if TRACE_VERBOSE GlobalLog.Print("SecureChannel::VerifyChainPolicy() error code: " + status.dwError + String.Format(" [0x{0:x8}", status.dwError) + " " + Interop.MapSecurityStatus(status.dwError) + "]"); #endif GlobalLog.Leave("SecureChannel::VerifyChainPolicy", status.dwError.ToString()); } return status.dwError; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.RegularExpressions; namespace NuGet { public static class PathResolver { /// <summary> /// Returns a collection of files from the source that matches the wildcard. /// </summary> /// <param name="source">The collection of files to match.</param> /// <param name="getPath">Function that returns the path to filter a package file </param> /// <param name="wildcards">The wildcard to apply to match the path with.</param> /// <returns></returns> public static IEnumerable<T> GetMatches<T>(IEnumerable<T> source, Func<T, string> getPath, IEnumerable<string> wildcards) where T : IPackageFile { IEnumerable<Regex> filters = wildcards.Select(WildcardToRegex); return source.Where(item => { string path = getPath(item); return filters.Any(f => f.IsMatch(path)); }); } /// <summary> /// Removes files from the source that match any wildcard. /// </summary> public static void FilterPackageFiles<T>(ICollection<T> source, Func<T, string> getPath, IEnumerable<string> wildcards) where T : IPackageFile { var matchedFiles = new HashSet<T>(GetMatches(source, getPath, wildcards)); source.RemoveAll(matchedFiles.Contains); } public static string NormalizeWildcard(string basePath, string wildcard) { basePath = NormalizeBasePath(basePath, ref wildcard); return Path.Combine(basePath, wildcard); } private static Regex WildcardToRegex(string wildcard) { return new Regex('^' + Regex.Escape(wildcard) .Replace(@"\*\*\\", ".*") //For recursive wildcards \**\, include the current directory. .Replace(@"\*\*", ".*") // For recursive wildcards that don't end in a slash e.g. **.txt would be treated as a .txt file at any depth .Replace(@"\*", @"[^\\]*(\\)?") // For non recursive searches, limit it any character that is not a directory separator .Replace(@"\?", ".") // ? translates to a single any character + '$', RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture); } internal static IEnumerable<PackageFileBase> ResolveSearchPattern(string basePath, string searchPath, string targetPath) { if (!searchPath.StartsWith(@"\\", StringComparison.OrdinalIgnoreCase)) { // If we aren't dealing with network paths, trim the leading slash. searchPath = searchPath.TrimStart(Path.DirectorySeparatorChar); } bool searchDirectory = false; // If the searchPath ends with \ or /, we treat searchPath as a directory, // and will include everything under it, recursively if (IsDirectoryPath(searchPath)) { searchPath = searchPath + "**" + Path.DirectorySeparatorChar + "*"; searchDirectory = true; } basePath = NormalizeBasePath(basePath, ref searchPath); string basePathToEnumerate = GetPathToEnumerateFrom(basePath, searchPath); // Append the basePath to searchPattern and get the search regex. We need to do this because the search regex is matched from line start. Regex searchRegex = WildcardToRegex(Path.Combine(basePath, searchPath)); // This is a hack to prevent enumerating over the entire directory tree if the only wildcard characters are the ones in the file name. // If the path portion of the search path does not contain any wildcard characters only iterate over the TopDirectory. SearchOption searchOption = SearchOption.AllDirectories; // (a) Path is not recursive search bool isRecursiveSearch = searchPath.IndexOf("**", StringComparison.OrdinalIgnoreCase) != -1; // (b) Path does not have any wildcards. bool isWildcardPath = Path.GetDirectoryName(searchPath).Contains('*'); if (!isRecursiveSearch && !isWildcardPath) { searchOption = SearchOption.TopDirectoryOnly; } // Starting from the base path, enumerate over all files and match it using the wildcard expression provided by the user. IEnumerable<string> files = Directory.EnumerateFiles(basePathToEnumerate, "*.*", searchOption); IEnumerable<PackageFileBase> matchedFiles = from file in files where searchRegex.IsMatch(file) let targetPathInPackage = ResolvePackagePath(basePathToEnumerate, searchPath, file, targetPath) select new PhysicalPackageFile(isTempFile: false, originalPath: file, targetPath: targetPathInPackage); if (searchDirectory && IsEmptyDirectory(basePathToEnumerate)) { matchedFiles = matchedFiles.Concat(new[] { new EmptyFolderFile(targetPath ?? String.Empty) }); } return matchedFiles; } internal static string GetPathToEnumerateFrom(string basePath, string searchPath) { string basePathToEnumerate; int wildcardIndex = searchPath.IndexOf('*'); if (wildcardIndex == -1) { // For paths without wildcard, we could either have base relative paths (such as lib\foo.dll) or paths outside the base path // (such as basePath: C:\packages and searchPath: D:\packages\foo.dll) // In this case, Path.Combine would pick up the right root to enumerate from. string searchRoot = Path.GetDirectoryName(searchPath); basePathToEnumerate = Path.Combine(basePath, searchRoot); } else { // If not, find the first directory separator and use the path to the left of it as the base path to enumerate from. int directorySeparatoryIndex = searchPath.LastIndexOf(Path.DirectorySeparatorChar, wildcardIndex); if (directorySeparatoryIndex == -1) { // We're looking at a path like "NuGet*.dll", NuGet*\bin\release\*.dll // In this case, the basePath would continue to be the path to begin enumeration from. basePathToEnumerate = basePath; } else { string nonWildcardPortion = searchPath.Substring(0, directorySeparatoryIndex); basePathToEnumerate = Path.Combine(basePath, nonWildcardPortion); } } return basePathToEnumerate; } /// <summary> /// Determins the path of the file inside a package. /// For recursive wildcard paths, we preserve the path portion beginning with the wildcard. /// For non-recursive wildcard paths, we use the file name from the actual file path on disk. /// </summary> internal static string ResolvePackagePath(string searchDirectory, string searchPattern, string fullPath, string targetPath) { string packagePath; bool isDirectorySearch = IsDirectoryPath(searchPattern); bool isWildcardSearch = IsWildcardSearch(searchPattern); bool isRecursiveWildcardSearch = isWildcardSearch && searchPattern.IndexOf("**", StringComparison.OrdinalIgnoreCase) != -1; if ((isRecursiveWildcardSearch || isDirectorySearch) && fullPath.StartsWith(searchDirectory, StringComparison.OrdinalIgnoreCase)) { // The search pattern is recursive. Preserve the non-wildcard portion of the path. // e.g. Search: X:\foo\**\*.cs results in SearchDirectory: X:\foo and a file path of X:\foo\bar\biz\boz.cs // Truncating X:\foo\ would result in the package path. packagePath = fullPath.Substring(searchDirectory.Length).TrimStart(Path.DirectorySeparatorChar); } else if (!isWildcardSearch && Path.GetExtension(searchPattern).Equals(Path.GetExtension(targetPath), StringComparison.OrdinalIgnoreCase)) { // If the search does not contain wild cards, and the target path shares the same extension, copy it // e.g. <file src="ie\css\style.css" target="Content\css\ie.css" /> --> Content\css\ie.css return targetPath; } else { packagePath = Path.GetFileName(fullPath); } return Path.Combine(targetPath ?? String.Empty, packagePath); } internal static string NormalizeBasePath(string basePath, ref string searchPath) { const string relativePath = @"..\"; // If no base path is provided, use the current directory. basePath = String.IsNullOrEmpty(basePath) ? @".\" : basePath; // If the search path is relative, transfer the ..\ portion to the base path. // This needs to be done because the base path determines the root for our enumeration. while (searchPath.StartsWith(relativePath, StringComparison.OrdinalIgnoreCase)) { basePath = Path.Combine(basePath, relativePath); searchPath = searchPath.Substring(relativePath.Length); } return Path.GetFullPath(basePath); } /// <summary> /// Returns true if the path contains any wildcard characters. /// </summary> internal static bool IsWildcardSearch(string filter) { return filter.IndexOf('*') != -1; } internal static bool IsDirectoryPath(string path) { return path != null && path.Length > 1 && path[path.Length - 1] == Path.DirectorySeparatorChar; } private static bool IsEmptyDirectory(string directory) { return !Directory.EnumerateFileSystemEntries(directory).Any(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections; using System.Globalization; using Xunit; using SortedList_SortedListUtils; namespace SortedListCtorIntIKeyComp { public class Driver<KeyType, ValueType> { private Test m_test; public Driver(Test test) { m_test = test; } private CultureInfo _english = new CultureInfo("en"); private CultureInfo _german = new CultureInfo("de"); private CultureInfo _danish = new CultureInfo("da"); private CultureInfo _turkish = new CultureInfo("tr"); //CompareString lcid_en-US, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 1, NULL_STRING //CompareString 0x10407, EMPTY_FLAGS, "AE", 0, 2, "\u00C4", 0, 1, 0, NULL_STRING //CompareString lcid_da-DK, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, -1, NULL_STRING //CompareString lcid_en-US, "NORM_IGNORECASE", "aA", 0, 2, "Aa", 0, 2, 0, NULL_STRING //CompareString lcid_tr-TR, "NORM_IGNORECASE", "\u0131", 0, 1, "\u0049", 0, 1, 0, NULL_STRING private const String strAE = "AE"; private const String strUC4 = "\u00C4"; private const String straA = "aA"; private const String strAa = "Aa"; private const String strI = "I"; private const String strTurkishUpperI = "\u0131"; private const String strBB = "BB"; private const String strbb = "bb"; private const String value = "Default_Value"; public void TestVanilla(int capacity) { SortedList<String, String> _dic; IComparer<String> comparer; IComparer<String>[] predefinedComparers = new IComparer<String>[] { StringComparer.CurrentCulture, StringComparer.CurrentCultureIgnoreCase, StringComparer.OrdinalIgnoreCase, StringComparer.Ordinal}; foreach (IComparer<String> predefinedComparer in predefinedComparers) { _dic = new SortedList<String, String>(capacity, predefinedComparer); m_test.Eval(_dic.Comparer == predefinedComparer, String.Format("Err_4568aijueud! Comparer differ expected: {0} actual: {1}", predefinedComparer, _dic.Comparer)); m_test.Eval(_dic.Count == 0, String.Format("Err_23497sg! Count different: {0}", _dic.Count)); m_test.Eval(((IDictionary<KeyType, ValueType>)_dic).IsReadOnly == false, String.Format("Err_435wsdg! Count different: {0}", ((IDictionary<KeyType, ValueType>)_dic).IsReadOnly)); m_test.Eval(_dic.Keys.Count == 0, String.Format("Err_25ag! Count different: {0}", _dic.Keys.Count)); m_test.Eval(_dic.Values.Count == 0, String.Format("Err_23agd! Count different: {0}", _dic.Values.Count)); } //Current culture CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.CurrentCulture; _dic = new SortedList<String, String>(capacity, comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_848652ahued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strAE, value); m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_235rdag! Wrong result returned: {0}", _dic.ContainsKey(strUC4))); //bug #11263 in NDPWhidbey CultureInfo.DefaultThreadCurrentCulture = _german; comparer = StringComparer.CurrentCulture; _dic = new SortedList<String, String>(capacity, comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_54848ahuede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strAE, value); m_test.Eval(!_dic.ContainsKey(strUC4), String.Format("Err_23r7ag! Wrong result returned: {0}", _dic.ContainsKey(strUC4))); //CurrentCultureIgnoreCase CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.CurrentCultureIgnoreCase; _dic = new SortedList<String, String>(capacity, comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_788989ajeude! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(straA, value); m_test.Eval(_dic.ContainsKey(strAa), String.Format("Err_237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; comparer = StringComparer.CurrentCultureIgnoreCase; _dic = new SortedList<String, String>(capacity, comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_54878aheuid! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); //OrdinalIgnoreCase CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.OrdinalIgnoreCase; _dic = new SortedList<String, String>(capacity, comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_5588ahied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strI, value); m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234qf! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI))); CultureInfo.DefaultThreadCurrentCulture = _turkish; comparer = StringComparer.OrdinalIgnoreCase; _dic = new SortedList<String, String>(capacity, comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_8488ahiued! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strI, value); m_test.Eval(!_dic.ContainsKey(strTurkishUpperI), String.Format("Err_234ra7g! Wrong result returned: {0}", _dic.ContainsKey(strTurkishUpperI))); //Ordinal - not that many meaningful test CultureInfo.DefaultThreadCurrentCulture = _english; comparer = StringComparer.Ordinal; _dic = new SortedList<String, String>(capacity, comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_488ahede! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strBB, value); m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_1244sd! Wrong result returned: {0}", _dic.ContainsKey(strbb))); CultureInfo.DefaultThreadCurrentCulture = _danish; comparer = StringComparer.Ordinal; _dic = new SortedList<String, String>(capacity, comparer); m_test.Eval(_dic.Comparer == comparer, String.Format("Err_05848ahied! Comparer differ expected: {0} actual: {1}", comparer, _dic.Comparer)); _dic.Add(strBB, value); m_test.Eval(!_dic.ContainsKey(strbb), String.Format("Err_235aeg! Wrong result returned: {0}", _dic.ContainsKey(strbb))); } public void TestParm() { //passing null will revert to the default comparison mechanism SortedList<String, String> _dic; IComparer<String> comparer = null; try { CultureInfo.DefaultThreadCurrentCulture = _english; _dic = new SortedList<String, String>(0, comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_9237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_90723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); } catch (Exception ex) { m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex)); } int[] negativeValues = { -1, -2, -5, Int32.MinValue }; comparer = StringComparer.CurrentCulture; for (int i = 0; i < negativeValues.Length; i++) { try { _dic = new SortedList<String, String>(negativeValues[i], comparer); m_test.Eval(false, String.Format("Err_387tsg! No exception thrown")); } catch (ArgumentOutOfRangeException) { } catch (Exception ex) { m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex)); } } } public void IkeyComparerOwnImplementation(int capacity) { //This just ensure that we can call our own implementation SortedList<String, String> _dic; IComparer<String> comparer = new MyOwnIKeyImplementation<String>(); try { CultureInfo.DefaultThreadCurrentCulture = _english; _dic = new SortedList<String, String>(capacity, comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_0237g! Wrong result returned: {0}", _dic.ContainsKey(strAa))); CultureInfo.DefaultThreadCurrentCulture = _danish; _dic = new SortedList<String, String>(comparer); _dic.Add(straA, value); m_test.Eval(!_dic.ContainsKey(strAa), String.Format("Err_00723f! Wrong result returned: {0}", _dic.ContainsKey(strAa))); } catch (Exception ex) { m_test.Eval(false, String.Format("Err_387tsg! Wrong exception thrown: {0}", ex)); } } } public class Constructor_int_IKeyComparer { [Fact] [ActiveIssue(5460, PlatformID.AnyUnix)] public static void RunTests() { //This mostly follows the format established by the original author of these tests //These tests mostly uses the scenarios that were used in the individual constructors Test test = new Test(); Driver<String, String> driver1 = new Driver<String, String>(test); //Scenario 1: Pass all the enum values and ensure that the behavior is correct int[] validCapacityValues = { 0, 1, 2, 5, 10, 16, 32, 50, 500, 5000, 10000 }; for (int i = 0; i < validCapacityValues.Length; i++) driver1.TestVanilla(validCapacityValues[i]); //Scenario 2: Parm validation: null for IKeyComparer and negative for capacity driver1.TestParm(); //Scenario 3: Implement our own IKeyComparer and check for (int i = 0; i < validCapacityValues.Length; i++) driver1.IkeyComparerOwnImplementation(validCapacityValues[i]); Assert.True(test.result); } } //[Serializable] internal class MyOwnIKeyImplementation<KeyType> : IComparer<KeyType> { public int GetHashCode(KeyType key) { //We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly return key.GetHashCode(); } public int Compare(KeyType key1, KeyType key2) { //We cannot get the hascode that is culture aware here since TextInfo doesn't expose this functionality publicly return key1.GetHashCode(); } public bool Equals(KeyType key1, KeyType key2) { return key1.Equals(key2); } } }
// Copyright 2021 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Cloud.Spanner.Data; using NHibernate.Cache; using NHibernate.Engine; using NHibernate.Mapping; using NHibernate.Persister.Entity; using NHibernate.SqlCommand; using NHibernate.Util; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Spanner.NHibernate { /// <summary> /// EntityPersister implementation for Cloud Spanner for entities that use a single /// table. This persister can generate commands that use mutations instead of DML /// when that is appropriate or requested by the client application. /// /// In addition, this persister can be used with tables that contain one or more columns that should be /// set to a fixed value when inserted/updated. The fixed value must be given as a string literal, and may be /// a server side function, such as PENDING_COMMIT_TIMESTAMP(). /// /// The persister will automatically set the value of a column to the fixed value of that column for any column /// that fulfills the following criteria: /// 1. INSERT: Default value of the column is not null and the column is not insertable in the Hibernate config. /// 2. UPDATE: Default value of the column is not null and the column is not insertable in the Hibernate config. /// /// The following example mapping will for example cause the ColCommitTs column to be set to /// PENDING_COMMIT_TIMESTAMP() for both insert and update statements: /// /// <code> /// Persister&lt;SpannerSingleTableWithFixedValuesEntityPersister&gt;(); /// Property(x => x.ColCommitTs, mapper => /// { /// mapper.Insert(false); /// mapper.Update(false); /// mapper.Column(c => /// { /// c.Default("PENDING_COMMIT_TIMESTAMP()"); /// }); /// } /// ); /// </code> /// </summary> public class SpannerSingleTableEntityPersister : SingleTableEntityPersister { // These maps contain the default values that should be set when a record is inserted // or updated, and no value has been set by NHibernate. private readonly LinkedHashMap<string, string> _defaultInsertValues = new LinkedHashMap<string, string>(); private readonly LinkedHashMap<string, string> _defaultUpdateValues = new LinkedHashMap<string, string>(); private readonly bool[][] _propertyColumnInsertable; private readonly bool _discriminatorInsertable; public SpannerSingleTableEntityPersister(PersistentClass persistentClass, ICacheConcurrencyStrategy cache, ISessionFactoryImplementor factory, IMapping mapping) : base(persistentClass, cache, factory, mapping) { var hydrateSpan = EntityMetamodel.PropertySpan; _propertyColumnInsertable = new bool[hydrateSpan][]; var i = 0; foreach (var prop in persistentClass.PropertyClosureIterator) { _propertyColumnInsertable[i] = prop.Value.ColumnInsertability; foreach (var col in prop.ColumnIterator.OfType<Column>()) { if (col.DefaultValue != null) { if (!prop.IsInsertable) { _defaultInsertValues[col.Name] = col.DefaultValue; } if (!prop.IsUpdateable) { _defaultUpdateValues[col.Name] = col.DefaultValue; } } } i++; } if (persistentClass.IsPolymorphic) { if (persistentClass.IsDiscriminatorValueNull) { _discriminatorInsertable = false; } else if (persistentClass.IsDiscriminatorValueNotNull) { _discriminatorInsertable = false; } else { var discriminatorValue = persistentClass.Discriminator; _discriminatorInsertable = persistentClass.IsDiscriminatorInsertable && !discriminatorValue.HasFormula; } } else { _discriminatorInsertable = false; } } protected override void AddDiscriminatorToInsert(SqlInsertBuilder insert) { base.AddDiscriminatorToInsert(insert); foreach (var col in _defaultInsertValues.Keys) { insert.AddColumn(col, _defaultInsertValues[col]); } } private SqlCommandInfo AppendUpdateString(SqlCommandInfo info) { if (_defaultUpdateValues.Count == 0) { return info; } if (!(info.Text is SpannerMutationSqlString spannerMutationSqlString)) { return info; } // This is safe because we know that the SQL string is a simple statement in the form: // UPDATE Foo SET Col1 = ?, Col2 = ?, ... WHERE ColId = ? var whereIndex = spannerMutationSqlString.LastIndexOfCaseInsensitive(" WHERE "); if (whereIndex > -1) { SqlString dmlSqlString = spannerMutationSqlString; foreach (var col in _defaultUpdateValues.Keys) { dmlSqlString = dmlSqlString.Insert(whereIndex, $", {col} = {_defaultUpdateValues[col]}"); } spannerMutationSqlString = new SpannerMutationSqlString(dmlSqlString, spannerMutationSqlString.Operation, spannerMutationSqlString.Table, spannerMutationSqlString.Columns, spannerMutationSqlString.CheckVersionText, spannerMutationSqlString.WhereColumns, spannerMutationSqlString.WhereParamsStartIndex, spannerMutationSqlString.IsVersioned); foreach (var col in _defaultUpdateValues.Keys) { var spannerParameter = CreateSpannerParameter(col, _defaultUpdateValues[col]); spannerMutationSqlString.AdditionalParameters.Add(spannerParameter); } } return new SqlCommandInfo(spannerMutationSqlString, info.ParameterTypes); } private static SpannerParameter CreateSpannerParameter(string col, object value) { var spannerParameter = new SpannerParameter { ParameterName = col }; if ("PENDING_COMMIT_TIMESTAMP()".Equals(value?.ToString() ?? "", StringComparison.OrdinalIgnoreCase)) { spannerParameter.Value = SpannerParameter.CommitTimestamp; spannerParameter.SpannerDbType = SpannerDbType.Timestamp; } else { spannerParameter.Value = value; } return spannerParameter; } protected override SqlCommandInfo GenerateInsertString(bool identityInsert, bool[] includeProperty, int j) { var sql = base.GenerateInsertString(identityInsert, includeProperty, j); return AddInsertColumnInformation(sql, includeProperty, j); } protected override void UpdateOrInsert(object id, object[] fields, object[] oldFields, object rowId, bool[] includeProperty, int j, object oldVersion, object obj, SqlCommandInfo sql, ISessionImplementor session) { sql = AddUpdateColumnInformation(sql, j); base.UpdateOrInsert(id, fields, oldFields, rowId, includeProperty, j, oldVersion, obj, sql, session); } protected override Task UpdateOrInsertAsync(object id, object[] fields, object[] oldFields, object rowId, bool[] includeProperty, int j, object oldVersion, object obj, SqlCommandInfo sql, ISessionImplementor session, CancellationToken cancellationToken) { sql = AddUpdateColumnInformation(sql, j); return base.UpdateOrInsertAsync(id, fields, oldFields, rowId, includeProperty, j, oldVersion, obj, sql, session, cancellationToken); } protected override SqlCommandInfo GenerateDeleteString(int j) { var sql = base.GenerateDeleteString(j); return AddDeleteColumnInformation(sql, j); } protected virtual SqlCommandInfo AddInsertColumnInformation(SqlCommandInfo sql, bool[] includeProperty, int j) { var columns = new List<string>(); // add normal properties for (var i = 0; i < EntityMetamodel.PropertySpan; i++) { if (includeProperty[i] && IsPropertyOfTable(i, j)) { AddInsertColumns(columns, GetPropertyColumnNames(i), _propertyColumnInsertable[i]); } } // add the primary key foreach (var col in GetKeyColumns(j)) { columns.Add(col); } var spannerMutationSqlString = new SpannerMutationSqlString(sql.Text, "INSERT", GetTableName(j), columns.ToArray()); // Add the discriminator. if (j == 0 && _discriminatorInsertable) { var spannerParameter = CreateSpannerParameter(DiscriminatorColumnName, DiscriminatorValue); spannerMutationSqlString.AdditionalParameters.Add(spannerParameter); } // Add default values. foreach (var col in _defaultInsertValues.Keys) { var spannerParameter = CreateSpannerParameter(col, _defaultInsertValues[col]); spannerMutationSqlString.AdditionalParameters.Add(spannerParameter); } return new SqlCommandInfo(spannerMutationSqlString, sql.ParameterTypes); } protected virtual SqlCommandInfo AddUpdateColumnInformation(SqlCommandInfo sql, int j) { var table = GetTableName(j); var columns = new List<string>(); var isVersioned = j == 0 && IsVersioned && EntityMetamodel.OptimisticLockMode == Versioning.OptimisticLock.Version; var checkVersionBuilder = new SqlStringBuilder().Add($"SELECT 1 AS C FROM {table}"); var whereColumns = new List<string>(); var inWhereClause = false; foreach (var part in sql.Text) { if (part == null) { continue; } var content = part.ToString()!.Trim(); if (content.StartsWith("WHERE", StringComparison.InvariantCultureIgnoreCase)) { inWhereClause = true; } if (inWhereClause) { if (content.EndsWith("=")) { var column = ExtractColumnNameFromUpdateStatementPart(content, table); if (!column.Equals(VersionColumnName, StringComparison.InvariantCultureIgnoreCase)) { columns.Add(column); } whereColumns.Add(column); } if (content.Equals("?")) { checkVersionBuilder.AddParameter(); } else { checkVersionBuilder.Add(part.ToString()); } } else { if (content.EndsWith("=")) { columns.Add(ExtractColumnNameFromUpdateStatementPart(content, table)); } } } // The columns that are added to the mutation command also include the key columns. // The WHERE parameters therefore start at the number of columns minus the number of key columns. var whereParamsStartIndex = columns.Count - GetKeyColumns(j).Length; var sqlString = new SpannerMutationSqlString(sql.Text, "UPDATE", table, columns.ToArray(), checkVersionBuilder.ToSqlString(), whereColumns.ToArray(), whereParamsStartIndex, isVersioned); return AppendUpdateString(new SqlCommandInfo(sqlString, sql.ParameterTypes)); } private SqlCommandInfo AddDeleteColumnInformation(SqlCommandInfo sql, int j) { var keyColumns = GetKeyColumns(j); var columns = new List<string>(); var checkVersionBuilder = new SqlStringBuilder().Add($"SELECT 1 AS C FROM {GetTableName(j)}"); var whereColumns = new List<string>(); // add the primary key var first = true; foreach (var col in keyColumns) { columns.Add(col); whereColumns.Add(col); if (first) { checkVersionBuilder = checkVersionBuilder.Add(" WHERE "); first = false; } else { checkVersionBuilder = checkVersionBuilder.Add(" AND "); } checkVersionBuilder.Add(col + " = ").AddParameter(); } var isVersioned = j == 0 && IsVersioned && EntityMetamodel.OptimisticLockMode == Versioning.OptimisticLock.Version; if (isVersioned) { whereColumns.Add(VersionColumnName); checkVersionBuilder.Add(" AND " + VersionColumnName + " = ").AddParameter(); } var sqlString = new SpannerMutationSqlString(sql.Text, "DELETE", GetTableName(j), columns.ToArray(), checkVersionBuilder.ToSqlString(), whereColumns.ToArray(), 0, isVersioned); return new SqlCommandInfo(sqlString, sql.ParameterTypes); } /// <summary> /// Adds the array of column names to the list of columns for each column that is insertable. /// </summary> /// <param name="columns">The list of columns to add the column names</param> /// <param name="columnNames">The column names to add</param> /// <param name="insertable">An array indicating which columns are insertable</param> private static void AddInsertColumns(List<string> columns, string[] columnNames, bool[] insertable) { for (int i = 0; i < columnNames.Length; i++) { if (insertable == null || insertable[i]) { columns.Add(columnNames[i]); } } } /// <summary> /// Removes ', ' from the start and ' = ' from the end of the string. /// </summary> /// <param name="part">The sql part to trim</param> /// <param name="table">The table that is being updated</param> /// <returns>The trimmed sql part</returns> private static string ExtractColumnNameFromUpdateStatementPart(string part, string table) { var column = part; int index; var updatePrefix = $"UPDATE {table} SET "; var wherePrefix = "WHERE "; var andPrefix = "AND "; if (part.StartsWith(",") && part.EndsWith("=")) { column = part.Substring(1, part.Length-2); } else if (part.StartsWith(wherePrefix) && part.EndsWith("=")) { column = part.Substring(wherePrefix.Length, part.Length - wherePrefix.Length - 1); } else if (part.StartsWith(andPrefix) && part.EndsWith("=")) { column = part.Substring(andPrefix.Length, part.Length - andPrefix.Length - 1); } else if (part.EndsWith("=") && (index = part.LastIndexOf(updatePrefix, StringComparison.InvariantCultureIgnoreCase)) > -1) { column = part.Substring(index + updatePrefix.Length, part.Length - updatePrefix.Length - index - 1); } return column.Trim(); } } }
// --------------------------------------------------------------------------- // <copyright company="Microsoft Corporation" file="XmlDiffViewElement.cs"> // Copyright (c) Microsoft Corporation 2005 // </copyright> // <project> // XmlDiffView // </project> // <summary> // Summary description for this file // </summary> // <history> // [barryw] 03MAR05 Created // </history> // --------------------------------------------------------------------------- namespace Microsoft.XmlDiffPatch { using System; using System.IO; using System.Xml; using System.Diagnostics; /// <summary> /// Class to generate output for xml elements. /// </summary> internal class XmlDiffViewElement : XmlDiffViewParentNode { #region Member variables section // name private string localName; private string prefix; private string namespaceUri; private string name; // attributes private XmlDiffViewAttribute attributes; private bool ignorePrefixes; #endregion #region Constructors section /// <summary> /// Constructor. /// </summary> /// <param name="localName">Element node name</param> /// <param name="prefix">xml node prefix</param> /// <param name="namespaceUri">Uniform Resource Identifier (URI) /// </param> /// <param name="ignorePrefix">Ignore differences in the prefix</param> public XmlDiffViewElement( string localName, string prefix, string namespaceUri, bool ignorePrefix) : base(XmlNodeType.Element) { this.LocalName = localName; this.Prefix = prefix; this.NamespaceUri = namespaceUri; if (this.Prefix != string.Empty) { this.Name = this.Prefix + ":" + this.LocalName; } else { this.Name = this.LocalName; } this.ignorePrefixes = ignorePrefix; } #endregion #region Properties section /// <summary> /// Gets or sets an attributes object. /// </summary> public XmlDiffViewAttribute Attributes { get { return this.attributes; } set { this.attributes = value; } } /// <summary> /// Returns and exception("OuterXml is not /// supported on XmlDiffViewElement. /// </summary> public override string OuterXml { get { string message = "OuterXml is not supported" + " on XmlDiffViewElement."; throw new Exception(message); } } /// <summary> /// Gets or sets the name of the element without the prefix. /// </summary> public string LocalName { get { return this.localName; } set { this.localName = value; } } /// <summary> /// Gets or sets the prefix. /// </summary> public string Prefix { get { return this.prefix; } set { this.prefix = value; } } /// <summary> /// Gets or sets the namespace Uniform Resource Identifier (URI) /// </summary> public string NamespaceUri { get { return this.namespaceUri; } set { this.namespaceUri = value; } } /// <summary> /// Gets or set the name of the element with the prefix. /// </summary> public string Name { get { return this.name; } set { this.name = value; } } #endregion #region Methods section /// <summary> /// Gets an attribute object for the specified attribute name. /// </summary> /// <param name="name">attribute name</param> /// <returns>an attribute object</returns> public XmlDiffViewAttribute GetAttribute(string name) { XmlDiffViewAttribute curAttr = this.Attributes; while (curAttr != null) { if (curAttr.Name == name && curAttr.Operation == XmlDiffViewOperation.Match) { return curAttr; } curAttr = (XmlDiffViewAttribute)curAttr.NextSibbling; } return null; } /// <summary> /// Inserts an attribute object after the specified attribute object. /// </summary> /// <param name="newAttr">the attribute object to insert</param> /// <param name="refAttr">attribute object to insert after</param> public void InsertAttributeAfter( XmlDiffViewAttribute newAttr, XmlDiffViewAttribute refAttr) { Debug.Assert(newAttr != null); if (refAttr == null) { newAttr.NextSibbling = this.Attributes; this.Attributes = newAttr; } else { newAttr.NextSibbling = refAttr.NextSibbling; refAttr.NextSibbling = newAttr; } newAttr.Parent = this; } /// <summary> /// Creates a complete copy of the current node. /// </summary> /// <param name="deep">has child nodes</param> /// <returns>A copy of the current node</returns> internal override XmlDiffViewNode Clone(bool deep) { XmlDiffViewElement newElement = new XmlDiffViewElement( this.LocalName, this.Prefix, this.NamespaceUri, this.ignorePrefixes); // attributes { XmlDiffViewAttribute curAttr = this.Attributes; XmlDiffViewAttribute lastNewAtt = null; while (curAttr != null) { XmlDiffViewAttribute newAttr = (XmlDiffViewAttribute)curAttr.Clone(true); newElement.InsertAttributeAfter(newAttr, lastNewAtt); lastNewAtt = newAttr; curAttr = (XmlDiffViewAttribute)curAttr.NextSibbling; } } if (!deep) { return newElement; } // child nodes { XmlDiffViewNode curChild = ChildNodes; XmlDiffViewNode lastNewChild = null; while (curChild != null) { XmlDiffViewNode newChild = curChild.Clone(true); newElement.InsertChildAfter(newChild, lastNewChild, false); lastNewChild = newChild; curChild = curChild.NextSibbling; } } return newElement; } /// <summary> /// Generates output data in html form /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> internal override void DrawHtml(XmlWriter writer, int indent) { XmlDiffViewOperation typeOfDifference = Operation; bool closeElement = false; XmlDiffView.HtmlStartRow(writer); this.DrawLinkNode(writer); for (int i = 0; i < 2; i++) { XmlDiffView.HtmlStartCell(writer, indent); if (XmlDiffView.HtmlWriteToPane[(int)Operation, i]) { closeElement = OutputNavigationHtml(writer); if (Operation == XmlDiffViewOperation.Change) { typeOfDifference = XmlDiffViewOperation.Match; XmlDiffView.HtmlWriteString( writer, typeOfDifference, Tags.XmlOpenBegin); if (i == 0) { this.DrawHtmlNameChange( writer, this.LocalName, this.Prefix); } else { this.DrawHtmlNameChange( writer, ChangeInformation.LocalName, ChangeInformation.Prefix); } } else { this.DrawHtmlName( writer, typeOfDifference, Tags.XmlOpenBegin, string.Empty); } if (closeElement) { // write the closing '</A>' tag. writer.WriteEndElement(); closeElement = false; } // attributes this.DrawHtmlAttributes(writer, i); // close start tag if (ChildNodes != null) { XmlDiffView.HtmlWriteString( writer, typeOfDifference, Tags.XmlOpenEnd); } else { XmlDiffView.HtmlWriteString( writer, typeOfDifference, Tags.XmlOpenEndTerse); } } else { XmlDiffView.HtmlWriteEmptyString(writer); } XmlDiffView.HtmlEndCell(writer); } XmlDiffView.HtmlEndRow(writer); // child nodes if (ChildNodes != null) { HtmlDrawChildNodes(writer, indent + XmlDiffView.DeltaIndent); // end element XmlDiffView.HtmlStartRow(writer); this.DrawLinkNode(writer); for (int i = 0; i < 2; i++) { XmlDiffView.HtmlStartCell(writer, indent); if (XmlDiffView.HtmlWriteToPane[(int)Operation, i]) { if (Operation == XmlDiffViewOperation.Change) { Debug.Assert(typeOfDifference == XmlDiffViewOperation.Match); XmlDiffView.HtmlWriteString( writer, typeOfDifference, Tags.XmlCloseBegin); if (i == 0) { this.DrawHtmlNameChange( writer, this.LocalName, this.Prefix); } else { this.DrawHtmlNameChange( writer, ChangeInformation.LocalName, ChangeInformation.Prefix); } XmlDiffView.HtmlWriteString( writer, typeOfDifference, Tags.XmlOpenEnd); } else { this.DrawHtmlName( writer, typeOfDifference, Tags.XmlCloseBegin, Tags.XmlCloseEnd); } } else { XmlDiffView.HtmlWriteEmptyString(writer); } XmlDiffView.HtmlEndCell(writer); } XmlDiffView.HtmlEndRow(writer); } } /// <summary> /// Generates output data in text form /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> internal override void DrawText( TextWriter writer, int indent) { Debug.Assert(XmlNodeType.Element == NodeType); switch (Operation) { case XmlDiffViewOperation.Add: this.DrawTextNameAdd( writer, indent, Tags.XmlOpenBegin, string.Empty); break; case XmlDiffViewOperation.Change: this.DrawTextNameChange( writer, indent, Tags.XmlOpenBegin, string.Empty); break; case XmlDiffViewOperation.Ignore: case XmlDiffViewOperation.Match: // No change or ignored /* write out the element but leave the * tag open in case there are attributes. */ this.DrawTextName( writer, indent, Tags.XmlOpenBegin, string.Empty); break; case XmlDiffViewOperation.MoveFrom: this.DrawTextNameMoveFrom( writer, indent, Tags.XmlOpenBegin, string.Empty); break; case XmlDiffViewOperation.MoveTo: this.DrawTextNameMoveTo( writer, indent, Tags.XmlOpenBegin, string.Empty); break; case XmlDiffViewOperation.Remove: this.DrawTextNameDelete( writer, indent, Tags.XmlOpenBegin, string.Empty); break; default: Debug.Assert(false); break; } // attributes this.DrawTextAttributes(writer, indent); // if there is children if (ChildNodes != null) { // close start tag writer.Write(Tags.XmlOpenEnd + writer.NewLine); // process child nodes TextDrawChildNodes(writer, indent); // end element this.DrawTextName( writer, indent, Tags.XmlCloseBegin, Tags.XmlCloseEnd + writer.NewLine); } else { // avoid the need for closing node name tag writer.Write(Tags.XmlOpenEndTerse + writer.NewLine); } } /// <summary> /// Generates attributes' output data in html form /// </summary> /// <param name="writer">output stream</param> /// <param name="paneNo">Pane number, indicating /// the left (baseline) or right side (actual) of the /// display</param> private void DrawHtmlAttributes( XmlWriter writer, int paneNo) { if (this.Attributes == null) { return; } string attrIndent = string.Empty; if (this.Attributes.NextSibbling != null) { attrIndent = XmlDiffView.GetIndent(this.Name.Length + 2); } XmlDiffViewAttribute curAttr = this.Attributes; while (curAttr != null) { if (XmlDiffView.HtmlWriteToPane[(int)curAttr.Operation, paneNo]) { if (curAttr == this.Attributes) { writer.WriteString(" "); } else { writer.WriteRaw(attrIndent); } if (curAttr.Operation == XmlDiffViewOperation.Change) { if (paneNo == 0) { this.DrawHtmlAttributeChange( writer, curAttr, curAttr.LocalName, curAttr.Prefix, curAttr.AttributeValue); } else { this.DrawHtmlAttributeChange( writer, curAttr, curAttr.ChangeInformation.LocalName, curAttr.ChangeInformation.Prefix, curAttr.ChangeInformation.Subset); } } else { this.DrawHtmlAttribute( writer, curAttr, curAttr.Operation); } } else { XmlDiffView.HtmlWriteEmptyString(writer); } curAttr = (XmlDiffViewAttribute)curAttr.NextSibbling; if (curAttr != null) { XmlDiffView.HtmlBr(writer); } } } /// <summary> /// Generates atrributes' output data in text form /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> private void DrawTextAttributes( TextWriter writer, int indent) { if (this.Attributes != null) { indent += Indent.IncrementSize; XmlDiffViewAttribute curAttr = this.Attributes; while (curAttr != null) { if (curAttr == this.Attributes) { writer.Write(" "); } else { // put subsequent attributes on their own line writer.Write( writer.NewLine + XmlDiffView.IndentText(indent)); } // The attributes could have their own // 'add'/'remove'/'move from'/ 'move to'/match/ignore // attribute operations so we check for that now switch (curAttr.Operation) { case XmlDiffViewOperation.Change: this.DrawTextAttributeChange(writer, curAttr); break; case XmlDiffViewOperation.Add: case XmlDiffViewOperation.Ignore: case XmlDiffViewOperation.MoveFrom: case XmlDiffViewOperation.MoveTo: case XmlDiffViewOperation.Remove: case XmlDiffViewOperation.Match: // for 'add'/'remove'/'move from'/'move to'/match // operations write out the baseline attributes // data. this.DrawTextAttribute(writer, curAttr); break; default: // raise exception for new type of // difference created in XmlDiff object. throw new ArgumentException( "Unrecognised type of difference", "Operation"); } curAttr = (XmlDiffViewAttribute)curAttr.NextSibbling; } } } /// <summary> /// Generates output data in html form for a difference due to /// a change in element name. /// </summary> /// <param name="writer">output stream</param> /// <param name="localName">name of the /// element (without the prefix)</param> /// <param name="prefix">prefix</param> private void DrawHtmlNameChange( XmlWriter writer, string localName, string prefix) { if (prefix != string.Empty) { XmlDiffView.HtmlWriteString( writer, this.ignorePrefixes ? XmlDiffViewOperation.Ignore : (prefix == ChangeInformation.Prefix) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change, prefix + ":"); } XmlDiffView.HtmlWriteString( writer, (localName == ChangeInformation.LocalName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change, localName); } /// <summary> /// Generates output data in text form for a difference due /// to adding data. /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> /// <param name="tagStart">xml tags at start of statement</param> /// <param name="tagEnd">xml tags at end of statement</param> private void DrawTextNameAdd( TextWriter writer, int indent, string tagStart, string tagEnd) { writer.Write(XmlDiffView.IndentText(indent) + tagStart); if (this.Prefix != string.Empty) { writer.Write(this.Prefix + ":"); } writer.Write(Difference.Tag + Difference.NodeAdded + this.LocalName); writer.Write(tagEnd); } /// <summary> /// Generates output data in text form for a difference due /// to deleting data. /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> /// <param name="tagStart">xml tags at start of statement</param> /// <param name="tagEnd">xml tags at end of statement</param> private void DrawTextNameDelete( TextWriter writer, int indent, string tagStart, string tagEnd) { writer.Write(XmlDiffView.IndentText(indent) + tagStart); if (this.Prefix != string.Empty) { writer.Write(this.Prefix + ":"); } writer.Write(this.LocalName + " " + Difference.Tag + Difference.NodeDeleted); writer.Write(tagEnd); } /// <summary> /// Generates output data in text form for a difference due /// to changing existing data. /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> /// <param name="tagStart">xml tags at start of statement</param> /// <param name="tagEnd">xml tags at end of statement</param> private void DrawTextNameChange( TextWriter writer, int indent, string tagStart, string tagEnd) { writer.Write(XmlDiffView.IndentText(indent) + tagStart); if (this.Prefix != string.Empty) { writer.Write(this.Prefix + ":"); } writer.Write(Difference.Tag + Difference.ChangeBegin + this.LocalName + Difference.ChangeTo + ChangeInformation.LocalName + Difference.ChangeEnd); writer.Write(tagEnd); } /// <summary> /// Generates output data in text form for a difference due /// to moving data from a location. /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> /// <param name="tagStart">xml tags at start of statement</param> /// <param name="tagEnd">xml tags at end of statement</param> private void DrawTextNameMoveFrom( TextWriter writer, int indent, string tagStart, string tagEnd) { writer.Write(XmlDiffView.IndentText(indent) + tagStart); if (this.Prefix != string.Empty) { writer.Write(this.Prefix + ":"); } writer.Write(this.LocalName + " " + Difference.Tag + Difference.NodeMovedFromBegin + OperationId + Difference.NodeMovedFromEnd); writer.Write(tagEnd); } /// <summary> /// Generates output data in text form for a difference due /// to moving data to a new location. /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> /// <param name="tagStart">xml tags at start of statement</param> /// <param name="tagEnd">xml tags at end of statement</param> private void DrawTextNameMoveTo( TextWriter writer, int indent, string tagStart, string tagEnd) { writer.Write(XmlDiffView.IndentText(indent) + tagStart); if (this.Prefix == string.Empty) { writer.Write(this.Prefix + ":"); } writer.Write(this.LocalName + " " + Difference.Tag + Difference.NodeMovedToBegin + OperationId + Difference.NodeMovedToEnd); writer.Write(tagEnd); } /// <summary> /// Generates output data in text form for a difference due /// to adding data. /// </summary> /// <param name="writer">output stream</param> /// <param name="typeOfDifference">type of difference</param> /// <param name="tagStart">xml tags at start of statement</param> /// <param name="tagEnd">xml tags at end of statement</param> private void DrawHtmlName( XmlWriter writer, XmlDiffViewOperation typeOfDifference, string tagStart, string tagEnd) { if (this.Prefix != string.Empty && this.ignorePrefixes) { XmlDiffView.HtmlWriteString( writer, typeOfDifference, tagStart); XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Ignore, this.Prefix + ":"); XmlDiffView.HtmlWriteString( writer, typeOfDifference, this.LocalName + tagEnd); } else { XmlDiffView.HtmlWriteString( writer, typeOfDifference, tagStart + this.Name + tagEnd); } } /// <summary> /// Generates output data in text form for the name of the element. /// </summary> /// <param name="writer">output stream</param> /// <param name="indent">number of indentations</param> /// <param name="tagStart">xml tags at start of statement</param> /// <param name="tagEnd">xml tags at end of statement</param> private void DrawTextName( TextWriter writer, int indent, string tagStart, string tagEnd) { if (this.Prefix != string.Empty && this.ignorePrefixes) { writer.Write( XmlDiffView.IndentText(indent) + tagStart + this.Prefix + ":" + this.LocalName + tagEnd); } else { writer.Write(XmlDiffView.IndentText(indent) + tagStart + this.Name + tagEnd); } } /// <summary> /// Generates output data in html for a difference due /// to changing attribute data. /// </summary> /// <param name="writer">output stream</param> /// <param name="attr">Attribute object</param> /// <param name="localName">name of attribute /// (without the prefix)</param> /// <param name="prefix">xml attribute prefix</param> /// <param name="attributeValue">The value for the attribute.</param> private void DrawHtmlAttributeChange( XmlWriter writer, XmlDiffViewAttribute attr, string localName, string prefix, string attributeValue) { if (prefix != string.Empty) { XmlDiffView.HtmlWriteString( writer, this.ignorePrefixes ? XmlDiffViewOperation.Ignore : (attr.Prefix == attr.ChangeInformation.Prefix) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change, prefix + ":"); } XmlDiffView.HtmlWriteString( writer, (attr.LocalName == attr.ChangeInformation.LocalName) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change, this.localName); if (attr.AttributeValue != attr.ChangeInformation.Subset) { XmlDiffView.HtmlWriteString(writer, "=\""); XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Change, attributeValue); XmlDiffView.HtmlWriteString(writer, "\""); } else { XmlDiffView.HtmlWriteString( writer, "=\"" + attributeValue + "\""); } } /// <summary> /// Generate text output data for a differences /// due to a change, which may or may not have been /// a change in the attribute. /// </summary> /// <param name="writer">output stream</param> /// <param name="attr">Attribute object</param> private void DrawTextAttributeChange( TextWriter writer, XmlDiffViewAttribute attr) { Debug.Assert(null != attr); if (this.Prefix != string.Empty) { //if the prefix changed then show the change XmlDiffViewOperation op = this.ignorePrefixes ? XmlDiffViewOperation.Ignore : (attr.Prefix == attr.ChangeInformation.Prefix) ? XmlDiffViewOperation.Match : XmlDiffViewOperation.Change; switch (op) { case XmlDiffViewOperation.Ignore: case XmlDiffViewOperation.Match: writer.Write(attr.Prefix + ":"); break; case XmlDiffViewOperation.Change: // show the new prefix writer.Write( Difference.Tag + "=" + Difference.ChangeBegin + attr.Prefix + Difference.ChangeTo + attr.ChangeInformation.Prefix + Difference.ChangeEnd); writer.Write(attr.ChangeInformation.Prefix + ":"); break; default: Trace.WriteLine("Unexpected type of difference"); throw new ArgumentException( "Unexpected type of difference", "Operation"); } } if (System.Diagnostics.Debugger.IsAttached) { string debugMessage = "It is not appropriate to call this function" + "when the ChangeInformation object is null."; Debug.Assert( null != attr.ChangeInformation, debugMessage); } // something changed if (attr.LocalName != attr.ChangeInformation.LocalName) { // show the change in the name writer.Write(" " + attr.LocalName + "=\"" + Difference.Tag + "RenamedNode" + Difference.ChangeTo + attr.ChangeInformation.LocalName + Difference.ChangeEnd + "="); } else { writer.Write(" " + attr.LocalName + "=\""); } // determine if the attribute value has changed if (attr.AttributeValue != attr.ChangeInformation.Subset) { // attribute value changed //Note: "xd_ChangeFrom('original value')To('new value')" string attributeValueChange = Difference.Tag + Difference.ChangeBegin + attr.AttributeValue + Difference.ChangeTo + RemoveTabsAndNewlines(attr.ChangeInformation.Subset) + Difference.ChangeEnd; writer.Write(attributeValueChange + "\""); } else { // attribute value is same writer.Write( RemoveTabsAndNewlines(attr.AttributeValue) + "\""); } } /// <summary> /// Generate html output data for a differences /// due to a change in an attribute. /// </summary> /// <param name="writer">output stream</param> /// <param name="attr">Attribute object</param> /// <param name="typeOfDifference">type of difference</param> private void DrawHtmlAttribute( XmlWriter writer, XmlDiffViewAttribute attr, XmlDiffViewOperation typeOfDifference) { if (this.ignorePrefixes) { if (attr.Prefix == "xmlns" || (attr.LocalName == "xmlns" && attr.Prefix == string.Empty)) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Ignore, attr.Name); XmlDiffView.HtmlWriteString( writer, typeOfDifference, "=\"" + attr.AttributeValue + "\""); return; } else if (attr.Prefix != string.Empty) { XmlDiffView.HtmlWriteString( writer, XmlDiffViewOperation.Ignore, attr.Prefix + ":"); XmlDiffView.HtmlWriteString( writer, typeOfDifference, attr.LocalName + "=\"" + attr.AttributeValue + "\""); return; } } XmlDiffView.HtmlWriteString( writer, typeOfDifference, attr.Name + "=\"" + attr.AttributeValue + "\""); } /// <summary> /// Generate text output data for an unchanged attribute. /// </summary> /// <param name="writer">output stream</param> /// <param name="attr">attribute object</param> private void DrawTextAttribute( TextWriter writer, XmlDiffViewAttribute attr) { if (this.ignorePrefixes) { if (attr.Prefix == "xmlns" || (attr.LocalName == "xmlns" && attr.Prefix == string.Empty)) { writer.Write(attr.Name); writer.Write("='" + RemoveTabsAndNewlines(attr.AttributeValue) + "'"); return; } else if (attr.Prefix != string.Empty) { writer.Write(attr.Prefix + ":"); writer.Write(attr.LocalName + "=\"" + RemoveTabsAndNewlines(attr.AttributeValue) + "\""); return; } } writer.Write(attr.Name + "=\"" + RemoveTabsAndNewlines(attr.AttributeValue) + "\""); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.Versioning; using NuGet.Resources; namespace NuGet { public class InstallWalker : PackageWalker, IPackageOperationResolver { private readonly bool _ignoreDependencies; private bool _allowPrereleaseVersions; private readonly OperationLookup _operations; private bool _isDowngrade; // This acts as a "retainment" queue. It contains packages that are already installed but need to be kept during // a package walk. This is to prevent those from being uninstalled in subsequent encounters. private readonly HashSet<IPackage> _packagesToKeep = new HashSet<IPackage>(PackageEqualityComparer.IdAndVersion); private IDictionary<string, IList<IPackage>> _packagesByDependencyOrder; // this ctor is used for unit tests internal InstallWalker(IPackageRepository localRepository, IDependencyResolver2 dependencyResolver, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions, DependencyVersion dependencyVersion) : this(localRepository, dependencyResolver, null, logger, ignoreDependencies, allowPrereleaseVersions, dependencyVersion) { } public InstallWalker(IPackageRepository localRepository, IDependencyResolver2 dependencyResolver, FrameworkName targetFramework, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions, DependencyVersion dependencyVersion) : this(localRepository, dependencyResolver, constraintProvider: NullConstraintProvider.Instance, targetFramework: targetFramework, logger: logger, ignoreDependencies: ignoreDependencies, allowPrereleaseVersions: allowPrereleaseVersions, dependencyVersion: dependencyVersion) { } public InstallWalker(IPackageRepository localRepository, IDependencyResolver2 dependencyResolver, IPackageConstraintProvider constraintProvider, FrameworkName targetFramework, ILogger logger, bool ignoreDependencies, bool allowPrereleaseVersions, DependencyVersion dependencyVersion) : base(targetFramework) { if (dependencyResolver == null) { throw new ArgumentNullException("dependencyResolver"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } if (logger == null) { throw new ArgumentNullException("logger"); } Repository = localRepository; Logger = logger; DependencyResolver = dependencyResolver; _ignoreDependencies = ignoreDependencies; ConstraintProvider = constraintProvider; _operations = new OperationLookup(); _allowPrereleaseVersions = allowPrereleaseVersions; DependencyVersion = dependencyVersion; CheckDowngrade = true; } internal bool DisableWalkInfo { get; set; } /// <summary> /// Indicates if this object checks the downgrade case. /// </summary> /// <remarks> /// Currently there is a concurrent issue: if there are multiple "nuget.exe install" running /// concurrently, then checking local repository for existing packages to see /// if current install is downgrade can generate file in use exception. /// This property is a temporary workaround: it is set to false when /// this object is called by "nuget.exe install/restore". /// </remarks> internal bool CheckDowngrade { get; set; } protected override bool IgnoreWalkInfo { get { return DisableWalkInfo ? true : base.IgnoreWalkInfo; } } protected ILogger Logger { get; private set; } protected IPackageRepository Repository { get; private set; } protected override bool IgnoreDependencies { get { return _ignoreDependencies; } } protected override bool AllowPrereleaseVersions { get { return _allowPrereleaseVersions; } } protected IDependencyResolver2 DependencyResolver { get; private set; } private IPackageConstraintProvider ConstraintProvider { get; set; } protected IList<PackageOperation> Operations { get { return _operations.ToList(); } } protected virtual ConflictResult GetConflict(IPackage package) { var conflictingPackage = Marker.FindPackage(package.Id); if (conflictingPackage != null) { return new ConflictResult(conflictingPackage, Marker, Marker); } return null; } protected override void OnBeforePackageWalk(IPackage package) { ConflictResult conflictResult = GetConflict(package); if (conflictResult == null) { return; } // If the conflicting package is the same as the package being installed // then no-op if (PackageEqualityComparer.IdAndVersion.Equals(package, conflictResult.Package)) { return; } // First we get a list of dependents for the installed package. // Then we find the dependency in the foreach dependent that this installed package used to satisfy. // We then check if the resolved package also meets that dependency and if it doesn't it's added to the list // i.e. A1 -> C >= 1 // B1 -> C >= 1 // C2 -> [] // Given the above graph, if we upgrade from C1 to C2, we need to see if A and B can work with the new C var incompatiblePackages = from dependentPackage in GetDependents(conflictResult) let dependency = dependentPackage.FindDependency(package.Id, TargetFramework) where dependency != null && !dependency.VersionSpec.Satisfies(package.Version) select dependentPackage; // If there were incompatible packages that we failed to update then we throw an exception if (incompatiblePackages.Any() && !TryUpdate(incompatiblePackages, conflictResult, package, out incompatiblePackages)) { throw CreatePackageConflictException(package, conflictResult.Package, incompatiblePackages); } else { if (!_isDowngrade && (package.Version < conflictResult.Package.Version)) { throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.NewerVersionAlreadyReferenced, package.Id)); } Uninstall(conflictResult.Package, conflictResult.DependentsResolver, conflictResult.Repository); } } private void Uninstall(IPackage package, IDependentsResolver dependentsResolver, IPackageRepository repository) { // If we explicitly want to uninstall this package, then remove it from the retainment queue. _packagesToKeep.Remove(package); // If this package isn't part of the current graph (i.e. hasn't been visited yet) and // is marked for removal, then do nothing. This is so we don't get unnecessary duplicates. if (!Marker.Contains(package) && _operations.Contains(package, PackageAction.Uninstall)) { return; } // Uninstall the conflicting package. We set throw on conflicts to false since we've // already decided that there were no conflicts based on the above code. var resolver = new UninstallWalker( repository, dependentsResolver, TargetFramework, NullLogger.Instance, removeDependencies: !IgnoreDependencies, forceRemove: false) { DisableWalkInfo = this.DisableWalkInfo, ThrowOnConflicts = false }; foreach (var operation in resolver.ResolveOperations(package)) { // If the operation is Uninstall, we don't want to uninstall the package if it is in the "retainment" queue. if (operation.Action == PackageAction.Install || !_packagesToKeep.Contains(operation.Package)) { _operations.AddOperation(operation); } } } private IPackage SelectDependency(IEnumerable<IPackage> dependencies) { return dependencies.SelectDependency(DependencyVersion); } private static IEnumerable<IPackage> FindCompatiblePackages( IDependencyResolver2 dependencyResolver, IPackageConstraintProvider constraintProvider, IEnumerable<string> packageIds, IPackage package, FrameworkName targetFramework, bool allowPrereleaseVersions) { return (from p in dependencyResolver.FindPackages(packageIds) where allowPrereleaseVersions || p.IsReleaseVersion() let dependency = p.FindDependency(package.Id, targetFramework) let otherConstaint = constraintProvider.GetConstraint(p.Id) where dependency != null && dependency.VersionSpec.Satisfies(package.Version) && (otherConstaint == null || otherConstaint.Satisfies(package.Version)) select p); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We re-throw a more specific exception later on")] private bool TryUpdate(IEnumerable<IPackage> dependents, ConflictResult conflictResult, IPackage package, out IEnumerable<IPackage> incompatiblePackages) { // Key dependents by id so we can look up the old package later var dependentsLookup = dependents.ToDictionary(d => d.Id, StringComparer.OrdinalIgnoreCase); var compatiblePackages = new Dictionary<IPackage, IPackage>(); // Initialize each compatible package to null foreach (var dependent in dependents) { compatiblePackages[dependent] = null; } // Get compatible packages in one batch so we don't have to make requests for each one var packages = from p in FindCompatiblePackages( DependencyResolver, ConstraintProvider, dependentsLookup.Keys, package, TargetFramework, AllowPrereleaseVersions) group p by p.Id into g let oldPackage = dependentsLookup[g.Key] select new { OldPackage = oldPackage, NewPackage = SelectDependency(g.Where(p => p.Version > oldPackage.Version) .OrderBy(p => p.Version)) }; foreach (var p in packages) { compatiblePackages[p.OldPackage] = p.NewPackage; } // Get all packages that have an incompatibility with the specified package i.e. // We couldn't find a version in the repository that works with the specified package. incompatiblePackages = compatiblePackages.Where(p => p.Value == null) .Select(p => p.Key); if (incompatiblePackages.Any()) { return false; } IPackageConstraintProvider currentConstraintProvider = ConstraintProvider; try { // Add a constraint for the incoming package so we don't try to update it by mistake. // Scenario: // A 1.0 -> B [1.0] // B 1.0.1, B 1.5, B 2.0 // A 2.0 -> B (any version) // We have A 1.0 and B 1.0 installed. When trying to update to B 1.0.1, we'll end up trying // to find a version of A that works with B 1.0.1. The version in the above case is A 2.0. // When we go to install A 2.0 we need to make sure that when we resolve it's dependencies that we stay within bounds // i.e. when we resolve B for A 2.0 we want to keep the B 1.0.1 we've already chosen instead of trying to grab // B 1.5 or B 2.0. In order to achieve this, we add a constraint for version of B 1.0.1 so we stay within those bounds for B. // Respect all existing constraints plus an additional one that we specify based on the incoming package var constraintProvider = new DefaultConstraintProvider(); constraintProvider.AddConstraint(package.Id, new VersionSpec(package.Version)); ConstraintProvider = new AggregateConstraintProvider(ConstraintProvider, constraintProvider); // Mark the incoming package as visited so that we don't try walking the graph again Marker.MarkVisited(package); var failedPackages = new List<IPackage>(); // Update each of the existing packages to more compatible one foreach (var pair in compatiblePackages) { try { // // BUGBUG: What if the new package required license acceptance but the new dependency package did not?! // When a dependency package that does not require license acceptance, like jQuery 1.7.1.1, // is being updated to a version incompatible with its dependents, like jQuery 2.0.3 and its dependent Microsoft.jQuery.Unobtrusive.Ajax 2.0.20710.0 // Then, the dependent package is updated such that the new dependent package is compatible with the new dependency package // In the example above, Microsoft.jQuery.Unobtrusive.Ajax 2.0.20710.0 will be updated to 2.0.30506.0. 2.0.30506.0 requires license acceptance // But, the update happens anyways, just because, the user chose to update jQuery // // Remove the old package Uninstall(pair.Key, conflictResult.DependentsResolver, conflictResult.Repository); // Install the new package Walk(pair.Value); } catch { // If we failed to update this package (most likely because of a conflict further up the dependency chain) // we keep track of it so we can report an error about the top level package. failedPackages.Add(pair.Key); } } incompatiblePackages = failedPackages; return !incompatiblePackages.Any(); } finally { // Restore the current constraint provider ConstraintProvider = currentConstraintProvider; // Mark the package as processing again Marker.MarkProcessing(package); } } protected override void OnAfterPackageWalk(IPackage package) { if (!Repository.Exists(package)) { // Don't add the package for installation if it already exists in the repository var operation = new PackageOperation(package, PackageAction.Install); var packageTarget = GetPackageTarget(package); if (packageTarget == PackageTargets.External) { operation.Target = PackageOperationTarget.PackagesFolder; }; _operations.AddOperation(operation); } else { // If we already added an entry for removing this package then remove it // (it's equivalent for doing +P since we're removing a -P from the list) _operations.RemoveOperation(package, PackageAction.Uninstall); // and mark the package as being "retained". _packagesToKeep.Add(package); } if (_packagesByDependencyOrder != null) { IList<IPackage> packages; if (!_packagesByDependencyOrder.TryGetValue(package.Id, out packages)) { _packagesByDependencyOrder[package.Id] = packages = new List<IPackage>(); } packages.Add(package); } } protected override IPackage ResolveDependency(PackageDependency dependency) { Logger.Log(MessageLevel.Info, NuGetResources.Log_AttemptingToRetrievePackageFromSource, dependency); // First try to get a local copy of the package // Bug1638: Include prereleases when resolving locally installed dependencies. //Prerelease is included when we try to look at the local repository. //In case of downgrade, we are going to look only at source repo and not local. //That way we will downgrade dependencies when parent package is downgraded. if (!_isDowngrade) { IPackage package = DependencyResolveUtility.ResolveDependency(Repository, dependency, ConstraintProvider, allowPrereleaseVersions: true, preferListedPackages: false, dependencyVersion: DependencyVersion); if (package != null) { return package; } } // Next, query the source repo for the same dependency IPackage sourcePackage = DependencyResolver.ResolveDependency(dependency, ConstraintProvider, AllowPrereleaseVersions, preferListedPackages: true, dependencyVersion: DependencyVersion); return sourcePackage; } protected override void OnDependencyResolveError(PackageDependency dependency) { IVersionSpec spec = ConstraintProvider.GetConstraint(dependency.Id); string message = String.Empty; if (spec != null) { message = String.Format(CultureInfo.CurrentCulture, NuGetResources.AdditonalConstraintsDefined, dependency.Id, VersionUtility.PrettyPrint(spec), ConstraintProvider.Source); } throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnableToResolveDependency + message, dependency)); } public IEnumerable<PackageOperation> ResolveOperations(IPackage package) { // The cases when we don't check downgrade is when this object is // called to restore packages, e.g. by nuget.exe restore command. // Otherwise, check downgrade is true, e.g. when user installs a package // inside VS. if (CheckDowngrade) { //Check if the package is installed. This is necessary to know if this is a fresh-install or a downgrade operation IPackage packageUnderInstallation = Repository.FindPackage(package.Id); if (packageUnderInstallation != null && packageUnderInstallation.Version > package.Version) { _isDowngrade = true; } } else { _isDowngrade = false; } _operations.Clear(); Marker.Clear(); _packagesToKeep.Clear(); Walk(package); return Operations.Reduce(); } /// <summary> /// Resolve operations for a list of packages clearing the package marker only once at the beginning. When the packages are interdependent, this method performs efficiently /// Also, sets the packagesByDependencyOrder to the input packages, but in dependency order /// NOTE: If package A 1.0 depends on package B 1.0 and A 2.0 does not depend on B 2.0; and, A 2.0 and B 2.0 are the input packages (likely from the updates tab in dialog) /// then, the packagesbyDependencyOrder will have A followed by B. Since, A 2.0 does not depend on B 2.0. This is also true because GetConflict in this class /// would only the PackageMarker and not the installed packages for information /// </summary> /// <param name="packages">The list of packages to resolve operations for. If from the dialog node, the list may be sorted, mostly, alphabetically</param> /// <param name="packagesByDependencyOrder">Same set of packages returned in the dependency order</param> /// <param name="allowPrereleaseVersionsBasedOnPackage">If true, allowPrereleaseVersion is determined based on package before walking that package. Otherwise, existing value is used</param> /// <returns> /// Returns a list of Package Operations to be performed for the installation of the packages passed /// Also, the out parameter packagesByDependencyOrder would returned the packages passed in the dependency order /// </returns> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "1#", Justification = "In addition to operations, need to return packagesByDependencyOrder.")] public IList<PackageOperation> ResolveOperations(IEnumerable<IPackage> packages, out IList<IPackage> packagesByDependencyOrder, bool allowPrereleaseVersionsBasedOnPackage = false) { _packagesByDependencyOrder = new Dictionary<string, IList<IPackage>>(); _operations.Clear(); Marker.Clear(); _packagesToKeep.Clear(); Debug.Assert(Operations is List<PackageOperation>); foreach (var package in packages) { if (!_operations.Contains(package, PackageAction.Install)) { var allowPrereleaseVersions = _allowPrereleaseVersions; try { if (allowPrereleaseVersionsBasedOnPackage) { // Update _allowPrereleaseVersions before walking a package if allowPrereleaseVersionsBasedOnPackage is set to true // This is mainly used when bulk resolving operations for reinstalling packages _allowPrereleaseVersions = _allowPrereleaseVersions || !package.IsReleaseVersion(); } Walk(package); } finally { _allowPrereleaseVersions = allowPrereleaseVersions; } } } // Flatten the dictionary to create a list of all the packages. Only this item the packages visited first during the walk will appear on the list. Also, only retain distinct elements IEnumerable<IPackage> allPackagesByDependencyOrder = _packagesByDependencyOrder.SelectMany(p => p.Value).Distinct(); // Only retain the packages for which the operations are being resolved for packagesByDependencyOrder = allPackagesByDependencyOrder.Where(p => packages.Any(q => p.Id == q.Id && p.Version == q.Version)).ToList(); Debug.Assert(packagesByDependencyOrder.Count == packages.Count()); _packagesByDependencyOrder.Clear(); _packagesByDependencyOrder = null; return Operations.Reduce(); } private IEnumerable<IPackage> GetDependents(ConflictResult conflict) { // Skip all dependents that are marked for uninstall IEnumerable<IPackage> packages = _operations.GetPackages(PackageAction.Uninstall); return conflict.DependentsResolver.GetDependents(conflict.Package) .Except<IPackage>(packages, PackageEqualityComparer.IdAndVersion); } private static InvalidOperationException CreatePackageConflictException(IPackage resolvedPackage, IPackage package, IEnumerable<IPackage> dependents) { if (dependents.Count() == 1) { return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ConflictErrorWithDependent, package.GetFullName(), resolvedPackage.GetFullName(), dependents.Single().Id)); } return new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.ConflictErrorWithDependents, package.GetFullName(), resolvedPackage.GetFullName(), String.Join(", ", dependents.Select(d => d.Id)))); } /// <summary> /// Operation lookup encapsulates an operation list and another efficient data structure for finding package operations /// by package id, version and PackageAction. /// </summary> private class OperationLookup { private readonly List<PackageOperation> _operations = new List<PackageOperation>(); private readonly Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>> _operationLookup = new Dictionary<PackageAction, Dictionary<IPackage, PackageOperation>>(); internal void Clear() { _operations.Clear(); _operationLookup.Clear(); } internal IList<PackageOperation> ToList() { return _operations; } internal IEnumerable<IPackage> GetPackages(PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); if (dictionary != null) { return dictionary.Keys; } return Enumerable.Empty<IPackage>(); } internal void AddOperation(PackageOperation operation) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(operation.Action, createIfNotExists: true); if (!dictionary.ContainsKey(operation.Package)) { dictionary.Add(operation.Package, operation); _operations.Add(operation); } } internal void RemoveOperation(IPackage package, PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); PackageOperation operation; if (dictionary != null && dictionary.TryGetValue(package, out operation)) { dictionary.Remove(package); _operations.Remove(operation); } } internal bool Contains(IPackage package, PackageAction action) { Dictionary<IPackage, PackageOperation> dictionary = GetPackageLookup(action); return dictionary != null && dictionary.ContainsKey(package); } private Dictionary<IPackage, PackageOperation> GetPackageLookup(PackageAction action, bool createIfNotExists = false) { Dictionary<IPackage, PackageOperation> packages; if (!_operationLookup.TryGetValue(action, out packages) && createIfNotExists) { packages = new Dictionary<IPackage, PackageOperation>(PackageEqualityComparer.IdAndVersion); _operationLookup.Add(action, packages); } return packages; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Fubu.CsProjFile.FubuCsProjFile.Templating.Graph; using Fubu.CsProjFile.FubuCsProjFile.Templating.Runtime; using FubuCore; namespace Fubu.CsProjFile.FubuCsProjFile.Templating.Planning { public class TemplatePlan { public const string SOLUTION_NAME = "%SOLUTION_NAME%"; public const string SOLUTION_PATH = "%SOLUTION_PATH%"; public const string INSTRUCTIONS = "%INSTRUCTIONS%"; public static readonly string RippleImportFile = "ripple-install.txt"; public static readonly string InstructionsFile = "instructions.txt"; private readonly IFileSystem _fileSystem = new FileSystem(); private readonly IList<string> _handled = new List<string>(); private readonly StringWriter _instructions = new StringWriter(); private readonly IList<string> _missingInputs = new List<string>(); private readonly IList<ITemplateStep> _steps = new List<ITemplateStep>(); private readonly Substitutions _substitutions = new Substitutions(); private ProjectPlan _currentProject; private Solution _solution; public IList<string> MissingInputs { get { return this._missingInputs; } } public Substitutions Substitutions { get { return this._substitutions; } } public ITemplateLogger Logger { get; private set; } public string Root { get; set; } public string SourceName { get; set; } public string SourceDirectory { get { return FubuCore.StringExtensions.AppendPath(this.Root, new string[] { this.SourceName }); } } public Solution Solution { get { return this._solution; } set { this._solution = value; this._substitutions.Set("%SOLUTION_NAME%", this._solution.Name); this._substitutions.Set("%SOLUTION_PATH%", FubuCore.StringExtensions.PathRelativeTo(this.Solution.Filename, this.Root).Replace("\\", "/")); } } public IFileSystem FileSystem { get { return this._fileSystem; } } public IEnumerable<ITemplateStep> Steps { get { return this._steps; } } public ProjectPlan CurrentProject { get { return this._currentProject ?? this._steps.OfType<ProjectPlan>().LastOrDefault<ProjectPlan>(); } } public TemplatePlan(string rootDirectory) { this.Root = rootDirectory; this.SourceName = "src"; this.Logger = new TemplateLogger(); } public static TemplatePlan CreateClean(string directory) { FileSystem system = new FileSystem(); system.CreateDirectory(directory); system.CleanDirectory(directory); return new TemplatePlan(directory); } public string ApplySubstitutions(string rawText) { return this._substitutions.ApplySubstitutions(rawText, delegate(StringBuilder builder) { if (this.CurrentProject != null) { this.CurrentProject.ApplySubstitutions(null, builder); } }); } public void MarkHandled(string file) { this._handled.Add(file.CanonicalPath()); } public void Add(ITemplateStep step) { this._steps.Add(step); } public void StartProject(ProjectPlan project) { this._currentProject = project; } public void Execute() { if (this._missingInputs.Any<string>()) { this.Logger.Trace("Missing Inputs:", new object[0]); this.Logger.Trace("---------------", new object[0]); GenericEnumerableExtensions.Each<string>(this._missingInputs, delegate(string x) { Console.WriteLine(x); }); throw new MissingInputException(this._missingInputs.ToArray<string>()); } this.Logger.Starting(this._steps.Count); this._substitutions.Trace(this.Logger); this._substitutions.Set("%INSTRUCTIONS%", this.GetInstructions().Replace("\"", "'")); GenericEnumerableExtensions.Each<ITemplateStep>(this._steps, delegate(ITemplateStep x) { this.Logger.TraceStep(x); x.Alter(this); }); if (this.Solution != null) { this.Logger.Trace("Saving solution to {0}", new object[] { this.Solution.Filename }); this.Solution.Save(true); } this.Substitutions.WriteTo(FubuCore.StringExtensions.AppendPath(this.Root, new string[] { Substitutions.ConfigFile })); this.WriteNugetImports(); this.Logger.Finish(); } public void WritePreview() { this.Logger.Starting(this._steps.Count); this._substitutions.Trace(this.Logger); GenericEnumerableExtensions.Each<ITemplateStep>(this._steps, delegate(ITemplateStep x) { this.Logger.TraceStep(x); ProjectPlan project = x as ProjectPlan; if (project != null) { this.Logger.StartProject(project.Alterations.Count); project.Substitutions.Trace(this.Logger); GenericEnumerableExtensions.Each<IProjectAlteration>(project.Alterations, delegate(IProjectAlteration alteration) { this.Logger.TraceAlteration(this.ApplySubstitutions(alteration.ToString())); }); this.Logger.EndProject(); } }); string[] projectsWithNugets = this.determineProjectsWithNugets(); if (projectsWithNugets.Any<string>()) { Console.WriteLine(); Console.WriteLine("Nuget imports:"); GenericEnumerableExtensions.Each<string>(projectsWithNugets, delegate(string x) { Console.WriteLine(x); }); } } public void AlterFile(string relativeName, Action<List<string>> alter) { this._fileSystem.AlterFlatFile(FubuCore.StringExtensions.AppendPath(this.Root, new string[] { relativeName }), alter); } public bool FileIsUnhandled(string file) { if (Path.GetFileName(file).ToLowerInvariant() == TemplateLibrary.DescriptionFile) { return false; } if (Path.GetFileName(file).ToLowerInvariant() == Input.File) { return false; } if (Path.GetFileName(file).ToLowerInvariant() == TemplatePlan.InstructionsFile) { return false; } string path = file.CanonicalPath(); return !this._handled.Contains(path); } public void CopyUnhandledFiles(string directory) { IEnumerable<string> unhandledFiles = this._fileSystem.FindFiles(directory, FileSet.Everything()).Where(new Func<string, bool>(this.FileIsUnhandled)); if (this.CurrentProject == null) { GenericEnumerableExtensions.Each<string>(unhandledFiles, delegate(string file) { this.Add(new CopyFileToSolution(FubuCore.StringExtensions.PathRelativeTo(file, directory), file)); }); return; } GenericEnumerableExtensions.Each<string>(unhandledFiles, delegate(string file) { this.CurrentProject.Add(new CopyFileToProject(FubuCore.StringExtensions.PathRelativeTo(file, directory), file)); }); } public void WriteNugetImports() { string[] projectsWithNugets = this.determineProjectsWithNugets(); if (projectsWithNugets.Any<string>()) { this.Logger.Trace("Writing nuget imports:", new object[0]); GenericEnumerableExtensions.Each<string>(projectsWithNugets, delegate(string x) { this.Logger.Trace(x, new object[0]); }); this.Logger.Trace("", new object[0]); TemplateLibrary.FileSystem.AlterFlatFile(FubuCore.StringExtensions.AppendPath(this.Root, new string[] { TemplatePlan.RippleImportFile }), delegate(List<string> list) { list.AddRange(projectsWithNugets); }); } } private string[] determineProjectsWithNugets() { return (from x in this.Steps.OfType<ProjectPlan>() where x.NugetDeclarations.Any<string>() select x.ToNugetImportStatement()).ToArray<string>(); } public ProjectPlan FindProjectPlan(string name) { return this._steps.OfType<ProjectPlan>().FirstOrDefault((ProjectPlan x) => x.ProjectName == name); } public void AddInstructions(string rawText) { this._instructions.WriteLine(rawText); this._instructions.WriteLine(); this._instructions.WriteLine(); } public void WriteInstructions() { if (FubuCore.StringExtensions.IsEmpty(this._instructions.ToString())) { return; } string instructionText = this.GetInstructions(); string[] contents = instructionText.SplitOnNewLine(); this.FileSystem.AlterFlatFile(FubuCore.StringExtensions.AppendPath(this.Root, new string[] { TemplatePlan.InstructionsFile }), delegate(List<string> list) { list.AddRange(contents); }); Console.WriteLine(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Cyan; GenericEnumerableExtensions.Each<string>(contents, delegate(string x) { Console.WriteLine(x); }); Console.ResetColor(); } public string GetInstructions() { return this.ApplySubstitutions(this._instructions.ToString()); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AzureStack.Management; using Microsoft.AzureStack.Management.Models; namespace Microsoft.AzureStack.Management { public static partial class DelegatedOfferOperationsExtensions { /// <summary> /// Gets a delegated offer. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IDelegatedOfferOperations. /// </param> /// <param name='offerName'> /// Required. the name of the delegated offer. /// </param> /// <returns> /// Delegated offer get result. /// </returns> public static DelegatedOfferGetResult Get(this IDelegatedOfferOperations operations, string offerName) { return Task.Factory.StartNew((object s) => { return ((IDelegatedOfferOperations)s).GetAsync(offerName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a delegated offer. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IDelegatedOfferOperations. /// </param> /// <param name='offerName'> /// Required. the name of the delegated offer. /// </param> /// <returns> /// Delegated offer get result. /// </returns> public static Task<DelegatedOfferGetResult> GetAsync(this IDelegatedOfferOperations operations, string offerName) { return operations.GetAsync(offerName, CancellationToken.None); } /// <summary> /// Get delegated offers for given subscription ID. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IDelegatedOfferOperations. /// </param> /// <returns> /// Your documentation here. /// </returns> public static DelegatedOfferListResult List(this IDelegatedOfferOperations operations) { return Task.Factory.StartNew((object s) => { return ((IDelegatedOfferOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get delegated offers for given subscription ID. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IDelegatedOfferOperations. /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<DelegatedOfferListResult> ListAsync(this IDelegatedOfferOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// Next for get delegated offers for given subscription ID. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IDelegatedOfferOperations. /// </param> /// <param name='nextLink'> /// Required. The next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static DelegatedOfferListResult ListNext(this IDelegatedOfferOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IDelegatedOfferOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Next for get delegated offers for given subscription ID. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IDelegatedOfferOperations. /// </param> /// <param name='nextLink'> /// Required. The next link. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </param> /// <returns> /// Your documentation here. /// </returns> public static Task<DelegatedOfferListResult> ListNextAsync(this IDelegatedOfferOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Update a delegated offer. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IDelegatedOfferOperations. /// </param> /// <param name='parameters'> /// Required. Parameters to update delegated offer. /// </param> /// <returns> /// Delegated offer update result. /// </returns> public static DelegatedOfferUpdateResult Update(this IDelegatedOfferOperations operations, DelegatedOfferUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IDelegatedOfferOperations)s).UpdateAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Update a delegated offer. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/XXXXX.aspx /// for more information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.AzureStack.Management.IDelegatedOfferOperations. /// </param> /// <param name='parameters'> /// Required. Parameters to update delegated offer. /// </param> /// <returns> /// Delegated offer update result. /// </returns> public static Task<DelegatedOfferUpdateResult> UpdateAsync(this IDelegatedOfferOperations operations, DelegatedOfferUpdateParameters parameters) { return operations.UpdateAsync(parameters, CancellationToken.None); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/monitoring/v3/common.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Cloud.Monitoring.V3 { /// <summary>Holder for reflection information generated from google/monitoring/v3/common.proto</summary> public static partial class CommonReflection { #region Descriptor /// <summary>File descriptor for google/monitoring/v3/common.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static CommonReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiFnb29nbGUvbW9uaXRvcmluZy92My9jb21tb24ucHJvdG8SFGdvb2dsZS5t", "b25pdG9yaW5nLnYzGh1nb29nbGUvYXBpL2Rpc3RyaWJ1dGlvbi5wcm90bxoe", "Z29vZ2xlL3Byb3RvYnVmL2R1cmF0aW9uLnByb3RvGh9nb29nbGUvcHJvdG9i", "dWYvdGltZXN0YW1wLnByb3RvIqoBCgpUeXBlZFZhbHVlEhQKCmJvb2xfdmFs", "dWUYASABKAhIABIVCgtpbnQ2NF92YWx1ZRgCIAEoA0gAEhYKDGRvdWJsZV92", "YWx1ZRgDIAEoAUgAEhYKDHN0cmluZ192YWx1ZRgEIAEoCUgAEjYKEmRpc3Ry", "aWJ1dGlvbl92YWx1ZRgFIAEoCzIYLmdvb2dsZS5hcGkuRGlzdHJpYnV0aW9u", "SABCBwoFdmFsdWUibAoMVGltZUludGVydmFsEiwKCGVuZF90aW1lGAIgASgL", "MhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcBIuCgpzdGFydF90aW1lGAEg", "ASgLMhouZ29vZ2xlLnByb3RvYnVmLlRpbWVzdGFtcCLkBgoLQWdncmVnYXRp", "b24SMwoQYWxpZ25tZW50X3BlcmlvZBgBIAEoCzIZLmdvb2dsZS5wcm90b2J1", "Zi5EdXJhdGlvbhJFChJwZXJfc2VyaWVzX2FsaWduZXIYAiABKA4yKS5nb29n", "bGUubW9uaXRvcmluZy52My5BZ2dyZWdhdGlvbi5BbGlnbmVyEkcKFGNyb3Nz", "X3Nlcmllc19yZWR1Y2VyGAQgASgOMikuZ29vZ2xlLm1vbml0b3JpbmcudjMu", "QWdncmVnYXRpb24uUmVkdWNlchIXCg9ncm91cF9ieV9maWVsZHMYBSADKAki", "2gIKB0FsaWduZXISDgoKQUxJR05fTk9ORRAAEg8KC0FMSUdOX0RFTFRBEAES", "DgoKQUxJR05fUkFURRACEhUKEUFMSUdOX0lOVEVSUE9MQVRFEAMSFAoQQUxJ", "R05fTkVYVF9PTERFUhAEEg0KCUFMSUdOX01JThAKEg0KCUFMSUdOX01BWBAL", "Eg4KCkFMSUdOX01FQU4QDBIPCgtBTElHTl9DT1VOVBANEg0KCUFMSUdOX1NV", "TRAOEhAKDEFMSUdOX1NURERFVhAPEhQKEEFMSUdOX0NPVU5UX1RSVUUQEBIX", "ChNBTElHTl9GUkFDVElPTl9UUlVFEBESFwoTQUxJR05fUEVSQ0VOVElMRV85", "ORASEhcKE0FMSUdOX1BFUkNFTlRJTEVfOTUQExIXChNBTElHTl9QRVJDRU5U", "SUxFXzUwEBQSFwoTQUxJR05fUEVSQ0VOVElMRV8wNRAVIpkCCgdSZWR1Y2Vy", "Eg8KC1JFRFVDRV9OT05FEAASDwoLUkVEVUNFX01FQU4QARIOCgpSRURVQ0Vf", "TUlOEAISDgoKUkVEVUNFX01BWBADEg4KClJFRFVDRV9TVU0QBBIRCg1SRURV", "Q0VfU1REREVWEAUSEAoMUkVEVUNFX0NPVU5UEAYSFQoRUkVEVUNFX0NPVU5U", "X1RSVUUQBxIYChRSRURVQ0VfRlJBQ1RJT05fVFJVRRAIEhgKFFJFRFVDRV9Q", "RVJDRU5USUxFXzk5EAkSGAoUUkVEVUNFX1BFUkNFTlRJTEVfOTUQChIYChRS", "RURVQ0VfUEVSQ0VOVElMRV81MBALEhgKFFJFRFVDRV9QRVJDRU5USUxFXzA1", "EAxCowEKGGNvbS5nb29nbGUubW9uaXRvcmluZy52M0ILQ29tbW9uUHJvdG9Q", "AVo+Z29vZ2xlLmdvbGFuZy5vcmcvZ2VucHJvdG8vZ29vZ2xlYXBpcy9tb25p", "dG9yaW5nL3YzO21vbml0b3JpbmeqAhpHb29nbGUuQ2xvdWQuTW9uaXRvcmlu", "Zy5WM8oCGkdvb2dsZVxDbG91ZFxNb25pdG9yaW5nXFYzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Api.DistributionReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.TypedValue), global::Google.Cloud.Monitoring.V3.TypedValue.Parser, new[]{ "BoolValue", "Int64Value", "DoubleValue", "StringValue", "DistributionValue" }, new[]{ "Value" }, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.TimeInterval), global::Google.Cloud.Monitoring.V3.TimeInterval.Parser, new[]{ "EndTime", "StartTime" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::Google.Cloud.Monitoring.V3.Aggregation), global::Google.Cloud.Monitoring.V3.Aggregation.Parser, new[]{ "AlignmentPeriod", "PerSeriesAligner", "CrossSeriesReducer", "GroupByFields" }, null, new[]{ typeof(global::Google.Cloud.Monitoring.V3.Aggregation.Types.Aligner), typeof(global::Google.Cloud.Monitoring.V3.Aggregation.Types.Reducer) }, null) })); } #endregion } #region Messages /// <summary> /// A single strongly-typed value. /// </summary> public sealed partial class TypedValue : pb::IMessage<TypedValue> { private static readonly pb::MessageParser<TypedValue> _parser = new pb::MessageParser<TypedValue>(() => new TypedValue()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TypedValue> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.CommonReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TypedValue() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TypedValue(TypedValue other) : this() { switch (other.ValueCase) { case ValueOneofCase.BoolValue: BoolValue = other.BoolValue; break; case ValueOneofCase.Int64Value: Int64Value = other.Int64Value; break; case ValueOneofCase.DoubleValue: DoubleValue = other.DoubleValue; break; case ValueOneofCase.StringValue: StringValue = other.StringValue; break; case ValueOneofCase.DistributionValue: DistributionValue = other.DistributionValue.Clone(); break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TypedValue Clone() { return new TypedValue(this); } /// <summary>Field number for the "bool_value" field.</summary> public const int BoolValueFieldNumber = 1; /// <summary> /// A Boolean value: `true` or `false`. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool BoolValue { get { return valueCase_ == ValueOneofCase.BoolValue ? (bool) value_ : false; } set { value_ = value; valueCase_ = ValueOneofCase.BoolValue; } } /// <summary>Field number for the "int64_value" field.</summary> public const int Int64ValueFieldNumber = 2; /// <summary> /// A 64-bit integer. Its range is approximately &amp;plusmn;9.2x10&lt;sup>18&lt;/sup>. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public long Int64Value { get { return valueCase_ == ValueOneofCase.Int64Value ? (long) value_ : 0L; } set { value_ = value; valueCase_ = ValueOneofCase.Int64Value; } } /// <summary>Field number for the "double_value" field.</summary> public const int DoubleValueFieldNumber = 3; /// <summary> /// A 64-bit double-precision floating-point number. Its magnitude /// is approximately &amp;plusmn;10&lt;sup>&amp;plusmn;300&lt;/sup> and it has 16 /// significant digits of precision. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public double DoubleValue { get { return valueCase_ == ValueOneofCase.DoubleValue ? (double) value_ : 0D; } set { value_ = value; valueCase_ = ValueOneofCase.DoubleValue; } } /// <summary>Field number for the "string_value" field.</summary> public const int StringValueFieldNumber = 4; /// <summary> /// A variable-length string value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string StringValue { get { return valueCase_ == ValueOneofCase.StringValue ? (string) value_ : ""; } set { value_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); valueCase_ = ValueOneofCase.StringValue; } } /// <summary>Field number for the "distribution_value" field.</summary> public const int DistributionValueFieldNumber = 5; /// <summary> /// A distribution value. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Api.Distribution DistributionValue { get { return valueCase_ == ValueOneofCase.DistributionValue ? (global::Google.Api.Distribution) value_ : null; } set { value_ = value; valueCase_ = value == null ? ValueOneofCase.None : ValueOneofCase.DistributionValue; } } private object value_; /// <summary>Enum of possible cases for the "value" oneof.</summary> public enum ValueOneofCase { None = 0, BoolValue = 1, Int64Value = 2, DoubleValue = 3, StringValue = 4, DistributionValue = 5, } private ValueOneofCase valueCase_ = ValueOneofCase.None; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ValueOneofCase ValueCase { get { return valueCase_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void ClearValue() { valueCase_ = ValueOneofCase.None; value_ = null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TypedValue); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TypedValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (BoolValue != other.BoolValue) return false; if (Int64Value != other.Int64Value) return false; if (DoubleValue != other.DoubleValue) return false; if (StringValue != other.StringValue) return false; if (!object.Equals(DistributionValue, other.DistributionValue)) return false; if (ValueCase != other.ValueCase) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (valueCase_ == ValueOneofCase.BoolValue) hash ^= BoolValue.GetHashCode(); if (valueCase_ == ValueOneofCase.Int64Value) hash ^= Int64Value.GetHashCode(); if (valueCase_ == ValueOneofCase.DoubleValue) hash ^= DoubleValue.GetHashCode(); if (valueCase_ == ValueOneofCase.StringValue) hash ^= StringValue.GetHashCode(); if (valueCase_ == ValueOneofCase.DistributionValue) hash ^= DistributionValue.GetHashCode(); hash ^= (int) valueCase_; return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (valueCase_ == ValueOneofCase.BoolValue) { output.WriteRawTag(8); output.WriteBool(BoolValue); } if (valueCase_ == ValueOneofCase.Int64Value) { output.WriteRawTag(16); output.WriteInt64(Int64Value); } if (valueCase_ == ValueOneofCase.DoubleValue) { output.WriteRawTag(25); output.WriteDouble(DoubleValue); } if (valueCase_ == ValueOneofCase.StringValue) { output.WriteRawTag(34); output.WriteString(StringValue); } if (valueCase_ == ValueOneofCase.DistributionValue) { output.WriteRawTag(42); output.WriteMessage(DistributionValue); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (valueCase_ == ValueOneofCase.BoolValue) { size += 1 + 1; } if (valueCase_ == ValueOneofCase.Int64Value) { size += 1 + pb::CodedOutputStream.ComputeInt64Size(Int64Value); } if (valueCase_ == ValueOneofCase.DoubleValue) { size += 1 + 8; } if (valueCase_ == ValueOneofCase.StringValue) { size += 1 + pb::CodedOutputStream.ComputeStringSize(StringValue); } if (valueCase_ == ValueOneofCase.DistributionValue) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DistributionValue); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TypedValue other) { if (other == null) { return; } switch (other.ValueCase) { case ValueOneofCase.BoolValue: BoolValue = other.BoolValue; break; case ValueOneofCase.Int64Value: Int64Value = other.Int64Value; break; case ValueOneofCase.DoubleValue: DoubleValue = other.DoubleValue; break; case ValueOneofCase.StringValue: StringValue = other.StringValue; break; case ValueOneofCase.DistributionValue: DistributionValue = other.DistributionValue; break; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { BoolValue = input.ReadBool(); break; } case 16: { Int64Value = input.ReadInt64(); break; } case 25: { DoubleValue = input.ReadDouble(); break; } case 34: { StringValue = input.ReadString(); break; } case 42: { global::Google.Api.Distribution subBuilder = new global::Google.Api.Distribution(); if (valueCase_ == ValueOneofCase.DistributionValue) { subBuilder.MergeFrom(DistributionValue); } input.ReadMessage(subBuilder); DistributionValue = subBuilder; break; } } } } } /// <summary> /// A time interval extending just after a start time through an end time. /// If the start time is the same as the end time, then the interval /// represents a single point in time. /// </summary> public sealed partial class TimeInterval : pb::IMessage<TimeInterval> { private static readonly pb::MessageParser<TimeInterval> _parser = new pb::MessageParser<TimeInterval>(() => new TimeInterval()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<TimeInterval> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.CommonReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeInterval() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeInterval(TimeInterval other) : this() { EndTime = other.endTime_ != null ? other.EndTime.Clone() : null; StartTime = other.startTime_ != null ? other.StartTime.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public TimeInterval Clone() { return new TimeInterval(this); } /// <summary>Field number for the "end_time" field.</summary> public const int EndTimeFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Timestamp endTime_; /// <summary> /// Required. The end of the time interval. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp EndTime { get { return endTime_; } set { endTime_ = value; } } /// <summary>Field number for the "start_time" field.</summary> public const int StartTimeFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Timestamp startTime_; /// <summary> /// Optional. The beginning of the time interval. The default value /// for the start time is the end time. The start time must not be /// later than the end time. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp StartTime { get { return startTime_; } set { startTime_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as TimeInterval); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(TimeInterval other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(EndTime, other.EndTime)) return false; if (!object.Equals(StartTime, other.StartTime)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (endTime_ != null) hash ^= EndTime.GetHashCode(); if (startTime_ != null) hash ^= StartTime.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (startTime_ != null) { output.WriteRawTag(10); output.WriteMessage(StartTime); } if (endTime_ != null) { output.WriteRawTag(18); output.WriteMessage(EndTime); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (endTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(EndTime); } if (startTime_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(StartTime); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(TimeInterval other) { if (other == null) { return; } if (other.endTime_ != null) { if (endTime_ == null) { endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } EndTime.MergeFrom(other.EndTime); } if (other.startTime_ != null) { if (startTime_ == null) { startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } StartTime.MergeFrom(other.StartTime); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (startTime_ == null) { startTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(startTime_); break; } case 18: { if (endTime_ == null) { endTime_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(endTime_); break; } } } } } /// <summary> /// Describes how to combine multiple time series to provide different views of /// the data. Aggregation consists of an alignment step on individual time /// series (`per_series_aligner`) followed by an optional reduction of the data /// across different time series (`cross_series_reducer`). For more details, see /// [Aggregation](/monitoring/api/learn_more#aggregation). /// </summary> public sealed partial class Aggregation : pb::IMessage<Aggregation> { private static readonly pb::MessageParser<Aggregation> _parser = new pb::MessageParser<Aggregation>(() => new Aggregation()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<Aggregation> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Cloud.Monitoring.V3.CommonReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Aggregation() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Aggregation(Aggregation other) : this() { AlignmentPeriod = other.alignmentPeriod_ != null ? other.AlignmentPeriod.Clone() : null; perSeriesAligner_ = other.perSeriesAligner_; crossSeriesReducer_ = other.crossSeriesReducer_; groupByFields_ = other.groupByFields_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public Aggregation Clone() { return new Aggregation(this); } /// <summary>Field number for the "alignment_period" field.</summary> public const int AlignmentPeriodFieldNumber = 1; private global::Google.Protobuf.WellKnownTypes.Duration alignmentPeriod_; /// <summary> /// The alignment period for per-[time series][google.monitoring.v3.TimeSeries] /// alignment. If present, `alignmentPeriod` must be at least 60 /// seconds. After per-time series alignment, each time series will /// contain data points only on the period boundaries. If /// `perSeriesAligner` is not specified or equals `ALIGN_NONE`, then /// this field is ignored. If `perSeriesAligner` is specified and /// does not equal `ALIGN_NONE`, then this field must be defined; /// otherwise an error is returned. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration AlignmentPeriod { get { return alignmentPeriod_; } set { alignmentPeriod_ = value; } } /// <summary>Field number for the "per_series_aligner" field.</summary> public const int PerSeriesAlignerFieldNumber = 2; private global::Google.Cloud.Monitoring.V3.Aggregation.Types.Aligner perSeriesAligner_ = 0; /// <summary> /// The approach to be used to align individual time series. Not all /// alignment functions may be applied to all time series, depending /// on the metric type and value type of the original time /// series. Alignment may change the metric type or the value type of /// the time series. /// /// Time series data must be aligned in order to perform cross-time /// series reduction. If `crossSeriesReducer` is specified, then /// `perSeriesAligner` must be specified and not equal `ALIGN_NONE` /// and `alignmentPeriod` must be specified; otherwise, an error is /// returned. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Monitoring.V3.Aggregation.Types.Aligner PerSeriesAligner { get { return perSeriesAligner_; } set { perSeriesAligner_ = value; } } /// <summary>Field number for the "cross_series_reducer" field.</summary> public const int CrossSeriesReducerFieldNumber = 4; private global::Google.Cloud.Monitoring.V3.Aggregation.Types.Reducer crossSeriesReducer_ = 0; /// <summary> /// The approach to be used to combine time series. Not all reducer /// functions may be applied to all time series, depending on the /// metric type and the value type of the original time /// series. Reduction may change the metric type of value type of the /// time series. /// /// Time series data must be aligned in order to perform cross-time /// series reduction. If `crossSeriesReducer` is specified, then /// `perSeriesAligner` must be specified and not equal `ALIGN_NONE` /// and `alignmentPeriod` must be specified; otherwise, an error is /// returned. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Cloud.Monitoring.V3.Aggregation.Types.Reducer CrossSeriesReducer { get { return crossSeriesReducer_; } set { crossSeriesReducer_ = value; } } /// <summary>Field number for the "group_by_fields" field.</summary> public const int GroupByFieldsFieldNumber = 5; private static readonly pb::FieldCodec<string> _repeated_groupByFields_codec = pb::FieldCodec.ForString(42); private readonly pbc::RepeatedField<string> groupByFields_ = new pbc::RepeatedField<string>(); /// <summary> /// The set of fields to preserve when `crossSeriesReducer` is /// specified. The `groupByFields` determine how the time series are /// partitioned into subsets prior to applying the aggregation /// function. Each subset contains time series that have the same /// value for each of the grouping fields. Each individual time /// series is a member of exactly one subset. The /// `crossSeriesReducer` is applied to each subset of time series. /// It is not possible to reduce across different resource types, so /// this field implicitly contains `resource.type`. Fields not /// specified in `groupByFields` are aggregated away. If /// `groupByFields` is not specified and all the time series have /// the same resource type, then the time series are aggregated into /// a single output time series. If `crossSeriesReducer` is not /// defined, this field is ignored. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> GroupByFields { get { return groupByFields_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as Aggregation); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(Aggregation other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(AlignmentPeriod, other.AlignmentPeriod)) return false; if (PerSeriesAligner != other.PerSeriesAligner) return false; if (CrossSeriesReducer != other.CrossSeriesReducer) return false; if(!groupByFields_.Equals(other.groupByFields_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (alignmentPeriod_ != null) hash ^= AlignmentPeriod.GetHashCode(); if (PerSeriesAligner != 0) hash ^= PerSeriesAligner.GetHashCode(); if (CrossSeriesReducer != 0) hash ^= CrossSeriesReducer.GetHashCode(); hash ^= groupByFields_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (alignmentPeriod_ != null) { output.WriteRawTag(10); output.WriteMessage(AlignmentPeriod); } if (PerSeriesAligner != 0) { output.WriteRawTag(16); output.WriteEnum((int) PerSeriesAligner); } if (CrossSeriesReducer != 0) { output.WriteRawTag(32); output.WriteEnum((int) CrossSeriesReducer); } groupByFields_.WriteTo(output, _repeated_groupByFields_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (alignmentPeriod_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(AlignmentPeriod); } if (PerSeriesAligner != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) PerSeriesAligner); } if (CrossSeriesReducer != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) CrossSeriesReducer); } size += groupByFields_.CalculateSize(_repeated_groupByFields_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(Aggregation other) { if (other == null) { return; } if (other.alignmentPeriod_ != null) { if (alignmentPeriod_ == null) { alignmentPeriod_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } AlignmentPeriod.MergeFrom(other.AlignmentPeriod); } if (other.PerSeriesAligner != 0) { PerSeriesAligner = other.PerSeriesAligner; } if (other.CrossSeriesReducer != 0) { CrossSeriesReducer = other.CrossSeriesReducer; } groupByFields_.Add(other.groupByFields_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (alignmentPeriod_ == null) { alignmentPeriod_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(alignmentPeriod_); break; } case 16: { perSeriesAligner_ = (global::Google.Cloud.Monitoring.V3.Aggregation.Types.Aligner) input.ReadEnum(); break; } case 32: { crossSeriesReducer_ = (global::Google.Cloud.Monitoring.V3.Aggregation.Types.Reducer) input.ReadEnum(); break; } case 42: { groupByFields_.AddEntriesFrom(input, _repeated_groupByFields_codec); break; } } } } #region Nested types /// <summary>Container for nested types declared in the Aggregation message type.</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static partial class Types { /// <summary> /// The Aligner describes how to bring the data points in a single /// time series into temporal alignment. /// </summary> public enum Aligner { /// <summary> /// No alignment. Raw data is returned. Not valid if cross-time /// series reduction is requested. The value type of the result is /// the same as the value type of the input. /// </summary> [pbr::OriginalName("ALIGN_NONE")] AlignNone = 0, /// <summary> /// Align and convert to delta metric type. This alignment is valid /// for cumulative metrics and delta metrics. Aligning an existing /// delta metric to a delta metric requires that the alignment /// period be increased. The value type of the result is the same /// as the value type of the input. /// </summary> [pbr::OriginalName("ALIGN_DELTA")] AlignDelta = 1, /// <summary> /// Align and convert to a rate. This alignment is valid for /// cumulative metrics and delta metrics with numeric values. The output is a /// gauge metric with value type /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("ALIGN_RATE")] AlignRate = 2, /// <summary> /// Align by interpolating between adjacent points around the /// period boundary. This alignment is valid for gauge /// metrics with numeric values. The value type of the result is the same /// as the value type of the input. /// </summary> [pbr::OriginalName("ALIGN_INTERPOLATE")] AlignInterpolate = 3, /// <summary> /// Align by shifting the oldest data point before the period /// boundary to the boundary. This alignment is valid for gauge /// metrics. The value type of the result is the same as the /// value type of the input. /// </summary> [pbr::OriginalName("ALIGN_NEXT_OLDER")] AlignNextOlder = 4, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the minimum of all data points in the /// period. This alignment is valid for gauge and delta metrics with numeric /// values. The value type of the result is the same as the value /// type of the input. /// </summary> [pbr::OriginalName("ALIGN_MIN")] AlignMin = 10, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the maximum of all data points in the /// period. This alignment is valid for gauge and delta metrics with numeric /// values. The value type of the result is the same as the value /// type of the input. /// </summary> [pbr::OriginalName("ALIGN_MAX")] AlignMax = 11, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the average or arithmetic mean of all /// data points in the period. This alignment is valid for gauge and delta /// metrics with numeric values. The value type of the output is /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("ALIGN_MEAN")] AlignMean = 12, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the count of all data points in the /// period. This alignment is valid for gauge and delta metrics with numeric /// or Boolean values. The value type of the output is /// [INT64][google.api.MetricDescriptor.ValueType.INT64]. /// </summary> [pbr::OriginalName("ALIGN_COUNT")] AlignCount = 13, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the sum of all data points in the /// period. This alignment is valid for gauge and delta metrics with numeric /// and distribution values. The value type of the output is the /// same as the value type of the input. /// </summary> [pbr::OriginalName("ALIGN_SUM")] AlignSum = 14, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the standard deviation of all data /// points in the period. This alignment is valid for gauge and delta metrics /// with numeric values. The value type of the output is /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("ALIGN_STDDEV")] AlignStddev = 15, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the count of True-valued data points in the /// period. This alignment is valid for gauge metrics with /// Boolean values. The value type of the output is /// [INT64][google.api.MetricDescriptor.ValueType.INT64]. /// </summary> [pbr::OriginalName("ALIGN_COUNT_TRUE")] AlignCountTrue = 16, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the fraction of True-valued data points in the /// period. This alignment is valid for gauge metrics with Boolean values. /// The output value is in the range [0, 1] and has value type /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("ALIGN_FRACTION_TRUE")] AlignFractionTrue = 17, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the 99th percentile of all data /// points in the period. This alignment is valid for gauge and delta metrics /// with distribution values. The output is a gauge metric with value type /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("ALIGN_PERCENTILE_99")] AlignPercentile99 = 18, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the 95th percentile of all data /// points in the period. This alignment is valid for gauge and delta metrics /// with distribution values. The output is a gauge metric with value type /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("ALIGN_PERCENTILE_95")] AlignPercentile95 = 19, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the 50th percentile of all data /// points in the period. This alignment is valid for gauge and delta metrics /// with distribution values. The output is a gauge metric with value type /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("ALIGN_PERCENTILE_50")] AlignPercentile50 = 20, /// <summary> /// Align time series via aggregation. The resulting data point in /// the alignment period is the 5th percentile of all data /// points in the period. This alignment is valid for gauge and delta metrics /// with distribution values. The output is a gauge metric with value type /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("ALIGN_PERCENTILE_05")] AlignPercentile05 = 21, } /// <summary> /// A Reducer describes how to aggregate data points from multiple /// time series into a single time series. /// </summary> public enum Reducer { /// <summary> /// No cross-time series reduction. The output of the aligner is /// returned. /// </summary> [pbr::OriginalName("REDUCE_NONE")] ReduceNone = 0, /// <summary> /// Reduce by computing the mean across time series for each /// alignment period. This reducer is valid for delta and /// gauge metrics with numeric or distribution values. The value type of the /// output is [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("REDUCE_MEAN")] ReduceMean = 1, /// <summary> /// Reduce by computing the minimum across time series for each /// alignment period. This reducer is valid for delta and /// gauge metrics with numeric values. The value type of the output /// is the same as the value type of the input. /// </summary> [pbr::OriginalName("REDUCE_MIN")] ReduceMin = 2, /// <summary> /// Reduce by computing the maximum across time series for each /// alignment period. This reducer is valid for delta and /// gauge metrics with numeric values. The value type of the output /// is the same as the value type of the input. /// </summary> [pbr::OriginalName("REDUCE_MAX")] ReduceMax = 3, /// <summary> /// Reduce by computing the sum across time series for each /// alignment period. This reducer is valid for delta and /// gauge metrics with numeric and distribution values. The value type of /// the output is the same as the value type of the input. /// </summary> [pbr::OriginalName("REDUCE_SUM")] ReduceSum = 4, /// <summary> /// Reduce by computing the standard deviation across time series /// for each alignment period. This reducer is valid for delta /// and gauge metrics with numeric or distribution values. The value type of /// the output is [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("REDUCE_STDDEV")] ReduceStddev = 5, /// <summary> /// Reduce by computing the count of data points across time series /// for each alignment period. This reducer is valid for delta /// and gauge metrics of numeric, Boolean, distribution, and string value /// type. The value type of the output is /// [INT64][google.api.MetricDescriptor.ValueType.INT64]. /// </summary> [pbr::OriginalName("REDUCE_COUNT")] ReduceCount = 6, /// <summary> /// Reduce by computing the count of True-valued data points across time /// series for each alignment period. This reducer is valid for delta /// and gauge metrics of Boolean value type. The value type of /// the output is [INT64][google.api.MetricDescriptor.ValueType.INT64]. /// </summary> [pbr::OriginalName("REDUCE_COUNT_TRUE")] ReduceCountTrue = 7, /// <summary> /// Reduce by computing the fraction of True-valued data points across time /// series for each alignment period. This reducer is valid for delta /// and gauge metrics of Boolean value type. The output value is in the /// range [0, 1] and has value type /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE]. /// </summary> [pbr::OriginalName("REDUCE_FRACTION_TRUE")] ReduceFractionTrue = 8, /// <summary> /// Reduce by computing 99th percentile of data points across time series /// for each alignment period. This reducer is valid for gauge and delta /// metrics of numeric and distribution type. The value of the output is /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE] /// </summary> [pbr::OriginalName("REDUCE_PERCENTILE_99")] ReducePercentile99 = 9, /// <summary> /// Reduce by computing 95th percentile of data points across time series /// for each alignment period. This reducer is valid for gauge and delta /// metrics of numeric and distribution type. The value of the output is /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE] /// </summary> [pbr::OriginalName("REDUCE_PERCENTILE_95")] ReducePercentile95 = 10, /// <summary> /// Reduce by computing 50th percentile of data points across time series /// for each alignment period. This reducer is valid for gauge and delta /// metrics of numeric and distribution type. The value of the output is /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE] /// </summary> [pbr::OriginalName("REDUCE_PERCENTILE_50")] ReducePercentile50 = 11, /// <summary> /// Reduce by computing 5th percentile of data points across time series /// for each alignment period. This reducer is valid for gauge and delta /// metrics of numeric and distribution type. The value of the output is /// [DOUBLE][google.api.MetricDescriptor.ValueType.DOUBLE] /// </summary> [pbr::OriginalName("REDUCE_PERCENTILE_05")] ReducePercentile05 = 12, } } #endregion } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Orleans.Runtime; namespace Orleans { /// <summary> /// Provides functionality for observing a lifecycle. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Single use, does not support multiple start/stop cycles.</description></item> /// <item><description>Once started, no other observers can be subscribed.</description></item> /// <item><description>OnStart starts stages in order until first failure or cancellation.</description></item> /// <item><description>OnStop stops states in reverse order starting from highest started stage.</description></item> /// <item><description>OnStop stops all stages regardless of errors even if canceled canceled.</description></item> /// </list> /// </remarks> public abstract class LifecycleSubject : ILifecycleSubject { private readonly List<OrderedObserver> subscribers; private readonly ILogger logger; private int? highStage = null; protected LifecycleSubject(ILogger logger) { this.logger = logger; this.subscribers = new List<OrderedObserver>(); } /// <summary> /// Gets the name of the specified numeric stage. /// </summary> /// <param name="stage">The stage number.</param> /// <returns>The name of the stage.</returns> protected virtual string GetStageName(int stage) => stage.ToString(); /// <summary> /// Gets the collection of all stage numbers and their corresponding names. /// </summary> /// <seealso cref="ServiceLifecycleStage"/> /// <param name="type">The lifecycle stage class.</param> /// <returns>The collection of all stage numbers and their corresponding names.</returns> protected static ImmutableDictionary<int, string> GetStageNames(Type type) { try { var result = ImmutableDictionary.CreateBuilder<int, string>(); var fields = type.GetFields( System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic); foreach (var field in fields) { if (typeof(int).IsAssignableFrom(field.FieldType)) { try { var value = (int)field.GetValue(null); result[value] = $"{field.Name} ({value})"; } catch { // Ignore. } } } return result.ToImmutable(); } catch { return ImmutableDictionary<int, string>.Empty; } } /// <summary> /// Logs the observed performance of an <see cref="OnStart"/> call. /// </summary> /// <param name="stage">The stage.</param> /// <param name="elapsed">The period of time which elapsed before <see cref="OnStart"/> completed once it was initiated.</param> protected virtual void PerfMeasureOnStart(int stage, TimeSpan elapsed) { if (this.logger != null && this.logger.IsEnabled(LogLevel.Trace)) { this.logger.LogTrace( (int)ErrorCode.SiloStartPerfMeasure, "Starting lifecycle stage {Stage} took {Elapsed} Milliseconds", stage, elapsed.TotalMilliseconds); } } /// <inheritdoc /> public virtual async Task OnStart(CancellationToken cancellationToken = default) { if (this.highStage.HasValue) throw new InvalidOperationException("Lifecycle has already been started."); try { foreach (IGrouping<int, OrderedObserver> observerGroup in this.subscribers .GroupBy(orderedObserver => orderedObserver.Stage) .OrderBy(group => group.Key)) { if (cancellationToken.IsCancellationRequested) { throw new OrleansLifecycleCanceledException("Lifecycle start canceled by request"); } var stage = observerGroup.Key; this.highStage = stage; var stopWatch = ValueStopwatch.StartNew(); await Task.WhenAll(observerGroup.Select(orderedObserver => CallOnStart(orderedObserver, cancellationToken))); stopWatch.Stop(); this.PerfMeasureOnStart(stage, stopWatch.Elapsed); this.OnStartStageCompleted(stage); } } catch (Exception ex) when (!(ex is OrleansLifecycleCanceledException)) { this.logger?.LogError( (int)ErrorCode.LifecycleStartFailure, "Lifecycle start canceled due to errors at stage {Stage}: {Exception}", this.highStage, ex); throw; } static Task CallOnStart(OrderedObserver observer, CancellationToken cancellationToken) { try { return observer.Observer?.OnStart(cancellationToken) ?? Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } } /// <summary> /// Signifies that <see cref="OnStart"/> completed. /// </summary> /// <param name="stage">The stage which completed.</param> protected virtual void OnStartStageCompleted(int stage) { } /// <summary> /// Logs the observed performance of an <see cref="OnStop"/> call. /// </summary> /// <param name="stage">The stage.</param> /// <param name="elapsed">The period of time which elapsed before <see cref="OnStop"/> completed once it was initiated.</param> protected virtual void PerfMeasureOnStop(int stage, TimeSpan elapsed) { if (this.logger != null && this.logger.IsEnabled(LogLevel.Trace)) { this.logger.LogTrace( (int)ErrorCode.SiloStartPerfMeasure, "Stopping lifecycle stage {Stage} took {Elapsed} Milliseconds", stage, elapsed.TotalMilliseconds); } } /// <inheritdoc /> public virtual async Task OnStop(CancellationToken cancellationToken = default) { // if not started, do nothing if (!this.highStage.HasValue) return; var loggedCancellation = false; foreach (IGrouping<int, OrderedObserver> observerGroup in this.subscribers // include up to highest started stage .Where(orderedObserver => orderedObserver.Stage <= highStage && orderedObserver.Observer != null) .GroupBy(orderedObserver => orderedObserver.Stage) .OrderByDescending(group => group.Key)) { if (cancellationToken.IsCancellationRequested && !loggedCancellation) { this.logger?.LogWarning("Lifecycle stop operations canceled by request."); loggedCancellation = true; } var stage = observerGroup.Key; this.highStage = stage; try { var stopwatch = ValueStopwatch.StartNew(); await Task.WhenAll(observerGroup.Select(orderedObserver => CallOnStop(orderedObserver, cancellationToken))); stopwatch.Stop(); this.PerfMeasureOnStop(stage, stopwatch.Elapsed); } catch (Exception ex) { this.logger?.LogError( (int)ErrorCode.LifecycleStopFailure, "Stopping lifecycle encountered an error at stage {Stage}. Continuing to stop. Exception: {Exception}", this.highStage, ex); } this.OnStopStageCompleted(stage); } static Task CallOnStop(OrderedObserver observer, CancellationToken cancellationToken) { try { return observer.Observer?.OnStop(cancellationToken) ?? Task.CompletedTask; } catch (Exception ex) { return Task.FromException(ex); } } } /// <summary> /// Signifies that <see cref="OnStop"/> completed. /// </summary> /// <param name="stage">The stage which completed.</param> protected virtual void OnStopStageCompleted(int stage) { } public virtual IDisposable Subscribe(string observerName, int stage, ILifecycleObserver observer) { if (observer == null) throw new ArgumentNullException(nameof(observer)); if (this.highStage.HasValue) throw new InvalidOperationException("Lifecycle has already been started."); var orderedObserver = new OrderedObserver(stage, observer); this.subscribers.Add(orderedObserver); return orderedObserver; } /// <summary> /// Represents a <see cref="ILifecycleObservable"/>'s participation in a given lifecycle stage. /// </summary> private class OrderedObserver : IDisposable { /// <summary> /// Gets the observer. /// </summary> public ILifecycleObserver Observer { get; private set; } /// <summary> /// Gets the stage which the observer is participating in. /// </summary> public int Stage { get; } /// <summary> /// Initializes a new instance of the <see cref="OrderedObserver"/> class. /// </summary> /// <param name="stage">The stage which the observer is participating in.</param> /// <param name="observer">The participating observer.</param> public OrderedObserver(int stage, ILifecycleObserver observer) { this.Stage = stage; this.Observer = observer; } /// <inheritdoc /> public void Dispose() => Observer = null; } } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using NSubstitute; using Xunit; namespace Octokit.Tests.Clients { /// <summary> /// Client tests mostly just need to make sure they call the IApiConnection with the correct /// relative Uri. No need to fake up the response. All *those* tests are in ApiConnectionTests.cs. /// </summary> public class RepositoriesClientTests { public class TheCtor { [Fact] public void EnsuresNonNullArguments() { Assert.Throws<ArgumentNullException>(() => new RepositoriesClient(null)); } } public class TheCreateMethodForUser { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null)); } [Fact] public void UsesTheUserReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.Create(new NewRepository("aName")); connection.Received().Post<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Any<NewRepository>()); } [Fact] public void TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository("aName"); client.Create(newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForCurrentUser() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create(newRepository)); Assert.False(exception.OwnerIsOrganization); Assert.Null(exception.Organization); Assert.Equal("aName", exception.RepositoryName); Assert.Null(exception.ExistingRepositoryWebUrl); } [Fact] public async Task ThrowsExceptionWhenPrivateRepositoryQuotaExceeded() { var newRepository = new NewRepository("aName") { Private = true }; var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":" + @"""name can't be private. You are over your quota.""}]}"); var credentials = new Credentials("haacked", "pwd"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Connection.Credentials.Returns(credentials); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<PrivateRepositoryQuotaExceededException>( () => client.Create(newRepository)); Assert.NotNull(exception); } } public class TheCreateMethodForOrganization { [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create(null, new NewRepository("aName"))); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Create("aLogin", null)); } [Fact] public async Task UsesTheOrganizationsReposUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Create("theLogin", new NewRepository("aName")); connection.Received().Post<Repository>( Arg.Is<Uri>(u => u.ToString() == "orgs/theLogin/repos"), Args.NewRepository); } [Fact] public async Task TheNewRepositoryDescription() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var newRepository = new NewRepository("aName"); await client.Create("aLogin", newRepository); connection.Received().Post<Repository>(Args.Uri, newRepository); } [Fact] public async Task ThrowsRepositoryExistsExceptionWhenRepositoryExistsForSpecifiedOrg() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create("illuminati", newRepository)); Assert.True(exception.OwnerIsOrganization); Assert.Equal("illuminati", exception.Organization); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://github.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); Assert.Equal("There is already a repository named 'aName' in the organization 'illuminati'.", exception.Message); } [Fact] public async Task ThrowsValidationException() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(GitHubClient.GitHubApiUrl); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<ApiValidationException>( () => client.Create("illuminati", newRepository)); Assert.Null(exception as RepositoryExistsException); } [Fact] public async Task ThrowsRepositoryExistsExceptionForEnterpriseInstance() { var newRepository = new NewRepository("aName"); var response = Substitute.For<IResponse>(); response.StatusCode.Returns((HttpStatusCode)422); response.Body.Returns(@"{""message"":""Validation Failed"",""documentation_url"":" + @"""http://developer.github.com/v3/repos/#create"",""errors"":[{""resource"":""Repository""," + @"""code"":""custom"",""field"":""name"",""message"":""name already exists on this account""}]}"); var connection = Substitute.For<IApiConnection>(); connection.Connection.BaseAddress.Returns(new Uri("https://example.com")); connection.Post<Repository>(Args.Uri, newRepository) .Returns<Task<Repository>>(_ => { throw new ApiValidationException(response); }); var client = new RepositoriesClient(connection); var exception = await Assert.ThrowsAsync<RepositoryExistsException>( () => client.Create("illuminati", newRepository)); Assert.Equal("aName", exception.RepositoryName); Assert.Equal(new Uri("https://example.com/illuminati/aName"), exception.ExistingRepositoryWebUrl); } } public class TheDeleteMethod { [Fact] public async Task RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Delete("owner", "name"); connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name")); } [Fact] public async Task RequestsCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Delete(1); connection.Received().Delete(Arg.Is<Uri>(u => u.ToString() == "repositories/1")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Delete("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Delete("", "name")); await Assert.ThrowsAsync<ArgumentException>(() => client.Delete("owner", "")); } } public class TheGetMethod { [Fact] public async Task RequestsCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Get("owner", "name"); connection.Received().Get<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name")); } [Fact] public async Task RequestsCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.Get(1); connection.Received().Get<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories/1")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "name")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "")); } } public class TheGetAllPublicMethod { [Fact] public async Task RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllPublic(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories")); } } public class TheGetAllPublicSinceMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllPublic(new PublicRepositoryRequest(364)); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories?since=364")); } [Fact] public async Task SendsTheCorrectParameter() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllPublic(new PublicRepositoryRequest(364)); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories?since=364")); } } public class TheGetAllForCurrentMethod { [Fact] public async Task RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllForCurrent(); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "user/repos"), Args.ApiOptions); } [Fact] public async Task CanFilterByType() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.All }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "all"), Args.ApiOptions); } [Fact] public async Task CanFilterBySort() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.Private, Sort = RepositorySort.FullName }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "private" && d["sort"] == "full_name"), Args.ApiOptions); } [Fact] public async Task CanFilterBySortDirection() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Type = RepositoryType.Member, Sort = RepositorySort.Updated, Direction = SortDirection.Ascending }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["type"] == "member" && d["sort"] == "updated" && d["direction"] == "asc"), Args.ApiOptions); } [Fact] public async Task CanFilterByVisibility() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Visibility = RepositoryVisibility.Private }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["visibility"] == "private"), Args.ApiOptions); } [Fact] public async Task CanFilterByAffiliation() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var request = new RepositoryRequest { Affiliation = RepositoryAffiliation.Owner, Sort = RepositorySort.FullName }; await client.GetAllForCurrent(request); connection.Received() .GetAll<Repository>( Arg.Is<Uri>(u => u.ToString() == "user/repos"), Arg.Is<Dictionary<string, string>>(d => d["affiliation"] == "owner" && d["sort"] == "full_name"), Args.ApiOptions); } } public class TheGetAllForUserMethod { [Fact] public async Task RequestsTheCorrectUrlAndReturnsRepositories() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllForUser("username"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "users/username/repos"), Args.ApiOptions); } [Fact] public async Task EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null)); await Assert.ThrowsAsync<ArgumentException>(() => reposEndpoint.GetAllForUser("")); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser(null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForUser("user", null)); await Assert.ThrowsAsync<ArgumentException>(() => reposEndpoint.GetAllForUser("", ApiOptions.None)); } } public class TheGetAllForOrgMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllForOrg("orgname"); connection.Received() .GetAll<Repository>(Arg.Is<Uri>(u => u.ToString() == "orgs/orgname/repos"), Args.ApiOptions); } [Fact] public async Task EnsuresNonNullArguments() { var reposEndpoint = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null)); await Assert.ThrowsAsync<ArgumentException>(() => reposEndpoint.GetAllForOrg("")); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg(null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => reposEndpoint.GetAllForOrg("org", null)); await Assert.ThrowsAsync<ArgumentException>(() => reposEndpoint.GetAllForOrg("", ApiOptions.None)); } } public class TheGetAllBranchesMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllBranches("owner", "name"); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllBranches(1); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllBranches("owner", "name", options); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/branches"), null, "application/vnd.github.loki-preview+json", options); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllBranches(1, options); connection.Received() .GetAll<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches"), null, "application/vnd.github.loki-preview+json", options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(null, "name")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(null, "name", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches("owner", "name", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllBranches(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("", "name")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("", "name", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllBranches("owner", "", ApiOptions.None)); } } public class TheGetAllContributorsMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllContributors("owner", "name"); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>(), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllContributors(1); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/contributors"), Arg.Any<IDictionary<string, string>>(), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllContributors("owner", "name", options); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Any<IDictionary<string, string>>(), options); } [Fact] public void RequestsTheCorrectUrlWithRepositoryIdWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; client.GetAllContributors(1, options); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/contributors"), Arg.Any<IDictionary<string, string>>(), options); } [Fact] public async Task RequestsTheCorrectUrlIncludeAnonymous() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllContributors("owner", "name", true); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Is<IDictionary<string, string>>(d => d["anon"] == "1"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdIncludeAnonymous() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllContributors(1, true); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/contributors"), Arg.Is<IDictionary<string, string>>(d => d["anon"] == "1"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptionsIncludeAnonymous() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllContributors("owner", "name", true, options); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/contributors"), Arg.Is<IDictionary<string, string>>(d => d["anon"] == "1"), options); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptionsIncludeAnonymous() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllContributors(1, true, options); connection.Received() .GetAll<RepositoryContributor>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/contributors"), Arg.Is<IDictionary<string, string>>(d => d["anon"] == "1"), options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(null, "repo", false, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", null, false, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors("owner", "repo", false, null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(1, null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllContributors(1, false, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", "", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("", "repo", false, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllContributors("owner", "", false, ApiOptions.None)); } } public class TheGetAllLanguagesMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllLanguages("owner", "name"); connection.Received() .Get<Dictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/languages")); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); client.GetAllLanguages(1); connection.Received() .Get<Dictionary<string, long>>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/languages")); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllLanguages("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllLanguages("owner", "")); } } public class TheGetAllTeamsMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllTeams("owner", "name"); connection.Received() .GetAll<Team>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllTeams(1); connection.Received() .GetAll<Team>( Arg.Is<Uri>(u => u.ToString() == "repositories/1/teams"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllTeams("owner", "name", options); connection.Received() .GetAll<Team>( Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/teams"), options); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryIdWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllTeams(1, options); connection.Received() .GetAll<Team>( Arg.Is<Uri>(u => u.ToString() == "repositories/1/teams"), options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(null, "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTeams(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("", "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTeams("owner", "", ApiOptions.None)); } } public class TheGetAllTagsMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllTags("owner", "name"); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetAllTags(1); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/tags"), Args.ApiOptions); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptions() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllTags("owner", "name", options); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/tags"), options); } [Fact] public async Task RequestsTheCorrectUrlWithApiOptionsWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var options = new ApiOptions { PageCount = 1, StartPage = 1, PageSize = 1 }; await client.GetAllTags(1, options); connection.Received() .GetAll<RepositoryTag>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/tags"), options); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(null, "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(null, "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", null, ApiOptions.None)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAllTags(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("", "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("owner", "")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("", "repo", ApiOptions.None)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAllTags("owner", "", ApiOptions.None)); } } public class TheGetBranchMethod { [Fact] public async Task RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetBranch("owner", "repo", "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); await client.GetBranch(1, "branch"); connection.Received() .Get<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), null, "application/vnd.github.loki-preview+json"); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch(null, "repo", "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", null, "branch")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetBranch(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("", "repo", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "", "branch")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetBranch("owner", "repo", "")); } } public class TheEditMethod { [Fact] public void PatchesCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new RepositoryUpdate(); client.Edit("owner", "repo", update); connection.Received() .Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo"), Arg.Any<RepositoryUpdate>()); } [Fact] public void PatchesCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new RepositoryUpdate(); client.Edit(1, update); connection.Received() .Patch<Repository>(Arg.Is<Uri>(u => u.ToString() == "repositories/1"), Arg.Any<RepositoryUpdate>()); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new RepositoryUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(null, "repo", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Edit(1, null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("", "repo", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.Edit("owner", "", update)); } } public class TheCompareMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare(null, "repo", "base", "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("", "repo", "base", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", null, "base", "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "", "base", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", null, "head")); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "", "head")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Compare("owner", "repo", "base", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Compare("owner", "repo", "base", "")); } [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "head"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...head")); } [Fact] public void EncodesUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Compare("owner", "repo", "base", "shiftkey/my-cool-branch"); connection.Received() .Get<CompareResult>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/compare/base...shiftkey%2Fmy-cool-branch")); } } public class TheGetCommitMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get(null, "repo", "reference")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("", "repo", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", null, "reference")); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.Get("owner", "repo", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.Get("owner", "repo", "")); } [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.Get("owner", "name", "reference"); connection.Received() .Get<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference")); } } public class TheGetAllCommitsMethod { [Fact] public async Task EnsureNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll(null, "repo")); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("", "repo")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.GetAll("owner", "")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetAll("owner", "repo", null, ApiOptions.None)); } [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.GetAll("owner", "name"); connection.Received() .GetAll<GitHubCommit>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits"), Args.EmptyDictionary, Args.ApiOptions); } } public class TheEditBranchMethod { [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new BranchUpdate(); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.EditBranch("owner", "repo", "branch", update); connection.Received() .Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/repo/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader); } [Fact] public void RequestsTheCorrectUrlWithRepositoryId() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoriesClient(connection); var update = new BranchUpdate(); const string previewAcceptsHeader = "application/vnd.github.loki-preview+json"; client.EditBranch(1, "branch", update); connection.Received() .Patch<Branch>(Arg.Is<Uri>(u => u.ToString() == "repositories/1/branches/branch"), Arg.Any<BranchUpdate>(), previewAcceptsHeader); } [Fact] public async Task EnsuresNonNullArguments() { var client = new RepositoriesClient(Substitute.For<IApiConnection>()); var update = new BranchUpdate(); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(null, "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", null, "branch", update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch("owner", "repo", "branch", null)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(1, null, update)); await Assert.ThrowsAsync<ArgumentNullException>(() => client.EditBranch(1, "branch", null)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("", "repo", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "", "branch", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch("owner", "repo", "", update)); await Assert.ThrowsAsync<ArgumentException>(() => client.EditBranch(1, "", update)); } } public class TheGetSha1Method { [Fact] public void EnsuresNonNullArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("", "name", "reference")); Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("owner", "", "reference")); Assert.ThrowsAsync<ArgumentException>(() => client.GetSha1("owner", "name", "")); } [Fact] public async Task EnsuresNonEmptyArguments() { var client = new RepositoryCommitsClient(Substitute.For<IApiConnection>()); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1(null, "name", "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1("owner", null, "reference")); await Assert.ThrowsAsync<ArgumentNullException>(() => client.GetSha1("owner", "name", null)); } [Fact] public void RequestsTheCorrectUrl() { var connection = Substitute.For<IApiConnection>(); var client = new RepositoryCommitsClient(connection); client.GetSha1("owner", "name", "reference"); connection.Received() .Get<string>(Arg.Is<Uri>(u => u.ToString() == "repos/owner/name/commits/reference"), null, AcceptHeaders.CommitReferenceSha1Preview); } } } }
/*This script has been, partially or completely, generated by the Fungus.GenerateVariableWindow*/ using UnityEngine; namespace Fungus { // <summary> /// Get or Set a property of a AudioSource component /// </summary> [CommandInfo("Property", "AudioSource", "Get or Set a property of a AudioSource component")] [AddComponentMenu("")] public class AudioSourceProperty : BaseVariableProperty { //generated property public enum Property { Volume, Pitch, Time, TimeSamples, IsPlaying, IsVirtual, Loop, IgnoreListenerVolume, PlayOnAwake, IgnoreListenerPause, PanStereo, SpatialBlend, Spatialize, SpatializePostEffects, ReverbZoneMix, BypassEffects, BypassListenerEffects, BypassReverbZones, DopplerLevel, Spread, Priority, Mute, MinDistance, MaxDistance, } [SerializeField] protected Property property; [SerializeField] [VariableProperty(typeof(AudioSourceVariable))] protected AudioSourceVariable audioSourceVar; [SerializeField] [VariableProperty(typeof(FloatVariable), typeof(IntegerVariable), typeof(BooleanVariable))] protected Variable inOutVar; public override void OnEnter() { var iof = inOutVar as FloatVariable; var ioi = inOutVar as IntegerVariable; var iob = inOutVar as BooleanVariable; var target = audioSourceVar.Value; switch (getOrSet) { case GetSet.Get: switch (property) { case Property.Volume: iof.Value = target.volume; break; case Property.Pitch: iof.Value = target.pitch; break; case Property.Time: iof.Value = target.time; break; case Property.TimeSamples: ioi.Value = target.timeSamples; break; case Property.IsPlaying: iob.Value = target.isPlaying; break; case Property.IsVirtual: iob.Value = target.isVirtual; break; case Property.Loop: iob.Value = target.loop; break; case Property.IgnoreListenerVolume: iob.Value = target.ignoreListenerVolume; break; case Property.PlayOnAwake: iob.Value = target.playOnAwake; break; case Property.IgnoreListenerPause: iob.Value = target.ignoreListenerPause; break; case Property.PanStereo: iof.Value = target.panStereo; break; case Property.SpatialBlend: iof.Value = target.spatialBlend; break; case Property.Spatialize: iob.Value = target.spatialize; break; case Property.SpatializePostEffects: iob.Value = target.spatializePostEffects; break; case Property.ReverbZoneMix: iof.Value = target.reverbZoneMix; break; case Property.BypassEffects: iob.Value = target.bypassEffects; break; case Property.BypassListenerEffects: iob.Value = target.bypassListenerEffects; break; case Property.BypassReverbZones: iob.Value = target.bypassReverbZones; break; case Property.DopplerLevel: iof.Value = target.dopplerLevel; break; case Property.Spread: iof.Value = target.spread; break; case Property.Priority: ioi.Value = target.priority; break; case Property.Mute: iob.Value = target.mute; break; case Property.MinDistance: iof.Value = target.minDistance; break; case Property.MaxDistance: iof.Value = target.maxDistance; break; default: Debug.Log("Unsupported get or set attempted"); break; } break; case GetSet.Set: switch (property) { case Property.Volume: target.volume = iof.Value; break; case Property.Pitch: target.pitch = iof.Value; break; case Property.Time: target.time = iof.Value; break; case Property.TimeSamples: target.timeSamples = ioi.Value; break; case Property.Loop: target.loop = iob.Value; break; case Property.IgnoreListenerVolume: target.ignoreListenerVolume = iob.Value; break; case Property.PlayOnAwake: target.playOnAwake = iob.Value; break; case Property.IgnoreListenerPause: target.ignoreListenerPause = iob.Value; break; case Property.PanStereo: target.panStereo = iof.Value; break; case Property.SpatialBlend: target.spatialBlend = iof.Value; break; case Property.Spatialize: target.spatialize = iob.Value; break; case Property.SpatializePostEffects: target.spatializePostEffects = iob.Value; break; case Property.ReverbZoneMix: target.reverbZoneMix = iof.Value; break; case Property.BypassEffects: target.bypassEffects = iob.Value; break; case Property.BypassListenerEffects: target.bypassListenerEffects = iob.Value; break; case Property.BypassReverbZones: target.bypassReverbZones = iob.Value; break; case Property.DopplerLevel: target.dopplerLevel = iof.Value; break; case Property.Spread: target.spread = iof.Value; break; case Property.Priority: target.priority = ioi.Value; break; case Property.Mute: target.mute = iob.Value; break; case Property.MinDistance: target.minDistance = iof.Value; break; case Property.MaxDistance: target.maxDistance = iof.Value; break; default: Debug.Log("Unsupported get or set attempted"); break; } break; default: break; } Continue(); } public override string GetSummary() { if (audioSourceVar == null) { return "Error: no audioSourceVar set"; } if (inOutVar == null) { return "Error: no variable set to push or pull data to or from"; } return getOrSet.ToString() + " " + property.ToString(); } public override Color GetButtonColor() { return new Color32(235, 191, 217, 255); } public override bool HasReference(Variable variable) { if (audioSourceVar == variable || inOutVar == variable) return true; return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Spark.Compiler; using Spark.Parser.Markup; using SparkLanguage.VsAdapters; using SparkLanguagePackageLib; using Spark.Parser; using Spark; namespace SparkLanguage { public class SourceSupervisor : ISourceSupervisor { readonly SparkViewEngine _engine; readonly MarkupGrammar _grammar; readonly ISparkSource _source; readonly string _path; uint _dwLastCookie; readonly IDictionary<uint, ISourceSupervisorEvents> _events = new Dictionary<uint, ISourceSupervisorEvents>(); static SourceSupervisor() { // To enable Visual Studio to correlate errors, the location of the // error must be allowed to come from the natural location // in the generated file. This setting is changed for the entire // AppDomain running inside the devenv process. SourceWriter.AdjustDebugSymbolsDefault = false; } public SourceSupervisor(ISparkSource source) { _source = source; IVsHierarchy hierarchy; uint itemid; IVsTextLines buffer; _source.GetDocument(out hierarchy, out itemid, out buffer); _path = GetDocumentPath(hierarchy, itemid); //Spark.Web.Mvc.SparkView //MyBaseView var settings = new VsProjectSparkSettings(hierarchy) { PageBaseType = source.GetDefaultPageBaseType() }; var viewFolder = new VsProjectViewFolder(_source, hierarchy); _engine = new SparkViewEngine(settings) { ViewFolder = viewFolder }; _grammar = new MarkupGrammar(settings); } private static string GetDocumentPath(IVsHierarchy hierarchy, uint itemid) { var rootid = -2; var rootItem = new HierarchyItem(hierarchy, (uint)rootid); var viewItem = rootItem.FirstOrDefault(child => child.Name == "Views"); var docItem = new HierarchyItem(hierarchy, itemid); var path = docItem.Name; while (!Equals(docItem.Parent, viewItem) && !Equals(docItem.Parent, rootItem)) { docItem = docItem.Parent; path = docItem.Name + "\\" + path; } if (Equals(docItem.Parent, rootItem)) path = "$\\" + path; return path; } public void Advise(ISourceSupervisorEvents pEvents, out uint pdwCookie) { pdwCookie = ++_dwLastCookie; _events[_dwLastCookie] = pEvents; } public void Unadvise(uint dwCookie) { if (_events.ContainsKey(dwCookie)) _events.Remove(dwCookie); } class PaintInfo { public int Count { get; set; } public _SOURCEPAINTING[] Paint { get; set; } public Exception ParseError { get; set; } } class MappingInfo { public string GeneratedCode { get; set; } public int Count { get; set; } public _SOURCEMAPPING[] Mapping { get; set; } public Exception GenerationError { get; set; } } public void PrimaryTextChanged(int processImmediately) { var primaryText = _source.GetPrimaryText(); var paintInfo = GetPaintInfo(primaryText); var mappingInfo = GetMappingInfo(); foreach (var events in _events.Values) { events.OnGenerated( primaryText, mappingInfo.GeneratedCode, mappingInfo.Count, ref mappingInfo.Mapping[0], paintInfo.Count, ref paintInfo.Paint[0]); } } private PaintInfo GetPaintInfo(string primaryText) { var paintInfo = new PaintInfo(); try { var sourceContext = new SourceContext(primaryText, 0, _path); var result = _grammar.Nodes(new Position(sourceContext)); paintInfo.Paint = result.Rest.GetPaint() .OfType<Paint<SparkTokenType>>() .Where(p => string.Equals(p.Begin.SourceContext.FileName, _path, StringComparison.InvariantCultureIgnoreCase)) .Select(p => new _SOURCEPAINTING { start = p.Begin.Offset, end = p.End.Offset, color = (int)p.Value }) .ToArray(); paintInfo.Count = paintInfo.Paint.Length; } catch (Exception ex) { paintInfo.ParseError = ex; } if (paintInfo.Count == 0) paintInfo.Paint = new _SOURCEPAINTING[1]; return paintInfo; } private MappingInfo GetMappingInfo() { var mappingInfo = new MappingInfo(); try { var descriptor = new SparkViewDescriptor() .AddTemplate(_path); var entry = _engine.CreateEntryInternal(descriptor, false); mappingInfo.GeneratedCode = entry.SourceCode; mappingInfo.Mapping = entry.SourceMappings .Where(m => string.Equals(m.Source.Begin.SourceContext.FileName, _path, StringComparison.InvariantCultureIgnoreCase)) .Select(m => new _SOURCEMAPPING { start1 = m.Source.Begin.Offset, end1 = m.Source.End.Offset, start2 = m.OutputBegin, end2 = m.OutputEnd }) .ToArray(); mappingInfo.Count = mappingInfo.Mapping.Length; } catch (Exception ex) { mappingInfo.GenerationError = ex; } if (mappingInfo.Count == 0) mappingInfo.Mapping = new _SOURCEMAPPING[1]; return mappingInfo; } public void OnTypeChar(IVsTextView pView, string ch) { if (ch == "{") { // add a closing "}" if it makes a complete expression or condition where one doesn't exist otherwise _TextSpan selection; pView.GetSelectionSpan(out selection); IVsTextLines buffer; pView.GetBuffer(out buffer); string before; buffer.GetLineText(0, 0, selection.iStartLine, selection.iStartIndex, out before); int iLastLine, iLastColumn; buffer.GetLastLineIndex(out iLastLine, out iLastColumn); string after; buffer.GetLineText(selection.iEndLine, selection.iEndIndex, iLastLine, iLastColumn, out after); var existingResult = _grammar.Nodes(new Position(new SourceContext(before + ch + after))); var expressionHits = existingResult.Rest.GetPaint() .OfType<Paint<Node>>() .Where(p => p.Begin.Offset <= before.Length && before.Length <= p.End.Offset && (p.Value is ExpressionNode || p.Value is ConditionNode)); // if a node exists normally, do nothing if (expressionHits.Count() != 0) return; var withCloseResult = _grammar.Nodes(new Position(new SourceContext(before + ch + "}" + after))); var withCloseHits = withCloseResult.Rest.GetPaint() .OfType<Paint<Node>>() .Where(p => p.Begin.Offset <= before.Length && before.Length <= p.End.Offset && (p.Value is ExpressionNode || p.Value is ConditionNode)); // if a close brace doesn't cause a node to exist, do nothing if (withCloseHits.Count() == 0) return; // add a closing } after the selection, then set the selection back to what it was int iAnchorLine, iAnchorCol, iEndLine, iEndCol; pView.GetSelection(out iAnchorLine, out iAnchorCol, out iEndLine, out iEndCol); _TextSpan inserted; buffer.ReplaceLines(selection.iEndLine, selection.iEndIndex, selection.iEndLine, selection.iEndIndex, "}", 1, out inserted); pView.SetSelection(iAnchorLine, iAnchorCol, iEndLine, iEndCol); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // namespace System.Reflection { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; #if FEATURE_REMOTING using System.Runtime.Remoting.Metadata; #endif //FEATURE_REMOTING using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading; using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache; [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_FieldInfo))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class FieldInfo : MemberInfo, _FieldInfo { #region Static Members public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); FieldInfo f = RuntimeType.GetFieldInfo(handle.GetRuntimeFieldInfo()); Type declaringType = f.DeclaringType; if (declaringType != null && declaringType.IsGenericType) throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_FieldDeclaringTypeGeneric"), f.Name, declaringType.GetGenericTypeDefinition())); return f; } [System.Runtime.InteropServices.ComVisible(false)] public static FieldInfo GetFieldFromHandle(RuntimeFieldHandle handle, RuntimeTypeHandle declaringType) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); return RuntimeType.GetFieldInfo(declaringType.GetRuntimeType(), handle.GetRuntimeFieldInfo()); } #endregion #region Constructor protected FieldInfo() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(FieldInfo left, FieldInfo right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null || left is RuntimeFieldInfo || right is RuntimeFieldInfo) { return false; } return left.Equals(right); } public static bool operator !=(FieldInfo left, FieldInfo right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region MemberInfo Overrides public override MemberTypes MemberType { get { return System.Reflection.MemberTypes.Field; } } #endregion #region Public Abstract\Virtual Members public virtual Type[] GetRequiredCustomModifiers() { throw new NotImplementedException(); } public virtual Type[] GetOptionalCustomModifiers() { throw new NotImplementedException(); } [CLSCompliant(false)] public virtual void SetValueDirect(TypedReference obj, Object value) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } [CLSCompliant(false)] public virtual Object GetValueDirect(TypedReference obj) { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } public abstract RuntimeFieldHandle FieldHandle { get; } public abstract Type FieldType { get; } public abstract Object GetValue(Object obj); public virtual Object GetRawConstantValue() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_AbstractNonCLS")); } public abstract void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture); public abstract FieldAttributes Attributes { get; } #endregion #region Public Members [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public void SetValue(Object obj, Object value) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. SetValue(obj, value, BindingFlags.Default, Type.DefaultBinder, null); } public bool IsPublic { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Public; } } public bool IsPrivate { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Private; } } public bool IsFamily { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Family; } } public bool IsAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.Assembly; } } public bool IsFamilyAndAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamANDAssem; } } public bool IsFamilyOrAssembly { get { return(Attributes & FieldAttributes.FieldAccessMask) == FieldAttributes.FamORAssem; } } public bool IsStatic { get { return(Attributes & FieldAttributes.Static) != 0; } } public bool IsInitOnly { get { return(Attributes & FieldAttributes.InitOnly) != 0; } } public bool IsLiteral { get { return(Attributes & FieldAttributes.Literal) != 0; } } public bool IsNotSerialized { get { return(Attributes & FieldAttributes.NotSerialized) != 0; } } public bool IsSpecialName { get { return(Attributes & FieldAttributes.SpecialName) != 0; } } public bool IsPinvokeImpl { get { return(Attributes & FieldAttributes.PinvokeImpl) != 0; } } public virtual bool IsSecurityCritical { get { return FieldHandle.IsSecurityCritical(); } } public virtual bool IsSecuritySafeCritical { get { return FieldHandle.IsSecuritySafeCritical(); } } public virtual bool IsSecurityTransparent { get { return FieldHandle.IsSecurityTransparent(); } } #endregion #if !FEATURE_CORECLR Type _FieldInfo.GetType() { return base.GetType(); } void _FieldInfo.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _FieldInfo.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _FieldInfo.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _FieldInfo.Invoke in VM\DangerousAPIs.h and // include _FieldInfo in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _FieldInfo.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } [Serializable] internal abstract class RuntimeFieldInfo : FieldInfo, ISerializable { #region Private Data Members private BindingFlags m_bindingFlags; protected RuntimeTypeCache m_reflectedTypeCache; protected RuntimeType m_declaringType; #endregion #region Constructor protected RuntimeFieldInfo() { // Used for dummy head node during population } protected RuntimeFieldInfo(RuntimeTypeCache reflectedTypeCache, RuntimeType declaringType, BindingFlags bindingFlags) { m_bindingFlags = bindingFlags; m_declaringType = declaringType; m_reflectedTypeCache = reflectedTypeCache; } #endregion #if FEATURE_REMOTING #region Legacy Remoting Cache // The size of CachedData is accounted for by BaseObjectWithCachedData in object.h. // This member is currently being used by Remoting for caching remoting data. If you // need to cache data here, talk to the Remoting team to work out a mechanism, so that // both caching systems can happily work together. private RemotingFieldCachedData m_cachedData; internal RemotingFieldCachedData RemotingCache { get { // This grabs an internal copy of m_cachedData and uses // that instead of looking at m_cachedData directly because // the cache may get cleared asynchronously. This prevents // us from having to take a lock. RemotingFieldCachedData cache = m_cachedData; if (cache == null) { cache = new RemotingFieldCachedData(this); RemotingFieldCachedData ret = Interlocked.CompareExchange(ref m_cachedData, cache, null); if (ret != null) cache = ret; } return cache; } } #endregion #endif //FEATURE_REMOTING #region NonPublic Members internal BindingFlags BindingFlags { get { return m_bindingFlags; } } private RuntimeType ReflectedTypeInternal { get { return m_reflectedTypeCache.GetRuntimeType(); } } internal RuntimeType GetDeclaringTypeInternal() { return m_declaringType; } internal RuntimeType GetRuntimeType() { return m_declaringType; } internal abstract RuntimeModule GetRuntimeModule(); #endregion #region MemberInfo Overrides public override MemberTypes MemberType { get { return MemberTypes.Field; } } public override Type ReflectedType { get { return m_reflectedTypeCache.IsGlobal ? null : ReflectedTypeInternal; } } public override Type DeclaringType { get { return m_reflectedTypeCache.IsGlobal ? null : m_declaringType; } } public override Module Module { get { return GetRuntimeModule(); } } #endregion #region Object Overrides public unsafe override String ToString() { return FieldType.FormatTypeName() + " " + Name; } #endregion #region ICustomAttributeProvider public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } [System.Security.SecuritySafeCritical] // auto-generated public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException("attributeType"); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"),"attributeType"); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } #endregion #region FieldInfo Overrides // All implemented on derived classes #endregion #region ISerializable Implementation [System.Security.SecurityCritical] // auto-generated public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException("info"); Contract.EndContractBlock(); MemberInfoSerializationHolder.GetSerializationInfo( info, Name, ReflectedTypeInternal, ToString(), MemberTypes.Field); } #endregion } [Serializable] internal unsafe sealed class RtFieldInfo : RuntimeFieldInfo, IRuntimeFieldInfo { #region FCalls [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] static private extern void PerformVisibilityCheckOnField(IntPtr field, Object target, RuntimeType declaringType, FieldAttributes attr, uint invocationFlags); #endregion #region Private Data Members // agressive caching private IntPtr m_fieldHandle; private FieldAttributes m_fieldAttributes; // lazy caching private string m_name; private RuntimeType m_fieldType; private INVOCATION_FLAGS m_invocationFlags; #if FEATURE_APPX private bool IsNonW8PFrameworkAPI() { if (GetRuntimeType().IsNonW8PFrameworkAPI()) return true; // Allow "value__" if (m_declaringType.IsEnum) return false; RuntimeAssembly rtAssembly = GetRuntimeAssembly(); if (rtAssembly.IsFrameworkAssembly()) { int ctorToken = rtAssembly.InvocableAttributeCtorToken; if (System.Reflection.MetadataToken.IsNullToken(ctorToken) || !CustomAttribute.IsAttributeDefined(GetRuntimeModule(), MetadataToken, ctorToken)) return true; } return false; } #endif internal INVOCATION_FLAGS InvocationFlags { get { if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0) { Type declaringType = DeclaringType; bool fIsReflectionOnlyType = (declaringType is ReflectionOnlyType); INVOCATION_FLAGS invocationFlags = 0; // first take care of all the NO_INVOKE cases if ( (declaringType != null && declaringType.ContainsGenericParameters) || (declaringType == null && Module.Assembly.ReflectionOnly) || (fIsReflectionOnlyType) ) { invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE; } // If the invocationFlags are still 0, then // this should be an usable field, determine the other flags if (invocationFlags == 0) { if ((m_fieldAttributes & FieldAttributes.InitOnly) != (FieldAttributes)0) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; if ((m_fieldAttributes & FieldAttributes.HasFieldRVA) != (FieldAttributes)0) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD; // A public field is inaccesible to Transparent code if the field is Critical. bool needsTransparencySecurityCheck = IsSecurityCritical && !IsSecuritySafeCritical; bool needsVisibilitySecurityCheck = ((m_fieldAttributes & FieldAttributes.FieldAccessMask) != FieldAttributes.Public) || (declaringType != null && declaringType.NeedsReflectionSecurityCheck); if (needsTransparencySecurityCheck || needsVisibilitySecurityCheck) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY; // find out if the field type is one of the following: Primitive, Enum or Pointer Type fieldType = FieldType; if (fieldType.IsPointer || fieldType.IsEnum || fieldType.IsPrimitive) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_FIELD_SPECIAL_CAST; } #if FEATURE_APPX if (AppDomain.ProfileAPICheck && IsNonW8PFrameworkAPI()) invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API; #endif // FEATURE_APPX // must be last to avoid threading problems m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED; } return m_invocationFlags; } } #endregion private RuntimeAssembly GetRuntimeAssembly() { return m_declaringType.GetRuntimeAssembly(); } #region Constructor [System.Security.SecurityCritical] // auto-generated internal RtFieldInfo( RuntimeFieldHandleInternal handle, RuntimeType declaringType, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringType, bindingFlags) { m_fieldHandle = handle.Value; m_fieldAttributes = RuntimeFieldHandle.GetAttributes(handle); } #endregion #region Private Members RuntimeFieldHandleInternal IRuntimeFieldInfo.Value { [System.Security.SecuritySafeCritical] get { return new RuntimeFieldHandleInternal(m_fieldHandle); } } #endregion #region Internal Members internal void CheckConsistency(Object target) { // only test instance fields if ((m_fieldAttributes & FieldAttributes.Static) != FieldAttributes.Static) { if (!m_declaringType.IsInstanceOfType(target)) { if (target == null) { throw new TargetException(Environment.GetResourceString("RFLCT.Targ_StatFldReqTarg")); } else { throw new ArgumentException( String.Format(CultureInfo.CurrentUICulture, Environment.GetResourceString("Arg_FieldDeclTarget"), Name, m_declaringType, target.GetType())); } } } } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { RtFieldInfo m = o as RtFieldInfo; if ((object)m == null) return false; return m.m_fieldHandle == m_fieldHandle; } [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal void InternalSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture, ref StackCrawlMark stackMark) { INVOCATION_FLAGS invocationFlags = InvocationFlags; RuntimeType declaringType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { if (declaringType != null && declaringType.ContainsGenericParameters) throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); throw new FieldAccessException(); } CheckConsistency(obj); RuntimeType fieldType = (RuntimeType)FieldType; value = fieldType.CheckValue(value, binder, culture, invokeAttr); #region Security Check #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD | INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY)) != 0) PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)m_invocationFlags); #endregion bool domainInitialized = false; if (declaringType == null) { RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; } } // UnsafeSetValue doesn't perform any consistency or visibility check. // It is the caller's responsibility to ensure the operation is safe. // When the caller needs to perform visibility checks they should call // InternalSetValue() instead. When the caller needs to perform // consistency checks they should call CheckConsistency() before // calling this method. [System.Security.SecurityCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal void UnsafeSetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { RuntimeType declaringType = DeclaringType as RuntimeType; RuntimeType fieldType = (RuntimeType)FieldType; value = fieldType.CheckValue(value, binder, culture, invokeAttr); bool domainInitialized = false; if (declaringType == null) { RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; RuntimeFieldHandle.SetValue(this, obj, value, fieldType, m_fieldAttributes, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; } } [System.Security.SecuritySafeCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal Object InternalGetValue(Object obj, ref StackCrawlMark stackMark) { INVOCATION_FLAGS invocationFlags = InvocationFlags; RuntimeType declaringType = DeclaringType as RuntimeType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE) != 0) { if (declaringType != null && DeclaringType.ContainsGenericParameters) throw new InvalidOperationException(Environment.GetResourceString("Arg_UnboundGenField")); if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("Arg_ReflectionOnlyField")); throw new FieldAccessException(); } CheckConsistency(obj); #if FEATURE_APPX if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NON_W8P_FX_API) != 0) { RuntimeAssembly caller = RuntimeAssembly.GetExecutingAssembly(ref stackMark); if (caller != null && !caller.IsSafeForReflection()) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_APIInvalidForCurrentContext", FullName)); } #endif RuntimeType fieldType = (RuntimeType)FieldType; if ((invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_NEED_SECURITY) != 0) PerformVisibilityCheckOnField(m_fieldHandle, obj, m_declaringType, m_fieldAttributes, (uint)(m_invocationFlags & ~INVOCATION_FLAGS.INVOCATION_FLAGS_SPECIAL_FIELD)); return UnsafeGetValue(obj); } // UnsafeGetValue doesn't perform any consistency or visibility check. // It is the caller's responsibility to ensure the operation is safe. // When the caller needs to perform visibility checks they should call // InternalGetValue() instead. When the caller needs to perform // consistency checks they should call CheckConsistency() before // calling this method. [System.Security.SecurityCritical] [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] internal Object UnsafeGetValue(Object obj) { RuntimeType declaringType = DeclaringType as RuntimeType; RuntimeType fieldType = (RuntimeType)FieldType; bool domainInitialized = false; if (declaringType == null) { return RuntimeFieldHandle.GetValue(this, obj, fieldType, null, ref domainInitialized); } else { domainInitialized = declaringType.DomainInitialized; object retVal = RuntimeFieldHandle.GetValue(this, obj, fieldType, declaringType, ref domainInitialized); declaringType.DomainInitialized = domainInitialized; return retVal; } } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = RuntimeFieldHandle.GetName(this); return m_name; } } internal String FullName { get { return String.Format("{0}.{1}", DeclaringType.FullName, Name); } } public override int MetadataToken { [System.Security.SecuritySafeCritical] // auto-generated get { return RuntimeFieldHandle.GetToken(this); } } [System.Security.SecuritySafeCritical] // auto-generated internal override RuntimeModule GetRuntimeModule() { return RuntimeTypeHandle.GetModule(RuntimeFieldHandle.GetApproxDeclaringType(this)); } #endregion #region FieldInfo Overrides public override Object GetValue(Object obj) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetValue(obj, ref stackMark); } public override object GetRawConstantValue() { throw new InvalidOperationException(); } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValueDirect(TypedReference obj) { if (obj.IsNull) throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); Contract.EndContractBlock(); unsafe { // Passing TypedReference by reference is easier to make correct in native code return RuntimeFieldHandle.GetValueDirect(this, (RuntimeType)FieldType, &obj, (RuntimeType)DeclaringType); } } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; InternalSetValue(obj, value, invokeAttr, binder, culture, ref stackMark); } [System.Security.SecuritySafeCritical] // auto-generated [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValueDirect(TypedReference obj, Object value) { if (obj.IsNull) throw new ArgumentException(Environment.GetResourceString("Arg_TypedReference_Null")); Contract.EndContractBlock(); unsafe { // Passing TypedReference by reference is easier to make correct in native code RuntimeFieldHandle.SetValueDirect(this, (RuntimeType)FieldType, &obj, value, (RuntimeType)DeclaringType); } } public override RuntimeFieldHandle FieldHandle { get { Type declaringType = DeclaringType; if ((declaringType == null && Module.Assembly.ReflectionOnly) || declaringType is ReflectionOnlyType) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_NotAllowedInReflectionOnly")); return new RuntimeFieldHandle(this); } } internal IntPtr GetFieldHandle() { return m_fieldHandle; } public override FieldAttributes Attributes { get { return m_fieldAttributes; } } public override Type FieldType { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_fieldType == null) m_fieldType = new Signature(this, m_declaringType).FieldType; return m_fieldType; } } [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetRequiredCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, true); } [System.Security.SecuritySafeCritical] // auto-generated public override Type[] GetOptionalCustomModifiers() { return new Signature(this, m_declaringType).GetCustomModifiers(1, false); } #endregion } [Serializable] internal sealed unsafe class MdFieldInfo : RuntimeFieldInfo, ISerializable { #region Private Data Members private int m_tkField; private string m_name; private RuntimeType m_fieldType; private FieldAttributes m_fieldAttributes; #endregion #region Constructor internal MdFieldInfo( int tkField, FieldAttributes fieldAttributes, RuntimeTypeHandle declaringTypeHandle, RuntimeTypeCache reflectedTypeCache, BindingFlags bindingFlags) : base(reflectedTypeCache, declaringTypeHandle.GetRuntimeType(), bindingFlags) { m_tkField = tkField; m_name = null; m_fieldAttributes = fieldAttributes; } #endregion #region Internal Members [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal override bool CacheEquals(object o) { MdFieldInfo m = o as MdFieldInfo; if ((object)m == null) return false; return m.m_tkField == m_tkField && m_declaringType.GetTypeHandleInternal().GetModuleHandle().Equals( m.m_declaringType.GetTypeHandleInternal().GetModuleHandle()); } #endregion #region MemberInfo Overrides public override String Name { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_name == null) m_name = GetRuntimeModule().MetadataImport.GetName(m_tkField).ToString(); return m_name; } } public override int MetadataToken { get { return m_tkField; } } internal override RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); } #endregion #region FieldInfo Overrides public override RuntimeFieldHandle FieldHandle { get { throw new NotSupportedException(); } } public override FieldAttributes Attributes { get { return m_fieldAttributes; } } public override bool IsSecurityCritical { get { return DeclaringType.IsSecurityCritical; } } public override bool IsSecuritySafeCritical { get { return DeclaringType.IsSecuritySafeCritical; } } public override bool IsSecurityTransparent { get { return DeclaringType.IsSecurityTransparent; } } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override Object GetValueDirect(TypedReference obj) { return GetValue(null); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValueDirect(TypedReference obj,Object value) { throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public unsafe override Object GetValue(Object obj) { return GetValue(false); } public unsafe override Object GetRawConstantValue() { return GetValue(true); } [System.Security.SecuritySafeCritical] // auto-generated private unsafe Object GetValue(bool raw) { // Cannot cache these because they could be user defined non-agile enumerations Object value = MdConstant.GetValue(GetRuntimeModule().MetadataImport, m_tkField, FieldType.GetTypeHandleInternal(), raw); if (value == DBNull.Value) throw new NotSupportedException(Environment.GetResourceString("Arg_EnumLitValueNotFound")); return value; } [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public override void SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { throw new FieldAccessException(Environment.GetResourceString("Acc_ReadOnly")); } public override Type FieldType { [System.Security.SecuritySafeCritical] // auto-generated get { if (m_fieldType == null) { ConstArray fieldMarshal = GetRuntimeModule().MetadataImport.GetSigOfFieldDef(m_tkField); m_fieldType = new Signature(fieldMarshal.Signature.ToPointer(), (int)fieldMarshal.Length, m_declaringType).FieldType; } return m_fieldType; } } public override Type[] GetRequiredCustomModifiers() { return EmptyArray<Type>.Value; } public override Type[] GetOptionalCustomModifiers() { return EmptyArray<Type>.Value; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Threading.Tasks; using Xunit; namespace System.IO.Compression.Tests { public class zip_InvalidParametersAndStrangeFiles : ZipFileTestBase { private static void ConstructorThrows<TException>(Func<ZipArchive> constructor, string Message) where TException : Exception { try { Assert.Throws<TException>(() => { using (ZipArchive archive = constructor()) { } }); } catch (Exception e) { Console.WriteLine(string.Format("{0}: {1}", Message, e.ToString())); throw; } } [Fact] public static async Task InvalidInstanceMethods() { Stream zipFile = await StreamHelpers.CreateTempCopyStream(zfile("normal.zip")); using (ZipArchive archive = new ZipArchive(zipFile, ZipArchiveMode.Update)) { //non-existent entry Assert.True(null == archive.GetEntry("nonExistentEntry")); //"Should return null on non-existent entry name" //null/empty string Assert.Throws<ArgumentNullException>(() => archive.GetEntry(null)); //"Should throw on null entry name" ZipArchiveEntry entry = archive.GetEntry("first.txt"); //null/empty string Assert.Throws<ArgumentException>(() => archive.CreateEntry("")); //"Should throw on empty entry name" Assert.Throws<ArgumentNullException>(() => archive.CreateEntry(null)); //"should throw on null entry name" } } [Fact] public static void InvalidConstructors() { //out of range enum values ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(-1)), "Out of range enum"); ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(4)), "out of range enum"); ConstructorThrows<ArgumentOutOfRangeException>(() => new ZipArchive(new MemoryStream(), (ZipArchiveMode)(10)), "Out of range enum"); //null/closed stream ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Read), "Null/closed stream"); ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Create), "Null/closed stream"); ConstructorThrows<ArgumentNullException>(() => new ZipArchive((Stream)null, ZipArchiveMode.Update), "Null/closed stream"); MemoryStream ms = new MemoryStream(); ms.Dispose(); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Read), "Disposed Base Stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Create), "Disposed Base Stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(ms, ZipArchiveMode.Update), "Disposed Base Stream"); //non-seekable to update using (LocalMemoryStream nonReadable = new LocalMemoryStream(), nonWriteable = new LocalMemoryStream(), nonSeekable = new LocalMemoryStream()) { nonReadable.SetCanRead(false); nonWriteable.SetCanWrite(false); nonSeekable.SetCanSeek(false); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonReadable, ZipArchiveMode.Read), "Non readable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonWriteable, ZipArchiveMode.Create), "Non-writable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonReadable, ZipArchiveMode.Update), "Non-readable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonWriteable, ZipArchiveMode.Update), "Non-writable stream"); ConstructorThrows<ArgumentException>(() => new ZipArchive(nonSeekable, ZipArchiveMode.Update), "Non-seekable stream"); } } [Theory] [InlineData("LZMA.zip")] [InlineData("invalidDeflate.zip")] public static async Task ZipArchiveEntry_InvalidUpdate(string zipname) { string filename = bad(zipname); Stream updatedCopy = await StreamHelpers.CreateTempCopyStream(filename); string name; long length, compressedLength; DateTimeOffset lastWriteTime; using (ZipArchive archive = new ZipArchive(updatedCopy, ZipArchiveMode.Update, true)) { ZipArchiveEntry e = archive.Entries[0]; name = e.FullName; lastWriteTime = e.LastWriteTime; length = e.Length; compressedLength = e.CompressedLength; Assert.Throws<InvalidDataException>(() => e.Open()); //"Should throw on open" } //make sure that update mode preserves that unreadable file using (ZipArchive archive = new ZipArchive(updatedCopy, ZipArchiveMode.Update)) { ZipArchiveEntry e = archive.Entries[0]; Assert.Equal(name, e.FullName); //"Name isn't the same" Assert.Equal(lastWriteTime, e.LastWriteTime); //"LastWriteTime not the same" Assert.Equal(length, e.Length); //"Length isn't the same" Assert.Equal(compressedLength, e.CompressedLength); //"CompressedLength isn't the same" Assert.Throws<InvalidDataException>(() => e.Open()); //"Should throw on open" } } [Theory] [InlineData("CDoffsetOutOfBounds.zip")] [InlineData("EOCDmissing.zip")] public static async Task ZipArchive_InvalidStream(string zipname) { string filename = bad(zipname); using (var stream = await StreamHelpers.CreateTempCopyStream(filename)) Assert.Throws<InvalidDataException>(() => new ZipArchive(stream, ZipArchiveMode.Read)); } [Theory] [InlineData("CDoffsetInBoundsWrong.zip")] [InlineData("numberOfEntriesDifferent.zip")] public static async Task ZipArchive_InvalidEntryTable(string zipname) { string filename = bad(zipname); using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(filename), ZipArchiveMode.Read)) Assert.Throws<InvalidDataException>(() => archive.Entries[0]); } [Theory] [InlineData("compressedSizeOutOfBounds.zip", true)] [InlineData("localFileHeaderSignatureWrong.zip", true)] [InlineData("localFileOffsetOutOfBounds.zip", true)] [InlineData("LZMA.zip", true)] [InlineData("invalidDeflate.zip", false)] public static async Task ZipArchive_InvalidEntry(string zipname, bool throwsOnOpen) { string filename = bad(zipname); using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream(filename), ZipArchiveMode.Read)) { ZipArchiveEntry e = archive.Entries[0]; if (throwsOnOpen) { Assert.Throws<InvalidDataException>(() => e.Open()); //"should throw on open" } else { using (Stream s = e.Open()) { Assert.Throws<InvalidDataException>(() => s.ReadByte()); //"Unreadable stream" } } } } [Fact] public static async Task ZipArchiveEntry_InvalidLastWriteTime_Read() { using (ZipArchive archive = new ZipArchive(await StreamHelpers.CreateTempCopyStream( bad("invaliddate.zip")), ZipArchiveMode.Read)) { Assert.Equal(new DateTime(1980, 1, 1, 0, 0, 0), archive.Entries[0].LastWriteTime.DateTime); //"Date isn't correct on invalid date" } } [Fact] public static void ZipArchiveEntry_InvalidLastWriteTime_Write() { using (ZipArchive archive = new ZipArchive(new MemoryStream(), ZipArchiveMode.Create)) { ZipArchiveEntry entry = archive.CreateEntry("test"); Assert.Throws<ArgumentOutOfRangeException>(() => { //"should throw on bad date" entry.LastWriteTime = new DateTimeOffset(1979, 12, 3, 5, 6, 2, new TimeSpan()); }); Assert.Throws<ArgumentOutOfRangeException>(() => { //"Should throw on bad date" entry.LastWriteTime = new DateTimeOffset(2980, 12, 3, 5, 6, 2, new TimeSpan()); }); } } [Theory] [InlineData("extradata/extraDataLHandCDentryAndArchiveComments.zip", "verysmall", true)] [InlineData("extradata/extraDataThenZip64.zip", "verysmall", true)] [InlineData("extradata/zip64ThenExtraData.zip", "verysmall", true)] [InlineData("dataDescriptor.zip", "normalWithoutBinary", false)] [InlineData("filenameTimeAndSizesDifferentInLH.zip", "verysmall", false)] public static async Task StrangeFiles(string zipFile, string zipFolder, bool requireExplicit) { IsZipSameAsDir(await StreamHelpers.CreateTempCopyStream(strange(zipFile)), zfolder(zipFolder), ZipArchiveMode.Update, requireExplicit, checkTimes: true); } /// <summary> /// This test tiptoes the buffer boundaries to ensure that the size of a read buffer doesn't /// cause any bytes to be left in ZLib's buffer. /// </summary> [Fact] public static void ZipWithLargeSparseFile() { string zipname = strange("largetrailingwhitespacedeflation.zip"); string entryname = "A/B/C/D"; using (FileStream stream = File.Open(zipname, FileMode.Open, FileAccess.Read)) using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read)) { ZipArchiveEntry entry = archive.GetEntry(entryname); long size = entry.Length; for (int bufferSize = 1; bufferSize <= size; bufferSize++) { using (Stream entryStream = entry.Open()) { byte[] b = new byte[bufferSize]; int read = 0, count = 0; while ((read = entryStream.Read(b, 0, bufferSize)) > 0) { count += read; } Assert.Equal(size, count); } } } } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; using System.Globalization; using System.IO; using NodaTime.Text; using NodaTime.TimeZones; using NodaTime.Utility; namespace NodaTime.TzdbCompiler.Tzdb { /// <summary> /// Provides a parser for TZDB time zone description files. /// </summary> internal class TzdbZoneInfoParser { /// <summary> /// The keyword that specifies the line defines an alias link. /// </summary> private const string KeywordLink = "Link"; /// <summary> /// The keyword that specifies the line defines a daylight savings rule. /// </summary> private const string KeywordRule = "Rule"; /// <summary> /// The keyword that specifies the line defines a time zone. /// </summary> private const string KeywordZone = "Zone"; /// <summary> /// The days of the week names as they appear in the TZDB zone files. They are /// always the short name in US English. /// </summary> public static readonly string[] DaysOfWeek = { "", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" }; /// <summary> /// The months of the year names as they appear in the TZDB zone files. They are /// always the short name in US English. Extra blank name at the beginning helps /// to make the indexes to come out right. /// </summary> public static readonly string[] Months = { "", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; /// <summary> /// Nexts the month. /// </summary> /// <param name="tokens">The tokens.</param> /// <param name="name">The name.</param> private int NextMonth(Tokens tokens, string name) { var value = NextString(tokens, name); int result = ParseMonth(value); return result == 0 ? 1 : result; } /// <summary> /// Nexts the offset. /// </summary> /// <param name="tokens">The tokens.</param> /// <param name="name">The name.</param> private Offset NextOffset(Tokens tokens, string name) { return ParserHelper.ParseOffset(NextString(tokens, name)); } /// <summary> /// Nexts the optional. /// </summary> /// <param name="tokens">The tokens.</param> /// <param name="name">The name.</param> private string NextOptional(Tokens tokens, string name) { return ParserHelper.ParseOptional(NextString(tokens, name)); } /// <summary> /// Nexts the string. /// </summary> /// <param name="tokens">The tokens.</param> /// <param name="name">The name.</param> private string NextString(Tokens tokens, string name) { if (!tokens.HasNextToken) { throw new InvalidDataException("Missing zone info token: " + name); } return tokens.NextToken(name); } /// <summary> /// Nexts the year. /// </summary> /// <param name="tokens">The tokens.</param> /// <param name="name">The name.</param> /// <param name="defaultValue">The default value.</param> private static int NextYear(Tokens tokens, string name, int defaultValue) { int result = defaultValue; string text; if (tokens.TryNextToken(name, out text)) { result = ParserHelper.ParseYear(text, defaultValue); } return result; } /// <summary> /// Parses the TZDB time zone info file from the given stream and merges its information /// with the given database. The stream is not closed or disposed. /// </summary> /// <param name="input">The stream input to parse.</param> /// <param name="database">The database to fill.</param> public void Parse(Stream input, TzdbDatabase database) { Parse(new StreamReader(input, true), database); } /// <summary> /// Parses the TZDB time zone info file from the given reader and merges its information /// with the given database. The reader is not closed or disposed. /// </summary> /// <param name="reader">The reader to read.</param> /// <param name="database">The database to fill.</param> public void Parse(TextReader reader, TzdbDatabase database) { bool firstLine = true; for (var line = reader.ReadLine(); line != null; line = reader.ReadLine()) { // Only bother with files which start with comments. if (firstLine && !line.StartsWith("# ", StringComparison.Ordinal)) { return; } firstLine = false; ParseLine(line, database); } } /// <summary> /// Parses the date time of year. /// </summary> /// <param name="tokens">The tokens to parse.</param> /// <param name="forRule">True if this is for a Rule line, in which case ON/AT are mandatory; /// false for a Zone line, in which case it's part of "until" and they're optional</param> /// <returns>The DateTimeOfYear object.</returns> /// <remarks> /// IN ON AT /// </remarks> internal ZoneYearOffset ParseDateTimeOfYear(Tokens tokens, bool forRule) { var mode = ZoneYearOffset.StartOfYear.Mode; var timeOfDay = ZoneYearOffset.StartOfYear.TimeOfDay; int monthOfYear = NextMonth(tokens, "MonthOfYear"); int dayOfMonth = 1; int dayOfWeek = 0; bool advanceDayOfWeek = false; bool addDay = false; if (tokens.HasNextToken || forRule) { var on = NextString(tokens, "On"); if (on.StartsWith("last", StringComparison.Ordinal)) { dayOfMonth = -1; dayOfWeek = ParseDayOfWeek(on.Substring(4)); } else { int index = on.IndexOf(">=", StringComparison.Ordinal); if (index > 0) { dayOfMonth = Int32.Parse(on.Substring(index + 2), CultureInfo.InvariantCulture); dayOfWeek = ParseDayOfWeek(on.Substring(0, index)); advanceDayOfWeek = true; } else { index = on.IndexOf("<=", StringComparison.Ordinal); if (index > 0) { dayOfMonth = Int32.Parse(on.Substring(index + 2), CultureInfo.InvariantCulture); dayOfWeek = ParseDayOfWeek(on.Substring(0, index)); } else { try { dayOfMonth = Int32.Parse(on, CultureInfo.InvariantCulture); dayOfWeek = 0; } catch (FormatException e) { throw new ArgumentException("Unparsable ON token: " + on, e); } } } } if (tokens.HasNextToken || forRule) { var atTime = NextString(tokens, "AT"); if (!string.IsNullOrEmpty(atTime)) { if (Char.IsLetter(atTime[atTime.Length - 1])) { char zoneCharacter = atTime[atTime.Length - 1]; mode = ConvertModeCharacter(zoneCharacter); atTime = atTime.Substring(0, atTime.Length - 1); } if (atTime == "24:00") { timeOfDay = LocalTime.Midnight; addDay = true; } else { timeOfDay = ParserHelper.ParseTime(atTime); } } } } return new ZoneYearOffset(mode, monthOfYear, dayOfMonth, dayOfWeek, advanceDayOfWeek, timeOfDay, addDay); } /// <summary> /// Parses the day of week. /// </summary> /// <param name="text">The text.</param> private static int ParseDayOfWeek(string text) { Preconditions.CheckArgument(!string.IsNullOrEmpty(text), "text", "Value must not be empty or null"); int index = Array.IndexOf(DaysOfWeek, text, 1); if (index == -1) { throw new InvalidDataException("Invalid day of week: " + text); } return index; } /// <summary> /// Parses a single line of an TZDB zone info file. /// </summary> /// <remarks> /// <para> /// TZDB files have a simple line based structure. Each line defines one item. Comments /// start with a hash or pound sign (#) and continue to the end of the line. Blank lines are /// ignored. Of the remaining there are four line types which are determined by the first /// keyword on the line. /// </para> /// <para> /// A line beginning with the keyword <c>Link</c> defines an alias between one time zone and /// another. Both time zones use the same definition but have different names. /// </para> /// <para> /// A line beginning with the keyword <c>Rule</c> defines a daylight savings time /// calculation rule. /// </para> /// <para> /// A line beginning with the keyword <c>Zone</c> defines a time zone. /// </para> /// <para> /// A line beginning with leading whitespace (an empty keyword) defines another part of the /// preceeding time zone. As many lines as necessary to define the time zone can be listed, /// but they must all be together and only the first line can have a name. /// </para> /// </remarks> /// <param name="line">The line to parse.</param> /// <param name="database">The database to fill.</param> internal void ParseLine(string line, TzdbDatabase database) { int index = line.IndexOf("#", StringComparison.Ordinal); if (index == 0) { return; } if (index > 0) { line = line.Substring(0, index - 1); } line = line.TrimEnd(); if (line.Length == 0) { return; } var tokens = Tokens.Tokenize(line); var keyword = NextString(tokens, "Keyword"); switch (keyword) { case KeywordRule: database.AddRule(ParseRule(tokens)); break; case KeywordLink: database.AddAlias(ParseLink(tokens)); break; case KeywordZone: var name = NextString(tokens, "GetName"); var namedZone = ParseZone(name, tokens); database.AddZone(namedZone); break; default: if (string.IsNullOrEmpty(keyword)) { var zone = ParseZone(string.Empty, tokens); database.AddZone(zone); } else { throw new InvalidDataException("Unexpected zone database keyword: " + keyword); } break; } } /// <summary> /// Parses an alias link and returns the ZoneAlias object. /// </summary> /// <param name="tokens">The tokens to parse.</param> /// <returns>The ZoneAlias object.</returns> internal ZoneAlias ParseLink(Tokens tokens) { var existing = NextString(tokens, "Existing"); var alias = NextString(tokens, "Alias"); return new ZoneAlias(existing, alias); } /// <summary> /// Parses the month. /// </summary> /// <param name="text">The text.</param> /// <returns>The month number 1-12 or 0 if the month is not valid</returns> internal static int ParseMonth(String text) { for (int i = 1; i < Months.Length; i++) { if (text == Months[i]) { return i; } } return 0; } /// <summary> /// Parses a daylight savings rule and returns the Rule object. /// </summary> /// <remarks> /// # Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S /// </remarks> /// <param name="tokens">The tokens to parse.</param> /// <returns>The Rule object.</returns> internal ZoneRule ParseRule(Tokens tokens) { var name = NextString(tokens, "GetName"); int fromYear = NextYear(tokens, "FromYear", 0); int toYear = NextYear(tokens, "ToYear", fromYear); if (toYear < fromYear) { throw new ArgumentException("To year cannot be before the from year in a Rule: " + toYear + " < " + fromYear); } /* string type = */ NextOptional(tokens, "Type"); var yearOffset = ParseDateTimeOfYear(tokens, true); var savings = NextOffset(tokens, "SaveMillis"); var letterS = NextOptional(tokens, "LetterS"); var recurrence = new ZoneRecurrence(name, savings, yearOffset, fromYear, toYear); return new ZoneRule(recurrence, letterS); } /// <summary> /// Parses a time zone definition and returns the Zone object. /// </summary> /// <remarks> /// # GMTOFF RULES FORMAT [ UntilYear [ UntilMonth [ UntilDay [ UntilTime [ ZoneCharacter ] ] ] ] ] /// </remarks> /// <param name="name">The name of the zone being parsed.</param> /// <param name="tokens">The tokens to parse.</param> /// <returns>The Zone object.</returns> internal Zone ParseZone(string name, Tokens tokens) { var offset = NextOffset(tokens, "Gmt Offset"); var rules = NextOptional(tokens, "Rules"); var format = NextString(tokens, "Format"); int year = NextYear(tokens, "Until Year", Int32.MaxValue); if (tokens.HasNextToken) { var until = ParseDateTimeOfYear(tokens, false); return new Zone(name, offset, rules, format, year, until); } return new Zone(name, offset, rules, format, year, ZoneYearOffset.StartOfYear); } /// <summary> /// Normalizes the transition mode characater. /// </summary> /// <param name="modeCharacter">The character to normalize.</param> /// <returns>The <see cref="TransitionMode"/>.</returns> private static TransitionMode ConvertModeCharacter(char modeCharacter) { switch (modeCharacter) { case 's': case 'S': return TransitionMode.Standard; case 'u': case 'U': case 'g': case 'G': case 'z': case 'Z': return TransitionMode.Utc; default: return TransitionMode.Wall; } } } }
using Meziantou.Framework.CodeDom; using Microsoft.CodeAnalysis; namespace Meziantou.Framework.StronglyTypedId; public partial class StronglyTypedIdSourceGenerator { private static void GenerateSystemTextJsonConverter(ClassOrStructDeclaration structDeclaration, Compilation compilation, StronglyTypedIdInfo stronglyTypedType) { if (!IsTypeDefined(compilation, "System.Text.Json.Serialization.JsonConverter`1")) return; var idType = stronglyTypedType.AttributeInfo.IdType; var typeReference = new TypeReference(structDeclaration); if (stronglyTypedType.IsReferenceType) { typeReference = typeReference.MakeNullable(); } var converter = structDeclaration.AddType(new ClassDeclaration(structDeclaration.Name + "JsonConverter") { Modifiers = Modifiers.Private | Modifiers.Partial }); structDeclaration.CustomAttributes.Add(new CustomAttribute(new TypeReference("System.Text.Json.Serialization.JsonConverterAttribute")) { Arguments = { new CustomAttributeArgument(new TypeOfExpression(converter)) } }); converter.BaseType = new TypeReference("System.Text.Json.Serialization.JsonConverter").MakeGeneric(typeReference); // public abstract void Write (System.Text.Json.Utf8JsonWriter writer, T value, System.Text.Json.JsonSerializerOptions options); { var writeMethod = converter.AddMember(new MethodDeclaration("Write") { Modifiers = Modifiers.Public | Modifiers.Override }); var writerArg = writeMethod.AddArgument("writer", new TypeReference("System.Text.Json.Utf8JsonWriter")); var valueArg = writeMethod.AddArgument("value", typeReference); var optionsArg = writeMethod.AddArgument("options", new TypeReference("System.Text.Json.JsonSerializerOptions")); if (stronglyTypedType.IsReferenceType) { writeMethod.Statements = new ConditionStatement { Condition = Expression.EqualsNull(valueArg), TrueStatements = writerArg.Member("WriteNullValue").InvokeMethod(), FalseStatements = GetWriteStatement(), }; } else { writeMethod.Statements = GetWriteStatement(); } StatementCollection GetWriteStatement() { if (idType == IdType.System_Boolean) { return new StatementCollection { new MethodInvokeExpression( new MemberReferenceExpression(writerArg, "WriteBooleanValue"), new MemberReferenceExpression(valueArg, "Value")), }; } else if (CanUseWriteNumberValue()) { return new StatementCollection { new MethodInvokeExpression( new MemberReferenceExpression(writerArg, "WriteNumberValue"), new MemberReferenceExpression(valueArg, "Value")), }; } else if (CanUseWriteNumberValueWithCastToInt()) { return new StatementCollection { new MethodInvokeExpression( new MemberReferenceExpression(writerArg, "WriteNumberValue"), new CastExpression(valueArg.Member("Value"), typeof(int))), }; } else if (CanUseWriteNumberValueWithCastToUInt()) { return new StatementCollection { new MethodInvokeExpression( new MemberReferenceExpression(writerArg, "WriteNumberValue"), new CastExpression(valueArg.Member("Value"), typeof(uint))), }; } else if (CanUseWriteStringValue()) { return new StatementCollection { new MethodInvokeExpression( new MemberReferenceExpression(writerArg, "WriteStringValue"), new MemberReferenceExpression(valueArg, "Value")), }; } else { // JsonSerializer.Serialize(writer, value.Value, options) return new StatementCollection { new MethodInvokeExpression( new MemberReferenceExpression(new TypeReference("System.Text.Json.JsonSerializer"), "Serialize"), writerArg, new MemberReferenceExpression(valueArg, "Value"), optionsArg), }; } } bool CanUseWriteNumberValue() { return idType == IdType.System_Decimal || idType == IdType.System_Double || idType == IdType.System_Int32 || idType == IdType.System_Int64 || idType == IdType.System_Single || idType == IdType.System_UInt32 || idType == IdType.System_UInt64; } bool CanUseWriteNumberValueWithCastToInt() { return idType == IdType.System_Int16 || idType == IdType.System_SByte; } bool CanUseWriteNumberValueWithCastToUInt() { return idType == IdType.System_Byte || idType == IdType.System_UInt16; } bool CanUseWriteStringValue() { return idType == IdType.System_DateTime || idType == IdType.System_DateTimeOffset || idType == IdType.System_Guid || idType == IdType.System_String; } } // public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var readMethod = converter.AddMember(new MethodDeclaration("Read") { Modifiers = Modifiers.Public | Modifiers.Override }); readMethod.ReturnType = typeReference; var readerArg = readMethod.AddArgument("reader", new TypeReference("System.Text.Json.Utf8JsonReader"), Direction.InOut); _ = readMethod.AddArgument("typeToConvert", typeof(Type)); _ = readMethod.AddArgument("options", new TypeReference("System.Text.Json.JsonSerializerOptions")); readMethod.Statements = new StatementCollection(); var valueVariable = readMethod.Statements.Add(new VariableDeclarationStatement("value", typeReference, new DefaultValueExpression(structDeclaration))); readMethod.Statements.Add(new ConditionStatement { Condition = CompareTokenType(BinaryOperator.Equals, "StartObject"), TrueStatements = CreateObjectParsing(), FalseStatements = ReadValue(), }); readMethod.Statements.Add(new ReturnStatement(valueVariable)); BinaryExpression CompareTokenType(BinaryOperator op, string tokenType) { return new BinaryExpression( op, readerArg.Member("TokenType"), new MemberReferenceExpression(new TypeReference("System.Text.Json.JsonTokenType"), tokenType)); } StatementCollection CreateObjectParsing() { var statements = new StatementCollection(); var valueRead = statements.Add(new VariableDeclarationStatement("valueRead", typeof(bool), Expression.False())); statements.Add(ReaderRead()); statements.Add(new WhileStatement() { Condition = CompareTokenType(BinaryOperator.NotEquals, "EndObject"), Body = new StatementCollection { new ConditionStatement() { Condition = Expression.And( UnaryExpression.Not(valueRead), CompareTokenType(BinaryOperator.Equals, "PropertyName"), readerArg.Member("ValueTextEquals").InvokeMethod(new LiteralExpression("Value"))), TrueStatements = new StatementCollection { ReaderRead(), ReadValue(), new AssignStatement(valueRead, Expression.True()), ReaderRead(), }, FalseStatements = new StatementCollection { ReaderSkip(), ReaderRead(), }, }, }, }); return statements; } Statement ReaderRead() { return new MethodInvokeExpression(readerArg.Member("Read")); } Statement ReaderSkip() { return new MethodInvokeExpression(readerArg.Member("Skip")); } Statement ReadValue() { return new AssignStatement( valueVariable, new NewObjectExpression( structDeclaration, new MethodInvokeExpression(new MemberReferenceExpression(readerArg, "Get" + GetShortName(GetTypeReference(idType)))))) { NullableContext = CodeDom.NullableContext.Disable, }; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using Microsoft.Practices.Prism.Regions; namespace StockTraderRI.Modules.Position.Tests.Mocks { public class MockRegionManager : IRegionManager { private MockRegionCollection _regions = new MockRegionCollection(); public IRegionCollection Regions { get { return _regions; } } public IRegion AttachNewRegion(object regionTarget, string regionName) { throw new NotImplementedException(); } public IRegionManager CreateRegionManager() { throw new NotImplementedException(); } public bool Navigate(Uri source) { throw new NotImplementedException(); } } internal class MockRegionCollection : IRegionCollection { private Dictionary<string, IRegion> regions = new Dictionary<string, IRegion>(); public IEnumerator<IRegion> GetEnumerator() { throw new System.NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IRegion this[string regionName] { get { return regions[regionName]; } } public void Add(IRegion region) { regions[region.Name] = region; } public bool Remove(string regionName) { throw new System.NotImplementedException(); } public bool ContainsRegionWithName(string regionName) { throw new System.NotImplementedException(); } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; } public class MockRegion : IRegion { public List<object> AddedViews = new List<object>(); public string Name { get; set; } public IRegionManager Add(object view) { AddedViews.Add(view); return null; } public void Remove(object view) { AddedViews.Remove(view); } public IViewsCollection Views { get { return new MockViewsCollection(AddedViews); } } public void Activate(object view) { SelectedItem = view; } public void Deactivate(object view) { throw new NotImplementedException(); } public IRegionManager Add(object view, string viewName) { Add(view); return null; } public object GetView(string viewName) { return AddedViews.Count > 0 ? AddedViews[0] : null; } public IRegionManager Add(object view, string viewName, bool createRegionManagerScope) { throw new NotImplementedException(); } public IRegionManager RegionManager { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public IRegionBehaviorCollection Behaviors { get { throw new System.NotImplementedException(); } } public object SelectedItem { get; set; } public IViewsCollection ActiveViews { get { throw new NotImplementedException(); } } public object Context { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public NavigationParameters NavigationParameters { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public event PropertyChangedEventHandler PropertyChanged; public void RequestNavigate(Uri source, Action<NavigationResult> navigationCallback) { throw new NotImplementedException(); } public void RequestNavigate(Uri source, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters) { throw new NotImplementedException(); } public IRegionNavigationService NavigationService { get { throw new NotImplementedException(); } set { throw new System.NotImplementedException(); } } public Comparison<object> SortComparison { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void MoveFrom(IRegion sourceRegion, object view) { throw new System.NotImplementedException(); } public void MoveFrom(IRegion sourceRegion, object view, string viewName) { throw new System.NotImplementedException(); } } internal class MockViewsCollection : IViewsCollection { private readonly IList<object> views; public MockViewsCollection(IList<object> views) { this.views = views; } public bool Contains(object value) { throw new NotImplementedException(); } public IEnumerator<object> GetEnumerator() { return views.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } public event System.Collections.Specialized.NotifyCollectionChangedEventHandler CollectionChanged; } }
using Mono.Cecil; using System.Linq; using Mono.Cecil.Cil; using System.IO; using System; using System.Linq.Expressions; using System.Collections.Generic; using Mono.Cecil.Rocks; namespace Signum.MSBuildTask { internal class ExpressionFieldGenerator { AssemblyDefinition Assembly; TextWriter Log; PreloadingAssemblyResolver Resolver; AssemblyDefinition SystemRuntime; AssemblyDefinition SignumUtilities; TypeDefinition ExpressionField; TypeDefinition AutoExpressionField; TypeDefinition ExpressionExtensions; MethodReference Type_GetTypeFromHandle; MethodReference Expression_Parameter; MethodReference Expression_Lambda; MethodReference Array_Empty; TypeDefinition ParameterExpression; bool hasErrors = false; public ExpressionFieldGenerator(AssemblyDefinition assembly, PreloadingAssemblyResolver resolver, TextWriter log) { this.Assembly = assembly; this.Resolver = resolver; this.Log = log; this.SystemRuntime = resolver.SystemRuntime; this.SignumUtilities = assembly.Name.Name == "Signum.Utilities" ? assembly : resolver.SignumUtilities; this.ExpressionField = SignumUtilities.MainModule.GetType("Signum.Utilities", "ExpressionFieldAttribute"); this.AutoExpressionField = SignumUtilities.MainModule.GetType("Signum.Utilities", "AutoExpressionFieldAttribute"); this.ExpressionExtensions = SignumUtilities.MainModule.GetType("Signum.Utilities", "ExpressionExtensions"); this.Type_GetTypeFromHandle = this.SystemRuntime.MainModule.GetType("System", "Type").Methods.Single(a => a.Name == "GetTypeFromHandle"); var expressionType = resolver.SystemLinqExpressions.MainModule.GetType("System.Linq.Expressions", nameof(System.Linq.Expressions.Expression)); this.Expression_Parameter = expressionType.Methods.Single(a => a.Name == nameof(Expression.Parameter) && a.Parameters.Count == 2); this.Expression_Lambda = expressionType.Methods.Single(a => a.Name == nameof(Expression.Lambda) && a.GenericParameters.Count == 1 && a.Parameters.Count == 2 && a.Parameters[1].ParameterType.IsArray); this.ParameterExpression = resolver.SystemLinqExpressions.MainModule.GetType("System.Linq.Expressions", nameof(System.Linq.Expressions.ParameterExpression)); this.Array_Empty = resolver.SystemRuntime.MainModule.GetType("System", "Array").Methods.Single(a => a.Name == "Empty"); } internal bool FixAutoExpressionField() { var methodPairs = (from type in this.Assembly.MainModule.Types where type.HasMethods from method in type.Methods where method.HasCustomAttributes let at = method.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == AutoExpressionField.FullName) where at != null select new { type, method, member = (IMemberDefinition)method, at }).ToList(); var propertyPairs = (from type in this.Assembly.MainModule.Types where type.HasProperties from p in type.Properties where p.HasCustomAttributes let at = p.CustomAttributes.SingleOrDefault(a => a.AttributeType.FullName == AutoExpressionField.FullName) where at != null select new { type, method = p.GetMethod, member = (IMemberDefinition)p, at }).ToList(); var VoidType = this.SystemRuntime.MainModule.ImportReference(typeof(void)); var StringType = this.SystemRuntime.MainModule.ImportReference(typeof(string)); foreach (var p in methodPairs.Concat(propertyPairs)) { string name = GetFreeName(p.member.Name, p.type); var fieldType = p.type.Module.ImportReference(GetExpressionType(p.method)); var expressionField = new FieldDefinition(name + "Expression", FieldAttributes.Static | FieldAttributes.Private, fieldType); p.type.Fields.Add(expressionField); var newMethod = new MethodDefinition(name + "Init", MethodAttributes.Static | MethodAttributes.Private, VoidType); newMethod.IsHideBySig = true; var constructor = p.type.Methods.SingleOrDefault(a => a.IsConstructor && a.IsStatic); if (constructor == null) { constructor = new MethodDefinition(".cctor", MethodAttributes.Private | MethodAttributes.Static | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName | MethodAttributes.HideBySig, VoidType); if (!constructor.IsConstructor) throw new InvalidOperationException(); constructor.Body.Instructions.Add(Instruction.Create(OpCodes.Ret)); p.type.Methods.Insert(0, constructor); } p.type.Methods.Add(newMethod); constructor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, newMethod)); Transform(p.type.Module, p.method, newMethod, expressionField, out var closureType); if (closureType != null) p.type.NestedTypes.Remove(closureType); p.member.CustomAttributes.Remove(p.at); var attrConstructor = p.type.Module.ImportReference(this.ExpressionField.Methods.Single(a => a.IsConstructor && a.IsPublic)); p.member.CustomAttributes.Add(new CustomAttribute(attrConstructor) { ConstructorArguments = { new CustomAttributeArgument(StringType, name + "Expression") } }); } return hasErrors; } private void Transform(ModuleDefinition mod, MethodDefinition method, MethodDefinition newMethod, FieldDefinition expressionField, out TypeDefinition closureType) { var writer = newMethod.Body.GetILProcessor(); Dictionary<ParameterReference, VariableDefinition> oldParameterToNNewVariable = new Dictionary<ParameterReference, VariableDefinition>(); newMethod.Body.InitLocals = true; writer.Emit(OpCodes.Nop); var allParameters = method.Parameters.ToList(); if (method.Body.ThisParameter != null) allParameters.Insert(0, method.Body.ThisParameter); foreach (var p in allParameters) { var variable = new VariableDefinition(mod.ImportReference(ParameterExpression)); newMethod.Body.Variables.Add(variable); writer.Emit(OpCodes.Ldtoken, p.ParameterType); writer.Emit(OpCodes.Call, mod.ImportReference(this.Type_GetTypeFromHandle)); writer.Emit(OpCodes.Ldstr, p == method.Body.ThisParameter ? "this" : p.Name); writer.Emit(OpCodes.Call, mod.ImportReference(this.Expression_Parameter)); writer.Emit(OpCodes.Stloc, variable.Index); oldParameterToNNewVariable.Add(p, variable); } method.Body.SimplifyMacros(); var reader = new ILReader(method.Body); //var c = new <>__DisplayClass bool isDup = false; Dictionary<MetadataToken, ParameterReference> captureFieldToParameter = new Dictionary<MetadataToken, ParameterReference>(); closureType = null; if (reader.Is(OpCodes.Newobj)) { var newObj = reader.Get(OpCodes.Newobj); closureType = ((MethodDefinition)newObj.Operand).DeclaringType; if(reader.TryGet(OpCodes.Stloc) != null) //DEBUG: stloc(ldloc ldarg sfld) * ldloc { //c.a = a; while (LookaheadClosureAssignment(isDup, ref reader, out var oldParameter, out var fieldReference)) { captureFieldToParameter.Add(fieldReference.MetadataToken, oldParameter); } } else if (reader.Is(OpCodes.Dup)) //RELEASE: (dup ldarg stfld)* { isDup = true; while (LookaheadClosureAssignment(isDup, ref reader, out var oldParameter, out var fieldReference)) { captureFieldToParameter.Add(fieldReference.MetadataToken, oldParameter); } } } Dictionary<VariableDefinition, VariableDefinition> rebasedVariables = new Dictionary<VariableDefinition, VariableDefinition>(); foreach (var v in method.Body.Variables) { if (closureType != null && v.VariableType == closureType) { } else { var newVariable = new VariableDefinition(mod.ImportReference(v.VariableType)); rebasedVariables.Add(v, newVariable); newMethod.Body.Variables.Add(newVariable); } } while (reader.HasMore()) { if (LookaheadExpressionFieldConstant(isDup, ref reader, out var token)) { var param = captureFieldToParameter[token.Value]; writer.Emit(OpCodes.Ldloc, oldParameterToNNewVariable[param].Index); } else if (!method.IsStatic && LookaheadExpressionThisConstant(ref reader, method.DeclaringType)) { writer.Emit(OpCodes.Ldloc, oldParameterToNNewVariable[method.Body.ThisParameter].Index); } else if (LookaheadArray(ref reader)) { if (reader.HasMore()) throw new InvalidOperationException($"The method {method.FullName} should only call As.Expression with an expression tree lambda"); if (oldParameterToNNewVariable.Count == 0) { writer.Emit(OpCodes.Call, mod.ImportReference(new GenericInstanceMethod(this.Array_Empty) { GenericArguments = { this.ParameterExpression } })); } else { writer.Emit(OpCodes.Ldc_I4, oldParameterToNNewVariable.Count); writer.Emit(OpCodes.Newarr, mod.ImportReference(this.ParameterExpression)); for (int i = 0; i < oldParameterToNNewVariable.Count; i++) { writer.Emit(OpCodes.Dup); writer.Emit(OpCodes.Ldc_I4, i); writer.Emit(OpCodes.Ldloc, i); writer.Emit(OpCodes.Stelem_Ref); } } var funcType = ((GenericInstanceType)expressionField.FieldType).GenericArguments.Single(); writer.Emit(OpCodes.Call, mod.ImportReference(new GenericInstanceMethod(this.Expression_Lambda) { GenericArguments = { funcType } })); writer.Emit(OpCodes.Stsfld, expressionField); writer.Emit(OpCodes.Ret); writer.Body.OptimizeMacros(); { method.Body.Instructions.Clear(); method.Body.Variables.Clear(); var oldWriter = method.Body.GetILProcessor(); oldWriter.Emit(OpCodes.Ldsfld, expressionField); for (int i = 0; i < allParameters.Count; i++) oldWriter.Emit(OpCodes.Ldarg, allParameters[i]); var evaluate = ExpressionExtensions.Methods.Single(a => a.Name == "Evaluate" && a.GenericParameters.Count == allParameters.Count + 1); var evaluateInstance = new GenericInstanceMethod(evaluate); foreach (var p in allParameters) evaluateInstance.GenericArguments.Add(p.ParameterType); evaluateInstance.GenericArguments.Add(method.ReturnType); oldWriter.Emit(OpCodes.Call, mod.ImportReference(evaluateInstance)); oldWriter.Emit(OpCodes.Ret); oldWriter.Body.Optimize(); } return; } else if (reader.TryGet(OpCodes.Ldloc) is Instruction ldloc) { writer.Emit(ldloc.OpCode, rebasedVariables[(VariableDefinition)ldloc.Operand]); } else if (reader.TryGet(OpCodes.Stloc) is Instruction stloc) { writer.Emit(stloc.OpCode, rebasedVariables[(VariableDefinition)stloc.Operand]); } else if (reader.TryGet(OpCodes.Ldloca) is Instruction ldloca) { writer.Emit(ldloca.OpCode, rebasedVariables[(VariableDefinition)ldloca.Operand]); } else { var ins = reader.Get(); writer.Append(ins); } } throw new InvalidOperationException($"The method {method.FullName} should only call As.Expression with an expression tree lambda"); } bool LookaheadClosureAssignment(bool isDup, ref ILReader reader, out ParameterReference parameterReference, out FieldReference fieldReference) { fieldReference = null; parameterReference = null; var fork = reader.Clone(); if ((isDup ? fork.TryGet(OpCodes.Dup) : fork.TryGet(OpCodes.Ldloc, 0)) != null && fork.TryGet(OpCodes.Ldarg) is Instruction ldarg && fork.TryGet(OpCodes.Stfld) is Instruction stfld) { parameterReference = (ParameterReference)ldarg.Operand; fieldReference = (FieldReference)stfld.Operand; reader.Position = fork.Position; return true; } return false; } bool LookaheadExpressionFieldConstant(bool isDup, ref ILReader reader, out MetadataToken? fieldToken) { fieldToken = null; var fork = reader.Clone(); if (//Expression.Constant(typeof(<>__DisplayClass>), c) (isDup || fork.TryGet(OpCodes.Ldloc, 0 ) != null) && fork.TryGet(OpCodes.Ldtoken) != null && fork.TryGetCall(nameof(Type.GetTypeFromHandle)) != null && fork.TryGetCall(nameof(Expression.Constant)) != null && //Expression.Field( , fieldof(c.a)); fork.TryGet(OpCodes.Ldtoken) is Instruction ldtoken && fork.TryGetCall(nameof(System.Reflection.FieldInfo.GetFieldFromHandle)) != null && fork.TryGetCall(nameof(Expression.Field)) != null) { fieldToken = ((FieldReference)ldtoken.Operand).MetadataToken; reader.Position = fork.Position; return true; } return false; } bool LookaheadExpressionThisConstant(ref ILReader reader, TypeReference thisType) { var fork = reader.Clone(); if (//Expression.Constant(typeof(ThisType), this) fork.TryGet(OpCodes.Ldarg, 0) != null && fork.TryGet(OpCodes.Ldtoken) is Instruction ldTok && ldTok.Operand.Equals(thisType) & fork.TryGetCall(nameof(Type.GetTypeFromHandle)) != null && fork.TryGetCall(nameof(Expression.Constant)) != null) { reader.Position = fork.Position; return true; } return false; } bool LookaheadArray(ref ILReader reader) { var fork = reader.Clone(); if (fork.TryGetCall(nameof(Array.Empty)) != null && fork.TryGetCall(nameof(Expression.Lambda)) != null && fork.TryGetCall("Expression") != null && fork.TryGet(OpCodes.Ret) != null) { reader.Position = fork.Position; return true; } return false; } public struct ILReader { public int Position; public MethodBody Body; public ILReader Clone() => new ILReader(Body) { Position = Position }; public ILReader(MethodBody body) { Body = body; this.Position = 0; } public Instruction Get() { return Body.Instructions[Position++]; } public bool Is(OpCode opCode, int? operand = null) { var ins = Body.Instructions[Position]; if (ins.OpCode != opCode) return false; if (operand == null) return true; if (ins.Operand is ParameterDefinition pd) return pd.Sequence == operand; else if (ins.Operand is VariableDefinition vd) return vd.Index == operand; else throw new Exception("Not Expected " + ins.Operand.GetType()); } public bool IsCall(string methodName) { var ins = Body.Instructions[Position]; return ins.OpCode == OpCodes.Call && ins.Operand is MethodReference mr && mr.Name == methodName; } public Instruction TryGet(OpCode opCode, int? operand = null) { if (Is(opCode, operand)) return Get(); return null; } public Instruction TryGetCall(string methodName) { if (IsCall(methodName)) return Get(); return null; } public Instruction Get(OpCode opCode, int? operand = null) { if (Is(opCode, operand)) return Get(); throw new InvalidOperationException($"{opCode} expected in Position {Position} of {Body.Method.FullName}"); } public Instruction GetCall(string methodName) { if (IsCall(methodName)) return Get(); throw new InvalidOperationException($"{OpCodes.Call} {methodName} expected in Position {Position} of {Body.Method.FullName}"); } internal bool HasMore() { return this.Position < this.Body.Instructions.Count; } } private TypeReference GetExpressionType(MethodDefinition method) { var mod = method.DeclaringType.Module; var numParams = (method.Body.ThisParameter != null ? 1 : 0) + method.Parameters.Count + 1; var func = this.Resolver.SystemRuntime.MainModule.GetType("System", "Func`" + numParams); var funcGeneric = new GenericInstanceType(func); if (method.Body.ThisParameter != null) funcGeneric.GenericArguments.Add(method.DeclaringType); foreach (var p in method.Parameters) funcGeneric.GenericArguments.Add(p.ParameterType); funcGeneric.GenericArguments.Add(method.ReturnType); var exprType = this.Resolver.SystemLinqExpressions.MainModule.GetType("System.Linq.Expressions", "Expression`1"); return new GenericInstanceType(exprType) { GenericArguments = { funcGeneric } }; } private string GetFreeName(string name, TypeDefinition type) { for (int i = 0; ; i++) { var result = name + (i == 0 ? "" : i.ToString()); if (!IsUsed(type, result + "Expression") && !IsUsed(type, result + "Init")) return result; } } private bool IsUsed(TypeDefinition type, string v) { if (type.HasFields && type.Fields.Any(f => f.Name == v)) return true; if (type.HasProperties && type.Properties.Any(f => f.Name == v)) return true; if (type.HasMethods && type.Methods.Any(f => f.Name == v)) return true; return false; } private void LogError(MethodDefinition m, string error) { Log.WriteLine("Signum.MSBuildTask: {0}.{1} should be a simple evaluation of an expression field in order to use ExpressionFieldAttribute without parameters ({2})", m.DeclaringType.Name, m.Name, error); hasErrors = true; } } }
// 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.Sql { using Azure; using Management; using Rest; using Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ElasticPoolsOperations. /// </summary> public static partial class ElasticPoolsOperationsExtensions { /// <summary> /// Creates a new elastic pool or updates an existing elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be operated on (updated or created). /// </param> /// <param name='parameters'> /// The required parameters for creating or updating an elastic pool. /// </param> public static ElasticPool CreateOrUpdate(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, serverName, elasticPoolName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates a new elastic pool or updates an existing elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be operated on (updated or created). /// </param> /// <param name='parameters'> /// The required parameters for creating or updating an elastic pool. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ElasticPool> CreateOrUpdateAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be deleted. /// </param> public static void Delete(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName) { operations.DeleteAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be deleted. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets an elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> public static ElasticPool Get(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName) { return operations.GetAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult(); } /// <summary> /// Gets an elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ElasticPool> GetAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns elastic pools. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> public static IEnumerable<ElasticPool> ListByServer(this IElasticPoolsOperations operations, string resourceGroupName, string serverName) { return operations.ListByServerAsync(resourceGroupName, serverName).GetAwaiter().GetResult(); } /// <summary> /// Returns elastic pools. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<ElasticPool>> ListByServerAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByServerWithHttpMessagesAsync(resourceGroupName, serverName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns elastic pool activities. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool for which to get the current activity. /// </param> public static IEnumerable<ElasticPoolActivity> ListActivity(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName) { return operations.ListActivityAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult(); } /// <summary> /// Returns elastic pool activities. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool for which to get the current activity. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<ElasticPoolActivity>> ListActivityAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListActivityWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns activity on databases inside of an elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool. /// </param> public static IEnumerable<ElasticPoolDatabaseActivity> ListDatabaseActivity(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName) { return operations.ListDatabaseActivityAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult(); } /// <summary> /// Returns activity on databases inside of an elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<ElasticPoolDatabaseActivity>> ListDatabaseActivityAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListDatabaseActivityWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a database inside of an elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> /// <param name='databaseName'> /// The name of the database to be retrieved. /// </param> public static Database GetDatabase(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string databaseName) { return operations.GetDatabaseAsync(resourceGroupName, serverName, elasticPoolName, databaseName).GetAwaiter().GetResult(); } /// <summary> /// Gets a database inside of an elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> /// <param name='databaseName'> /// The name of the database to be retrieved. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Database> GetDatabaseAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, string databaseName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetDatabaseWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, databaseName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns a database inside of an elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> public static IEnumerable<Database> ListDatabases(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName) { return operations.ListDatabasesAsync(resourceGroupName, serverName, elasticPoolName).GetAwaiter().GetResult(); } /// <summary> /// Returns a database inside of an elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be retrieved. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<Database>> ListDatabasesAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListDatabasesWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new elastic pool or updates an existing elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be operated on (updated or created). /// </param> /// <param name='parameters'> /// The required parameters for creating or updating an elastic pool. /// </param> public static ElasticPool BeginCreateOrUpdate(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, serverName, elasticPoolName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Creates a new elastic pool or updates an existing elastic pool. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group that contains the resource. You can obtain /// this value from the Azure Resource Manager API or the portal. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='elasticPoolName'> /// The name of the elastic pool to be operated on (updated or created). /// </param> /// <param name='parameters'> /// The required parameters for creating or updating an elastic pool. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ElasticPool> BeginCreateOrUpdateAsync(this IElasticPoolsOperations operations, string resourceGroupName, string serverName, string elasticPoolName, ElasticPool parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, elasticPoolName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using Sandbox.ModAPI; using VRageMath; using VRage; using NaniteConstructionSystem.Entities; using NaniteConstructionSystem.Settings; namespace NaniteConstructionSystem.Extensions { public static class Sync { public static bool IsServer { get { if (MyAPIGateway.Session == null) return false; if (MyAPIGateway.Multiplayer == null) return false; if (MyAPIGateway.Session.OnlineMode == VRage.Game.MyOnlineModeEnum.OFFLINE || MyAPIGateway.Multiplayer.IsServer) return true; return false; } } public static bool IsClient { get { if (MyAPIGateway.Session == null) return false; if (MyAPIGateway.Session.OnlineMode == VRage.Game.MyOnlineModeEnum.OFFLINE) return true; if (MyAPIGateway.Session.Player != null && MyAPIGateway.Session.Player.Client != null && MyAPIGateway.Multiplayer.IsServerPlayer(MyAPIGateway.Session.Player.Client)) return true; if (!MyAPIGateway.Multiplayer.IsServer) return true; return false; } } public static bool IsDedicated { get { if (MyAPIGateway.Utilities.IsDedicated) return true; return false; } } } public class StateData { public long EntityId { get; set; } public NaniteConstructionBlock.FactoryStates State { get; set; } } /* I have a bug report of clients crashing: 2016-04-04 18:17:33.837 - Thread: 1 -> Exception occured: System.InvalidOperationException: Unable to generate a temporary class (result=1). error CS0012: The type 'VRageMath.Vector3I' is defined in an assembly that is not referenced. You must add a reference to assembly 'VRage.Math, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. I have no idea wtf is going on? TargetData used to use SerializableVector3I as a position, but apparently this fails ... sometimes? I have no idea why. So I guess I will unwrap position. UGLY. */ public enum TargetTypes { Construction, Projection, Floating, Deconstruction, Voxel, Medical } [Serializable] public class TargetVector3I { public int X { get; set; } public int Y { get; set; } public int Z { get; set; } public TargetVector3I() { X = 0; Y = 0; Z = 0; } public TargetVector3I(int x, int y, int z) { X = x; Y = y; Z = z; } public static implicit operator TargetVector3I(Vector3I position) { return new TargetVector3I(position.X, position.Y, position.Z); } public override string ToString() { return string.Format("(X:{0},Y:{1},Z:{2})", X, Y, Z); } } [Serializable] public class TargetVector3D { public double X { get; set; } public double Y { get; set; } public double Z { get; set; } public TargetVector3D() { X = 0f; Y = 0f; Z = 0f; } public TargetVector3D(double x, double y, double z) { X = x; Y = y; Z = z; } public static implicit operator TargetVector3D(Vector3D position) { return new TargetVector3D(position.X, position.Y, position.Z); } public override string ToString() { return string.Format("(X:{0},Y:{1},Z:{2})", X, Y, Z); } } [Serializable] public class TargetData { public long EntityId { get; set; } public long TargetId { get; set; } public TargetVector3I PositionI { get; set; } public TargetVector3D PositionD { get; set; } public TargetTypes TargetType { get; set; } public long SubTargetId { get; set; } public override string ToString() { return string.Format("EntityId={0},TargetId={1},SubTargetId={2},TargetType={3},PositionI={4},PositionD={5}", EntityId, TargetId, SubTargetId, TargetType, PositionI, PositionD); } } [Serializable] public class DetailData { public long EntityId { get; set; } public string Details { get; set; } } [Serializable] public class LoginData { public ulong SteamId { get; set; } } [Serializable] public class SettingsData { public NaniteSettings Settings { get; set; } } [Serializable] public class ParticleData { public long EntityId { get; set; } public long TargetId { get; set; } public int PositionX { get; set; } public int PositionY { get; set; } public int PositionZ { get; set; } public int EffectId { get; set; } } [Serializable] public class VoxelRemovalData { public long VoxelID { get; set; } public Vector3D Position { get; set; } } }
//! \file GarCreate.cs //! \date Fri Jul 25 05:56:29 2014 //! \brief Create archive frontend. // // Copyright (C) 2014 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Input; using GameRes; using GARbro.GUI.Strings; using GARbro.GUI.Properties; using Ookii.Dialogs.Wpf; namespace GARbro.GUI { public partial class MainWindow : Window { private void CreateArchiveExec (object sender, ExecutedRoutedEventArgs args) { StopWatchDirectoryChanges(); try { var archive_creator = new GarCreate (this); if (!archive_creator.Run()) ResumeWatchDirectoryChanges(); } catch (Exception X) { ResumeWatchDirectoryChanges(); PopupError (X.Message, guiStrings.TextCreateArchiveError); } } } internal class GarCreate { private MainWindow m_main; private string m_arc_name; private IList<Entry> m_file_list; private ProgressDialog m_progress_dialog; private ArchiveFormat m_format; private ResourceOptions m_options; private Exception m_pending_error; delegate void AddFilesEnumerator (IList<Entry> list, string path, DirectoryInfo path_info); public GarCreate (MainWindow parent) { m_main = parent; m_arc_name = Settings.Default.appLastCreatedArchive; } public bool Run () { Directory.SetCurrentDirectory (m_main.CurrentPath); var items = m_main.CurrentDirectory.SelectedItems.Cast<EntryViewModel> (); if (string.IsNullOrEmpty (m_arc_name)) { m_arc_name = Path.GetFileName (m_main.CurrentPath); if (!items.Skip (1).Any()) // items.Count() == 1 { var item = items.First(); if (item.IsDirectory) m_arc_name = Path.GetFileNameWithoutExtension (item.Name); } } var dialog = new CreateArchiveDialog (m_arc_name); dialog.Owner = m_main; if (!dialog.ShowDialog().Value) { return false; } if (string.IsNullOrEmpty (dialog.ArchiveName.Text)) { m_main.SetStatusText ("Archive name is empty"); return false; } m_format = dialog.ArchiveFormat.SelectedItem as ArchiveFormat; if (null == m_format) { m_main.SetStatusText ("Format is not selected"); return false; } m_options = dialog.ArchiveOptions; if (m_format.IsHierarchic) m_file_list = BuildFileList (items, AddFilesRecursive); else m_file_list = BuildFileList (items, AddFilesFromDir); m_arc_name = Path.GetFullPath (dialog.ArchiveName.Text); m_progress_dialog = new ProgressDialog () { WindowTitle = guiStrings.TextTitle, Text = string.Format (guiStrings.MsgCreatingArchive, Path.GetFileName (m_arc_name)), Description = "", MinimizeBox = true, }; m_progress_dialog.DoWork += CreateWorker; m_progress_dialog.RunWorkerCompleted += OnCreateComplete; m_progress_dialog.ShowDialog (m_main); return true; } private int m_total = 1; ArchiveOperation CreateEntryCallback (int i, Entry entry, string msg) { if (m_progress_dialog.CancellationPending) throw new OperationCanceledException(); if (null == entry && null == msg && 0 != i) { m_total = i; m_progress_dialog.ReportProgress (0); return ArchiveOperation.Continue; } int progress = i*100/m_total; if (progress > 100) progress = 100; string notice = msg; if (null != entry) { if (null != msg) notice = string.Format ("{0} {1}", msg, entry.Name); else notice = entry.Name; } m_progress_dialog.ReportProgress (progress, null, notice); return ArchiveOperation.Continue; } void CreateWorker (object sender, DoWorkEventArgs e) { m_pending_error = null; try { using (var tmp_file = new GARbro.Shell.TemporaryFile (Path.GetDirectoryName (m_arc_name), Path.GetRandomFileName ())) { m_total = m_file_list.Count() + 1; using (var file = File.Create (tmp_file.Name)) { m_format.Create (file, m_file_list, m_options, CreateEntryCallback); } if (!GARbro.Shell.File.Rename (tmp_file.Name, m_arc_name)) { throw new Win32Exception (GARbro.Shell.File.GetLastError()); } } } catch (Exception X) { m_pending_error = X; } } void OnCreateComplete (object sender, RunWorkerCompletedEventArgs e) { m_progress_dialog.Dispose(); m_main.Activate(); if (null == m_pending_error) { Settings.Default.appLastCreatedArchive = m_arc_name; m_main.Dispatcher.Invoke (() => { m_main.ChangePosition (new DirectoryPosition (m_arc_name)); }); } else { if (m_pending_error is OperationCanceledException) m_main.SetStatusText (m_pending_error.Message); else m_main.PopupError (m_pending_error.Message, guiStrings.TextCreateArchiveError); } } IList<Entry> BuildFileList (IEnumerable<EntryViewModel> files, AddFilesEnumerator add_files) { var list = new List<Entry>(); foreach (var entry in files) { if (entry.IsDirectory) { if (".." != entry.Name) { var dir = new DirectoryInfo (entry.Name); add_files (list, entry.Name, dir); } } else if (entry.Size < uint.MaxValue) { var e = new Entry { Name = entry.Name, Type = entry.Source.Type, Size = entry.Source.Size, }; list.Add (e); } } return list; } void AddFilesFromDir (IList<Entry> list, string path, DirectoryInfo dir) { foreach (var file in dir.EnumerateFiles()) { if (0 != (file.Attributes & (FileAttributes.Hidden | FileAttributes.System))) continue; if (file.Length >= uint.MaxValue) continue; string name = Path.Combine (path, file.Name); var e = FormatCatalog.Instance.Create<Entry> (name); e.Size = (uint)file.Length; list.Add (e); } } void AddFilesRecursive (IList<Entry> list, string path, DirectoryInfo info) { foreach (var dir in info.EnumerateDirectories()) { string subdir = Path.Combine (path, dir.Name); var subdir_info = new DirectoryInfo (subdir); AddFilesRecursive (list, subdir, subdir_info); } AddFilesFromDir (list, path, info); } } }
/* Copyright (c) Microsoft Corporation All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Globalization; namespace mammerla.SharePointIntegration { /// <summary> /// A static class with methods for working with URL strings. /// </summary> public static partial class UrlUtilities { /// <summary> /// Returns whether a URL is local to a particular machine. /// </summary> /// <param name="url">URL to test.</param> /// <returns>True if the URL is local to a machine.</returns> public static bool IsLocal(String url) { String serverBaseName = GetServerBaseName(url); if (serverBaseName.Equals(Environment.MachineName, StringComparison.InvariantCultureIgnoreCase)) { return true; } if (serverBaseName.Equals("localhost", StringComparison.InvariantCultureIgnoreCase)) { return true; } return false; } /// <summary> /// Returns the base name of the server in a given URL. e.g., if you use http://myawesomeserver:52/baz.htm, returns myawesomeserver. /// </summary> /// <param name="fullUrl">URL to use.</param> /// <returns>Name of the server base name.</returns> public static String GetServerBaseName(String fullUrl) { String serverBaseName = GetBaseUrlFromFullUrl(fullUrl); int slashSlash = serverBaseName.IndexOf("//"); if (slashSlash >= 0) { serverBaseName = serverBaseName.Substring(slashSlash + 2); } int lastSlash = serverBaseName.LastIndexOf("/"); if (lastSlash > 0) { serverBaseName = serverBaseName.Substring(0, lastSlash); } int lastColon = serverBaseName.LastIndexOf(":"); if (lastColon > 0) { serverBaseName = serverBaseName.Substring(0, lastColon); } return serverBaseName; } public static String GetServerFromUrl(String fullUrl) { fullUrl = fullUrl.ToUpper(); if (fullUrl.Length > 8) { int nextSlash = fullUrl.IndexOf('/', 9); if (nextSlash >= 0) { fullUrl = fullUrl.Substring(0, nextSlash); } } return fullUrl; } public static string ConvertServerRelativeUrlToFullUrl(String serverRelativeUrl) { return serverRelativeUrl; } public static String UrlEncode(String url) { url = url.Replace(" ", "%20"); return url; } public static String UrlDecode(String url) { url = url.Replace("%20", " "); return url; } public static String ReplaceLocalhost(String sourceUrl, String urlWithoutLocalhost) { int index = sourceUrl.IndexOf("/localhost"); // is this http://localhost or https://localhost if (index < 6 || index > 7) { return sourceUrl; } return GetBaseUrlFromFullUrl(urlWithoutLocalhost) + GetServerRelativeUrlFromFullUrl(sourceUrl); } public static String GetParentFolderUrl(String url) { int lastSlash = url.LastIndexOf("/"); if (lastSlash == url.Length - 1) { lastSlash = url.LastIndexOf("/", lastSlash - 1); } if (lastSlash < 0) { return null; } if (url.StartsWith("http://", StringComparison.InvariantCulture) && lastSlash <= 7) { return null; } if (url.StartsWith("https://", StringComparison.InvariantCulture) && lastSlash <= 8) { return null; } return url.Substring(0, lastSlash + 1); } public static bool IsUrlForIntranet(String fullUrl) { return UrlUtilities.IsBaseUrlForIntranet(UrlUtilities.GetBaseUrlFromFullUrl(fullUrl)); } public static bool IsBaseUrlForIntranet(String baseUrl) { return baseUrl.IndexOf(".") < 0; } public static bool ServerNamesAreEqual(String fullUrlA, String fullUrlB) { String serverNameA = GetCanonicalServerNameFromFullUrl(fullUrlA); String serverNameB = GetCanonicalServerNameFromFullUrl(fullUrlB); return serverNameA.Equals(serverNameB); } public static String GetObjectRelativeUrl(String baseUrl, String childObjectUrl) { if (!childObjectUrl.StartsWith("http", StringComparison.InvariantCultureIgnoreCase)) { childObjectUrl = UrlUtilities.EnsurePathStartsWithSlash(childObjectUrl); baseUrl = UrlUtilities.EnsurePathStartsWithSlash(baseUrl); } if (!childObjectUrl.StartsWith(baseUrl, StringComparison.InvariantCulture)) { throw new InvalidOperationException(); } return childObjectUrl.Substring(baseUrl.Length, childObjectUrl.Length - baseUrl.Length); } public static String GetServerNameFromFullUrl(String fullUrl) { if (fullUrl.Length > 8) { if (fullUrl.StartsWith("http://", StringComparison.InvariantCulture) || fullUrl.StartsWith("https://", StringComparison.InvariantCulture)) { int firstSlash = fullUrl.IndexOf("://") + 3; int nextSlash = fullUrl.IndexOf('/', 9); if (nextSlash >= 0) { fullUrl = fullUrl.Substring(firstSlash, nextSlash - firstSlash); } } } return fullUrl; } public static String GetBaseUrlFromFullUrl(String fullUrl) { if (fullUrl.Length > 8) { if (fullUrl.StartsWith("http://", StringComparison.InvariantCulture) || fullUrl.StartsWith("https://", StringComparison.InvariantCulture)) { int firstSlash = fullUrl.IndexOf("://") + 3; int nextSlash = fullUrl.IndexOf('/', 9); if (nextSlash >= 0) { fullUrl = fullUrl.Substring(0, nextSlash); } } } return fullUrl; } public static String GetCanonicalServerNameFromFullUrl(String fullUrl) { String serverName = GetServerNameFromFullUrl(fullUrl); return serverName.ToLower(); } public static String GetSuggestedContentTypeForUrl(String url) { String extension = GetFileExtensionFromFullUrl(url); switch (extension.ToLower()) { case "jpeg": case "jpg": return "image/jpeg"; case "html": case "htm": return "text/html"; case "xml": return "text/xml"; case "swf": return "application/x-shockwave-flash"; case "xap": return "application/x-silverlight-app"; case "txt": return "text/plain"; case "css": return "text/css"; case "js": return "application/x-javascript"; case "png": return "image/png"; case "mp3": return "audio/mpeg"; case "mp4": return "video/mp4"; case "pptx": return "application/vnd.ms-powerpoint.presentation.12"; case "docx": return "application/vnd.ms-word.document.12"; case "xlsx": return "application/vnd.ms-excel.12"; default: return "unknown/unknown"; } } public static bool IsRelativeUrl(String url) { if (url.Length > 8) { if (url.StartsWith("http://", StringComparison.InvariantCulture) || url.StartsWith("https://", StringComparison.InvariantCulture)) { return false; } } return true; } public static String GetFileUrlFromFullUrl(String fullUrl) { String fileName = null; if (!fullUrl.EndsWith("/")) { int end = fullUrl.Length - 1; int questionMark = fullUrl.LastIndexOf("?"); if (questionMark >= 0) { end = questionMark - 1; } int lastSlash = fullUrl.LastIndexOf('/', end); fileName = fullUrl.Substring(lastSlash + 1, end - lastSlash); } return fileName; } public static String GetFileUrlAndParamsFromFullUrl(String fullUrl) { String fileName = null; if (!fullUrl.EndsWith("/")) { int end = fullUrl.Length - 1; int questionMark = fullUrl.LastIndexOf("?"); if (questionMark >= 0) { end = questionMark; } int lastSlash = fullUrl.LastIndexOf('/', end); fileName = fullUrl.Substring(lastSlash + 1, fullUrl.Length - (lastSlash + 1)); } return fileName; } public static bool IsFullUrlImage(String fullUrl) { String extension = GetFileExtensionFromFullUrl(fullUrl); switch (extension.ToLower()) { case "jpg": return true; case "jpeg": return true; case "png": return true; case "gif": return true; } return false; } public static String GetFileExtensionFromFullUrl(String fullUrl) { String extension = GetFileUrlFromFullUrl(fullUrl); if (extension == null) { return null; } int lastPeriod = extension.LastIndexOf("."); if (lastPeriod > 0) { extension = extension.Substring(lastPeriod + 1); } return extension.ToLower(); } public static String GetBaseFileNameFromFullUrl(String fullUrl) { String fileName = GetFileUrlFromFullUrl(fullUrl); if (fileName == null) { return null; } int lastPeriod = fileName.LastIndexOf("."); if (lastPeriod > 0) { fileName = fileName.Substring(0, lastPeriod); } return fileName; } public static String GetFolderUrlFromFullUrl(String fullUrl) { fullUrl = StripQueryParams(fullUrl); if (!fullUrl.EndsWith("/")) { int lastSlash = fullUrl.LastIndexOf('/'); fullUrl = fullUrl.Substring(0, lastSlash + 1); } return fullUrl; } public static String GetRelativeUrlFromBaseUrl(String fullUrl, String baseUrl) { if (!fullUrl.StartsWith(baseUrl, StringComparison.InvariantCultureIgnoreCase)) { throw new InvalidOperationException(); } return fullUrl.Substring(baseUrl.Length , fullUrl.Length - (baseUrl.Length)); } public static String GetServerRelativeUrlFromFullUrl(String fullUrl) { //fullUrl = fullUrl.ToUpper(); fullUrl = StripQueryParams(fullUrl); if (fullUrl.Length > 8) { if (fullUrl.StartsWith("http://") || fullUrl.StartsWith("https://")) { int nextSlash = fullUrl.IndexOf('/', 9); if (nextSlash >= 0) { fullUrl = fullUrl.Substring(nextSlash, fullUrl.Length - nextSlash); } } } // Debug.Assert(fullUrl.IndexOf("//") < 0); return fullUrl; } public static String StripQueryParams(String url) { int lastQuestion = url.LastIndexOf("?"); if (lastQuestion >= 0) { url = url.Substring(0, lastQuestion); } return url; } public static String EnsurePathDoesNotEndWithSlash(String url) { if (url.EndsWith("/")) { url = url.Substring(0, url.Length - 1); } return url; } public static String EnsurePathEndsWithSlash(String url) { if (!url.EndsWith("/")) { url += "/"; } return url; } public static String EnsurePathDoesNotStartWithSlash(String url) { if (url.StartsWith("/")) { url = url.Substring(1); } return url; } public static String EnsurePathStartsWithSlash(String url) { if (!url.StartsWith("/")) { url = "/" + url; } return url; } public static bool UrlsAreEqual(String relativeUrlA, String relativeUrlB) { if (relativeUrlA != null && relativeUrlB == null) { return false; } if (relativeUrlB != null && relativeUrlA == null) { return false; } if (relativeUrlA == null && relativeUrlA == relativeUrlB) { return true; } try { relativeUrlA = CanonicalizeRelativeUrlForCompare(relativeUrlA); relativeUrlB = CanonicalizeRelativeUrlForCompare(relativeUrlB); } catch (UriFormatException) { return false; } return relativeUrlA == relativeUrlB; } public static bool FullUrlsAreEqual(String fullUrlA, String fullUrlB) { if (fullUrlA != null && fullUrlB == null) { return false; } if (fullUrlB != null && fullUrlA == null) { return false; } if (fullUrlA == null && fullUrlA == fullUrlB) { return true; } try { fullUrlA = CanonicalizeUrlForCompare(fullUrlA); fullUrlB = CanonicalizeUrlForCompare(fullUrlB); } catch (UriFormatException) { return false; } return fullUrlA == fullUrlB; } public static String CanonicalizeUrlForCompare(String fullUrl) { fullUrl = CanonicalizeUrl(fullUrl); fullUrl = fullUrl.ToUpper(CultureInfo.InvariantCulture); if (fullUrl.EndsWith("/")) { fullUrl = fullUrl.Substring(0, fullUrl.Length - 1); } return fullUrl; } public static String CanonicalizeRelativeUrlForCompare(String url) { url = CanonicalizeRelativeUrl(url); return url.ToUpper(); } public static String CanonicalizeRelativeFolderUrlForCompare(String url) { url = CanonicalizeRelativeUrl(url); if (!url.EndsWith("/")) { url += "/"; } return url.ToUpper(); } public static String CanonicalizeFolderUrl(String url) { url = CanonicalizeUrl(url); String fileName = GetName(url); if (fileName.IndexOf(".") > 0) { url = url.Substring(0, url.Length - fileName.Length); } else if (!url.EndsWith("/")) { url += "/"; } return url; } public static String CanonicalizeRelativeUrl(String url) { url = url.Replace(" ", "%20"); Uri uri = new Uri(url, UriKind.Relative); return uri.ToString(); } public static String CanonicalizeUrl(String url) { if (url.StartsWith("/")) { } Uri uri = new Uri(url); return uri.AbsoluteUri; } public static String TryCanonicalizeUrl(String url) { if (url.StartsWith("/")) { } Uri uri = null; try { uri = new Uri(url); } catch (UriFormatException) { return null; } return uri.AbsoluteUri; } public static bool IsFolderUrl(String url) { if (url == null) { return false; } return url.EndsWith("/"); } public static bool IsFullUrl(String url) { if (url.StartsWith("http://", StringComparison.InvariantCultureIgnoreCase)) { return true; } if (url.StartsWith("https://", StringComparison.InvariantCultureIgnoreCase)) { return true; } if (url.StartsWith("file://", StringComparison.InvariantCultureIgnoreCase)) { return true; } return false; } public static String GetFirstFolderName(String url) { while (url.StartsWith("/")) { url = url.Substring(1, url.Length - 1); } int firstSlash = url.IndexOf("/"); if (firstSlash < 0) { return null; } return url.Substring(0, firstSlash); } public static String GetName(String url) { int lastSlash = url.LastIndexOf("/"); if (lastSlash < 0) { return url; } else if (lastSlash == 0) { return String.Empty; } if (lastSlash == url.Length - 1) { lastSlash = url.LastIndexOf("/", lastSlash - 1); if (UrlUtilities.IsFullUrl(url) && lastSlash < 9) { return String.Empty; } } String name = url.Substring(lastSlash + 1, url.Length - (lastSlash + 1)); if (name.EndsWith("/")) { name = name.Substring(0, name.Length - 1); } return name; } /// <summary> /// Returns the name of the folder in the URL. e.g., if the URL is http://contoso.sharepoint.com/foo/baz/test.htm, returns "baz". /// </summary> /// <param name="url">URL to find a folder name for.</param> /// <returns>Folder component of the URL.</returns> public static String GetLastFolderName(String url) { int lastSlash = url.LastIndexOf("/"); if (lastSlash < 0) { return null; } int firstSlash = url.LastIndexOf("/", lastSlash - 1); if (firstSlash < 0) { return null; } return url.Substring(firstSlash + 1, lastSlash - (firstSlash + 1)); } } }
using RootSystem = System; using System.Linq; using System.Collections.Generic; namespace Windows.Kinect { // // Windows.Kinect.ColorFrame // public sealed partial class ColorFrame : RootSystem.IDisposable, Helper.INativeWrapper { internal RootSystem.IntPtr _pNative; RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } } // Constructors and Finalizers internal ColorFrame(RootSystem.IntPtr pNative) { _pNative = pNative; Windows_Kinect_ColorFrame_AddRefObject(ref _pNative); } ~ColorFrame() { Dispose(false); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrame_ReleaseObject(ref RootSystem.IntPtr pNative); [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrame_AddRefObject(ref RootSystem.IntPtr pNative); private void Dispose(bool disposing) { if (_pNative == RootSystem.IntPtr.Zero) { return; } __EventCleanup(); Helper.NativeObjectCache.RemoveObject<ColorFrame>(_pNative); if (disposing) { Windows_Kinect_ColorFrame_Dispose(_pNative); } Windows_Kinect_ColorFrame_ReleaseObject(ref _pNative); _pNative = RootSystem.IntPtr.Zero; } // Public Properties [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_get_ColorCameraSettings(RootSystem.IntPtr pNative); public Windows.Kinect.ColorCameraSettings ColorCameraSettings { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_get_ColorCameraSettings(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.ColorCameraSettings>(objectPointer, n => new Windows.Kinect.ColorCameraSettings(n)); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_get_ColorFrameSource(RootSystem.IntPtr pNative); public Windows.Kinect.ColorFrameSource ColorFrameSource { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_get_ColorFrameSource(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.ColorFrameSource>(objectPointer, n => new Windows.Kinect.ColorFrameSource(n)); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_get_FrameDescription(RootSystem.IntPtr pNative); public Windows.Kinect.FrameDescription FrameDescription { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_get_FrameDescription(_pNative); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.FrameDescription>(objectPointer, n => new Windows.Kinect.FrameDescription(n)); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern Windows.Kinect.ColorImageFormat Windows_Kinect_ColorFrame_get_RawColorImageFormat(RootSystem.IntPtr pNative); public Windows.Kinect.ColorImageFormat RawColorImageFormat { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } return Windows_Kinect_ColorFrame_get_RawColorImageFormat(_pNative); } } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern long Windows_Kinect_ColorFrame_get_RelativeTime(RootSystem.IntPtr pNative); public RootSystem.TimeSpan RelativeTime { get { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } return RootSystem.TimeSpan.FromMilliseconds(Windows_Kinect_ColorFrame_get_RelativeTime(_pNative)); } } // Public Methods [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrame_CopyRawFrameDataToArray(RootSystem.IntPtr pNative, RootSystem.IntPtr frameData, int frameDataSize); public void CopyRawFrameDataToArray(byte[] frameData) { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } var frameDataSmartGCHandle = new Helper.SmartGCHandle(RootSystem.Runtime.InteropServices.GCHandle.Alloc(frameData, RootSystem.Runtime.InteropServices.GCHandleType.Pinned)); var _frameData = frameDataSmartGCHandle.AddrOfPinnedObject(); Windows_Kinect_ColorFrame_CopyRawFrameDataToArray(_pNative, _frameData, frameData.Length); Helper.ExceptionHelper.CheckLastError(); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrame_CopyConvertedFrameDataToArray(RootSystem.IntPtr pNative, RootSystem.IntPtr frameData, int frameDataSize, Windows.Kinect.ColorImageFormat colorFormat); public void CopyConvertedFrameDataToArray(byte[] frameData, Windows.Kinect.ColorImageFormat colorFormat) { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } var frameDataSmartGCHandle = new Helper.SmartGCHandle(RootSystem.Runtime.InteropServices.GCHandle.Alloc(frameData, RootSystem.Runtime.InteropServices.GCHandleType.Pinned)); var _frameData = frameDataSmartGCHandle.AddrOfPinnedObject(); Windows_Kinect_ColorFrame_CopyConvertedFrameDataToArray(_pNative, _frameData, frameData.Length, colorFormat); Helper.ExceptionHelper.CheckLastError(); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern RootSystem.IntPtr Windows_Kinect_ColorFrame_CreateFrameDescription(RootSystem.IntPtr pNative, Windows.Kinect.ColorImageFormat format); public Windows.Kinect.FrameDescription CreateFrameDescription(Windows.Kinect.ColorImageFormat format) { if (_pNative == RootSystem.IntPtr.Zero) { throw new RootSystem.ObjectDisposedException("ColorFrame"); } RootSystem.IntPtr objectPointer = Windows_Kinect_ColorFrame_CreateFrameDescription(_pNative, format); Helper.ExceptionHelper.CheckLastError(); if (objectPointer == RootSystem.IntPtr.Zero) { return null; } return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.FrameDescription>(objectPointer, n => new Windows.Kinect.FrameDescription(n)); } [RootSystem.Runtime.InteropServices.DllImport("KinectUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl, SetLastError=true)] private static extern void Windows_Kinect_ColorFrame_Dispose(RootSystem.IntPtr pNative); public void Dispose() { if (_pNative == RootSystem.IntPtr.Zero) { return; } Dispose(true); RootSystem.GC.SuppressFinalize(this); } private void __EventCleanup() { } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Data; using System.Drawing.Drawing2D; using System.Text; using System.Windows.Forms; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.BlogClient; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.PostEditor.PostPropertyEditing { /* * TODO * Bugs: - Visibility is all screwed up!! - Position of page-relevant labels vs. controls in dialog * Putting focus in a textbox that has a cue banner, causes dirty flag to be marked - Space should trigger View All - F2 during page context shows too many labels - Label visibility not staying in sync with control - Unchecking publish date in dialog doesn't set cue banner in band - Activate main window when dialog is dismissed - Some labels not localized - Labels do not have mnemonics - Clicking on View All should restore a visible but minimized dialog * Horizontal scrollbar sometimes flickers on - Trackback detailed label * Dropdown for Page Parent combo is not the right width * Each Page Parent combo makes its own delayed request - Tags control should share leftover space with category control x Properties dialog should hide and come back * * Questions: * Should Enter dismiss the properties dialog? * Should properties dialog scroll state be remembered between views? */ public partial class PostPropertiesBandControl : UserControl, IBlogPostEditor, IRtlAware, INewCategoryContext { private Blog _targetBlog; private IBlogClientOptions _clientOptions; private const int COL_CATEGORY = 0; private const int COL_TAGS = 1; private const int COL_DATE = 2; private const int COL_PAGEPARENTLABEL = 3; private const int COL_PAGEPARENT = 4; private const int COL_PAGEORDERLABEL = 5; private const int COL_PAGEORDER = 6; private const int COL_FILLER = 7; private const int COL_VIEWALL = 8; private readonly PostPropertiesForm postPropertiesForm; private readonly List<PropertyField> fields = new List<PropertyField>(); private readonly SharedPropertiesController controller; private readonly CategoryContext categoryContext; public PostPropertiesBandControl(CommandManager commandManager) { SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); InitializeComponent(); categoryContext = new CategoryContext(); controller = new SharedPropertiesController(this, null, categoryDropDown, null, textTags, labelPageOrder, textPageOrder, labelPageParent, comboPageParent, null, datePublishDate, fields, categoryContext); SimpleTextEditorCommandHelper.UseNativeBehaviors(commandManager, textTags, textPageOrder); postPropertiesForm = new PostPropertiesForm(commandManager, categoryContext); if (components == null) components = new Container(); components.Add(postPropertiesForm); postPropertiesForm.Synchronize(controller); commandManager.Add(CommandId.PostProperties, PostProperties_Execute); commandManager.Add(CommandId.ShowCategoryPopup, ShowCategoryPopup_Execute); linkViewAll.KeyDown += (sender, args) => { if (args.KeyValue == ' ') linkViewAll_LinkClicked(sender, new LinkLabelLinkClickedEventArgs(null)); }; // WinLive 180287: We don't want to show or use mnemonics on labels in the post properties band because // they can steal focus from the canvas. linkViewAll.Text = TextHelper.StripAmpersands(Res.Get(StringId.ViewAll)); linkViewAll.UseMnemonic = false; labelPageParent.Text = TextHelper.StripAmpersands(Res.Get(StringId.PropertiesPageParent)); labelPageParent.UseMnemonic = false; labelPageOrder.Text = TextHelper.StripAmpersands(Res.Get(StringId.PropertiesPageOrder)); labelPageOrder.UseMnemonic = false; } private void ShowCategoryPopup_Execute(object sender, EventArgs e) { if (postPropertiesForm.Visible) postPropertiesForm.DisplayCategoryForm(); else categoryDropDown.DisplayCategoryForm(); } protected override void OnLoad(EventArgs args) { base.OnLoad(args); FixCategoryDropDown(); } private void FixCategoryDropDown() { // Exactly align the sizes of the category control and the publish datetime picker control int nonItemHeight = categoryDropDown.Height - categoryDropDown.ItemHeight; categoryDropDown.ItemHeight = datePublishDate.Height - nonItemHeight; categoryDropDown.Height = datePublishDate.Height; datePublishDate.LocationChanged += delegate { // Exactly align the vertical position of the category control and the publish datetime picker control categoryDropDown.Anchor = categoryDropDown.Anchor | AnchorStyles.Top; Padding margin = categoryDropDown.Margin; margin.Top = datePublishDate.Top; categoryDropDown.Margin = margin; }; } private void PostProperties_Execute(object sender, EventArgs e) { if (!Visible) return; if (postPropertiesForm.Visible) postPropertiesForm.Hide(); else postPropertiesForm.Show(FindForm()); } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); Invalidate(); } protected override void OnPaintBackground(PaintEventArgs e) { // Without the height/width checks, minimizing and restoring causes painting to blow up if (!SystemInformation.HighContrast && table.Height > 0 && table.Width > 0 && panelShadow.Height > 0 && panelShadow.Width > 0) { using ( Brush brush = new LinearGradientBrush(table.Bounds, Color.FromArgb(0xDC, 0xE7, 0xF5), Color.White, LinearGradientMode.Vertical)) e.Graphics.FillRectangle(brush, table.Bounds); using ( Brush brush = new LinearGradientBrush(panelShadow.Bounds, Color.FromArgb(208, 208, 208), Color.White, LinearGradientMode.Vertical)) e.Graphics.FillRectangle(brush, panelShadow.Bounds); } else { e.Graphics.Clear(SystemColors.Window); } } private bool categoryVisible = true; private bool CategoryVisible { set { table.ColumnStyles[COL_CATEGORY].SizeType = value ? SizeType.Percent : SizeType.AutoSize; categoryDropDown.Visible = categoryVisible = value; ManageFillerVisibility(); } } private bool tagsVisible = true; private bool TagsVisible { set { table.ColumnStyles[COL_TAGS].SizeType = value ? SizeType.Percent : SizeType.AutoSize; textTags.Visible = tagsVisible = value; ManageFillerVisibility(); } } private void ManageFillerVisibility() { bool shouldShow = !categoryVisible && !tagsVisible; table.ColumnStyles[COL_FILLER].SizeType = shouldShow ? SizeType.Percent : SizeType.AutoSize; } private IBlogPostEditingContext _editorContext; public void Initialize(IBlogPostEditingContext editorContext, IBlogClientOptions clientOptions) { _editorContext = editorContext; _clientOptions = clientOptions; controller.Initialize(editorContext, clientOptions); ((IBlogPostEditor)postPropertiesForm).Initialize(editorContext, clientOptions); ManageLayout(); } private bool IsPage { get { return _editorContext != null && _editorContext.BlogPost != null ? _editorContext.BlogPost.IsPage : false; } } public void OnBlogChanged(Blog newBlog) { _clientOptions = newBlog.ClientOptions; _targetBlog = newBlog; controller.OnBlogChanged(newBlog); ((IBlogPostEditor)postPropertiesForm).OnBlogChanged(newBlog); ManageLayout(); } public void OnBlogSettingsChanged(bool templateChanged) { controller.OnBlogSettingsChanged(templateChanged); ((IBlogPostEditor)postPropertiesForm).OnBlogSettingsChanged(templateChanged); ManageLayout(); } private void ManageLayout() { if (IsPage) { bool showViewAll = _clientOptions.SupportsCommentPolicy || _clientOptions.SupportsPingPolicy || _clientOptions.SupportsAuthor || _clientOptions.SupportsSlug || _clientOptions.SupportsPassword; linkViewAll.Visible = showViewAll; CategoryVisible = false; TagsVisible = false; Visible = showViewAll || _clientOptions.SupportsPageParent || _clientOptions.SupportsPageOrder; } else { bool showViewAll = _clientOptions.SupportsCommentPolicy || _clientOptions.SupportsPingPolicy || _clientOptions.SupportsAuthor || _clientOptions.SupportsSlug || _clientOptions.SupportsPassword || _clientOptions.SupportsExcerpt || _clientOptions.SupportsTrackbacks; bool showTags = (_clientOptions.SupportsKeywords && (_clientOptions.KeywordsAsTags || _clientOptions.SupportsGetKeywords)); Visible = showViewAll || _clientOptions.SupportsCustomDate || showTags || _clientOptions.SupportsCategories; CategoryVisible = _clientOptions.SupportsCategories; TagsVisible = showTags; linkViewAll.Visible = showViewAll; } } public bool IsDirty { get { return controller.IsDirty || ((IBlogPostEditor)postPropertiesForm).IsDirty; } } public bool HasKeywords { get { return postPropertiesForm.HasKeywords; } } public void SaveChanges(BlogPost post, BlogPostSaveOptions options) { ((IBlogPostEditor)postPropertiesForm).SaveChanges(post, options); } public bool ValidatePublish() { return controller.ValidatePublish(); } public void OnPublishSucceeded(BlogPost blogPost, PostResult postResult) { controller.OnPublishSucceeded(blogPost, postResult); ((IBlogPostEditor)postPropertiesForm).OnPublishSucceeded(blogPost, postResult); } public void OnClosing(CancelEventArgs e) { controller.OnClosing(e); ((IBlogPostEditor)postPropertiesForm).OnClosing(e); } public void OnPostClosing(CancelEventArgs e) { controller.OnPostClosing(e); ((IBlogPostEditor)postPropertiesForm).OnPostClosing(e); } public void OnClosed() { controller.OnClosed(); ((IBlogPostEditor)postPropertiesForm).OnClosed(); } public void OnPostClosed() { controller.OnPostClosed(); ((IBlogPostEditor)postPropertiesForm).OnPostClosed(); } private void linkViewAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (e.Button != MouseButtons.Left) return; if (!postPropertiesForm.Visible) postPropertiesForm.Show(FindForm()); else { if (postPropertiesForm.WindowState == FormWindowState.Minimized) postPropertiesForm.WindowState = FormWindowState.Normal; postPropertiesForm.Activate(); } } void IRtlAware.Layout() { } #region Implementation of INewCategoryContext public void NewCategoryAdded(BlogPostCategory category) { controller.NewCategoryAdded(category); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.InteropServices { using System; using System.Runtime.CompilerServices; using System.Threading; using System.Diagnostics.Contracts; #if BIT64 using nint = System.Int64; #else using nint = System.Int32; #endif // These are the types of handles used by the EE. // IMPORTANT: These must match the definitions in ObjectHandle.h in the EE. // IMPORTANT: If new values are added to the enum the GCHandle::MaxHandleType // constant must be updated. [Serializable] public enum GCHandleType { Weak = 0, WeakTrackResurrection = 1, Normal = 2, Pinned = 3 } // This class allows you to create an opaque, GC handle to any // COM+ object. A GC handle is used when an object reference must be // reachable from unmanaged memory. There are 3 kinds of roots: // Normal - keeps the object from being collected. // Weak - allows object to be collected and handle contents will be zeroed. // Weak references are zeroed before the finalizer runs, so if the // object is resurrected in the finalizer the weak reference is // still zeroed. // WeakTrackResurrection - Same as weak, but stays until after object is // really gone. // Pinned - same as normal, but allows the address of the actual object // to be taken. // [StructLayout(LayoutKind.Sequential)] public struct GCHandle { // IMPORTANT: This must be kept in sync with the GCHandleType enum. private const GCHandleType MaxHandleType = GCHandleType.Pinned; #if MDA_SUPPORTED static GCHandle() { s_probeIsActive = Mda.IsInvalidGCHandleCookieProbeEnabled(); if (s_probeIsActive) s_cookieTable = new GCHandleCookieTable(); } #endif // Allocate a handle storing the object and the type. internal GCHandle(Object value, GCHandleType type) { // Make sure the type parameter is within the valid range for the enum. if ((uint)type > (uint)MaxHandleType) ThrowArgumentOutOfRangeException_ArgumentOutOfRange_Enum(); Contract.EndContractBlock(); IntPtr handle = InternalAlloc(value, type); if (type == GCHandleType.Pinned) { // Record if the handle is pinned. handle = (IntPtr)((nint)handle | 1); } m_handle = handle; } // Used in the conversion functions below. internal GCHandle(IntPtr handle) { m_handle = handle; } // Creates a new GC handle for an object. // // value - The object that the GC handle is created for. // type - The type of GC handle to create. // // returns a new GC handle that protects the object. public static GCHandle Alloc(Object value) { return new GCHandle(value, GCHandleType.Normal); } public static GCHandle Alloc(Object value, GCHandleType type) { return new GCHandle(value, type); } // Frees a GC handle. public void Free() { // Free the handle if it hasn't already been freed. IntPtr handle = Interlocked.Exchange(ref m_handle, IntPtr.Zero); ValidateHandle(handle); #if MDA_SUPPORTED // If this handle was passed out to unmanaged code, we need to remove it // from the cookie table. // NOTE: the entry in the cookie table must be released before the // internal handle is freed to prevent a race with reusing GC handles. if (s_probeIsActive) s_cookieTable.RemoveHandleIfPresent(handle); #endif InternalFree(GetHandleValue(handle)); } // Target property - allows getting / updating of the handle's referent. public Object Target { get { ValidateHandle(); return InternalGet(GetHandleValue()); } set { ValidateHandle(); InternalSet(GetHandleValue(), value, IsPinned()); } } // Retrieve the address of an object in a Pinned handle. This throws // an exception if the handle is any type other than Pinned. public IntPtr AddrOfPinnedObject() { // Check if the handle was not a pinned handle. if (!IsPinned()) { ValidateHandle(); // You can only get the address of pinned handles. throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned); } // Get the address. return InternalAddrOfPinnedObject(GetHandleValue()); } // Determine whether this handle has been allocated or not. public bool IsAllocated => !m_handle.IsNull(); // Used to create a GCHandle from an int. This is intended to // be used with the reverse conversion. public static explicit operator GCHandle(IntPtr value) { ValidateHandle(value); return new GCHandle(value); } public static GCHandle FromIntPtr(IntPtr value) { ValidateHandle(value); Contract.EndContractBlock(); #if MDA_SUPPORTED IntPtr handle = value; if (s_probeIsActive) { // Make sure this cookie matches up with a GCHandle we've passed out a cookie for. handle = s_cookieTable.GetHandle(value); if (IntPtr.Zero == handle) { // Fire an MDA if we were unable to retrieve the GCHandle. Mda.FireInvalidGCHandleCookieProbe(value); return new GCHandle(IntPtr.Zero); } return new GCHandle(handle); } #endif return new GCHandle(value); } // Used to get the internal integer representation of the handle out. public static explicit operator IntPtr(GCHandle value) { return ToIntPtr(value); } public static IntPtr ToIntPtr(GCHandle value) { #if MDA_SUPPORTED if (s_probeIsActive) { // Remember that we passed this GCHandle out by storing the cookie we returned so we // can later validate. return s_cookieTable.FindOrAddHandle(value.m_handle); } #endif return value.m_handle; } public override int GetHashCode() { return m_handle.GetHashCode(); } public override bool Equals(Object o) { GCHandle hnd; // Check that o is a GCHandle first if (o == null || !(o is GCHandle)) return false; else hnd = (GCHandle)o; return m_handle == hnd.m_handle; } public static bool operator ==(GCHandle a, GCHandle b) { return a.m_handle == b.m_handle; } public static bool operator !=(GCHandle a, GCHandle b) { return a.m_handle != b.m_handle; } internal IntPtr GetHandleValue() { return GetHandleValue(m_handle); } private static IntPtr GetHandleValue(IntPtr handle) { // Remove Pin flag return new IntPtr((nint)handle & ~(nint)1); } internal bool IsPinned() { // Check Pin flag return ((nint)m_handle & 1) != 0; } // Internal native calls that this implementation uses. [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr InternalAlloc(Object value, GCHandleType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalFree(IntPtr handle); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object InternalGet(IntPtr handle); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void InternalSet(IntPtr handle, Object value, bool isPinned); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object InternalCompareExchange(IntPtr handle, Object value, Object oldValue, bool isPinned); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IntPtr InternalAddrOfPinnedObject(IntPtr handle); // The actual integer handle value that the EE uses internally. private IntPtr m_handle; #if MDA_SUPPORTED // The GCHandle cookie table. static private volatile GCHandleCookieTable s_cookieTable = null; static private volatile bool s_probeIsActive = false; #endif private void ValidateHandle() { // Check if the handle was never initialized or was freed. if (m_handle.IsNull()) ThrowInvalidOperationException_HandleIsNotInitialized(); } private static void ValidateHandle(IntPtr handle) { // Check if the handle was never initialized or was freed. if (handle.IsNull()) ThrowInvalidOperationException_HandleIsNotInitialized(); } private static void ThrowArgumentOutOfRangeException_ArgumentOutOfRange_Enum() { throw ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.type, ExceptionResource.ArgumentOutOfRange_Enum); } private static void ThrowInvalidOperationException_HandleIsNotInitialized() { throw ThrowHelper.GetInvalidOperationException(ExceptionResource.InvalidOperation_HandleIsNotInitialized); } } }
using Boo.Lang; namespace Rhino.Etl.Core { using System; using System.Collections; using System.Diagnostics; using System.Text; using Exceptions; /// <summary> /// A dictionary that can be access with a natural syntax from Boo /// </summary> [Serializable] public class QuackingDictionary : IDictionary, IQuackFu { /// <summary> /// Default value for the Comparer property. /// Defines how keys are compared (case sensitivity, hashing algorithm, etc.) /// </summary> public static StringComparer DefaultComparer { get; set; } /// <summary> /// Initialization for static members/properties /// </summary> static QuackingDictionary() { DefaultComparer = StringComparer.InvariantCultureIgnoreCase; } /// <summary> /// The inner items collection /// </summary> protected IDictionary items; /// <summary> /// The last item that was access, useful for debugging /// </summary> protected string lastAccess; private bool throwOnMissing = false; /// <summary> /// Defines how keys are compared (case sensitivity, hashing algorithm, etc.) /// </summary> protected StringComparer Comparer { get; set; } /// <summary> /// Set the flag to thorw if key not found. /// </summary> public void ShouldThorwIfKeyNotFound() { throwOnMissing = true; } /// <summary> /// Initializes a new instance of the <see cref="QuackingDictionary"/> class. /// </summary> /// <param name="items">The items.</param> /// <param name="comparer">Defines key equality</param> public QuackingDictionary(IDictionary items, StringComparer comparer) { Comparer = comparer; if (items != null) this.items = new Hashtable(items, Comparer); else this.items = new Hashtable(Comparer); } /// <summary> /// Initializes a new instance of the <see cref="QuackingDictionary"/> class. /// </summary> /// <param name="items">The items.</param> public QuackingDictionary(IDictionary items) : this(items, DefaultComparer) { } /// <summary> /// Gets or sets the <see cref="System.Object"/> with the specified key. /// </summary> /// <value></value> public object this[string key] { get { if (throwOnMissing && items.Contains(key) == false) throw new MissingKeyException(key); lastAccess = key; return items[key]; } set { lastAccess = key; if(value == DBNull.Value) items[key] = null; else items[key] = value; } } /// <summary> /// Get a value by name or first parameter /// </summary> public virtual object QuackGet(string name, object[] parameters) { if (parameters == null || parameters.Length == 0) return this[name]; if (parameters.Length == 1) return this[(string)parameters[0]]; throw new ParameterCountException("You can only call indexer with a single parameter"); } /// <summary> /// Set a value on the given name or first parameter /// </summary> public object QuackSet(string name, object[] parameters, object value) { if (parameters == null || parameters.Length == 0) return this[name] = value; if (parameters.Length == 1) return this[(string)parameters[0]] = value; throw new ParameterCountException("You can only call indexer with a single parameter"); } /// <summary> /// Not supported /// </summary> public object QuackInvoke(string name, params object[] args) { throw new NotSupportedException( "You cannot invoke methods on a row, it is merely a data structure, after all."); } /// <summary> /// A debbug view of quacking dictionary /// </summary> internal class QuackingDictionaryDebugView { private readonly IDictionary items; /// <summary> /// Initializes a new instance of the <see cref="QuackingDictionaryDebugView"/> class. /// </summary> /// <param name="dictionary">The dictionary.</param> public QuackingDictionaryDebugView(QuackingDictionary dictionary) { this.items = dictionary.items; } /// <summary> /// Gets the items. /// </summary> /// <value>The items.</value> [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] public KeyValuePair[] Items { get { var pairs = new System.Collections.Generic.List<KeyValuePair>(); foreach (DictionaryEntry item in items) { pairs.Add(new KeyValuePair(item.Key, item.Value)); } return pairs.ToArray(); } } /// <summary> /// Represent a single key/value pair for the debugger /// </summary> [DebuggerDisplay("{value}", Name = "[{key}]", Type = "")] internal class KeyValuePair { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly object key; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly object value; /// <summary> /// Initializes a new instance of the <see cref="KeyValuePair"/> class. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> public KeyValuePair(object key, object value) { this.key = key; this.value = value; } /// <summary> /// Gets the key. /// </summary> /// <value>The key.</value> public object Key { get { return key; } } /// <summary> /// Gets the value. /// </summary> /// <value>The value.</value> public object Value { get { return value; } } } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("{"); foreach (DictionaryEntry item in items) { sb.Append(item.Key) .Append(" : "); if (item.Value is string) { sb.Append("\"") .Append(item.Value) .Append("\""); } else { sb.Append(item.Value); } sb.Append(", "); } sb.Append("}"); return sb.ToString(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> public IEnumerator GetEnumerator() { return new Hashtable(items).GetEnumerator(); } ///<summary> ///Returns an <see cref="T:System.Collections.IDictionaryEnumerator"></see> object for the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.IDictionaryEnumerator"></see> object for the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> ///<filterpriority>2</filterpriority> IDictionaryEnumerator IDictionary.GetEnumerator() { return items.GetEnumerator(); } ///<summary> ///Determines whether the <see cref="T:System.Collections.IDictionary"></see> object contains an element with the specified key. ///</summary> /// ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> contains an element with the key; otherwise, false. ///</returns> /// ///<param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary"></see> object.</param> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public bool Contains(object key) { return items.Contains(key); } ///<summary> ///Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<param name="value">The <see cref="T:System.Object"></see> to use as the value of the element to add. </param> ///<param name="key">The <see cref="T:System.Object"></see> to use as the key of the element to add. </param> ///<exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.IDictionary"></see> object. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> is read-only.-or- The <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception><filterpriority>2</filterpriority> public void Add(object key, object value) { items.Add(key, value); } ///<summary> ///Removes all elements from the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> object is read-only. </exception><filterpriority>2</filterpriority> public void Clear() { items.Clear(); } ///<summary> ///Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<param name="key">The key of the element to remove. </param> ///<exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IDictionary"></see> object is read-only.-or- The <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public void Remove(object key) { items.Remove(key); } ///<summary> ///Gets or sets the element with the specified key. ///</summary> /// ///<returns> ///The element with the specified key. ///</returns> /// ///<param name="key">The key of the element to get or set. </param> ///<exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.IDictionary"></see> object is read-only.-or- The property is set, key does not exist in the collection, and the <see cref="T:System.Collections.IDictionary"></see> has a fixed size. </exception> ///<exception cref="T:System.ArgumentNullException">key is null. </exception><filterpriority>2</filterpriority> public object this[object key] { get { return items[key]; } set { items[key] = value; } } ///<summary> ///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.ICollection"></see> object containing the keys of the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> ///<filterpriority>2</filterpriority> public ICollection Keys { get { return items.Keys; } } ///<summary> ///Gets an <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:System.Collections.IDictionary"></see> object. ///</summary> /// ///<returns> ///An <see cref="T:System.Collections.ICollection"></see> object containing the values in the <see cref="T:System.Collections.IDictionary"></see> object. ///</returns> ///<filterpriority>2</filterpriority> public ICollection Values { get { return items.Values; } } ///<summary> ///Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"></see> object is read-only. ///</summary> /// ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> object is read-only; otherwise, false. ///</returns> ///<filterpriority>2</filterpriority> public bool IsReadOnly { get { return items.IsReadOnly; } } ///<summary> ///Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"></see> object has a fixed size. ///</summary> /// ///<returns> ///true if the <see cref="T:System.Collections.IDictionary"></see> object has a fixed size; otherwise, false. ///</returns> ///<filterpriority>2</filterpriority> public bool IsFixedSize { get { return items.IsFixedSize; } } ///<summary> ///Copies the elements of the <see cref="T:System.Collections.ICollection"></see> to an <see cref="T:System.Array"></see>, starting at a particular <see cref="T:System.Array"></see> index. ///</summary> /// ///<param name="array">The one-dimensional <see cref="T:System.Array"></see> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"></see>. The <see cref="T:System.Array"></see> must have zero-based indexing. </param> ///<param name="index">The zero-based index in array at which copying begins. </param> ///<exception cref="T:System.ArgumentNullException">array is null. </exception> ///<exception cref="T:System.ArgumentException">The type of the source <see cref="T:System.Collections.ICollection"></see> cannot be cast automatically to the type of the destination array. </exception> ///<exception cref="T:System.ArgumentOutOfRangeException">index is less than zero. </exception> ///<exception cref="T:System.ArgumentException">array is multidimensional.-or- index is equal to or greater than the length of array.-or- The number of elements in the source <see cref="T:System.Collections.ICollection"></see> is greater than the available space from index to the end of the destination array. </exception><filterpriority>2</filterpriority> public void CopyTo(Array array, int index) { items.CopyTo(array, index); } ///<summary> ///Gets the number of elements contained in the <see cref="T:System.Collections.ICollection"></see>. ///</summary> /// ///<returns> ///The number of elements contained in the <see cref="T:System.Collections.ICollection"></see>. ///</returns> ///<filterpriority>2</filterpriority> public int Count { get { return items.Count; } } ///<summary> ///Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"></see>. ///</summary> /// ///<returns> ///An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"></see>. ///</returns> ///<filterpriority>2</filterpriority> public object SyncRoot { get { return items.SyncRoot; } } ///<summary> ///Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"></see> is synchronized (thread safe). ///</summary> /// ///<returns> ///true if access to the <see cref="T:System.Collections.ICollection"></see> is synchronized (thread safe); otherwise, false. ///</returns> ///<filterpriority>2</filterpriority> public bool IsSynchronized { get { return items.IsSynchronized; } } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Specialized; using gov.va.medora.mdws.dto; using gov.va.medora.mdo; using gov.va.medora.mdo.api; using gov.va.medora.mdo.dao; using System.Collections.Generic; namespace gov.va.medora.mdws { public class EncounterLib { MySession mySession; public EncounterLib(MySession mySession) { this.mySession = mySession; } public TaggedPatientArrays getPatientsWithUpdatedFutureAppointments(string username, string pwd, string updatedSince) { TaggedPatientArrays result = new TaggedPatientArrays(); //if (String.IsNullOrEmpty(username) | String.IsNullOrEmpty(pwd) | String.IsNullOrEmpty(updatedSince)) //{ // result.fault = new FaultTO("Must supply all arguments"); //} try { EncounterApi api = new EncounterApi(); DataSource ds = new DataSource { ConnectionString = mySession.MdwsConfiguration.CdwConnectionString }; AbstractConnection cxn = new gov.va.medora.mdo.dao.sql.cdw.CdwConnection(ds); Dictionary<string, HashSet<string>> dict = api.getUpdatedFutureAppointments(cxn, DateTime.Parse(updatedSince)); result.arrays = new TaggedPatientArray[dict.Keys.Count]; int arrayCount = 0; foreach (string key in dict.Keys) { TaggedPatientArray tpa = new TaggedPatientArray(key); tpa.patients = new PatientTO[dict[key].Count]; int patientCount = 0; foreach (string patientICN in dict[key]) { PatientTO p = new PatientTO { mpiPid = patientICN }; tpa.patients[patientCount] = p; patientCount++; } result.arrays[arrayCount] = tpa; arrayCount++; } } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TaggedHospitalLocationArray getLocations(string target, string direction) { return getLocations(null, target, direction); } public TaggedHospitalLocationArray getLocations(string sitecode, string target, string direction) { TaggedHospitalLocationArray result = new TaggedHospitalLocationArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } if (direction == "") { direction = "1"; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); EncounterApi api = new EncounterApi(); HospitalLocation[] locations = api.getLocations(cxn,target,direction); result = new TaggedHospitalLocationArray(sitecode,locations); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedVisitArray getVisits(string fromDate, string toDate) { return getVisits(null, fromDate, toDate); } public TaggedVisitArray getVisits(string sitecode, string fromDate, string toDate) { TaggedVisitArray result = new TaggedVisitArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { toDate = DateTime.Today.ToString("yyyyMMdd"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); EncounterApi api = new EncounterApi(); Visit[] v = api.getVisits(cxn, fromDate, toDate); result = new TaggedVisitArray(sitecode, v); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedInpatientStayArray getAdmissions() { return getAdmissions(null); } public TaggedInpatientStayArray getAdmissions(string sitecode) { TaggedInpatientStayArray result = new TaggedInpatientStayArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); EncounterApi api = new EncounterApi(); InpatientStay[] stays = api.getAdmissions(cxn); result = new TaggedInpatientStayArray(sitecode, stays); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TextTO getNoteEncounterString(string noteId) { return getNoteEncounterString(null, noteId); } public TextTO getNoteEncounterString(string sitecode, string noteId) { TextTO result = new TextTO(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (noteId == "") { result.fault = new FaultTO("Missing noteId"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); NoteApi api = new NoteApi(); result.text = api.getNoteEncounterString(cxn, noteId); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedHospitalLocationArray getWards() { return getWards(null); } public TaggedHospitalLocationArray getWards(string sitecode) { TaggedHospitalLocationArray result = new TaggedHospitalLocationArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); EncounterApi api = new EncounterApi(); HospitalLocation[] wards = api.getWards(cxn); result = new TaggedHospitalLocationArray(sitecode, wards); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedHospitalLocationArray getClinics(string target) { return getClinics(null, target, null); } public TaggedHospitalLocationArray getClinics(string target, string direction) { return getClinics(null, target, direction); } public TaggedHospitalLocationArray getClinics(string sitecode, string target, string direction) { TaggedHospitalLocationArray result = new TaggedHospitalLocationArray(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); EncounterApi api = new EncounterApi(); HospitalLocation[] clinics = api.getClinics(cxn, target, direction); result = new TaggedHospitalLocationArray(sitecode, clinics); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedText getSpecialties() { return getSpecialties(null); } public TaggedText getSpecialties(string sitecode) { TaggedText result = new TaggedText(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { EncounterApi api = new EncounterApi(); AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); DictionaryHashList specialties = api.getSpecialties(cxn); result = new TaggedText(sitecode, specialties); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedText getTeams() { return getTeams(null); } public TaggedText getTeams(string sitecode) { TaggedText result = new TaggedText(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); EncounterApi api = new EncounterApi(); DictionaryHashList teams = api.getTeams(cxn); result = new TaggedText(sitecode, teams); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedTextArray getOutpatientEncounterReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getOutpatientEncounterReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedTextArray getAdmissionsReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getAdmissionsReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getExpandedAdtReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getExpandedAdtReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getDischargeDiagnosisReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getDischargeDiagnosisReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getDischargesReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getDischargesReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getTransfersReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getTransfersReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getFutureClinicVisitsReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getFutureClinicVisitsReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getPastClinicVisitsReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getPastClinicVisitsReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getTreatingSpecialtyReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getTreatingSpecialtyReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getCompAndPenReports(string fromDate, string toDate, int nrpts) { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getCompAndPenReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedTextArray getCareTeamReports() { TaggedTextArray result = new TaggedTextArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getCareTeamReports(mySession.ConnectionSet); result = new TaggedTextArray(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedIcdRptArrays getIcdProceduresReports(string fromDate, string toDate, int nrpts) { TaggedIcdRptArrays result = new TaggedIcdRptArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getIcdProceduresReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedIcdRptArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedIcdRptArrays getIcdSurgeryReports(string fromDate, string toDate, int nrpts) { TaggedIcdRptArrays result = new TaggedIcdRptArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getIcdSurgeryReports(mySession.ConnectionSet, fromDate, toDate, nrpts); result = new TaggedIcdRptArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedAppointmentArrays getAppointments() { TaggedAppointmentArrays result = new TaggedAppointmentArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getAppointments(mySession.ConnectionSet); return new TaggedAppointmentArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); return result; } } public TextTO getAppointmentText(string siteId, string apptId) { TextTO result = new TextTO(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (siteId == "") { result.fault = new FaultTO("Missing siteId"); } else if (apptId == "") { result.fault = new FaultTO("Missing apptId"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); string s = api.getAppointmentText(mySession.ConnectionSet.getConnection(siteId), apptId); result = new TextTO(s); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedDrgArrays getDRGRecords() { TaggedDrgArrays result = new TaggedDrgArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getDRGRecords(mySession.ConnectionSet); result = new TaggedDrgArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedAdtArrays getInpatientMoves() { TaggedAdtArrays result = new TaggedAdtArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getInpatientMoves(mySession.ConnectionSet); result = new TaggedAdtArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedAdtArrays getInpatientMoves(string fromDate, string toDate) { TaggedAdtArrays result = new TaggedAdtArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getInpatientMoves(mySession.ConnectionSet, fromDate, toDate); result = new TaggedAdtArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedAdtArrays getInpatientMoves(string fromDate, string toDate, string iterLength) { TaggedAdtArrays result = new TaggedAdtArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getInpatientMoves(mySession.ConnectionSet, fromDate, toDate, iterLength); result = new TaggedAdtArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } // This needs to be changed to a single-site call. public TaggedAdtArrays getInpatientMovesByCheckinId(string checkinId) { TaggedAdtArrays result = new TaggedAdtArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getInpatientMovesByCheckinId(mySession.ConnectionSet, checkinId); result = new TaggedAdtArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedAdtArray getInpatientDischarges(string sitecode, string pid) { TaggedAdtArray result = new TaggedAdtArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); Adt[] adts = api.getInpatientDischarges(mySession.ConnectionSet.getConnection(sitecode), pid); result = new TaggedAdtArray(sitecode, adts); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public TaggedInpatientStayArrays getStayMovementsByDateRange(string fromDate, string toDate) { TaggedInpatientStayArrays result = new TaggedInpatientStayArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (fromDate == "") { result.fault = new FaultTO("Missing fromDate"); } else if (toDate == "") { result.fault = new FaultTO("Missing toDate"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getStayMovementsByDateRange(mySession.ConnectionSet,fromDate,toDate); result = new TaggedInpatientStayArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public InpatientStayTO getStayMovements(string checkinId) { return getStayMovements(null, checkinId); } public InpatientStayTO getStayMovements(string sitecode, string checkinId) { InpatientStayTO result = new InpatientStayTO(); string msg = MdwsUtils.isAuthorizedConnection(mySession, sitecode); if (msg != "OK") { result.fault = new FaultTO(msg); } else if (checkinId == "") { result.fault = new FaultTO("Missing checkinId"); } if (result.fault != null) { return result; } if (sitecode == null) { sitecode = mySession.ConnectionSet.BaseSiteId; } try { AbstractConnection cxn = mySession.ConnectionSet.getConnection(sitecode); EncounterApi api = new EncounterApi(); InpatientStay stay = api.getStayMovements(cxn, checkinId); result = new InpatientStayTO(stay); } catch (Exception e) { result.fault = new FaultTO(e.Message); } return result; } public TaggedInpatientStayArrays getStayMovementsByPatient() { TaggedInpatientStayArrays result = new TaggedInpatientStayArrays(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); IndexedHashtable t = api.getStayMovementsByPatient(mySession.ConnectionSet, mySession.Patient.LocalPid); result = new TaggedInpatientStayArrays(t); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public SiteArray getSiteDivisions(string sitecode) { SiteArray result = new SiteArray(); if (sitecode == "") { result.fault = new FaultTO("Missing sitecode"); } if (result.fault != null) { return result; } try { EncounterApi api = new EncounterApi(); Site[] sites = api.getSiteDivisions(mySession.ConnectionSet.getConnection(sitecode), sitecode); result = new SiteArray(sites); } catch (Exception e) { result.fault = new FaultTO(e); } return result; } public AppointmentTypeArray getAppointmentTypes(string target) { AppointmentTypeArray result = new AppointmentTypeArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } if (String.IsNullOrEmpty(target)) { target = "A"; } if (result.fault != null) { return result; } try { IList<AppointmentType> types = new EncounterApi().getAppointmentTypes(mySession.ConnectionSet.BaseConnection, target); result = new AppointmentTypeArray(types); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TaggedAppointmentArray getPendingAppointments(string startDate) { TaggedAppointmentArray result = new TaggedAppointmentArray(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (String.IsNullOrEmpty(startDate)) { result.fault = new FaultTO("Missing startDate"); } if (result.fault != null) { return result; } try { IList<Appointment> appts = new EncounterApi().getPendingAppointments(mySession.ConnectionSet.BaseConnection, startDate); result = new TaggedAppointmentArray(mySession.ConnectionSet.BaseConnection.DataSource.SiteId.Id, appts); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public TextTO getClinicAvailability(string clinicId) { TextTO result = new TextTO(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (String.IsNullOrEmpty(clinicId)) { result.fault = new FaultTO("Missing clinic ID"); } if (result.fault != null) { return result; } try { string availabilityString = new EncounterApi().getClinicAvailability(mySession.ConnectionSet.BaseConnection, clinicId); result = new TextTO(availabilityString); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public AppointmentTO makeAppointment(string clinicId, string appointmentType, string appointmentTimestamp, string appointmentLength) { AppointmentTO result = new AppointmentTO(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (String.IsNullOrEmpty(clinicId)) { result.fault = new FaultTO("Missing clinic ID"); } else if (String.IsNullOrEmpty(appointmentTimestamp)) { result.fault = new FaultTO("Missing appointment timestamp"); } else if (String.IsNullOrEmpty(appointmentType)) { result.fault = new FaultTO("Missing appointment type"); } else if (String.IsNullOrEmpty(appointmentLength)) { result.fault = new FaultTO("Missing appointment length"); } if (result.fault != null) { return result; } try { Appointment appt = new Appointment() { AppointmentType = new AppointmentType() { ID = appointmentType }, Clinic = new HospitalLocation() { Id = clinicId }, Length = appointmentLength, Timestamp = appointmentTimestamp }; appt = new EncounterApi().makeAppointment(mySession.ConnectionSet.BaseConnection, appt); result = new AppointmentTO(appt); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } public HospitalLocationTO getClinicSchedulingDetails(string clinicId) { HospitalLocationTO result = new HospitalLocationTO(); if (!mySession.ConnectionSet.IsAuthorized) { result.fault = new FaultTO("Connections not ready for operation", "Need to login?"); } else if (String.IsNullOrEmpty(clinicId)) { result.fault = new FaultTO("Missing clinic ID"); } if (result.fault != null) { return result; } try { result = new HospitalLocationTO(new EncounterApi().getClinicSchedulingDetails(mySession.ConnectionSet.BaseConnection, clinicId)); } catch (Exception exc) { result.fault = new FaultTO(exc); } return result; } } }
// *********************************************************************** // Copyright (c) 2007 Charlie Poole, Rob Prouse // // 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; using System.Collections.Generic; using NUnit.Framework.Internal; using NUnit.TestUtilities; using NUnit.TestUtilities.Comparers; namespace NUnit.Framework.Constraints { [TestFixture] public class CollectionOrderedConstraintTests { private readonly string NL = Environment.NewLine; #region Ordering Tests [TestCaseSource(nameof(OrderedByData))] public void IsOrderedBy(IEnumerable collection, Constraint constraint) { Assert.That(collection, constraint); } static readonly object[] OrderedByData = new[] { // Simple Ordering new TestCaseData( new[] { "x", "y", "z" }, Is.Ordered), new TestCaseData( new[] { 1, 2, 3 }, Is.Ordered), new TestCaseData( new[] { "x", "y", "z" }, Is.Ordered.Ascending), new TestCaseData( new[] { 1, 2, 3 }, Is.Ordered.Ascending), new TestCaseData( new[] { "z", "y", "x" }, Is.Ordered.Descending), new TestCaseData( new[] { 3, 2, 1 }, Is.Ordered.Descending), new TestCaseData( new[] { "x", "x", "z" }, Is.Ordered), new TestCaseData( new[] { null, "x", "y" }, Is.Ordered), new TestCaseData( new[] {"y", "x", null}, Is.Ordered.Descending), new TestCaseData( new[] { "x", null, "y" }, Is.Not.Ordered), // Ordered By Single Property new TestCaseData( new[] { new TestClass1(1), new TestClass1(2), new TestClass1(3) }, Is.Ordered.By("Value") ), new TestCaseData( new[] { new TestClass1(1), new TestClass1(2), new TestClass1(3) }, Is.Ordered.By("Value").Ascending ), new TestCaseData( new[] { new TestClass1(1), new TestClass1(2), new TestClass1(3) }, Is.Ordered.Ascending.By("Value") ), new TestCaseData( new[] { new TestClass1(3), new TestClass1(2), new TestClass1(1) }, Is.Ordered.By("Value").Descending ), new TestCaseData( new[] { new TestClass1(3), new TestClass1(2), new TestClass1(1) }, Is.Ordered.Descending.By("Value") ), new TestCaseData( new[] { new TestClass1(1), new TestClass1(2), new TestClass1(3) }, Is.Ordered.By("Value").Using(ObjectComparer.Default) ), new TestCaseData( new object[] { new TestClass1(1), new TestClass2(2) }, Is.Ordered.By("Value") ), // Ordered By Two Properties new TestCaseData( new [] { new TestClass3("ABC", 1), new TestClass3("ABC", 42), new TestClass3("XYZ", 2) }, Is.Ordered.By("A").By("B") ), new TestCaseData( new [] { new TestClass3("ABC", 1), new TestClass3("ABC", 42), new TestClass3("XYZ", 2) }, Is.Ordered.By("A").Then.By("B") ), new TestCaseData( new [] { new TestClass3("ABC", 1), new TestClass3("ABC", 42), new TestClass3("XYZ", 2) }, Is.Ordered.Ascending.By("A").Then.Ascending.By("B") ), new TestCaseData( new [] { new TestClass3("ABC", 1), new TestClass3("ABC", 42), new TestClass3("XYZ", 2) }, Is.Ordered.By("A").Ascending.Then.By("B").Ascending ), new TestCaseData( new [] { new TestClass3("ABC", 42), new TestClass3("XYZ", 99), new TestClass3("XYZ", 2) }, Is.Not.Ordered.By("A").Then.By("B") ), new TestCaseData( new [] { new TestClass3("XYZ", 2), new TestClass3("ABC", 1), new TestClass3("ABC", 42) }, Is.Ordered.By("A").Descending.Then.By("B") ), new TestCaseData( new [] { new TestClass3("XYZ", 2), new TestClass3("ABC", 1), new TestClass3("ABC", 42) }, Is.Ordered.Descending.By("A").Then.By("B") ), new TestCaseData( new [] { new TestClass3("ABC", 42), new TestClass3("ABC", 1), new TestClass3("XYZ", 2) }, Is.Ordered.By("A").Ascending.Then.By("B").Descending ), new TestCaseData( new [] { new TestClass3("ABC", 42), new TestClass3("ABC", 1), new TestClass3("XYZ", 2) }, Is.Ordered.Ascending.By("A").Then.Descending.By("B") ), new TestCaseData( new [] { new TestClass3("ABC", 42), new TestClass3("ABC", 1), new TestClass3("XYZ", 2) }, Is.Not.Ordered.By("A").Then.By("B") ), new TestCaseData( new[] { new TestClass3("XYZ", 2), new TestClass3("ABC", 42), new TestClass3("ABC", 1) }, Is.Ordered.By("A").Descending.Then.By("B").Descending ), new TestCaseData( new[] { new TestClass3("XYZ", 2), new TestClass3("ABC", 42), new TestClass3("ABC", 1) }, Is.Ordered.Descending.By("A").Then.Descending.By("B") ) }; #endregion #region Error Message Tests [Test] public void IsOrdered_Fails() { var expectedMessage = " Expected: collection ordered" + NL + " But was: < \"x\", \"z\", \"y\" >" + NL; var ex = Assert.Throws<AssertionException>(() => Assert.That(new[] { "x", "z", "y" }, Is.Ordered)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region Custom Comparer Tests [Test] public void IsOrdered_HandlesCustomComparison() { AlwaysEqualComparer comparer = new AlwaysEqualComparer(); Assert.That(new[] { new object(), new object() }, Is.Ordered.Using(comparer)); Assert.That(comparer.CallCount, Is.GreaterThan(0), "TestComparer was not called"); } [Test] public void ExceptionThrownForMultipleComparersInStep() { Assert.That(() => Is.Ordered.Using(new TestComparer()).Using(new AlwaysEqualComparer()), Throws.TypeOf<InvalidOperationException>()); } [Test] public void MultipleComparersUsedInDifferentSteps() { var comparer1 = new TestComparer(); var comparer2 = new AlwaysEqualComparer(); var collection = new[] { new TestClass3("XYZ", 2), new TestClass3("ABC", 42), new TestClass3("ABC", 1) }; Assert.That(collection, Is.Ordered.By("A").Using(comparer1).Then.By("B").Using(comparer2)); // First comparer is called for every pair of items in the collection Assert.That(comparer1.CallCount, Is.EqualTo(2), "First comparer should be called twice"); // Second comparer is only called where the first property matches Assert.That(comparer2.CallCount, Is.EqualTo(1), "Second comparer should be called once"); } [Test] public void IsOrdered_HandlesCustomComparison2() { TestComparer comparer = new TestComparer(); Assert.That(new[] { 2, 1 }, Is.Ordered.Using(comparer)); Assert.That(comparer.CallCount, Is.GreaterThan(0), "TestComparer was not called"); } [Test] public void UsesProvidedGenericComparer() { var comparer = new GenericComparer<int>(); Assert.That(new[] { 1, 2 }, Is.Ordered.Using(comparer)); Assert.That(comparer.WasCalled, "Comparer was not called"); } [Test] public void UsesProvidedGenericComparison() { var comparer = new GenericComparison<int>(); Assert.That(new[] { 1, 2 }, Is.Ordered.Using(comparer.Delegate)); Assert.That(comparer.WasCalled, "Comparer was not called"); } [Test] public void UsesProvidedLambda() { Comparison<int> comparer = (x, y) => x.CompareTo(y); Assert.That(new[] { 1, 2 }, Is.Ordered.Using(comparer)); } #endregion #region Exception Tests [Test] public void ExceptionThrownForRepeatedAscending() { Assert.That(() => Is.Ordered.Ascending.Ascending, Throws.TypeOf<InvalidOperationException>()); } [Test] public void ExceptionThrownForRepeatedDescending() { Assert.That(() => Is.Ordered.Descending.Descending, Throws.TypeOf<InvalidOperationException>()); } [Test] public void ExceptionThrownForAscendingPlusDescending() { Assert.That(() => Is.Ordered.Ascending.Descending, Throws.TypeOf<InvalidOperationException>()); } [Test] public void ExceptionThrownForAscendingByDescending() { Assert.That(() => Is.Ordered.Ascending.By("A").Descending, Throws.TypeOf<InvalidOperationException>()); } [Test] public void IsOrderedByProperty_ThrowsOnNull() { var ex = Assert.Throws<ArgumentNullException>(() => Assert.That(new[] { new TestClass4("x"), null, new TestClass4("z") }, Is.Ordered.By("Value"))); Assert.That(ex.Message, Does.Contain("index 1")); } [Test] public void IsOrdered_TypesMustBeComparable() { Assert.Throws<ArgumentException>(() => Assert.That(new object[] { 1, "x" }, Is.Ordered)); } [Test] public void IsOrdered_AtLeastOneArgMustImplementIComparable() { Assert.Throws<ArgumentException>(() => Assert.That(new [] { new object(), new object() }, Is.Ordered)); } [TestCaseSource(nameof(InvalidOrderedByData))] public void IsOrdered_ThrowsOnMissingProperty(object[] collection, string property, string expectedIndex) { Assert.That(() => Assert.That(collection, Is.Ordered.By(property)), Throws.ArgumentException.With.Message.Contain(expectedIndex)); } static readonly object[] InvalidOrderedByData = new[] { new TestCaseData( new object [] { "a", "b" }, "A", "index 0"), new TestCaseData( new object [] { new TestClass3("a", 1), "b" }, "A", "index 1"), new TestCaseData( new object [] { new TestClass3("a", 1), new TestClass3("b", 1), new TestClass4("c") }, "A", "index 2"), }; #endregion #region Test Classes public class TestClass1 { public int Value { get; } public TestClass1(int value) { Value = value; } public override string ToString() { return Value.ToString(); } } class TestClass2 { public int Value { get; } public TestClass2(int value) { Value = value; } public override string ToString() { return Value.ToString(); } } public class TestClass3 { public string A { get; } public int B { get; } public TestClass3(string a, int b) { A = a; B = b; } public override string ToString() { return A.ToString() + "," + B.ToString(); } } public class TestClass4 { public readonly string A; public TestClass4(string a) { A = a; } public override string ToString() { return A; } } #endregion } }
//----------------------------------------------------------------------- // <copyright file="TcpHelper.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Net; using Akka.Actor; using Akka.IO; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.TestKit; using Reactive.Streams; using Xunit.Abstractions; namespace Akka.Streams.Tests.IO { public abstract class TcpHelper : AkkaSpec { protected TcpHelper(string config, ITestOutputHelper helper) : base(config, helper) { Settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(4, 4); Materializer = Sys.Materializer(Settings); } protected ActorMaterializerSettings Settings { get; } protected ActorMaterializer Materializer { get; } protected sealed class ClientWrite { public ClientWrite(ByteString bytes) { Bytes = bytes; } public ByteString Bytes { get; } } protected sealed class ClientRead { public ClientRead(int count, IActorRef readTo) { Count = count; ReadTo = readTo; } public int Count { get; } public IActorRef ReadTo { get; } } protected sealed class ClientClose { public ClientClose(Tcp.CloseCommand cmd) { Cmd = cmd; } public Tcp.CloseCommand Cmd { get; } } protected sealed class ReadResult { public ReadResult(ByteString bytes) { Bytes = bytes; } public ByteString Bytes { get; } } // FIXME: Workaround object just to force a ResumeReading that will poll for a possibly pending close event // See https://github.com/akka/akka/issues/16552 // remove this and corresponding code path once above is fixed protected sealed class PingClose { public PingClose(IActorRef requester) { Requester = requester; } public IActorRef Requester { get; } } protected sealed class WriteAck : Tcp.Event { public static WriteAck Instance { get; } = new WriteAck(); private WriteAck() { } } protected static Props TestClientProps(IActorRef connection) => Props.Create(() => new TestClient(connection)).WithDispatcher("akka.test.stream-dispatcher"); protected static Props TestServerProps(EndPoint address, IActorRef probe) => Props.Create(() => new TestServer(address, probe)).WithDispatcher("akka.test.stream-dispatcher"); protected class TestClient : UntypedActor { private readonly IActorRef _connection; private readonly Queue<ByteString> _queuedWrites = new Queue<ByteString>(); private bool _writePending; private int _toRead; private ByteString _readBuffer = ByteString.Empty; private IActorRef _readTo = Context.System.DeadLetters; private Tcp.CloseCommand _closeAfterWrite; public TestClient(IActorRef connection) { _connection = connection; connection.Tell(new Tcp.Register(Self, keepOpenonPeerClosed: true, useResumeWriting: false)); } protected override void OnReceive(object message) { message.Match().With<ClientWrite>(w => { if (!_writePending) { _writePending = true; _connection.Tell(Tcp.Write.Create(w.Bytes, WriteAck.Instance)); } else _queuedWrites.Enqueue(w.Bytes); }).With<WriteAck>(() => { if (_queuedWrites.Count != 0) { var next = _queuedWrites.Dequeue(); _connection.Tell(Tcp.Write.Create(next, WriteAck.Instance)); } else { _writePending = false; if(_closeAfterWrite != null) _connection.Tell(_closeAfterWrite); } }).With<ClientRead>(r => { _readTo = r.ReadTo; _toRead = r.Count; _connection.Tell(Tcp.ResumeReading.Instance); }).With<Tcp.Received>(r => { _readBuffer += r.Data; if (_readBuffer.Count >= _toRead) { _readTo.Tell(new ReadResult(_readBuffer)); _readBuffer = ByteString.Empty; _toRead = 0; _readTo = Context.System.DeadLetters; } else _connection.Tell(Tcp.ResumeReading.Instance); }).With<PingClose>(p => { _readTo = p.Requester; _connection.Tell(Tcp.ResumeReading.Instance); }).With<Tcp.ConnectionClosed>(c => { _readTo.Tell(c); if(!c.IsPeerClosed) Context.Stop(Self); }).With<ClientClose>(c => { if (!_writePending) _connection.Tell(c.Cmd); else _closeAfterWrite = c.Cmd; }); } } protected sealed class ServerClose { public static ServerClose Instance { get; } = new ServerClose(); private ServerClose() { } } protected class TestServer : UntypedActor { private readonly IActorRef _probe; private IActorRef _listener = Nobody.Instance; public TestServer(EndPoint address, IActorRef probe) { _probe = probe; Context.System.Tcp().Tell(new Tcp.Bind(Self, address, pullMode: true)); } protected override void OnReceive(object message) { message.Match().With<Tcp.Bound>(b => { _listener = Sender; _listener.Tell(new Tcp.ResumeAccepting(1)); _probe.Tell(b); }).With<Tcp.Connected>(() => { var handler = Context.ActorOf(TestClientProps(Sender)); _listener.Tell(new Tcp.ResumeAccepting(1)); _probe.Tell(handler); }).With<ServerClose>(() => { _listener.Tell(Tcp.Unbind.Instance); Context.Stop(Self); }); } } protected class Server { private readonly TestKitBase _testkit; public Server(TestKitBase testkit, EndPoint address = null) { _testkit = testkit; Address = address ?? TestUtils.TemporaryServerAddress(); ServerProbe = testkit.CreateTestProbe(); ServerRef = testkit.ActorOf(TestServerProps(Address, ServerProbe.Ref)); ServerProbe.ExpectMsg<Tcp.Bound>(); } public EndPoint Address { get; } public TestProbe ServerProbe { get; } public IActorRef ServerRef { get; } public ServerConnection WaitAccept() => new ServerConnection(_testkit, ServerProbe.ExpectMsg<IActorRef>()); public void Close() => ServerRef.Tell(ServerClose.Instance); } protected class ServerConnection { private readonly IActorRef _connectionActor; private readonly TestProbe _connectionProbe; public ServerConnection(TestKitBase testkit, IActorRef connectionActor) { _connectionActor = connectionActor; _connectionProbe = testkit.CreateTestProbe(); } public void Write(ByteString bytes) => _connectionActor.Tell(new ClientWrite(bytes)); public void Read(int count) => _connectionActor.Tell(new ClientRead(count, _connectionProbe.Ref)); public ByteString WaitRead() => _connectionProbe.ExpectMsg<ReadResult>().Bytes; public void ConfirmedClose() => _connectionActor.Tell(new ClientClose(Tcp.ConfirmedClose.Instance)); public void Close() => _connectionActor.Tell(new ClientClose(Tcp.Close.Instance)); public void Abort() => _connectionActor.Tell(new ClientClose(Tcp.Abort.Instance)); public void ExpectClosed(Tcp.ConnectionClosed expected) => ExpectClosed(close => close == expected); public void ExpectClosed(Predicate<Tcp.ConnectionClosed> isMessage, TimeSpan? max = null) { max = max ?? TimeSpan.FromSeconds(3); _connectionActor.Tell(new PingClose(_connectionProbe.Ref)); _connectionProbe.FishForMessage(isMessage, max); } public void ExpectTerminated() { _connectionProbe.Watch(_connectionActor); _connectionProbe.ExpectTerminated(_connectionActor); } } protected class TcpReadProbe { public TcpReadProbe(TestKitBase testkit) { SubscriberProbe = testkit.CreateManualProbe<ByteString>(); TcpReadSubscription = new Lazy<ISubscription>(() => SubscriberProbe.ExpectSubscription()); } public Lazy<ISubscription> TcpReadSubscription { get; } public TestSubscriber.ManualProbe<ByteString> SubscriberProbe { get; } public ByteString Read(int count) { var result = ByteString.Empty; while (result.Count < count) { TcpReadSubscription.Value.Request(1); result += SubscriberProbe.ExpectNext(); } return result; } public void Close() => TcpReadSubscription.Value.Cancel(); } protected class TcpWriteProbe { private long _demand; public TcpWriteProbe(TestKitBase testkit) { PublisherProbe = TestPublisher.CreateManualProbe<ByteString>(testkit); TcpWriteSubscription = new Lazy<StreamTestKit.PublisherProbeSubscription<ByteString>>( () => PublisherProbe.ExpectSubscription()); } public Lazy<StreamTestKit.PublisherProbeSubscription<ByteString>> TcpWriteSubscription { get; } public TestPublisher.ManualProbe<ByteString> PublisherProbe { get; } public void Write(ByteString bytes) { if (_demand == 0) _demand += TcpWriteSubscription.Value.ExpectRequest(); TcpWriteSubscription.Value.SendNext(bytes); _demand -= 1; } public void Close() => TcpWriteSubscription.Value.SendComplete(); } } }
// // Copyright (C) Microsoft. All rights reserved. // using Microsoft.PowerShell.Activities; using System.Management.Automation; using System.Activities; using System.Collections.Generic; using System.ComponentModel; namespace Microsoft.PowerShell.Core.Activities { /// <summary> /// Activity to invoke the Microsoft.PowerShell.Core\Get-Job command in a Workflow. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Microsoft.PowerShell.Activities.ActivityGenerator.GenerateFromName", "3.0")] public sealed class GetJob : PSRemotingActivity { /// <summary> /// Gets the display name of the command invoked by this activity. /// </summary> public GetJob() { this.DisplayName = "Get-Job"; } /// <summary> /// Gets the fully qualified name of the command invoked by this activity. /// </summary> public override string PSCommandName { get { return "Microsoft.PowerShell.Core\\Get-Job"; } } // Arguments /// <summary> /// Provides access to the IncludeChildJob parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.SwitchParameter> IncludeChildJob { get; set; } /// <summary> /// Provides access to the ChildJobState parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.JobState> ChildJobState { get; set; } /// <summary> /// Provides access to the HasMoreData parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Boolean> HasMoreData { get; set; } /// <summary> /// Provides access to the Before parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.DateTime> Before { get; set; } /// <summary> /// Provides access to the After parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.DateTime> After { get; set; } /// <summary> /// Provides access to the Newest parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32> Newest { get; set; } /// <summary> /// Provides access to the JobId parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Int32[]> JobId { get; set; } /// <summary> /// Provides access to the Name parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Name { get; set; } /// <summary> /// Provides access to the InstanceId parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Guid[]> InstanceId { get; set; } /// <summary> /// Provides access to the State parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Management.Automation.JobState> State { get; set; } /// <summary> /// Provides access to the Command parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.String[]> Command { get; set; } /// <summary> /// Provides access to the Filter parameter. /// </summary> [ParameterSpecificCategory] [DefaultValue(null)] public InArgument<System.Collections.Hashtable> Filter { get; set; } // Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of System.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if(IncludeChildJob.Expression != null) { targetCommand.AddParameter("IncludeChildJob", IncludeChildJob.Get(context)); } if(ChildJobState.Expression != null) { targetCommand.AddParameter("ChildJobState", ChildJobState.Get(context)); } if(HasMoreData.Expression != null) { targetCommand.AddParameter("HasMoreData", HasMoreData.Get(context)); } if(Before.Expression != null) { targetCommand.AddParameter("Before", Before.Get(context)); } if(After.Expression != null) { targetCommand.AddParameter("After", After.Get(context)); } if(Newest.Expression != null) { targetCommand.AddParameter("Newest", Newest.Get(context)); } if(JobId.Expression != null) { targetCommand.AddParameter("Id", JobId.Get(context)); } if(Name.Expression != null) { targetCommand.AddParameter("Name", Name.Get(context)); } if(InstanceId.Expression != null) { targetCommand.AddParameter("InstanceId", InstanceId.Get(context)); } if(State.Expression != null) { targetCommand.AddParameter("State", State.Get(context)); } if(Command.Expression != null) { targetCommand.AddParameter("Command", Command.Get(context)); } if(Filter.Expression != null) { targetCommand.AddParameter("Filter", Filter.Get(context)); } return new ActivityImplementationContext() { PowerShellInstance = invoker }; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Searchservice { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Indexes. /// </summary> public static partial class IndexesExtensions { /// <summary> /// Creates a new Azure Search index. /// <see href="https://msdn.microsoft.com/library/azure/dn798941.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='index'> /// The definition of the index to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index Create(this IIndexes operations, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateAsync(index, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search index. /// <see href="https://msdn.microsoft.com/library/azure/dn798941.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='index'> /// The definition of the index to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> CreateAsync(this IIndexes operations, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(index, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all indexes available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn798923.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='select'> /// Selects which properties of the index definitions to retrieve. Specified as /// a comma-separated list of JSON property names, or '*' for all properties. /// The default is all properties. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexListResult List(this IIndexes operations, string select = default(string), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.ListAsync(select, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Lists all indexes available for an Azure Search service. /// <see href="https://msdn.microsoft.com/library/azure/dn798923.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='select'> /// Selects which properties of the index definitions to retrieve. Specified as /// a comma-separated list of JSON property names, or '*' for all properties. /// The default is all properties. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexListResult> ListAsync(this IIndexes operations, string select = default(string), SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(select, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates a new Azure Search index or updates an index if it already exists. /// <see href="https://msdn.microsoft.com/library/azure/dn800964.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The definition of the index to create or update. /// </param> /// <param name='index'> /// The definition of the index to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index CreateOrUpdate(this IIndexes operations, string indexName, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.CreateOrUpdateAsync(indexName, index, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Creates a new Azure Search index or updates an index if it already exists. /// <see href="https://msdn.microsoft.com/library/azure/dn800964.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The definition of the index to create or update. /// </param> /// <param name='index'> /// The definition of the index to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> CreateOrUpdateAsync(this IIndexes operations, string indexName, Index index, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(indexName, index, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes an Azure Search index and all the documents it contains. /// <see href="https://msdn.microsoft.com/library/azure/dn798926.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static void Delete(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { operations.DeleteAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Deletes an Azure Search index and all the documents it contains. /// <see href="https://msdn.microsoft.com/library/azure/dn798926.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieves an index definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn798939.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static Index Get(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Retrieves an index definition from Azure Search. /// <see href="https://msdn.microsoft.com/library/azure/dn798939.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Index> GetAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Returns statistics for the given index, including a document count and /// storage usage. /// <see href="https://msdn.microsoft.com/library/azure/dn798942.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index for which to retrieve statistics. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> public static IndexGetStatisticsResult GetStatistics(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions)) { return operations.GetStatisticsAsync(indexName, searchRequestOptions).GetAwaiter().GetResult(); } /// <summary> /// Returns statistics for the given index, including a document count and /// storage usage. /// <see href="https://msdn.microsoft.com/library/azure/dn798942.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='indexName'> /// The name of the index for which to retrieve statistics. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IndexGetStatisticsResult> GetStatisticsAsync(this IIndexes operations, string indexName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStatisticsWithHttpMessagesAsync(indexName, searchRequestOptions, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; namespace RefactoringEssentials.CSharp.Diagnostics { [DiagnosticAnalyzer(LanguageNames.CSharp)] [NotPortedYet] public class PossibleMultipleEnumerationAnalyzer : DiagnosticAnalyzer { static readonly DiagnosticDescriptor descriptor = new DiagnosticDescriptor( CSharpDiagnosticIDs.PossibleMultipleEnumerationAnalyzerID, GettextCatalog.GetString("Possible multiple enumeration of IEnumerable"), GettextCatalog.GetString("Possible multiple enumeration of IEnumerable"), DiagnosticAnalyzerCategories.CodeQualityIssues, DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: HelpLink.CreateFor(CSharpDiagnosticIDs.PossibleMultipleEnumerationAnalyzerID) ); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(descriptor); public override void Initialize(AnalysisContext context) { context.EnableConcurrentExecution(); context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); //context.RegisterSyntaxNodeAction( // (nodeContext) => { // Diagnostic diagnostic; // if (TryGetDiagnostic (nodeContext, out diagnostic)) { // nodeContext.ReportDiagnostic(diagnostic); // } // }, // new SyntaxKind[] { SyntaxKind.None } //); } static bool TryGetDiagnostic(SyntaxNodeAnalysisContext nodeContext, out Diagnostic diagnostic) { diagnostic = default(Diagnostic); //var node = nodeContext.Node as ; //diagnostic = Diagnostic.Create (descriptor, node.GetLocation ()); //return true; return false; } // class AnalysisStatementCollector : DepthFirstAstVisitor // { // List<Statement> statements; // AstNode variableDecl; // // AnalysisStatementCollector (AstNode variableDecl) // { // this.variableDecl = variableDecl; // } // // IList<Statement> GetStatements () // { // if (statements != null) // return statements; // // statements = new List<Statement> (); // var parent = variableDecl.Parent; // while (parent != null) { // if (parent is BlockStatement || parent is MethodDeclaration || // parent is AnonymousMethodExpression || parent is LambdaExpression) { // parent.AcceptVisitor (this); // if (parent is BlockStatement) // statements.Add ((BlockStatement)parent); // break; // } // parent = parent.Parent; // } // return statements; // } // // public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) // { // statements.Add (methodDeclaration.Body); // // base.VisitMethodDeclaration (methodDeclaration); // } // // public override void VisitAnonymousMethodExpression (AnonymousMethodExpression anonymousMethodExpression) // { // statements.Add (anonymousMethodExpression.Body); // // base.VisitAnonymousMethodExpression (anonymousMethodExpression); // } // // public override void VisitLambdaExpression (LambdaExpression lambdaExpression) // { // var body = lambdaExpression.Body as BlockStatement; // if (body != null) // statements.Add (body); // // base.VisitLambdaExpression (lambdaExpression); // } // // public static IList<Statement> Collect (AstNode variableDecl) // { // return new AnalysisStatementCollector (variableDecl).GetStatements (); // } // } // class GatherVisitor : GatherVisitorBase<PossibleMultipleEnumerationAnalyzer> // { // //HashSet<AstNode> collectedAstNodes; // public GatherVisitor(SemanticModel semanticModel, Action<Diagnostic> addDiagnostic, CancellationToken cancellationToken) // : base (semanticModel, addDiagnostic, cancellationToken) // { // //this.collectedAstNodes = new HashSet<AstNode> (); // } //// void ResolveIssue(Script s, AstNode node, Func<TypeSystemAstBuilder, AstType> type, string methodCall) //// { //// var rr = ctx.Resolve(node) as LocalResolveResult; //// if (rr == null || rr.IsError) //// return; //// var refs = ctx.FindReferences(ctx.RootNode, rr.Variable); //// var nodes = refs.Select(r => r.Node).Where(IsEnumeration).OfType<Expression>().ToList(); //// if (nodes.Count == 0) //// return; //// var first = nodes.First().GetParent<Statement>(); //// var varName = ctx.GetNameProposal("enumerable", first.StartLocation); //// var astBuilder = ctx.CreateTypeSystemAstBuilder(first); //// //// var links = new List<AstNode>(); //// var varDec = new VariableDeclarationStatement(new PrimitiveType("var"), varName, new BinaryOperatorExpression(new AsExpression((Expression)node.Clone(), type (astBuilder)), BinaryOperatorType.NullCoalescing, new InvocationExpression(new MemberReferenceExpression((Expression)node.Clone(), methodCall)))); //// //// links.Add(varDec.Variables.First().NameToken); //// s.InsertBefore(first, varDec); //// foreach (var n in nodes) { //// var id = new IdentifierExpression(varName); //// links.Add(id); //// s.Replace(n, id); //// } //// s.Link(links); //// } //// //// void AddDiagnosticAnalyzer (AstNode node, IType elementType, IList<AstNode> nodes) //// { //// if (collectedAstNodes.Add(node)) { //// var actions = new List<CodeAction>(); //// actions.Add( //// new CodeAction( //// ctx.TranslateString("Enumerate to array"), //// s => ResolveIssue(s, node, ab => new ComposedType { BaseType = ab.ConvertType(elementType), ArraySpecifiers = { new ArraySpecifier() } }, "ToArray"), //// node //// ) //// ); //// //// actions.Add( //// new CodeAction( //// ctx.TranslateString("Enumerate to list"), //// s => { //// var listType = ctx.Compilation.FindType(typeof(IList<>)); //// ResolveIssue(s, node, ab => ab.ConvertType(new ParameterizedType(listType.GetDefinition(), new IType[]{ elementType })), "ToList"); //// }, //// node //// ) //// ); //// //// AddDiagnosticAnalyzer(new CodeIssue(node, ctx.TranslateString("Possible multiple enumeration of IEnumerable"), actions)); //// } //// } //// //// void AddDiagnosticAnalyzers (IList<AstNode> nodes) //// { //// if (nodes.Count == 0) //// return; //// var rr = ctx.Resolve(nodes[0]); //// var elementType = TypeGuessing.GetElementType(ctx.Resolver, rr.Type); //// //// foreach (var node in nodes) //// AddDiagnosticAnalyzer (node, elementType, nodes); //// } //// //// public override void VisitParameterDeclaration (ParameterDeclaration parameterDeclaration) //// { //// base.VisitParameterDeclaration (parameterDeclaration); //// //// var resolveResult = ctx.Resolve (parameterDeclaration) as LocalResolveResult; //// CollectIssues (parameterDeclaration, parameterDeclaration.Parent, resolveResult); //// } //// //// public override void VisitVariableInitializer (VariableInitializer variableInitializer) //// { //// base.VisitVariableInitializer (variableInitializer); //// //// var resolveResult = ctx.Resolve (variableInitializer) as LocalResolveResult; //// CollectIssues (variableInitializer, variableInitializer.Parent.Parent, resolveResult); //// } //// //// static bool IsAssignment (AstNode node) //// { //// var assignment = node.Parent as AssignmentExpression; //// if (assignment != null) //// return assignment.Left == node; //// //// var direction = node.Parent as DirectionExpression; //// if (direction != null) //// return direction.FieldDirection == FieldDirection.Out && direction.Expression == node; //// //// return false; //// } //// //// bool IsEnumeration (AstNode node) //// { //// var foreachStatement = node.Parent as ForeachStatement; //// if (foreachStatement != null && foreachStatement.InExpression == node) { //// return true; //// } //// //// var memberRef = node.Parent as MemberReferenceExpression; //// if (memberRef != null && memberRef.Target == node) { //// var invocation = memberRef.Parent as InvocationExpression; //// if (invocation == null || invocation.Target != memberRef) //// return false; //// //// var methodGroup = ctx.Resolve (memberRef) as MethodGroupResolveResult; //// if (methodGroup == null) //// return false; //// //// var method = methodGroup.Methods.FirstOrDefault (); //// if (method != null) { //// var declaringTypeDef = method.DeclaringTypeDefinition; //// if (declaringTypeDef != null && declaringTypeDef.KnownTypeCode == KnownTypeCode.Object) //// return false; //// } //// return true; //// } //// //// return false; //// } //// //// HashSet<AstNode> references; //// HashSet<Statement> refStatements; //// HashSet<LambdaExpression> lambdaExpressions; //// //// HashSet<VariableReferenceNode> visitedNodes; //// HashSet<VariableReferenceNode> collectedNodes; //// Dictionary<VariableReferenceNode, int> nodeDegree; // number of enumerations a node can reach //// //// void FindReferences (AstNode variableDecl, AstNode rootNode, IVariable variable) //// { //// references = new HashSet<AstNode> (); //// refStatements = new HashSet<Statement> (); //// lambdaExpressions = new HashSet<LambdaExpression> (); //// //// foreach (var result in ctx.FindReferences (rootNode, variable)) { //// var astNode = result.Node; //// if (astNode == variableDecl) //// continue; //// //// var parent = astNode.Parent; //// while (!(parent == null || parent is Statement || parent is LambdaExpression)) //// parent = parent.Parent; //// if (parent == null) //// continue; //// //// // lambda expression with expression body, should be analyzed separately //// var expr = parent as LambdaExpression; //// if (expr != null) { //// if (IsAssignment (astNode) || IsEnumeration (astNode)) { //// references.Add (astNode); //// lambdaExpressions.Add (expr); //// } //// continue; //// } //// //// if (IsAssignment (astNode) || IsEnumeration (astNode)) { //// references.Add (astNode); //// var statement = (Statement)parent; //// refStatements.Add (statement); //// } //// } //// } //// //// void CollectIssues (AstNode variableDecl, AstNode rootNode, LocalResolveResult resolveResult) //// { //// if (resolveResult == null) //// return; //// var type = resolveResult.Type; //// var typeDef = type.GetDefinition (); //// if (typeDef == null || //// (typeDef.KnownTypeCode != KnownTypeCode.IEnumerable && //// typeDef.KnownTypeCode != KnownTypeCode.IEnumerableOfT)) //// return; //// //// FindReferences (variableDecl, rootNode, resolveResult.Variable); //// //// var statements = AnalysisStatementCollector.Collect (variableDecl); //// var builder = new VariableReferenceGraphBuilder (ctx); //// foreach (var statement in statements) { //// var vrNode = builder.Build (statement, references, refStatements, ctx); //// FindMultipleEnumeration (vrNode); //// } //// foreach (var lambda in lambdaExpressions) { //// var vrNode = builder.Build (references, ctx.Resolver, (Expression)lambda.Body); //// FindMultipleEnumeration (vrNode); //// } //// } //// //// /// <summary> //// /// split references in the specified node into sub nodes according to the value they uses //// /// </summary> //// /// <param name="node">node to split</param> //// /// <returns>list of sub nodes</returns> //// static IList<VariableReferenceNode> SplitNode (VariableReferenceNode node) //// { //// var subNodes = new List<VariableReferenceNode> (); //// // find indices of all assignments in node and use them to split references //// var assignmentIndices = new List<int> { -1 }; //// for (int i = 0; i < node.References.Count; i++) { //// if (IsAssignment (node.References [i])) //// assignmentIndices.Add (i); //// } //// assignmentIndices.Add (node.References.Count); //// for (int i = 0; i < assignmentIndices.Count - 1; i++) { //// var index1 = assignmentIndices [i]; //// var index2 = assignmentIndices [i + 1]; //// if (index1 + 1 >= index2) //// continue; //// var subNode = new VariableReferenceNode (); //// for (int refIndex = index1 + 1; refIndex < index2; refIndex++) //// subNode.References.Add (node.References [refIndex]); //// subNodes.Add (subNode); //// } //// if (subNodes.Count == 0) //// subNodes.Add (new VariableReferenceNode ()); //// //// var firstNode = subNodes [0]; //// foreach (var prevNode in node.PreviousNodes) { //// prevNode.NextNodes.Remove (node); //// // connect two nodes if the first ref is not an assignment //// if (firstNode.References.FirstOrDefault () == node.References.FirstOrDefault ()) //// prevNode.NextNodes.Add (firstNode); //// } //// //// var lastNode = subNodes [subNodes.Count - 1]; //// foreach (var nextNode in node.NextNodes) { //// nextNode.PreviousNodes.Remove (node); //// lastNode.AddNextNode (nextNode); //// } //// //// return subNodes; //// } //// //// /// <summary> //// /// convert a variable reference graph starting from the specified node to an assignment usage graph, //// /// in which nodes are connect if and only if they contains references using the same assigned value //// /// </summary> //// /// <param name="startNode">starting node of the variable reference graph</param> //// /// <returns> //// /// list of VariableReferenceNode, each of which is a starting node of a sub-graph in which references all //// /// use the same assigned value //// /// </returns> //// static IEnumerable<VariableReferenceNode> GetAssignmentUsageGraph (VariableReferenceNode startNode) //// { //// var graph = new List<VariableReferenceNode> (); //// var visited = new HashSet<VariableReferenceNode> (); //// var stack = new Stack<VariableReferenceNode> (); //// stack.Push (startNode); //// while (stack.Count > 0) { //// var node = stack.Pop (); //// if (!visited.Add (node)) //// continue; //// //// var nodes = SplitNode (node); //// graph.AddRange (nodes); //// foreach (var addedNode in nodes) //// visited.Add (addedNode); //// //// foreach (var nextNode in nodes.Last ().NextNodes) //// stack.Push (nextNode); //// } //// return graph; //// } //// //// void FindMultipleEnumeration (VariableReferenceNode startNode) //// { //// var vrg = GetAssignmentUsageGraph (startNode); //// visitedNodes = new HashSet<VariableReferenceNode> (); //// collectedNodes = new HashSet<VariableReferenceNode> (); //// //// // degree of a node is the number of references that can be reached by the node //// nodeDegree = new Dictionary<VariableReferenceNode, int> (); //// //// foreach (var node in vrg) { //// if (node.References.Count == 0 || !visitedNodes.Add (node)) //// continue; //// ProcessNode (node); //// if (nodeDegree [node] > 1) //// collectedNodes.Add (node); //// } //// foreach (var node in collectedNodes) //// AddDiagnosticAnalyzers (node.References); //// } //// //// void ProcessNode (VariableReferenceNode node) //// { //// var degree = nodeDegree [node] = 0; //// foreach (var nextNode in node.NextNodes) { //// collectedNodes.Add (nextNode); //// if (visitedNodes.Add (nextNode)) //// ProcessNode (nextNode); //// degree = Math.Max (degree, nodeDegree [nextNode]); //// } //// nodeDegree [node] = degree + node.References.Count; //// } // } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.10.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * DoubleClick Bid Manager API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/bid-manager/'>DoubleClick Bid Manager API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20160225 (420) * <tr><th>API Docs * <td><a href='https://developers.google.com/bid-manager/'> * https://developers.google.com/bid-manager/</a> * <tr><th>Discovery Name<td>doubleclickbidmanager * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using DoubleClick Bid Manager API can be found at * <a href='https://developers.google.com/bid-manager/'>https://developers.google.com/bid-manager/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.DoubleClickBidManager.v1 { /// <summary>The DoubleClickBidManager Service.</summary> public class DoubleClickBidManagerService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public DoubleClickBidManagerService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public DoubleClickBidManagerService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { lineitems = new LineitemsResource(this); queries = new QueriesResource(this); reports = new ReportsResource(this); rubicon = new RubiconResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "doubleclickbidmanager"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/doubleclickbidmanager/v1/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "doubleclickbidmanager/v1/"; } } private readonly LineitemsResource lineitems; /// <summary>Gets the Lineitems resource.</summary> public virtual LineitemsResource Lineitems { get { return lineitems; } } private readonly QueriesResource queries; /// <summary>Gets the Queries resource.</summary> public virtual QueriesResource Queries { get { return queries; } } private readonly ReportsResource reports; /// <summary>Gets the Reports resource.</summary> public virtual ReportsResource Reports { get { return reports; } } private readonly RubiconResource rubicon; /// <summary>Gets the Rubicon resource.</summary> public virtual RubiconResource Rubicon { get { return rubicon; } } } ///<summary>A base abstract class for DoubleClickBidManager requests.</summary> public abstract class DoubleClickBidManagerBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new DoubleClickBidManagerBaseServiceRequest instance.</summary> protected DoubleClickBidManagerBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes DoubleClickBidManager parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "lineitems" collection of methods.</summary> public class LineitemsResource { private const string Resource = "lineitems"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public LineitemsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Retrieves line items in CSV format.</summary> /// <param name="body">The body of the request.</param> public virtual DownloadlineitemsRequest Downloadlineitems(Google.Apis.DoubleClickBidManager.v1.Data.DownloadLineItemsRequest body) { return new DownloadlineitemsRequest(service, body); } /// <summary>Retrieves line items in CSV format.</summary> public class DownloadlineitemsRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.DownloadLineItemsResponse> { /// <summary>Constructs a new Downloadlineitems request.</summary> public DownloadlineitemsRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.DownloadLineItemsRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.DoubleClickBidManager.v1.Data.DownloadLineItemsRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "downloadlineitems"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "lineitems/downloadlineitems"; } } /// <summary>Initializes Downloadlineitems parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Uploads line items in CSV format.</summary> /// <param name="body">The body of the request.</param> public virtual UploadlineitemsRequest Uploadlineitems(Google.Apis.DoubleClickBidManager.v1.Data.UploadLineItemsRequest body) { return new UploadlineitemsRequest(service, body); } /// <summary>Uploads line items in CSV format.</summary> public class UploadlineitemsRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.UploadLineItemsResponse> { /// <summary>Constructs a new Uploadlineitems request.</summary> public UploadlineitemsRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.UploadLineItemsRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.DoubleClickBidManager.v1.Data.UploadLineItemsRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "uploadlineitems"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "lineitems/uploadlineitems"; } } /// <summary>Initializes Uploadlineitems parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } /// <summary>The "queries" collection of methods.</summary> public class QueriesResource { private const string Resource = "queries"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public QueriesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Creates a query.</summary> /// <param name="body">The body of the request.</param> public virtual CreatequeryRequest Createquery(Google.Apis.DoubleClickBidManager.v1.Data.Query body) { return new CreatequeryRequest(service, body); } /// <summary>Creates a query.</summary> public class CreatequeryRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.Query> { /// <summary>Constructs a new Createquery request.</summary> public CreatequeryRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.Query body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.DoubleClickBidManager.v1.Data.Query Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "createquery"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "query"; } } /// <summary>Initializes Createquery parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Deletes a stored query as well as the associated stored reports.</summary> /// <param name="queryId">Query ID to delete.</param> public virtual DeletequeryRequest Deletequery(long queryId) { return new DeletequeryRequest(service, queryId); } /// <summary>Deletes a stored query as well as the associated stored reports.</summary> public class DeletequeryRequest : DoubleClickBidManagerBaseServiceRequest<string> { /// <summary>Constructs a new Deletequery request.</summary> public DeletequeryRequest(Google.Apis.Services.IClientService service, long queryId) : base(service) { QueryId = queryId; InitParameters(); } /// <summary>Query ID to delete.</summary> [Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)] public virtual long QueryId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "deletequery"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "query/{queryId}"; } } /// <summary>Initializes Deletequery parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "queryId", new Google.Apis.Discovery.Parameter { Name = "queryId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Retrieves a stored query.</summary> /// <param name="queryId">Query ID to retrieve.</param> public virtual GetqueryRequest Getquery(long queryId) { return new GetqueryRequest(service, queryId); } /// <summary>Retrieves a stored query.</summary> public class GetqueryRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.Query> { /// <summary>Constructs a new Getquery request.</summary> public GetqueryRequest(Google.Apis.Services.IClientService service, long queryId) : base(service) { QueryId = queryId; InitParameters(); } /// <summary>Query ID to retrieve.</summary> [Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)] public virtual long QueryId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "getquery"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "query/{queryId}"; } } /// <summary>Initializes Getquery parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "queryId", new Google.Apis.Discovery.Parameter { Name = "queryId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Retrieves stored queries.</summary> public virtual ListqueriesRequest Listqueries() { return new ListqueriesRequest(service); } /// <summary>Retrieves stored queries.</summary> public class ListqueriesRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.ListQueriesResponse> { /// <summary>Constructs a new Listqueries request.</summary> public ListqueriesRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "listqueries"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "queries"; } } /// <summary>Initializes Listqueries parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Runs a stored query to generate a report.</summary> /// <param name="body">The body of the request.</param> /// <param name="queryId">Query ID to run.</param> public virtual RunqueryRequest Runquery(Google.Apis.DoubleClickBidManager.v1.Data.RunQueryRequest body, long queryId) { return new RunqueryRequest(service, body, queryId); } /// <summary>Runs a stored query to generate a report.</summary> public class RunqueryRequest : DoubleClickBidManagerBaseServiceRequest<string> { /// <summary>Constructs a new Runquery request.</summary> public RunqueryRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.RunQueryRequest body, long queryId) : base(service) { QueryId = queryId; Body = body; InitParameters(); } /// <summary>Query ID to run.</summary> [Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)] public virtual long QueryId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.DoubleClickBidManager.v1.Data.RunQueryRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "runquery"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "query/{queryId}"; } } /// <summary>Initializes Runquery parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "queryId", new Google.Apis.Discovery.Parameter { Name = "queryId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "reports" collection of methods.</summary> public class ReportsResource { private const string Resource = "reports"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public ReportsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Retrieves stored reports.</summary> /// <param name="queryId">Query ID with which the reports are associated.</param> public virtual ListreportsRequest Listreports(long queryId) { return new ListreportsRequest(service, queryId); } /// <summary>Retrieves stored reports.</summary> public class ListreportsRequest : DoubleClickBidManagerBaseServiceRequest<Google.Apis.DoubleClickBidManager.v1.Data.ListReportsResponse> { /// <summary>Constructs a new Listreports request.</summary> public ListreportsRequest(Google.Apis.Services.IClientService service, long queryId) : base(service) { QueryId = queryId; InitParameters(); } /// <summary>Query ID with which the reports are associated.</summary> [Google.Apis.Util.RequestParameterAttribute("queryId", Google.Apis.Util.RequestParameterType.Path)] public virtual long QueryId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "listreports"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "queries/{queryId}/reports"; } } /// <summary>Initializes Listreports parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "queryId", new Google.Apis.Discovery.Parameter { Name = "queryId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "rubicon" collection of methods.</summary> public class RubiconResource { private const string Resource = "rubicon"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public RubiconResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Update proposal upon actions of Rubicon publisher.</summary> /// <param name="body">The body of the request.</param> public virtual NotifyproposalchangeRequest Notifyproposalchange(Google.Apis.DoubleClickBidManager.v1.Data.NotifyProposalChangeRequest body) { return new NotifyproposalchangeRequest(service, body); } /// <summary>Update proposal upon actions of Rubicon publisher.</summary> public class NotifyproposalchangeRequest : DoubleClickBidManagerBaseServiceRequest<string> { /// <summary>Constructs a new Notifyproposalchange request.</summary> public NotifyproposalchangeRequest(Google.Apis.Services.IClientService service, Google.Apis.DoubleClickBidManager.v1.Data.NotifyProposalChangeRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.DoubleClickBidManager.v1.Data.NotifyProposalChangeRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "notifyproposalchange"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "rubicon/notifyproposalchange"; } } /// <summary>Initializes Notifyproposalchange parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.DoubleClickBidManager.v1.Data { /// <summary>Request to fetch stored line items.</summary> public class DownloadLineItemsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>File specification (column names, types, order) in which the line items will be returned. Default /// to EWF.</summary> [Newtonsoft.Json.JsonPropertyAttribute("fileSpec")] public virtual string FileSpec { get; set; } /// <summary>Ids of the specified filter type used to filter line items to fetch. If omitted, all the line items /// will be returned.</summary> [Newtonsoft.Json.JsonPropertyAttribute("filterIds")] public virtual System.Collections.Generic.IList<System.Nullable<long>> FilterIds { get; set; } /// <summary>Filter type used to filter line items to fetch.</summary> [Newtonsoft.Json.JsonPropertyAttribute("filterType")] public virtual string FilterType { get; set; } /// <summary>Format in which the line items will be returned. Default to CSV.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Download line items response.</summary> public class DownloadLineItemsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Retrieved line items in CSV format. Refer to Entity Write File Format or Structured Data File /// Format for more information on file formats.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lineItems")] public virtual string LineItems { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Filter used to match traffic data in your report.</summary> public class FilterPair : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Filter type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>Filter value.</summary> [Newtonsoft.Json.JsonPropertyAttribute("value")] public virtual string Value { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>List queries response.</summary> public class ListQueriesResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Identifies what kind of resource this is. Value: the fixed string /// "doubleclickbidmanager#listQueriesResponse".</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Retrieved queries.</summary> [Newtonsoft.Json.JsonPropertyAttribute("queries")] public virtual System.Collections.Generic.IList<Query> Queries { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>List reports response.</summary> public class ListReportsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Identifies what kind of resource this is. Value: the fixed string /// "doubleclickbidmanager#listReportsResponse".</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Retrieved reports.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reports")] public virtual System.Collections.Generic.IList<Report> Reports { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Publisher comment from Rubicon.</summary> public class Note : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Note id.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual System.Nullable<long> Id { get; set; } /// <summary>Message from publisher.</summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>Equals "publisher" for notification from Rubicon.</summary> [Newtonsoft.Json.JsonPropertyAttribute("source")] public virtual string Source { get; set; } /// <summary>Time when the note was added, e.g. "2015-12-16T17:25:35.000-08:00".</summary> [Newtonsoft.Json.JsonPropertyAttribute("timestamp")] public virtual string Timestamp { get; set; } /// <summary>Publisher user name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("username")] public virtual string Username { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>NotifyProposalChange request.</summary> public class NotifyProposalChangeRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Action taken by publisher. One of: Accept, Decline, Append</summary> [Newtonsoft.Json.JsonPropertyAttribute("action")] public virtual string Action { get; set; } /// <summary>URL to access proposal detail.</summary> [Newtonsoft.Json.JsonPropertyAttribute("href")] public virtual string Href { get; set; } /// <summary>Below are contents of notification from Rubicon. Proposal id.</summary> [Newtonsoft.Json.JsonPropertyAttribute("id")] public virtual System.Nullable<long> Id { get; set; } /// <summary>Notes from publisher</summary> [Newtonsoft.Json.JsonPropertyAttribute("notes")] public virtual System.Collections.Generic.IList<Note> Notes { get; set; } /// <summary>Deal token, available when proposal is accepted by publisher.</summary> [Newtonsoft.Json.JsonPropertyAttribute("token")] public virtual string Token { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Parameters of a query or report.</summary> public class Parameters : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Filters used to match traffic data in your report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("filters")] public virtual System.Collections.Generic.IList<FilterPair> Filters { get; set; } /// <summary>Data is grouped by the filters listed in this field.</summary> [Newtonsoft.Json.JsonPropertyAttribute("groupBys")] public virtual System.Collections.Generic.IList<string> GroupBys { get; set; } /// <summary>Whether to include data from Invite Media.</summary> [Newtonsoft.Json.JsonPropertyAttribute("includeInviteData")] public virtual System.Nullable<bool> IncludeInviteData { get; set; } /// <summary>Metrics to include as columns in your report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("metrics")] public virtual System.Collections.Generic.IList<string> Metrics { get; set; } /// <summary>Report type.</summary> [Newtonsoft.Json.JsonPropertyAttribute("type")] public virtual string Type { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents a query.</summary> public class Query : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Identifies what kind of resource this is. Value: the fixed string /// "doubleclickbidmanager#query".</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Query metadata.</summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual QueryMetadata Metadata { get; set; } /// <summary>Query parameters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("params")] public virtual Parameters Params__ { get; set; } /// <summary>Query ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("queryId")] public virtual System.Nullable<long> QueryId { get; set; } /// <summary>The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if /// metadata.dataRange is CUSTOM_DATES and ignored otherwise.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")] public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; } /// <summary>The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required /// if metadata.dataRange is CUSTOM_DATES and ignored otherwise.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")] public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; } /// <summary>Information on how often and when to run a query.</summary> [Newtonsoft.Json.JsonPropertyAttribute("schedule")] public virtual QuerySchedule Schedule { get; set; } /// <summary>Canonical timezone code for report data time. Defaults to America/New_York.</summary> [Newtonsoft.Json.JsonPropertyAttribute("timezoneCode")] public virtual string TimezoneCode { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Query metadata.</summary> public class QueryMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Range of report data.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dataRange")] public virtual string DataRange { get; set; } /// <summary>Format of the generated report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } /// <summary>The path to the location in Google Cloud Storage where the latest report is stored.</summary> [Newtonsoft.Json.JsonPropertyAttribute("googleCloudStoragePathForLatestReport")] public virtual string GoogleCloudStoragePathForLatestReport { get; set; } /// <summary>The path in Google Drive for the latest report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("googleDrivePathForLatestReport")] public virtual string GoogleDrivePathForLatestReport { get; set; } /// <summary>The time when the latest report started to run.</summary> [Newtonsoft.Json.JsonPropertyAttribute("latestReportRunTimeMs")] public virtual System.Nullable<long> LatestReportRunTimeMs { get; set; } /// <summary>Locale of the generated reports. Valid values are cs CZECH de GERMAN en ENGLISH es SPANISH fr /// FRENCH it ITALIAN ja JAPANESE ko KOREAN pl POLISH pt-BR BRAZILIAN_PORTUGUESE ru RUSSIAN tr TURKISH uk /// UKRAINIAN zh-CN CHINA_CHINESE zh-TW TAIWAN_CHINESE /// /// An locale string not in the list above will generate reports in English.</summary> [Newtonsoft.Json.JsonPropertyAttribute("locale")] public virtual string Locale { get; set; } /// <summary>Number of reports that have been generated for the query.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportCount")] public virtual System.Nullable<int> ReportCount { get; set; } /// <summary>Whether the latest report is currently running.</summary> [Newtonsoft.Json.JsonPropertyAttribute("running")] public virtual System.Nullable<bool> Running { get; set; } /// <summary>Whether to send an email notification when a report is ready. Default to false.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sendNotification")] public virtual System.Nullable<bool> SendNotification { get; set; } /// <summary>List of email addresses which are sent email notifications when the report is finished. Separate /// from sendNotification.</summary> [Newtonsoft.Json.JsonPropertyAttribute("shareEmailAddress")] public virtual System.Collections.Generic.IList<string> ShareEmailAddress { get; set; } /// <summary>Query title. It is used to name the reports generated from this query.</summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Information on how frequently and when to run a query.</summary> public class QuerySchedule : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Datetime to periodically run the query until.</summary> [Newtonsoft.Json.JsonPropertyAttribute("endTimeMs")] public virtual System.Nullable<long> EndTimeMs { get; set; } /// <summary>How often the query is run.</summary> [Newtonsoft.Json.JsonPropertyAttribute("frequency")] public virtual string Frequency { get; set; } /// <summary>Time of day at which a new report will be generated, represented as minutes past midnight. Range is /// 0 to 1439. Only applies to scheduled reports.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextRunMinuteOfDay")] public virtual System.Nullable<int> NextRunMinuteOfDay { get; set; } /// <summary>Canonical timezone code for report generation time. Defaults to America/New_York.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextRunTimezoneCode")] public virtual string NextRunTimezoneCode { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents a report.</summary> public class Report : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Key used to identify a report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("key")] public virtual ReportKey Key { get; set; } /// <summary>Report metadata.</summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual ReportMetadata Metadata { get; set; } /// <summary>Report parameters.</summary> [Newtonsoft.Json.JsonPropertyAttribute("params")] public virtual Parameters Params__ { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>An explanation of a report failure.</summary> public class ReportFailure : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Error code that shows why the report was not created.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errorCode")] public virtual string ErrorCode { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Key used to identify a report.</summary> public class ReportKey : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Query ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("queryId")] public virtual System.Nullable<long> QueryId { get; set; } /// <summary>Report ID.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportId")] public virtual System.Nullable<long> ReportId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Report metadata.</summary> public class ReportMetadata : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The path to the location in Google Cloud Storage where the report is stored.</summary> [Newtonsoft.Json.JsonPropertyAttribute("googleCloudStoragePath")] public virtual string GoogleCloudStoragePath { get; set; } /// <summary>The ending time for the data that is shown in the report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")] public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; } /// <summary>The starting time for the data that is shown in the report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")] public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; } /// <summary>Report status.</summary> [Newtonsoft.Json.JsonPropertyAttribute("status")] public virtual ReportStatus Status { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Report status.</summary> public class ReportStatus : Google.Apis.Requests.IDirectResponseSchema { /// <summary>If the report failed, this records the cause.</summary> [Newtonsoft.Json.JsonPropertyAttribute("failure")] public virtual ReportFailure Failure { get; set; } /// <summary>The time when this report either completed successfully or failed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("finishTimeMs")] public virtual System.Nullable<long> FinishTimeMs { get; set; } /// <summary>The file type of the report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } /// <summary>The state of the report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("state")] public virtual string State { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents the upload status of a row in the request.</summary> public class RowStatus : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Whether the stored entity is changed as a result of upload.</summary> [Newtonsoft.Json.JsonPropertyAttribute("changed")] public virtual System.Nullable<bool> Changed { get; set; } /// <summary>Entity Id.</summary> [Newtonsoft.Json.JsonPropertyAttribute("entityId")] public virtual System.Nullable<long> EntityId { get; set; } /// <summary>Entity name.</summary> [Newtonsoft.Json.JsonPropertyAttribute("entityName")] public virtual string EntityName { get; set; } /// <summary>Reasons why the entity can't be uploaded.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errors")] public virtual System.Collections.Generic.IList<string> Errors { get; set; } /// <summary>Whether the entity is persisted.</summary> [Newtonsoft.Json.JsonPropertyAttribute("persisted")] public virtual System.Nullable<bool> Persisted { get; set; } /// <summary>Row number.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rowNumber")] public virtual System.Nullable<int> RowNumber { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request to run a stored query to generate a report.</summary> public class RunQueryRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Report data range used to generate the report.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dataRange")] public virtual string DataRange { get; set; } /// <summary>The ending time for the data that is shown in the report. Note, reportDataEndTimeMs is required if /// dataRange is CUSTOM_DATES and ignored otherwise.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportDataEndTimeMs")] public virtual System.Nullable<long> ReportDataEndTimeMs { get; set; } /// <summary>The starting time for the data that is shown in the report. Note, reportDataStartTimeMs is required /// if dataRange is CUSTOM_DATES and ignored otherwise.</summary> [Newtonsoft.Json.JsonPropertyAttribute("reportDataStartTimeMs")] public virtual System.Nullable<long> ReportDataStartTimeMs { get; set; } /// <summary>Canonical timezone code for report data time. Defaults to America/New_York.</summary> [Newtonsoft.Json.JsonPropertyAttribute("timezoneCode")] public virtual string TimezoneCode { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request to upload line items.</summary> public class UploadLineItemsRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Set to true to get upload status without actually persisting the line items.</summary> [Newtonsoft.Json.JsonPropertyAttribute("dryRun")] public virtual System.Nullable<bool> DryRun { get; set; } /// <summary>Format the line items are in. Default to CSV.</summary> [Newtonsoft.Json.JsonPropertyAttribute("format")] public virtual string Format { get; set; } /// <summary>Line items in CSV to upload. Refer to Entity Write File Format for more information on file /// format.</summary> [Newtonsoft.Json.JsonPropertyAttribute("lineItems")] public virtual string LineItems { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Upload line items response.</summary> public class UploadLineItemsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Status of upload.</summary> [Newtonsoft.Json.JsonPropertyAttribute("uploadStatus")] public virtual UploadStatus UploadStatus { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Represents the status of upload.</summary> public class UploadStatus : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Reasons why upload can't be completed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("errors")] public virtual System.Collections.Generic.IList<string> Errors { get; set; } /// <summary>Per-row upload status.</summary> [Newtonsoft.Json.JsonPropertyAttribute("rowStatus")] public virtual System.Collections.Generic.IList<RowStatus> RowStatus { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Collections; namespace System.Data { public sealed class DataTableReader : DbDataReader { private readonly DataTable[] _tables = null; private bool _isOpen = true; private DataTable _schemaTable = null; private int _tableCounter = -1; private int _rowCounter = -1; private DataTable _currentDataTable = null; private DataRow _currentDataRow = null; private bool _hasRows = true; private bool _reachEORows = false; private bool _currentRowRemoved = false; private bool _schemaIsChanged = false; private bool _started = false; private bool _readerIsInvalid = false; private DataTableReaderListener _listener = null; private bool _tableCleared = false; public DataTableReader(DataTable dataTable) { if (dataTable == null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } _tables = new DataTable[1] { dataTable }; Init(); } public DataTableReader(DataTable[] dataTables) { if (dataTables == null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } if (dataTables.Length == 0) { throw ExceptionBuilder.DataTableReaderArgumentIsEmpty(); } _tables = new DataTable[dataTables.Length]; for (int i = 0; i < dataTables.Length; i++) { if (dataTables[i] == null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } _tables[i] = dataTables[i]; } Init(); } private bool ReaderIsInvalid { get { return _readerIsInvalid; } set { if (_readerIsInvalid == value) { return; } _readerIsInvalid = value; if (_readerIsInvalid && _listener != null) { _listener.CleanUp(); } } } private bool IsSchemaChanged { get { return _schemaIsChanged; } set { if (!value || _schemaIsChanged == value) //once it is set to false; should not change unless in init() or NextResult() { return; } _schemaIsChanged = value; if (_listener != null) { _listener.CleanUp(); } } } internal DataTable CurrentDataTable => _currentDataTable; private void Init() { _tableCounter = 0; _reachEORows = false; _schemaIsChanged = false; _currentDataTable = _tables[_tableCounter]; _hasRows = (_currentDataTable.Rows.Count > 0); ReaderIsInvalid = false; // we need to listen to current tables event so create a listener, it will listen to events and call us back. _listener = new DataTableReaderListener(this); } public override void Close() { if (!_isOpen) { return; } // no need to listen to events after close if (_listener != null) { _listener.CleanUp(); } _listener = null; _schemaTable = null; _isOpen = false; } public override DataTable GetSchemaTable() { ValidateOpen(nameof(GetSchemaTable)); ValidateReader(); // each time, we just get schema table of current table for once, no need to recreate each time, if schema is changed, reader is already // is invalid if (_schemaTable == null) { _schemaTable = GetSchemaTableFromDataTable(_currentDataTable); } return _schemaTable; } public override bool NextResult() { // next result set; reset everything ValidateOpen(nameof(NextResult)); if ((_tableCounter == _tables.Length - 1)) { return false; } _currentDataTable = _tables[++_tableCounter]; if (_listener != null) { _listener.UpdataTable(_currentDataTable); // it will unsubscribe from preveous tables events and subscribe to new table's events } _schemaTable = null; _rowCounter = -1; _currentRowRemoved = false; _reachEORows = false; _schemaIsChanged = false; _started = false; ReaderIsInvalid = false; _tableCleared = false; _hasRows = (_currentDataTable.Rows.Count > 0); return true; } public override bool Read() { if (!_started) { _started = true; } ValidateOpen(nameof(Read)); ValidateReader(); if (_reachEORows) { return false; } if (_rowCounter >= _currentDataTable.Rows.Count - 1) { _reachEORows = true; if (_listener != null) { _listener.CleanUp(); } return false; } _rowCounter++; ValidateRow(_rowCounter); _currentDataRow = _currentDataTable.Rows[_rowCounter]; while (_currentDataRow.RowState == DataRowState.Deleted) { _rowCounter++; if (_rowCounter == _currentDataTable.Rows.Count) { _reachEORows = true; if (_listener != null) { _listener.CleanUp(); } return false; } ValidateRow(_rowCounter); _currentDataRow = _currentDataTable.Rows[_rowCounter]; } if (_currentRowRemoved) { _currentRowRemoved = false; } return true; } public override int Depth { get { ValidateOpen(nameof(Depth)); ValidateReader(); return 0; } } public override bool IsClosed => !_isOpen; public override int RecordsAffected { get { ValidateReader(); return 0; } } public override bool HasRows { get { ValidateOpen(nameof(HasRows)); ValidateReader(); return _hasRows; } } public override object this[int ordinal] { get { ValidateOpen("Item"); ValidateReader(); if ((_currentDataRow == null) || (_currentDataRow.RowState == DataRowState.Deleted)) { ReaderIsInvalid = true; throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); } try { return _currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } } public override object this[string name] { get { ValidateOpen("Item"); ValidateReader(); if ((_currentDataRow == null) || (_currentDataRow.RowState == DataRowState.Deleted)) { ReaderIsInvalid = true; throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); } return _currentDataRow[name]; } } public override int FieldCount { get { ValidateOpen(nameof(FieldCount)); ValidateReader(); return _currentDataTable.Columns.Count; } } public override Type GetProviderSpecificFieldType(int ordinal) { ValidateOpen(nameof(GetProviderSpecificFieldType)); ValidateReader(); return GetFieldType(ordinal); } public override object GetProviderSpecificValue(int ordinal) { ValidateOpen(nameof(GetProviderSpecificValue)); ValidateReader(); return GetValue(ordinal); } public override int GetProviderSpecificValues(object[] values) { ValidateOpen(nameof(GetProviderSpecificValues)); ValidateReader(); return GetValues(values); } public override bool GetBoolean(int ordinal) { ValidateState(nameof(GetBoolean)); ValidateReader(); try { return (bool)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override byte GetByte(int ordinal) { ValidateState(nameof(GetByte)); ValidateReader(); try { return (byte)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override long GetBytes(int ordinal, long dataIndex, byte[] buffer, int bufferIndex, int length) { ValidateState(nameof(GetBytes)); ValidateReader(); byte[] tempBuffer; try { tempBuffer = (byte[])_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } if (buffer == null) { return tempBuffer.Length; } int srcIndex = (int)dataIndex; int byteCount = Math.Min(tempBuffer.Length - srcIndex, length); if (srcIndex < 0) { throw ADP.InvalidSourceBufferIndex(tempBuffer.Length, srcIndex, nameof(dataIndex)); } else if ((bufferIndex < 0) || (bufferIndex > 0 && bufferIndex >= buffer.Length)) { throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, nameof(bufferIndex)); } if (0 < byteCount) { Array.Copy(tempBuffer, dataIndex, buffer, bufferIndex, byteCount); } else if (length < 0) { throw ADP.InvalidDataLength(length); } else { byteCount = 0; } return byteCount; } public override char GetChar(int ordinal) { ValidateState(nameof(GetChar)); ValidateReader(); try { return (char)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override long GetChars(int ordinal, long dataIndex, char[] buffer, int bufferIndex, int length) { ValidateState(nameof(GetChars)); ValidateReader(); char[] tempBuffer; try { tempBuffer = (char[])_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } if (buffer == null) { return tempBuffer.Length; } int srcIndex = (int)dataIndex; int charCount = Math.Min(tempBuffer.Length - srcIndex, length); if (srcIndex < 0) { throw ADP.InvalidSourceBufferIndex(tempBuffer.Length, srcIndex, nameof(dataIndex)); } else if ((bufferIndex < 0) || (bufferIndex > 0 && bufferIndex >= buffer.Length)) { throw ADP.InvalidDestinationBufferIndex(buffer.Length, bufferIndex, nameof(bufferIndex)); } if (0 < charCount) { Array.Copy(tempBuffer, dataIndex, buffer, bufferIndex, charCount); } else if (length < 0) { throw ADP.InvalidDataLength(length); } else { charCount = 0; } return charCount; } public override string GetDataTypeName(int ordinal) { ValidateOpen(nameof(GetDataTypeName)); ValidateReader(); return GetFieldType(ordinal).Name; } public override DateTime GetDateTime(int ordinal) { ValidateState(nameof(GetDateTime)); ValidateReader(); try { return (DateTime)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override decimal GetDecimal(int ordinal) { ValidateState(nameof(GetDecimal)); ValidateReader(); try { return (decimal)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override double GetDouble(int ordinal) { ValidateState(nameof(GetDouble)); ValidateReader(); try { return (double)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override Type GetFieldType(int ordinal) { ValidateOpen(nameof(GetFieldType)); ValidateReader(); try { return (_currentDataTable.Columns[ordinal].DataType); } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override float GetFloat(int ordinal) { ValidateState(nameof(GetFloat)); ValidateReader(); try { return (float)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override Guid GetGuid(int ordinal) { ValidateState(nameof(GetGuid)); ValidateReader(); try { return (Guid)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override short GetInt16(int ordinal) { ValidateState(nameof(GetInt16)); ValidateReader(); try { return (short)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override int GetInt32(int ordinal) { ValidateState(nameof(GetInt32)); ValidateReader(); try { return (int)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override long GetInt64(int ordinal) { ValidateState(nameof(GetInt64)); ValidateReader(); try { return (long)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override string GetName(int ordinal) { ValidateOpen(nameof(GetName)); ValidateReader(); try { return (_currentDataTable.Columns[ordinal].ColumnName); } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override int GetOrdinal(string name) { ValidateOpen(nameof(GetOrdinal)); ValidateReader(); DataColumn dc = _currentDataTable.Columns[name]; if (dc != null) { return dc.Ordinal; } else { throw ExceptionBuilder.ColumnNotInTheTable(name, _currentDataTable.TableName); } } public override string GetString(int ordinal) { ValidateState(nameof(GetString)); ValidateReader(); try { return (string)_currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override object GetValue(int ordinal) { ValidateState(nameof(GetValue)); ValidateReader(); try { return _currentDataRow[ordinal]; } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override int GetValues(object[] values) { ValidateState(nameof(GetValues)); ValidateReader(); if (values == null) { throw ExceptionBuilder.ArgumentNull(nameof(values)); } Array.Copy(_currentDataRow.ItemArray, values, _currentDataRow.ItemArray.Length > values.Length ? values.Length : _currentDataRow.ItemArray.Length); return (_currentDataRow.ItemArray.Length > values.Length ? values.Length : _currentDataRow.ItemArray.Length); } public override bool IsDBNull(int ordinal) { ValidateState(nameof(IsDBNull)); ValidateReader(); try { return (_currentDataRow.IsNull(ordinal)); } catch (IndexOutOfRangeException e) { // thrown by DataColumnCollection ExceptionBuilder.TraceExceptionWithoutRethrow(e); throw ExceptionBuilder.ArgumentOutOfRange(nameof(ordinal)); } } public override IEnumerator GetEnumerator() { ValidateOpen(nameof(GetEnumerator)); return new DbEnumerator((IDataReader)this); } internal static DataTable GetSchemaTableFromDataTable(DataTable table) { if (table == null) { throw ExceptionBuilder.ArgumentNull(nameof(DataTable)); } DataTable tempSchemaTable = new DataTable("SchemaTable"); tempSchemaTable.Locale = System.Globalization.CultureInfo.InvariantCulture; DataColumn ColumnName = new DataColumn(SchemaTableColumn.ColumnName, typeof(string)); DataColumn ColumnOrdinal = new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(int)); DataColumn ColumnSize = new DataColumn(SchemaTableColumn.ColumnSize, typeof(int)); DataColumn NumericPrecision = new DataColumn(SchemaTableColumn.NumericPrecision, typeof(short)); DataColumn NumericScale = new DataColumn(SchemaTableColumn.NumericScale, typeof(short)); DataColumn DataType = new DataColumn(SchemaTableColumn.DataType, typeof(Type)); DataColumn ProviderType = new DataColumn(SchemaTableColumn.ProviderType, typeof(int)); DataColumn IsLong = new DataColumn(SchemaTableColumn.IsLong, typeof(bool)); DataColumn AllowDBNull = new DataColumn(SchemaTableColumn.AllowDBNull, typeof(bool)); DataColumn IsReadOnly = new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(bool)); DataColumn IsRowVersion = new DataColumn(SchemaTableOptionalColumn.IsRowVersion, typeof(bool)); DataColumn IsUnique = new DataColumn(SchemaTableColumn.IsUnique, typeof(bool)); DataColumn IsKeyColumn = new DataColumn(SchemaTableColumn.IsKey, typeof(bool)); DataColumn IsAutoIncrement = new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(bool)); DataColumn BaseSchemaName = new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(string)); DataColumn BaseCatalogName = new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(string)); DataColumn BaseTableName = new DataColumn(SchemaTableColumn.BaseTableName, typeof(string)); DataColumn BaseColumnName = new DataColumn(SchemaTableColumn.BaseColumnName, typeof(string)); DataColumn AutoIncrementSeed = new DataColumn(SchemaTableOptionalColumn.AutoIncrementSeed, typeof(long)); DataColumn AutoIncrementStep = new DataColumn(SchemaTableOptionalColumn.AutoIncrementStep, typeof(long)); DataColumn DefaultValue = new DataColumn(SchemaTableOptionalColumn.DefaultValue, typeof(object)); DataColumn Expression = new DataColumn(SchemaTableOptionalColumn.Expression, typeof(string)); DataColumn ColumnMapping = new DataColumn(SchemaTableOptionalColumn.ColumnMapping, typeof(MappingType)); DataColumn BaseTableNamespace = new DataColumn(SchemaTableOptionalColumn.BaseTableNamespace, typeof(string)); DataColumn BaseColumnNamespace = new DataColumn(SchemaTableOptionalColumn.BaseColumnNamespace, typeof(string)); ColumnSize.DefaultValue = -1; if (table.DataSet != null) { BaseCatalogName.DefaultValue = table.DataSet.DataSetName; } BaseTableName.DefaultValue = table.TableName; BaseTableNamespace.DefaultValue = table.Namespace; IsRowVersion.DefaultValue = false; IsLong.DefaultValue = false; IsReadOnly.DefaultValue = false; IsKeyColumn.DefaultValue = false; IsAutoIncrement.DefaultValue = false; AutoIncrementSeed.DefaultValue = 0; AutoIncrementStep.DefaultValue = 1; tempSchemaTable.Columns.Add(ColumnName); tempSchemaTable.Columns.Add(ColumnOrdinal); tempSchemaTable.Columns.Add(ColumnSize); tempSchemaTable.Columns.Add(NumericPrecision); tempSchemaTable.Columns.Add(NumericScale); tempSchemaTable.Columns.Add(DataType); tempSchemaTable.Columns.Add(ProviderType); tempSchemaTable.Columns.Add(IsLong); tempSchemaTable.Columns.Add(AllowDBNull); tempSchemaTable.Columns.Add(IsReadOnly); tempSchemaTable.Columns.Add(IsRowVersion); tempSchemaTable.Columns.Add(IsUnique); tempSchemaTable.Columns.Add(IsKeyColumn); tempSchemaTable.Columns.Add(IsAutoIncrement); tempSchemaTable.Columns.Add(BaseCatalogName); tempSchemaTable.Columns.Add(BaseSchemaName); // specific to datatablereader tempSchemaTable.Columns.Add(BaseTableName); tempSchemaTable.Columns.Add(BaseColumnName); tempSchemaTable.Columns.Add(AutoIncrementSeed); tempSchemaTable.Columns.Add(AutoIncrementStep); tempSchemaTable.Columns.Add(DefaultValue); tempSchemaTable.Columns.Add(Expression); tempSchemaTable.Columns.Add(ColumnMapping); tempSchemaTable.Columns.Add(BaseTableNamespace); tempSchemaTable.Columns.Add(BaseColumnNamespace); foreach (DataColumn dc in table.Columns) { DataRow dr = tempSchemaTable.NewRow(); dr[ColumnName] = dc.ColumnName; dr[ColumnOrdinal] = dc.Ordinal; dr[DataType] = dc.DataType; if (dc.DataType == typeof(string)) { dr[ColumnSize] = dc.MaxLength; } dr[AllowDBNull] = dc.AllowDBNull; dr[IsReadOnly] = dc.ReadOnly; dr[IsUnique] = dc.Unique; if (dc.AutoIncrement) { dr[IsAutoIncrement] = true; dr[AutoIncrementSeed] = dc.AutoIncrementSeed; dr[AutoIncrementStep] = dc.AutoIncrementStep; } if (dc.DefaultValue != DBNull.Value) { dr[DefaultValue] = dc.DefaultValue; } if (dc.Expression.Length != 0) { bool hasExternalDependency = false; DataColumn[] dependency = dc.DataExpression.GetDependency(); for (int j = 0; j < dependency.Length; j++) { if (dependency[j].Table != table) { hasExternalDependency = true; break; } } if (!hasExternalDependency) { dr[Expression] = dc.Expression; } } dr[ColumnMapping] = dc.ColumnMapping; dr[BaseColumnName] = dc.ColumnName; dr[BaseColumnNamespace] = dc.Namespace; tempSchemaTable.Rows.Add(dr); } foreach (DataColumn key in table.PrimaryKey) { tempSchemaTable.Rows[key.Ordinal][IsKeyColumn] = true; } tempSchemaTable.AcceptChanges(); return tempSchemaTable; } private void ValidateOpen(string caller) { if (!_isOpen) { throw ADP.DataReaderClosed(caller); } } private void ValidateReader() { if (ReaderIsInvalid) { throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); } if (IsSchemaChanged) { throw ExceptionBuilder.DataTableReaderSchemaIsInvalid(_currentDataTable.TableName); // may be we can use better error message! } } private void ValidateState(string caller) { ValidateOpen(caller); if (_tableCleared) { throw ExceptionBuilder.EmptyDataTableReader(_currentDataTable.TableName); } // see if without any event raising, if our current row has some changes!if so reader is invalid. if ((_currentDataRow == null) || (_currentDataTable == null)) { ReaderIsInvalid = true; throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); } //See if without any event raing, if our rows are deleted, or removed! Reader is not invalid, user should be able to read and reach goo row if ((_currentDataRow.RowState == DataRowState.Deleted) || (_currentDataRow.RowState == DataRowState.Detached) || _currentRowRemoved) { throw ExceptionBuilder.InvalidCurrentRowInDataTableReader(); } // user may have called clear (which removes the rows without raing event) or deleted part of rows without raising event!if so reader is invalid. if (0 > _rowCounter || _currentDataTable.Rows.Count <= _rowCounter) { ReaderIsInvalid = true; throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); } } private void ValidateRow(int rowPosition) { if (ReaderIsInvalid) { throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); } if (0 > rowPosition || _currentDataTable.Rows.Count <= rowPosition) { ReaderIsInvalid = true; throw ExceptionBuilder.InvalidDataTableReader(_currentDataTable.TableName); } } // Event Call backs from DataTableReaderListener, will invoke these methods internal void SchemaChanged() { IsSchemaChanged = true; } internal void DataTableCleared() { if (!_started) { return; } _rowCounter = -1; if (!_reachEORows) { _currentRowRemoved = true; } } internal void DataChanged(DataRowChangeEventArgs args) { if ((!_started) || (_rowCounter == -1 && !_tableCleared)) { return; } switch (args.Action) { case DataRowAction.Add: ValidateRow(_rowCounter + 1); if (_currentDataRow == _currentDataTable.Rows[_rowCounter + 1]) { // check if we moved one position up _rowCounter++; // if so, refresh the datarow and fix the counter } break; case DataRowAction.Delete: // delete case DataRowAction.Rollback:// rejectchanges case DataRowAction.Commit: // acceptchanges if (args.Row.RowState == DataRowState.Detached) { if (args.Row != _currentDataRow) { if (_rowCounter == 0) // if I am at first row and no previous row exist,NOOP break; ValidateRow(_rowCounter - 1); if (_currentDataRow == _currentDataTable.Rows[_rowCounter - 1]) { // one of previous rows is detached, collection size is changed! _rowCounter--; } } else { // we are proccessing current datarow _currentRowRemoved = true; if (_rowCounter > 0) { // go back one row, no matter what the state is _rowCounter--; _currentDataRow = _currentDataTable.Rows[_rowCounter]; } else { // we are on 0th row, so reset data to initial state! _rowCounter = -1; _currentDataRow = null; } } } break; default: break; } } } }
// // ConnectedSeekSlider.cs // // Author: // Aaron Bockover <[email protected]> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Gtk; using Banshee.Widgets; using Banshee.MediaEngine; using Banshee.ServiceStack; namespace Banshee.Gui.Widgets { public enum SeekSliderLayout { Horizontal, Vertical } public class ConnectedSeekSlider : Alignment { private SeekSlider seek_slider; private StreamPositionLabel stream_position_label; private Box box; private Hyena.Widgets.GrabHandle grabber; public ConnectedSeekSlider () : this (SeekSliderLayout.Vertical) { } public ConnectedSeekSlider (SeekSliderLayout layout) : base (0.5f, 0.5f, 1.0f, 0.0f) { RightPadding = 10; LeftPadding = 10; BuildSeekSlider (layout); ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent, PlayerEvent.Iterate | PlayerEvent.Buffering | PlayerEvent.StartOfStream | PlayerEvent.StateChange); ServiceManager.PlayerEngine.TrackIntercept += OnTrackIntercept; SizeAllocated += delegate { QueueDraw (); }; seek_slider.SeekRequested += OnSeekRequested; // Initialize the display if we're paused since we won't get any // events or state change until something actually happens (BGO #536564) if (ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused) { OnPlayerEngineTick (); } } public void Disconnect () { ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent); ServiceManager.PlayerEngine.TrackIntercept -= OnTrackIntercept; seek_slider.SeekRequested -= OnSeekRequested; base.Dispose (); } public StreamPositionLabel StreamPositionLabel { get { return stream_position_label; } } public SeekSlider SeekSlider { get { return seek_slider; } } public int Spacing { get { return box.Spacing; } set { box.Spacing = value; } } private void BuildSeekSlider (SeekSliderLayout layout) { var hbox = new HBox () { Spacing = 2 }; seek_slider = new SeekSlider (); stream_position_label = new StreamPositionLabel (seek_slider); if (layout == SeekSliderLayout.Horizontal) { box = new HBox (); box.Spacing = 5; stream_position_label.FormatString = "<b>{0}</b>"; } else { box = new VBox (); } seek_slider.SetSizeRequest (175, -1); box.PackStart (seek_slider, true, true, 0); box.PackStart (stream_position_label, false, false, 0); hbox.PackStart (box, true, true, 0); grabber = new Hyena.Widgets.GrabHandle () { NoShowAll = true }; grabber.ControlWidthOf (seek_slider, 125, 1024, true); hbox.PackStart (grabber, true, true, 0); hbox.ShowAll (); Resizable = false; Add (hbox); } public bool Resizable { get { return grabber.Visible; } set { grabber.Visible = value; // grabber is 5 + 2 spacing, do reduce right padding to 3 RightPadding = value ? (uint)3 : (uint)10; } } private bool transitioning = false; private bool OnTrackIntercept (Banshee.Collection.TrackInfo track) { transitioning = true; return false; } private void OnPlayerEvent (PlayerEventArgs args) { switch (args.Event) { case PlayerEvent.Iterate: OnPlayerEngineTick (); break; case PlayerEvent.StartOfStream: stream_position_label.StreamState = StreamLabelState.Playing; seek_slider.CanSeek = ServiceManager.PlayerEngine.CanSeek; break; case PlayerEvent.Buffering: PlayerEventBufferingArgs buffering = (PlayerEventBufferingArgs)args; if (buffering.Progress >= 1.0) { stream_position_label.StreamState = StreamLabelState.Playing; break; } stream_position_label.StreamState = StreamLabelState.Buffering; stream_position_label.BufferingProgress = buffering.Progress; seek_slider.Sensitive = false; break; case PlayerEvent.StateChange: switch (((PlayerEventStateChangeArgs)args).Current) { case PlayerState.Contacting: transitioning = false; stream_position_label.StreamState = StreamLabelState.Contacting; seek_slider.SetIdle (); break; case PlayerState.Loading: transitioning = false; if (((PlayerEventStateChangeArgs)args).Previous == PlayerState.Contacting) { stream_position_label.StreamState = StreamLabelState.Loading; seek_slider.SetIdle (); } break; case PlayerState.Idle: seek_slider.CanSeek = false; if (!transitioning) { stream_position_label.StreamState = StreamLabelState.Idle; seek_slider.Duration = 0; seek_slider.SeekValue = 0; seek_slider.SetIdle (); } break; default: transitioning = false; break; } break; } } private void OnPlayerEngineTick () { if (ServiceManager.PlayerEngine == null) { return; } Banshee.Collection.TrackInfo track = ServiceManager.PlayerEngine.CurrentTrack; stream_position_label.IsLive = track == null ? false : track.IsLive; seek_slider.Duration = ServiceManager.PlayerEngine.Length; if (stream_position_label.StreamState != StreamLabelState.Buffering) { stream_position_label.StreamState = StreamLabelState.Playing; seek_slider.SeekValue = ServiceManager.PlayerEngine.Position; } seek_slider.CanSeek = ServiceManager.PlayerEngine.CanSeek; } private void OnSeekRequested (object o, EventArgs args) { ServiceManager.PlayerEngine.Position = (uint)seek_slider.Value; } } }
// // Encog(tm) Core v3.2 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using Encog.MathUtil.Error; using Encog.MathUtil.Matrices.Decomposition; using Encog.MathUtil.Matrices.Hessian; using Encog.ML; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.ML.Train; using Encog.Neural.Networks.Structure; using Encog.Neural.Networks.Training.Propagation; using Encog.Util.Concurrency; using Encog.Util.Validate; namespace Encog.Neural.Networks.Training.Lma { /// <summary> /// Trains a neural network using a Levenberg Marquardt algorithm (LMA). This /// training technique is based on the mathematical technique of the same name. /// The LMA interpolates between the Gauss-Newton algorithm (GNA) and the /// method of gradient descent (similar to what is used by backpropagation. /// The lambda parameter determines the degree to which GNA and Gradient /// Descent are used. A lower lambda results in heavier use of GNA, /// whereas a higher lambda results in a heavier use of gradient descent. /// Each iteration starts with a low lambda that builds if the improvement /// to the neural network is not desirable. At some point the lambda is /// high enough that the training method reverts totally to gradient descent. /// This allows the neural network to be trained effectively in cases where GNA /// provides the optimal training time, but has the ability to fall back to the /// more primitive gradient descent method /// LMA finds only a local minimum, not a global minimum. /// References: /// C. R. Souza. (2009). Neural Network Learning by the Levenberg-Marquardt Algorithm /// with Bayesian Regularization. Website, available from: /// http://crsouza.blogspot.com/2009/11/neural-network-learning-by-levenberg_18.html /// http://www.heatonresearch.com/wiki/LMA /// http://en.wikipedia.org/wiki/Levenberg%E2%80%93Marquardt_algorithm /// http://en.wikipedia.org/wiki/Finite_difference_method /// http://mathworld.wolfram.com/FiniteDifference.html /// http://www-alg.ist.hokudai.ac.jp/~jan/alpha.pdf - /// http://www.inference.phy.cam.ac.uk/mackay/Bayes_FAQ.html /// </summary> public class LevenbergMarquardtTraining : BasicTraining, IMultiThreadable { /// <summary> /// The amount to scale the lambda by. /// </summary> public const double ScaleLambda = 10.0; /// <summary> /// The max amount for the LAMBDA. /// </summary> public const double LambdaMax = 1e25; /// <summary> /// he diagonal of the hessian. /// </summary> private readonly double[] _diagonal; /// <summary> /// Utility class to compute the Hessian. /// </summary> private readonly IComputeHessian _hessian; /// <summary> /// The training set that we are using to train. /// </summary> private readonly IMLDataSet _indexableTraining; /// <summary> /// The network that is to be trained. /// </summary> private readonly BasicNetwork _network; /// <summary> /// The training set length. /// </summary> private readonly int _trainingLength; /// <summary> /// How many weights are we dealing with? /// </summary> private readonly int _weightCount; /// <summary> /// The amount to change the weights by. /// </summary> private double[] _deltas; /// <summary> /// Is the init complete? /// </summary> private bool _initComplete; /// <summary> /// The lambda, or damping factor. This is increased until a desirable /// adjustment is found. /// </summary> private double _lambda; /// <summary> /// The training elements. /// </summary> private IMLDataPair _pair; /// <summary> /// The neural network weights and bias values. /// </summary> private double[] _weights; /// <summary> /// Construct the LMA object. /// </summary> /// <param name="network">The network to train. Must have a single output neuron.</param> /// <param name="training">The training data to use. Must be indexable.</param> public LevenbergMarquardtTraining(BasicNetwork network, IMLDataSet training) : this(network, training, new HessianCR()) { } /// <summary> /// Construct the LMA object. /// </summary> /// <param name="network">The network to train. Must have a single output neuron.</param> /// <param name="training"></param> /// <param name="h">The training data to use. Must be indexable.</param> public LevenbergMarquardtTraining(BasicNetwork network, IMLDataSet training, IComputeHessian h) : base(TrainingImplementationType.Iterative) { ValidateNetwork.ValidateMethodToData(network, training); Training = training; _indexableTraining = Training; this._network = network; _trainingLength = _indexableTraining.Count; _weightCount = this._network.Structure.CalculateSize(); _lambda = 0.1; _deltas = new double[_weightCount]; _diagonal = new double[_weightCount]; var input = new BasicMLData( _indexableTraining.InputSize); var ideal = new BasicMLData( _indexableTraining.IdealSize); _pair = new BasicMLDataPair(input, ideal); _hessian = h; } /// <inheritdoc /> public override bool CanContinue { get { return false; } } /// <inheritdoc /> public override IMLMethod Method { get { return _network; } } /// <summary> /// The Hessian calculation method used. /// </summary> public IComputeHessian Hessian { get { return _hessian; } } /// <inheritdoc /> public int ThreadCount { get { if (_hessian is IMultiThreadable) { return ((IMultiThreadable) _hessian).ThreadCount; } return 1; } set { if (_hessian is IMultiThreadable) { ((IMultiThreadable) _hessian).ThreadCount = value; } else if (value != 1 && value != 0) { throw new TrainingError("The Hessian object in use(" + _hessian.GetType().Name + ") does not support multi-threaded mode."); } } } /// <summary> /// Save the diagonal of the hessian. /// </summary> private void SaveDiagonal() { double[][] h = _hessian.Hessian; for (int i = 0; i < _weightCount; i++) { _diagonal[i] = h[i][i]; } } /// <summary> /// The SSE error with the current weights. /// </summary> /// <returns></returns> private double CalculateError() { var result = new ErrorCalculation(); for (int i = 0; i < _trainingLength; i++) { _pair = _indexableTraining[i]; IMLData actual = _network.Compute(_pair.Input); result.UpdateError(actual, _pair.Ideal, _pair.Significance); } return result.CalculateSSE(); } /// <summary> /// Apply the lambda. /// </summary> private void ApplyLambda() { double[][] h = _hessian.Hessian; for (int i = 0; i < _weightCount; i++) { h[i][i] = _diagonal[i] + _lambda; } } /// <inheritdoc /> public override void Iteration() { if (!_initComplete) { _hessian.Init(_network, Training); _initComplete = true; } PreIteration(); _hessian.Clear(); _weights = NetworkCODEC.NetworkToArray(_network); _hessian.Compute(); double currentError = _hessian.SSE; SaveDiagonal(); double startingError = currentError; bool done = false; bool singular; while (!done) { ApplyLambda(); var decomposition = new LUDecomposition(_hessian.HessianMatrix); singular = decomposition.IsNonsingular; if (singular) { _deltas = decomposition.Solve(_hessian.Gradients); UpdateWeights(); currentError = CalculateError(); } if (!singular || currentError >= startingError) { _lambda *= ScaleLambda; if (_lambda > LambdaMax) { _lambda = LambdaMax; done = true; } } else { _lambda /= ScaleLambda; done = true; } } Error = currentError; PostIteration(); } /// <inheritdoc /> public override TrainingContinuation Pause() { return null; } /// <inheritdoc /> public override void Resume(TrainingContinuation state) { } /// <summary> /// Update the weights in the neural network. /// </summary> public void UpdateWeights() { var w = (double[]) _weights.Clone(); for (int i = 0; i < w.Length; i++) { w[i] += _deltas[i]; } NetworkCODEC.ArrayToNetwork(w, _network); } } }
// 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.Contracts; using System.Globalization; using System.Text; namespace System.Net.Http.Headers { public class CacheControlHeaderValue : ICloneable { private const string maxAgeString = "max-age"; private const string maxStaleString = "max-stale"; private const string minFreshString = "min-fresh"; private const string mustRevalidateString = "must-revalidate"; private const string noCacheString = "no-cache"; private const string noStoreString = "no-store"; private const string noTransformString = "no-transform"; private const string onlyIfCachedString = "only-if-cached"; private const string privateString = "private"; private const string proxyRevalidateString = "proxy-revalidate"; private const string publicString = "public"; private const string sharedMaxAgeString = "s-maxage"; private static readonly HttpHeaderParser s_nameValueListParser = GenericHeaderParser.MultipleValueNameValueParser; private static readonly Action<string> s_checkIsValidToken = CheckIsValidToken; private bool _noCache; private ICollection<string> _noCacheHeaders; private bool _noStore; private TimeSpan? _maxAge; private TimeSpan? _sharedMaxAge; private bool _maxStale; private TimeSpan? _maxStaleLimit; private TimeSpan? _minFresh; private bool _noTransform; private bool _onlyIfCached; private bool _publicField; private bool _privateField; private ICollection<string> _privateHeaders; private bool _mustRevalidate; private bool _proxyRevalidate; private ICollection<NameValueHeaderValue> _extensions; public bool NoCache { get { return _noCache; } set { _noCache = value; } } public ICollection<string> NoCacheHeaders { get { if (_noCacheHeaders == null) { _noCacheHeaders = new ObjectCollection<string>(s_checkIsValidToken); } return _noCacheHeaders; } } public bool NoStore { get { return _noStore; } set { _noStore = value; } } public TimeSpan? MaxAge { get { return _maxAge; } set { _maxAge = value; } } public TimeSpan? SharedMaxAge { get { return _sharedMaxAge; } set { _sharedMaxAge = value; } } public bool MaxStale { get { return _maxStale; } set { _maxStale = value; } } public TimeSpan? MaxStaleLimit { get { return _maxStaleLimit; } set { _maxStaleLimit = value; } } public TimeSpan? MinFresh { get { return _minFresh; } set { _minFresh = value; } } public bool NoTransform { get { return _noTransform; } set { _noTransform = value; } } public bool OnlyIfCached { get { return _onlyIfCached; } set { _onlyIfCached = value; } } public bool Public { get { return _publicField; } set { _publicField = value; } } public bool Private { get { return _privateField; } set { _privateField = value; } } public ICollection<string> PrivateHeaders { get { if (_privateHeaders == null) { _privateHeaders = new ObjectCollection<string>(s_checkIsValidToken); } return _privateHeaders; } } public bool MustRevalidate { get { return _mustRevalidate; } set { _mustRevalidate = value; } } public bool ProxyRevalidate { get { return _proxyRevalidate; } set { _proxyRevalidate = value; } } public ICollection<NameValueHeaderValue> Extensions { get { if (_extensions == null) { _extensions = new ObjectCollection<NameValueHeaderValue>(); } return _extensions; } } public CacheControlHeaderValue() { } private CacheControlHeaderValue(CacheControlHeaderValue source) { Contract.Requires(source != null); _noCache = source._noCache; _noStore = source._noStore; _maxAge = source._maxAge; _sharedMaxAge = source._sharedMaxAge; _maxStale = source._maxStale; _maxStaleLimit = source._maxStaleLimit; _minFresh = source._minFresh; _noTransform = source._noTransform; _onlyIfCached = source._onlyIfCached; _publicField = source._publicField; _privateField = source._privateField; _mustRevalidate = source._mustRevalidate; _proxyRevalidate = source._proxyRevalidate; if (source._noCacheHeaders != null) { foreach (var noCacheHeader in source._noCacheHeaders) { NoCacheHeaders.Add(noCacheHeader); } } if (source._privateHeaders != null) { foreach (var privateHeader in source._privateHeaders) { PrivateHeaders.Add(privateHeader); } } if (source._extensions != null) { foreach (var extension in source._extensions) { Extensions.Add((NameValueHeaderValue)((ICloneable)extension).Clone()); } } } public override string ToString() { StringBuilder sb = new StringBuilder(); AppendValueIfRequired(sb, _noStore, noStoreString); AppendValueIfRequired(sb, _noTransform, noTransformString); AppendValueIfRequired(sb, _onlyIfCached, onlyIfCachedString); AppendValueIfRequired(sb, _publicField, publicString); AppendValueIfRequired(sb, _mustRevalidate, mustRevalidateString); AppendValueIfRequired(sb, _proxyRevalidate, proxyRevalidateString); if (_noCache) { AppendValueWithSeparatorIfRequired(sb, noCacheString); if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0)) { sb.Append("=\""); AppendValues(sb, _noCacheHeaders); sb.Append('\"'); } } if (_maxAge.HasValue) { AppendValueWithSeparatorIfRequired(sb, maxAgeString); sb.Append('='); sb.Append(((int)_maxAge.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo)); } if (_sharedMaxAge.HasValue) { AppendValueWithSeparatorIfRequired(sb, sharedMaxAgeString); sb.Append('='); sb.Append(((int)_sharedMaxAge.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo)); } if (_maxStale) { AppendValueWithSeparatorIfRequired(sb, maxStaleString); if (_maxStaleLimit.HasValue) { sb.Append('='); sb.Append(((int)_maxStaleLimit.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo)); } } if (_minFresh.HasValue) { AppendValueWithSeparatorIfRequired(sb, minFreshString); sb.Append('='); sb.Append(((int)_minFresh.Value.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo)); } if (_privateField) { AppendValueWithSeparatorIfRequired(sb, privateString); if ((_privateHeaders != null) && (_privateHeaders.Count > 0)) { sb.Append("=\""); AppendValues(sb, _privateHeaders); sb.Append('\"'); } } NameValueHeaderValue.ToString(_extensions, ',', false, sb); return sb.ToString(); } public override bool Equals(object obj) { CacheControlHeaderValue other = obj as CacheControlHeaderValue; if (other == null) { return false; } if ((_noCache != other._noCache) || (_noStore != other._noStore) || (_maxAge != other._maxAge) || (_sharedMaxAge != other._sharedMaxAge) || (_maxStale != other._maxStale) || (_maxStaleLimit != other._maxStaleLimit) || (_minFresh != other._minFresh) || (_noTransform != other._noTransform) || (_onlyIfCached != other._onlyIfCached) || (_publicField != other._publicField) || (_privateField != other._privateField) || (_mustRevalidate != other._mustRevalidate) || (_proxyRevalidate != other._proxyRevalidate)) { return false; } if (!HeaderUtilities.AreEqualCollections(_noCacheHeaders, other._noCacheHeaders, StringComparer.OrdinalIgnoreCase)) { return false; } if (!HeaderUtilities.AreEqualCollections(_privateHeaders, other._privateHeaders, StringComparer.OrdinalIgnoreCase)) { return false; } if (!HeaderUtilities.AreEqualCollections(_extensions, other._extensions)) { return false; } return true; } public override int GetHashCode() { // Use a different bit for bool fields: bool.GetHashCode() will return 0 (false) or 1 (true). So we would // end up having the same hash code for e.g. two instances where one has only noCache set and the other // only noStore. int result = _noCache.GetHashCode() ^ (_noStore.GetHashCode() << 1) ^ (_maxStale.GetHashCode() << 2) ^ (_noTransform.GetHashCode() << 3) ^ (_onlyIfCached.GetHashCode() << 4) ^ (_publicField.GetHashCode() << 5) ^ (_privateField.GetHashCode() << 6) ^ (_mustRevalidate.GetHashCode() << 7) ^ (_proxyRevalidate.GetHashCode() << 8); // XOR the hashcode of timespan values with different numbers to make sure two instances with the same // timespan set on different fields result in different hashcodes. result = result ^ (_maxAge.HasValue ? _maxAge.Value.GetHashCode() ^ 1 : 0) ^ (_sharedMaxAge.HasValue ? _sharedMaxAge.Value.GetHashCode() ^ 2 : 0) ^ (_maxStaleLimit.HasValue ? _maxStaleLimit.Value.GetHashCode() ^ 4 : 0) ^ (_minFresh.HasValue ? _minFresh.Value.GetHashCode() ^ 8 : 0); if ((_noCacheHeaders != null) && (_noCacheHeaders.Count > 0)) { foreach (var noCacheHeader in _noCacheHeaders) { result = result ^ noCacheHeader.ToLowerInvariant().GetHashCode(); } } if ((_privateHeaders != null) && (_privateHeaders.Count > 0)) { foreach (var privateHeader in _privateHeaders) { result = result ^ privateHeader.ToLowerInvariant().GetHashCode(); } } if ((_extensions != null) && (_extensions.Count > 0)) { foreach (var extension in _extensions) { result = result ^ extension.GetHashCode(); } } return result; } public static CacheControlHeaderValue Parse(string input) { int index = 0; return (CacheControlHeaderValue)CacheControlHeaderParser.Parser.ParseValue(input, null, ref index); } public static bool TryParse(string input, out CacheControlHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (CacheControlHeaderParser.Parser.TryParseValue(input, null, ref index, out output)) { parsedValue = (CacheControlHeaderValue)output; return true; } return false; } internal static int GetCacheControlLength(string input, int startIndex, CacheControlHeaderValue storeValue, out CacheControlHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Cache-Control header consists of a list of name/value pairs, where the value is optional. So use an // instance of NameValueHeaderParser to parse the string. int current = startIndex; object nameValue = null; List<NameValueHeaderValue> nameValueList = new List<NameValueHeaderValue>(); while (current < input.Length) { if (!s_nameValueListParser.TryParseValue(input, null, ref current, out nameValue)) { return 0; } nameValueList.Add(nameValue as NameValueHeaderValue); } // If we get here, we were able to successfully parse the string as list of name/value pairs. Now analyze // the name/value pairs. // Cache-Control is a header supporting lists of values. However, expose the header as an instance of // CacheControlHeaderValue. So if we already have an instance of CacheControlHeaderValue, add the values // from this string to the existing instances. CacheControlHeaderValue result = storeValue; if (result == null) { result = new CacheControlHeaderValue(); } if (!TrySetCacheControlValues(result, nameValueList)) { return 0; } // If we had an existing store value and we just updated that instance, return 'null' to indicate that // we don't have a new instance of CacheControlHeaderValue, but just updated an existing one. This is the // case if we have multiple 'Cache-Control' headers set in a request/response message. if (storeValue == null) { parsedValue = result; } // If we get here we successfully parsed the whole string. return input.Length - startIndex; } private static bool TrySetCacheControlValues(CacheControlHeaderValue cc, List<NameValueHeaderValue> nameValueList) { foreach (NameValueHeaderValue nameValue in nameValueList) { bool success = true; string name = nameValue.Name.ToLowerInvariant(); switch (name) { case noCacheString: success = TrySetOptionalTokenList(nameValue, ref cc._noCache, ref cc._noCacheHeaders); break; case noStoreString: success = TrySetTokenOnlyValue(nameValue, ref cc._noStore); break; case maxAgeString: success = TrySetTimeSpan(nameValue, ref cc._maxAge); break; case maxStaleString: success = ((nameValue.Value == null) || TrySetTimeSpan(nameValue, ref cc._maxStaleLimit)); if (success) { cc._maxStale = true; } break; case minFreshString: success = TrySetTimeSpan(nameValue, ref cc._minFresh); break; case noTransformString: success = TrySetTokenOnlyValue(nameValue, ref cc._noTransform); break; case onlyIfCachedString: success = TrySetTokenOnlyValue(nameValue, ref cc._onlyIfCached); break; case publicString: success = TrySetTokenOnlyValue(nameValue, ref cc._publicField); break; case privateString: success = TrySetOptionalTokenList(nameValue, ref cc._privateField, ref cc._privateHeaders); break; case mustRevalidateString: success = TrySetTokenOnlyValue(nameValue, ref cc._mustRevalidate); break; case proxyRevalidateString: success = TrySetTokenOnlyValue(nameValue, ref cc._proxyRevalidate); break; case sharedMaxAgeString: success = TrySetTimeSpan(nameValue, ref cc._sharedMaxAge); break; default: cc.Extensions.Add(nameValue); // success is always true break; } if (!success) { return false; } } return true; } private static bool TrySetTokenOnlyValue(NameValueHeaderValue nameValue, ref bool boolField) { if (nameValue.Value != null) { return false; } boolField = true; return true; } private static bool TrySetOptionalTokenList(NameValueHeaderValue nameValue, ref bool boolField, ref ICollection<string> destination) { Contract.Requires(nameValue != null); if (nameValue.Value == null) { boolField = true; return true; } // We need the string to be at least 3 chars long: 2x quotes and at least 1 character. Also make sure we // have a quoted string. Note that NameValueHeaderValue will never have leading/trailing whitespaces. string valueString = nameValue.Value; if ((valueString.Length < 3) || (valueString[0] != '\"') || (valueString[valueString.Length - 1] != '\"')) { return false; } // We have a quoted string. Now verify that the string contains a list of valid tokens separated by ','. int current = 1; // skip the initial '"' character. int maxLength = valueString.Length - 1; // -1 because we don't want to parse the final '"'. bool separatorFound = false; int originalValueCount = destination == null ? 0 : destination.Count; while (current < maxLength) { current = HeaderUtilities.GetNextNonEmptyOrWhitespaceIndex(valueString, current, true, out separatorFound); if (current == maxLength) { break; } int tokenLength = HttpRuleParser.GetTokenLength(valueString, current); if (tokenLength == 0) { // We already skipped whitespaces and separators. If we don't have a token it must be an invalid // character. return false; } if (destination == null) { destination = new ObjectCollection<string>(s_checkIsValidToken); } destination.Add(valueString.Substring(current, tokenLength)); current = current + tokenLength; } // After parsing a valid token list, we expect to have at least one value if ((destination != null) && (destination.Count > originalValueCount)) { boolField = true; return true; } return false; } private static bool TrySetTimeSpan(NameValueHeaderValue nameValue, ref TimeSpan? timeSpan) { Contract.Requires(nameValue != null); if (nameValue.Value == null) { return false; } int seconds; if (!HeaderUtilities.TryParseInt32(nameValue.Value, out seconds)) { return false; } timeSpan = new TimeSpan(0, 0, seconds); return true; } private static void AppendValueIfRequired(StringBuilder sb, bool appendValue, string value) { if (appendValue) { AppendValueWithSeparatorIfRequired(sb, value); } } private static void AppendValueWithSeparatorIfRequired(StringBuilder sb, string value) { if (sb.Length > 0) { sb.Append(", "); } sb.Append(value); } private static void AppendValues(StringBuilder sb, IEnumerable<string> values) { bool first = true; foreach (string value in values) { if (first) { first = false; } else { sb.Append(", "); } sb.Append(value); } } private static void CheckIsValidToken(string item) { HeaderUtilities.CheckValidToken(item, "item"); } object ICloneable.Clone() { return new CacheControlHeaderValue(this); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Nini.Config; using OpenMetaverse; using OpenSim.Data; using OpenSim.Framework; using OpenSim.Services.Interfaces; using OpenSim.Framework.Console; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Services.UserAccountService { public class UserAccountService : UserAccountServiceBase, IUserAccountService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static UserAccountService m_RootInstance; /// <summary> /// Should we create default entries (minimum body parts/clothing, avatar wearable entries) for a new avatar? /// </summary> private bool m_CreateDefaultAvatarEntries; protected IGridService m_GridService; protected IAuthenticationService m_AuthenticationService; protected IGridUserService m_GridUserService; protected IInventoryService m_InventoryService; protected IAvatarService m_AvatarService; public UserAccountService(IConfigSource config) : base(config) { IConfig userConfig = config.Configs["UserAccountService"]; if (userConfig == null) throw new Exception("No UserAccountService configuration"); string gridServiceDll = userConfig.GetString("GridService", string.Empty); if (gridServiceDll != string.Empty) m_GridService = LoadPlugin<IGridService>(gridServiceDll, new Object[] { config }); string authServiceDll = userConfig.GetString("AuthenticationService", string.Empty); if (authServiceDll != string.Empty) m_AuthenticationService = LoadPlugin<IAuthenticationService>(authServiceDll, new Object[] { config }); string presenceServiceDll = userConfig.GetString("GridUserService", string.Empty); if (presenceServiceDll != string.Empty) m_GridUserService = LoadPlugin<IGridUserService>(presenceServiceDll, new Object[] { config }); string invServiceDll = userConfig.GetString("InventoryService", string.Empty); if (invServiceDll != string.Empty) m_InventoryService = LoadPlugin<IInventoryService>(invServiceDll, new Object[] { config }); string avatarServiceDll = userConfig.GetString("AvatarService", string.Empty); if (avatarServiceDll != string.Empty) m_AvatarService = LoadPlugin<IAvatarService>(avatarServiceDll, new Object[] { config }); m_CreateDefaultAvatarEntries = userConfig.GetBoolean("CreateDefaultAvatarEntries", false); // In case there are several instances of this class in the same process, // the console commands are only registered for the root instance if (m_RootInstance == null && MainConsole.Instance != null) { m_RootInstance = this; MainConsole.Instance.Commands.AddCommand("Users", false, "create user", "create user [<first> [<last> [<pass> [<email> [<user id>]]]]]", "Create a new user", HandleCreateUser); MainConsole.Instance.Commands.AddCommand("Users", false, "reset user password", "reset user password [<first> [<last> [<password>]]]", "Reset a user password", HandleResetUserPassword); MainConsole.Instance.Commands.AddCommand("Users", false, "set user level", "set user level [<first> [<last> [<level>]]]", "Set user level. If >= 200 and 'allow_grid_gods = true' in OpenSim.ini, " + "this account will be treated as god-moded. " + "It will also affect the 'login level' command. ", HandleSetUserLevel); MainConsole.Instance.Commands.AddCommand("Users", false, "show account", "show account <first> <last>", "Show account details for the given user", HandleShowAccount); } } #region IUserAccountService public UserAccount GetUserAccount(UUID scopeID, string firstName, string lastName) { // m_log.DebugFormat( // "[USER ACCOUNT SERVICE]: Retrieving account by username for {0} {1}, scope {2}", // firstName, lastName, scopeID); UserAccountData[] d; if (scopeID != UUID.Zero) { d = m_Database.Get( new string[] { "ScopeID", "FirstName", "LastName" }, new string[] { scopeID.ToString(), firstName, lastName }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "FirstName", "LastName" }, new string[] { UUID.Zero.ToString(), firstName, lastName }); } } else { d = m_Database.Get( new string[] { "FirstName", "LastName" }, new string[] { firstName, lastName }); } if (d.Length < 1) return null; return MakeUserAccount(d[0]); } private UserAccount MakeUserAccount(UserAccountData d) { UserAccount u = new UserAccount(); u.FirstName = d.FirstName; u.LastName = d.LastName; u.PrincipalID = d.PrincipalID; u.ScopeID = d.ScopeID; if (d.Data.ContainsKey("Email") && d.Data["Email"] != null) u.Email = d.Data["Email"].ToString(); else u.Email = string.Empty; u.Created = Convert.ToInt32(d.Data["Created"].ToString()); if (d.Data.ContainsKey("UserTitle") && d.Data["UserTitle"] != null) u.UserTitle = d.Data["UserTitle"].ToString(); else u.UserTitle = string.Empty; if (d.Data.ContainsKey("UserLevel") && d.Data["UserLevel"] != null) Int32.TryParse(d.Data["UserLevel"], out u.UserLevel); if (d.Data.ContainsKey("UserFlags") && d.Data["UserFlags"] != null) Int32.TryParse(d.Data["UserFlags"], out u.UserFlags); if (d.Data.ContainsKey("ServiceURLs") && d.Data["ServiceURLs"] != null) { string[] URLs = d.Data["ServiceURLs"].ToString().Split(new char[] { ' ' }); u.ServiceURLs = new Dictionary<string, object>(); foreach (string url in URLs) { string[] parts = url.Split(new char[] { '=' }); if (parts.Length != 2) continue; string name = System.Web.HttpUtility.UrlDecode(parts[0]); string val = System.Web.HttpUtility.UrlDecode(parts[1]); u.ServiceURLs[name] = val; } } else u.ServiceURLs = new Dictionary<string, object>(); return u; } public UserAccount GetUserAccount(UUID scopeID, string email) { UserAccountData[] d; if (scopeID != UUID.Zero) { d = m_Database.Get( new string[] { "ScopeID", "Email" }, new string[] { scopeID.ToString(), email }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "Email" }, new string[] { UUID.Zero.ToString(), email }); } } else { d = m_Database.Get( new string[] { "Email" }, new string[] { email }); } if (d.Length < 1) return null; return MakeUserAccount(d[0]); } public UserAccount GetUserAccount(UUID scopeID, UUID principalID) { UserAccountData[] d; if (scopeID != UUID.Zero) { d = m_Database.Get( new string[] { "ScopeID", "PrincipalID" }, new string[] { scopeID.ToString(), principalID.ToString() }); if (d.Length < 1) { d = m_Database.Get( new string[] { "ScopeID", "PrincipalID" }, new string[] { UUID.Zero.ToString(), principalID.ToString() }); } } else { d = m_Database.Get( new string[] { "PrincipalID" }, new string[] { principalID.ToString() }); } if (d.Length < 1) { return null; } return MakeUserAccount(d[0]); } public void InvalidateCache(UUID userID) { } public bool StoreUserAccount(UserAccount data) { // m_log.DebugFormat( // "[USER ACCOUNT SERVICE]: Storing user account for {0} {1} {2}, scope {3}", // data.FirstName, data.LastName, data.PrincipalID, data.ScopeID); UserAccountData d = new UserAccountData(); d.FirstName = data.FirstName; d.LastName = data.LastName; d.PrincipalID = data.PrincipalID; d.ScopeID = data.ScopeID; d.Data = new Dictionary<string, string>(); d.Data["Email"] = data.Email; d.Data["Created"] = data.Created.ToString(); d.Data["UserLevel"] = data.UserLevel.ToString(); d.Data["UserFlags"] = data.UserFlags.ToString(); if (data.UserTitle != null) d.Data["UserTitle"] = data.UserTitle.ToString(); List<string> parts = new List<string>(); foreach (KeyValuePair<string, object> kvp in data.ServiceURLs) { string key = System.Web.HttpUtility.UrlEncode(kvp.Key); string val = System.Web.HttpUtility.UrlEncode(kvp.Value.ToString()); parts.Add(key + "=" + val); } d.Data["ServiceURLs"] = string.Join(" ", parts.ToArray()); return m_Database.Store(d); } public List<UserAccount> GetUserAccounts(UUID scopeID, string query) { UserAccountData[] d = m_Database.GetUsers(scopeID, query); if (d == null) return new List<UserAccount>(); List<UserAccount> ret = new List<UserAccount>(); foreach (UserAccountData data in d) ret.Add(MakeUserAccount(data)); return ret; } #endregion #region Console commands /// <summary> /// Handle the create user command from the console. /// </summary> /// <param name="cmdparams">string array with parameters: firstname, lastname, password, locationX, locationY, email</param> protected void HandleCreateUser(string module, string[] cmdparams) { string firstName; string lastName; string password; string email; string rawPrincipalId; List<char> excluded = new List<char>(new char[]{' '}); if (cmdparams.Length < 3) firstName = MainConsole.Instance.CmdPrompt("First name", "Default", excluded); else firstName = cmdparams[2]; if (cmdparams.Length < 4) lastName = MainConsole.Instance.CmdPrompt("Last name", "User", excluded); else lastName = cmdparams[3]; if (cmdparams.Length < 5) password = MainConsole.Instance.PasswdPrompt("Password"); else password = cmdparams[4]; if (cmdparams.Length < 6) email = MainConsole.Instance.CmdPrompt("Email", ""); else email = cmdparams[5]; if (cmdparams.Length < 7) rawPrincipalId = MainConsole.Instance.CmdPrompt("User ID", UUID.Random().ToString()); else rawPrincipalId = cmdparams[6]; UUID principalId = UUID.Zero; if (!UUID.TryParse(rawPrincipalId, out principalId)) throw new Exception(string.Format("ID {0} is not a valid UUID", rawPrincipalId)); CreateUser(UUID.Zero, principalId, firstName, lastName, password, email); } protected void HandleShowAccount(string module, string[] cmdparams) { if (cmdparams.Length != 4) { MainConsole.Instance.Output("Usage: show account <first-name> <last-name>"); return; } string firstName = cmdparams[2]; string lastName = cmdparams[3]; UserAccount ua = GetUserAccount(UUID.Zero, firstName, lastName); if (ua == null) { MainConsole.Instance.OutputFormat("No user named {0} {1}", firstName, lastName); return; } MainConsole.Instance.OutputFormat("Name: {0}", ua.Name); MainConsole.Instance.OutputFormat("ID: {0}", ua.PrincipalID); MainConsole.Instance.OutputFormat("Title: {0}", ua.UserTitle); MainConsole.Instance.OutputFormat("E-mail: {0}", ua.Email); MainConsole.Instance.OutputFormat("Created: {0}", Utils.UnixTimeToDateTime(ua.Created)); MainConsole.Instance.OutputFormat("Level: {0}", ua.UserLevel); MainConsole.Instance.OutputFormat("Flags: {0}", ua.UserFlags); foreach (KeyValuePair<string, Object> kvp in ua.ServiceURLs) MainConsole.Instance.OutputFormat("{0}: {1}", kvp.Key, kvp.Value); } protected void HandleResetUserPassword(string module, string[] cmdparams) { string firstName; string lastName; string newPassword; if (cmdparams.Length < 4) firstName = MainConsole.Instance.CmdPrompt("First name"); else firstName = cmdparams[3]; if (cmdparams.Length < 5) lastName = MainConsole.Instance.CmdPrompt("Last name"); else lastName = cmdparams[4]; if (cmdparams.Length < 6) newPassword = MainConsole.Instance.PasswdPrompt("New password"); else newPassword = cmdparams[5]; UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) { MainConsole.Instance.OutputFormat("No such user as {0} {1}", firstName, lastName); return; } bool success = false; if (m_AuthenticationService != null) success = m_AuthenticationService.SetPassword(account.PrincipalID, newPassword); if (!success) MainConsole.Instance.OutputFormat("Unable to reset password for account {0} {1}.", firstName, lastName); else MainConsole.Instance.OutputFormat("Password reset for user {0} {1}", firstName, lastName); } protected void HandleSetUserLevel(string module, string[] cmdparams) { string firstName; string lastName; string rawLevel; int level; if (cmdparams.Length < 4) firstName = MainConsole.Instance.CmdPrompt("First name"); else firstName = cmdparams[3]; if (cmdparams.Length < 5) lastName = MainConsole.Instance.CmdPrompt("Last name"); else lastName = cmdparams[4]; UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (account == null) { MainConsole.Instance.OutputFormat("No such user"); return; } if (cmdparams.Length < 6) rawLevel = MainConsole.Instance.CmdPrompt("User level"); else rawLevel = cmdparams[5]; if(int.TryParse(rawLevel, out level) == false) { MainConsole.Instance.OutputFormat("Invalid user level"); return; } account.UserLevel = level; bool success = StoreUserAccount(account); if (!success) MainConsole.Instance.OutputFormat("Unable to set user level for account {0} {1}.", firstName, lastName); else MainConsole.Instance.OutputFormat("User level set for user {0} {1} to {2}", firstName, lastName, level); } #endregion /// <summary> /// Create a user /// </summary> /// <param name="scopeID">Allows hosting of multiple grids in a single database. Normally left as UUID.Zero</param> /// <param name="principalID">ID of the user</param> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="password"></param> /// <param name="email"></param> public UserAccount CreateUser(UUID scopeID, UUID principalID, string firstName, string lastName, string password, string email) { UserAccount account = GetUserAccount(UUID.Zero, firstName, lastName); if (null == account) { account = new UserAccount(UUID.Zero, principalID, firstName, lastName, email); if (account.ServiceURLs == null || (account.ServiceURLs != null && account.ServiceURLs.Count == 0)) { account.ServiceURLs = new Dictionary<string, object>(); account.ServiceURLs["HomeURI"] = string.Empty; account.ServiceURLs["InventoryServerURI"] = string.Empty; account.ServiceURLs["AssetServerURI"] = string.Empty; } if (StoreUserAccount(account)) { bool success; if (m_AuthenticationService != null) { success = m_AuthenticationService.SetPassword(account.PrincipalID, password); if (!success) m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set password for account {0} {1}.", firstName, lastName); } GridRegion home = null; if (m_GridService != null) { List<GridRegion> defaultRegions = m_GridService.GetDefaultRegions(UUID.Zero); if (defaultRegions != null && defaultRegions.Count >= 1) home = defaultRegions[0]; if (m_GridUserService != null && home != null) m_GridUserService.SetHome(account.PrincipalID.ToString(), home.RegionID, new Vector3(128, 128, 0), new Vector3(0, 1, 0)); else m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to set home for account {0} {1}.", firstName, lastName); } else { m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to retrieve home region for account {0} {1}.", firstName, lastName); } if (m_InventoryService != null) { success = m_InventoryService.CreateUserInventory(account.PrincipalID); if (!success) { m_log.WarnFormat("[USER ACCOUNT SERVICE]: Unable to create inventory for account {0} {1}.", firstName, lastName); } else { m_log.DebugFormat( "[USER ACCOUNT SERVICE]: Created user inventory for {0} {1}", firstName, lastName); } if (m_CreateDefaultAvatarEntries) CreateDefaultAppearanceEntries(account.PrincipalID); } m_log.InfoFormat( "[USER ACCOUNT SERVICE]: Account {0} {1} {2} created successfully", firstName, lastName, account.PrincipalID); } else { m_log.ErrorFormat("[USER ACCOUNT SERVICE]: Account creation failed for account {0} {1}", firstName, lastName); } } else { m_log.ErrorFormat("[USER ACCOUNT SERVICE]: A user with the name {0} {1} already exists!", firstName, lastName); } return account; } protected void CreateDefaultAppearanceEntries(UUID principalID) { m_log.DebugFormat("[USER ACCOUNT SERVICE]: Creating default appearance items for {0}", principalID); InventoryFolderBase bodyPartsFolder = m_InventoryService.GetFolderForType(principalID, AssetType.Bodypart); InventoryItemBase eyes = new InventoryItemBase(UUID.Random(), principalID); eyes.AssetID = new UUID("4bb6fa4d-1cd2-498a-a84c-95c1a0e745a7"); eyes.Name = "Default Eyes"; eyes.CreatorId = principalID.ToString(); eyes.AssetType = (int)AssetType.Bodypart; eyes.InvType = (int)InventoryType.Wearable; eyes.Folder = bodyPartsFolder.ID; eyes.BasePermissions = (uint)PermissionMask.All; eyes.CurrentPermissions = (uint)PermissionMask.All; eyes.EveryOnePermissions = (uint)PermissionMask.All; eyes.GroupPermissions = (uint)PermissionMask.All; eyes.NextPermissions = (uint)PermissionMask.All; eyes.Flags = (uint)WearableType.Eyes; m_InventoryService.AddItem(eyes); InventoryItemBase shape = new InventoryItemBase(UUID.Random(), principalID); shape.AssetID = AvatarWearable.DEFAULT_BODY_ASSET; shape.Name = "Default Shape"; shape.CreatorId = principalID.ToString(); shape.AssetType = (int)AssetType.Bodypart; shape.InvType = (int)InventoryType.Wearable; shape.Folder = bodyPartsFolder.ID; shape.BasePermissions = (uint)PermissionMask.All; shape.CurrentPermissions = (uint)PermissionMask.All; shape.EveryOnePermissions = (uint)PermissionMask.All; shape.GroupPermissions = (uint)PermissionMask.All; shape.NextPermissions = (uint)PermissionMask.All; shape.Flags = (uint)WearableType.Shape; m_InventoryService.AddItem(shape); InventoryItemBase skin = new InventoryItemBase(UUID.Random(), principalID); skin.AssetID = AvatarWearable.DEFAULT_SKIN_ASSET; skin.Name = "Default Skin"; skin.CreatorId = principalID.ToString(); skin.AssetType = (int)AssetType.Bodypart; skin.InvType = (int)InventoryType.Wearable; skin.Folder = bodyPartsFolder.ID; skin.BasePermissions = (uint)PermissionMask.All; skin.CurrentPermissions = (uint)PermissionMask.All; skin.EveryOnePermissions = (uint)PermissionMask.All; skin.GroupPermissions = (uint)PermissionMask.All; skin.NextPermissions = (uint)PermissionMask.All; skin.Flags = (uint)WearableType.Skin; m_InventoryService.AddItem(skin); InventoryItemBase hair = new InventoryItemBase(UUID.Random(), principalID); hair.AssetID = AvatarWearable.DEFAULT_HAIR_ASSET; hair.Name = "Default Hair"; hair.CreatorId = principalID.ToString(); hair.AssetType = (int)AssetType.Bodypart; hair.InvType = (int)InventoryType.Wearable; hair.Folder = bodyPartsFolder.ID; hair.BasePermissions = (uint)PermissionMask.All; hair.CurrentPermissions = (uint)PermissionMask.All; hair.EveryOnePermissions = (uint)PermissionMask.All; hair.GroupPermissions = (uint)PermissionMask.All; hair.NextPermissions = (uint)PermissionMask.All; hair.Flags = (uint)WearableType.Hair; m_InventoryService.AddItem(hair); InventoryFolderBase clothingFolder = m_InventoryService.GetFolderForType(principalID, AssetType.Clothing); InventoryItemBase shirt = new InventoryItemBase(UUID.Random(), principalID); shirt.AssetID = AvatarWearable.DEFAULT_SHIRT_ASSET; shirt.Name = "Default Shirt"; shirt.CreatorId = principalID.ToString(); shirt.AssetType = (int)AssetType.Clothing; shirt.InvType = (int)InventoryType.Wearable; shirt.Folder = clothingFolder.ID; shirt.BasePermissions = (uint)PermissionMask.All; shirt.CurrentPermissions = (uint)PermissionMask.All; shirt.EveryOnePermissions = (uint)PermissionMask.All; shirt.GroupPermissions = (uint)PermissionMask.All; shirt.NextPermissions = (uint)PermissionMask.All; shirt.Flags = (uint)WearableType.Shirt; m_InventoryService.AddItem(shirt); InventoryItemBase pants = new InventoryItemBase(UUID.Random(), principalID); pants.AssetID = AvatarWearable.DEFAULT_PANTS_ASSET; pants.Name = "Default Pants"; pants.CreatorId = principalID.ToString(); pants.AssetType = (int)AssetType.Clothing; pants.InvType = (int)InventoryType.Wearable; pants.Folder = clothingFolder.ID; pants.BasePermissions = (uint)PermissionMask.All; pants.CurrentPermissions = (uint)PermissionMask.All; pants.EveryOnePermissions = (uint)PermissionMask.All; pants.GroupPermissions = (uint)PermissionMask.All; pants.NextPermissions = (uint)PermissionMask.All; pants.Flags = (uint)WearableType.Pants; m_InventoryService.AddItem(pants); if (m_AvatarService != null) { m_log.DebugFormat("[USER ACCOUNT SERVICE]: Creating default avatar entries for {0}", principalID); AvatarWearable[] wearables = new AvatarWearable[6]; wearables[AvatarWearable.EYES] = new AvatarWearable(eyes.ID, eyes.AssetID); wearables[AvatarWearable.BODY] = new AvatarWearable(shape.ID, shape.AssetID); wearables[AvatarWearable.SKIN] = new AvatarWearable(skin.ID, skin.AssetID); wearables[AvatarWearable.HAIR] = new AvatarWearable(hair.ID, hair.AssetID); wearables[AvatarWearable.SHIRT] = new AvatarWearable(shirt.ID, shirt.AssetID); wearables[AvatarWearable.PANTS] = new AvatarWearable(pants.ID, pants.AssetID); AvatarAppearance ap = new AvatarAppearance(); for (int i = 0; i < 6; i++) { ap.SetWearable(i, wearables[i]); } m_AvatarService.SetAppearance(principalID, ap); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. using System; using System.ComponentModel; using Microsoft.WindowsAPICodePack.DirectX.Direct2D1; using Microsoft.WindowsAPICodePack.DirectX.DirectWrite; using System.Text; using System.Globalization; namespace D2DShapes { internal class TextShape : DrawingShape { private RectF layoutRect; protected internal DWriteFactory dwriteFactory; [TypeConverter(typeof(ExpandableObjectConverter))] public RenderingParams RenderingParams { get; set; } [TypeConverter(typeof (ExpandableObjectConverter))] public DrawTextOptions? Options { get; set; } [TypeConverter(typeof(ExpandableObjectConverter))] public TextFormat TextFormat { get; set; } public string Text { get; set; } protected bool NiceGabriola; public TextShape(RenderTarget initialRenderTarget, Random random, D2DFactory d2DFactory, D2DBitmap bitmap, DWriteFactory dwriteFactory) : base(initialRenderTarget, random, d2DFactory, bitmap) { this.dwriteFactory = dwriteFactory; layoutRect = RandomRect(CanvasWidth, CanvasHeight); NiceGabriola = Random.NextDouble() < 0.25 && dwriteFactory.SystemFontFamilyCollection.Contains("Gabriola"); TextFormat = dwriteFactory.CreateTextFormat( RandomFontFamily(), RandomFontSize(), RandomFontWeight(), RandomFontStyle(), RandomFontStretch(), System.Globalization.CultureInfo.CurrentUICulture); if (CoinFlip) TextFormat.LineSpacing = RandomLineSpacing(TextFormat.FontSize); Text = RandomString(Random.Next(1000, 1000)); FillBrush = RandomBrush(); RenderingParams = RandomRenderingParams(); if (CoinFlip) { Options = DrawTextOptions.None; if (CoinFlip) Options |= DrawTextOptions.Clip; if (CoinFlip) Options |= DrawTextOptions.NoSnap; } } protected internal RenderingParams RandomRenderingParams() { RenderingParams rp = dwriteFactory.CreateCustomRenderingParams( (float)Math.Max(0.001, Math.Min(1, Random.NextDouble() * 2)), //gamma needs to be nonzero (float)Math.Max(0, Math.Min(1, Random.NextDouble() * 3 - 1)), //equal chances for 0, 1 and something in between (float)Math.Max(0, Math.Min(1, Random.NextDouble() * 3 - 1)), //equal chances for 0, 1 and something in between RandomPixelGeometry(), RandomRenderingMode()); return rp; } private PixelGeometry RandomPixelGeometry() { return (PixelGeometry) Random.Next(0, 2); } private RenderingMode RandomRenderingMode() { return (RenderingMode)Random.Next(0, 6); } protected internal LineSpacing RandomLineSpacing(float fontSize) { LineSpacingMethod method = CoinFlip ? LineSpacingMethod.Default : LineSpacingMethod.Uniform; var spacing = (float)(Random.NextDouble()*fontSize*4 + 0.5); var baseline = (float)Random.NextDouble(); return new LineSpacing( method, spacing, baseline); } private string RandomFontFamily() { if (NiceGabriola) return "Gabriola"; if (CoinFlip) { //get random font out of the list of installed fonts int i = Random.Next(0, dwriteFactory.SystemFontFamilyCollection.Count - 1); FontFamily f = dwriteFactory.SystemFontFamilyCollection[i]; string ret = null; if (f.FamilyNames.ContainsKey(CultureInfo.CurrentUICulture)) ret = f.FamilyNames[CultureInfo.CurrentUICulture]; else if (f.FamilyNames.ContainsKey(CultureInfo.InvariantCulture)) ret = f.FamilyNames[CultureInfo.InvariantCulture]; else if (f.FamilyNames.ContainsKey(CultureInfo.GetCultureInfo("EN-us"))) ret = f.FamilyNames[CultureInfo.GetCultureInfo("EN-us")]; else { foreach (var c in f.FamilyNames.Keys) { ret = f.FamilyNames[c]; break; } } f.Dispose(); return ret; } //get one of the common fonts return new[] {"Arial", "Times New Roman", "Courier New", "Impact", "Tahoma", "Calibri", "Consolas", "Segoe", "Cambria" }[Random.Next(0, 8)]; } private float RandomFontSize() { return 6 + (float)(138 * Random.NextDouble() * Random.NextDouble()); } private FontWeight RandomFontWeight() { return (FontWeight)(Math.Min(950, 100 * Random.Next(1, 10))); } private FontStyle RandomFontStyle() { return (FontStyle)Random.Next(0, 2); } private FontStretch RandomFontStretch() { return (FontStretch) Random.Next(1, 9); } private string RandomString(int size) { var builder = new StringBuilder(size + 1) { Length = size }; builder[0] = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * Random.NextDouble() + 65))); for (int i = 1; i < size - 1; i++) { builder[i] = Random.NextDouble() < 0.2 ? ' ' : Convert.ToChar(Convert.ToInt32(Math.Floor(26 * Random.NextDouble() + 97))); } builder[size - 1] = '.'; return builder.ToString(); } protected internal override void ChangeRenderTarget(RenderTarget newRenderTarget) { FillBrush = CopyBrushToRenderTarget(FillBrush, newRenderTarget); } protected internal override void Draw(RenderTarget renderTarget) { DrawingStateBlock stateBlock = d2DFactory.CreateDrawingStateBlock(); renderTarget.SaveDrawingState(stateBlock); renderTarget.TextRenderingParams = RenderingParams; if (Options.HasValue) { renderTarget.DrawText(Text, TextFormat, layoutRect, FillBrush, Options.Value); } else renderTarget.DrawText(Text, TextFormat, layoutRect, FillBrush); renderTarget.RestoreDrawingState(stateBlock); stateBlock.Dispose(); } public override bool HitTest(Point2F point) { return point.X >= layoutRect.Left && point.Y >= layoutRect.Top && point.X <= layoutRect.Right && point.Y <= layoutRect.Bottom; } public override void Dispose() { if (TextFormat != null) TextFormat.Dispose(); TextFormat = null; if (RenderingParams != null) RenderingParams.Dispose(); RenderingParams = null; base.Dispose(); } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Security; using System.Windows; using System.Windows.Media; namespace System.Windows.Input { /// <summary> /// Provides an update on an ocurring manipulation. /// </summary> public sealed class ManipulationDeltaEventArgs : InputEventArgs { /// <summary> /// Instantiates a new instance of this class. /// </summary> internal ManipulationDeltaEventArgs( ManipulationDevice manipulationDevice, int timestamp, IInputElement manipulationContainer, Point origin, ManipulationDelta delta, ManipulationDelta cumulative, ManipulationVelocities velocities, bool isInertial) : base(manipulationDevice, timestamp) { if (delta == null) { throw new ArgumentNullException("delta"); } if (cumulative == null) { throw new ArgumentNullException("cumulative"); } if (velocities == null) { throw new ArgumentNullException("velocities"); } RoutedEvent = Manipulation.ManipulationDeltaEvent; ManipulationContainer = manipulationContainer; ManipulationOrigin = origin; DeltaManipulation = delta; CumulativeManipulation = cumulative; Velocities = velocities; IsInertial = isInertial; } /// <summary> /// Invokes a handler of this event. /// </summary> protected override void InvokeEventHandler(Delegate genericHandler, object genericTarget) { if (genericHandler == null) { throw new ArgumentNullException("genericHandler"); } if (genericTarget == null) { throw new ArgumentNullException("genericTarget"); } if (RoutedEvent == Manipulation.ManipulationDeltaEvent) { ((EventHandler<ManipulationDeltaEventArgs>)genericHandler)(genericTarget, this); } else { base.InvokeEventHandler(genericHandler, genericTarget); } } /// <summary> /// Whether the event was generated due to inertia. /// </summary> public bool IsInertial { get; private set; } /// <summary> /// Defines the coordinate space of the other properties. /// </summary> public IInputElement ManipulationContainer { get; private set; } /// <summary> /// Returns the value of the origin. /// </summary> public Point ManipulationOrigin { get; private set; } /// <summary> /// Returns the cumulative transformation associated with the manipulation. /// </summary> public ManipulationDelta CumulativeManipulation { get; private set; } /// <summary> /// Returns the delta transformation associated with the manipulation. /// </summary> public ManipulationDelta DeltaManipulation { get; private set; } /// <summary> /// Returns the current velocities associated with a manipulation. /// </summary> public ManipulationVelocities Velocities { get; private set; } /// <summary> /// Allows a handler to specify that the manipulation has gone beyond certain boundaries. /// By default, this value will then be used to provide panning feedback on the window, but /// it can be change by handling the ManipulationBoundaryFeedback event. /// </summary> public void ReportBoundaryFeedback(ManipulationDelta unusedManipulation) { if (unusedManipulation == null) { throw new ArgumentNullException("unusedManipulation"); } UnusedManipulation = unusedManipulation; } /// <summary> /// The value of the unused manipulation information in global coordinate space. /// </summary> internal ManipulationDelta UnusedManipulation { get; private set; } /// <summary> /// Preempts further processing and completes the manipulation without any inertia. /// </summary> public void Complete() { RequestedComplete = true; RequestedInertia = false; RequestedCancel = false; } /// <summary> /// Preempts further processing and completes the manipulation, allowing inertia to continue. /// </summary> public void StartInertia() { RequestedComplete = true; RequestedInertia = true; RequestedCancel = false; } /// <summary> /// Method to cancel the Manipulation /// </summary> /// <returns>A bool indicating the success of Cancel</returns> public bool Cancel() { if (!IsInertial) { RequestedCancel = true; RequestedComplete = false; RequestedInertia = false; return true; } return false; } /// <summary> /// A handler requested that the manipulation complete. /// </summary> internal bool RequestedComplete { get; private set; } /// <summary> /// A handler requested that the manipulation complete with inertia. /// </summary> internal bool RequestedInertia { get; private set; } /// <summary> /// A handler Requested to cancel the Manipulation /// </summary> internal bool RequestedCancel { get; private set; } /// <summary> /// The Manipulators for this manipulation. /// </summary> public IEnumerable<IManipulator> Manipulators { get { if (_manipulators == null) { _manipulators = ((ManipulationDevice)Device).GetManipulatorsReadOnly(); } return _manipulators; } } private IEnumerable<IManipulator> _manipulators; } }